问:
Why doesn't likely and unlikely macros have any effect on ARM assembly code?
I took below example from https://kernelnewbies.org/FAQ/LikelyUnlikely

```<code>#include <stdio.h>
#define likely(x)    __builtin_expect(!!(x), 1)
#define unlikely(x)  __builtin_expect(!!(x), 0)

int main(char *argv[], int argc)
{
   int a;

   /* Get the value from somewhere GCC can't optimize */
   a = atoi (argv[1]);

   if (likely (a == 2))
      a++;
   else
      a--;

   printf ("%d\n", a);

   return 0;
}
</code>```

and compiled it https://godbolt.org/z/IC0aif with arm gcc 8.2 compiler.

In the original link, they have tested it for X86 and the assembly output is different if likely(in the if condition in above code) is replaced with unlikely, which shows the optimisation performed by compiler for branch prediction.

But when I compile the above code for ARM (arm-gcc -O2), I don't see any difference in assembly code. Below is the output of ARM assembly in both the case - likely and unlikely

```<code>main:
        push    {r4, lr}
        ldr     r0, [r0, #4]
        bl      atoi
        cmp     r0, #2
        subne   r1, r0, #1
        moveq   r1, #3
        ldr     r0, .L6
        bl      printf
        mov     r0, #0
        pop     {r4, pc}
.L6:
        .word   .LC0
.LC0:
        .ascii  "%d\012\000"
</code>```

Why doesn't the compiler optimize for branch prediction in case of ARM ?

答:
As @rici said, your code is simple enough that it can be realized by conditional instructions. You can see a difference, e.g., if you call functions which are implemented in a different compilation unit:

```<code>#define likely(x)    __builtin_expect(!!(x), 1)
#define unlikely(x)  __builtin_expect(!!(x), 0)

// only forward declarations:
void foo();
void bar();

int main(char *argv[], int argc)
{
   if (likely (argc == 2))
      foo();
   else
      bar();
}
</code>```

Changing likely to unlikely switches the order of the if and else branch, for ARM and x86: https://godbolt.org/z/UDzvf0. If this really makes a difference likely depends on the hardware you are running on, whether you call the function the first time (otherwise, the CPU-internal branch prediction likely has a higher influence than the order of the instructions), and probably many other things.

Body:
I took below example from https://kernelnewbies.org/FAQ/LikelyUnlikely

#include <stdio.h>
#define likely(x)    __builtin_expect(!!(x), 1)
#define unlikely(x)  __builtin_expect(!!(x), 0)

int main(char *argv[], int argc)
{
   int a;

   /* Get the value from somewhere GCC can't optimize */
   a = atoi (argv[1]);

   if (likely (a == 2))
      a++;
   else
      a--;

   printf ("%d\n", a);

   return 0;
}

and compiled it https://godbolt.org/z/IC0aif with arm gcc 8.2 compiler.

In the original link, they have tested it for X86 and the assembly output is different if likely(in the if condition in above code) is replaced with unlikely, which shows the optimisation performed by compiler for branch prediction.

But when I compile the above code for ARM (arm-gcc -O2), I don't see any difference in assembly code. Below is the output of ARM assembly in both the case - likely and unlikely

main:
        push    {r4, lr}
        ldr     r0, [r0, #4]
        bl      atoi
        cmp     r0, #2
        subne   r1, r0, #1
        moveq   r1, #3
        ldr     r0, .L6
        bl      printf
        mov     r0, #0
        pop     {r4, pc}
.L6:
        .word   .LC0
.LC0:
        .ascii  "%d\012\000"

Why doesn't the compiler optimize for branch prediction in case of ARM ?

Body:
As @rici said, your code is simple enough that it can be realized by conditional instructions. You can see a difference, e.g., if you call functions which are implemented in a different compilation unit:

#define likely(x)    __builtin_expect(!!(x), 1)
#define unlikely(x)  __builtin_expect(!!(x), 0)

// only forward declarations:
void foo();
void bar();

int main(char *argv[], int argc)
{
   if (likely (argc == 2))
      foo();
   else
      bar();
}

Changing likely to unlikely switches the order of the if and else branch, for ARM and x86: https://godbolt.org/z/UDzvf0. If this really makes a difference likely depends on the hardware you are running on, whether you call the function the first time (otherwise, the CPU-internal branch prediction likely has a higher influence than the order of the instructions), and probably many other things.


来源: stackexchange

问:
Figuring out the IP address of a service for dockerized Consul
I am building a microservices based application and would like to use Consul as service registry. All in all I have three scenarios:

All the services run on the host.

All the services run on the host, but Consul runs in Docker.

All the services and Consul run in Docker.

Now I have the problem of how to register the services with their IP address, because I need to figure out their IP address so that it is reachable by Consul (e.g., for the health checks):

If everything runs on the same host, it's pretty easy: Simply use 127.0.0.1, and you're done.

If everything (including Consul) runs in Docker, I could use hostname -i from within the Docker containers to figure out their external IP and hand it over to Consul. This works, but I wonder if there is  a better way to solve this? (Ideally, the solution should also work in the same way on Kubernetes.)

If the services run on the host, but Consul runs in Docker, right now I am missing any idea at all. Basically, Consul requires the host's IP address to be able to talk to the services, but I can only detect this from within the Consul container (by resolving host.docker.internal). But first, this does not work from externally, and second it only works for Docker for Mac / Windows, not e.g. with Kubernetes.

How could I solve these issues?

PS: I would like to avoid using a container such as registrator by Gliderlabs, since I have doubts how well this works on Kubernetes, and also it won't help with the mixed Docker / host scenario.

答:
If you're using Kubernetes, you might start by checking whether its built-in service registry meets your needs.  There's generally not a direct path to reach a pod via its node's host's IP address, so the setup you describe won't really work well.  (I might consider Consul for a key/value store but I wouldn't reach for it as a service registry in Kubernetes land.)

In plain multi-host Docker land, this is one of the few situations I've found where host networking is appropriate.  Start Consul with --net host or an equivalent option in Docker Compose or another orchestration tool.  Then Consul will believe "its" IP address is the host's, and if you have automated TCP probes of well-known ports, you can search every service that's running on the host and discover e.g. a MySQL service on port 3306, whether running in a container or natively on the host.

With this setup, servicename.service.consul will resolve to some physical-host IP address.  If you have a Docker container pointing at its current host for DNS service, then that will route a service to some host, maybe the same one, but this has worked reliably for me in the past.

Note that the relevant hostnames will be different in different environments: servicename.service.consul for a Consul-based setup, servicename.namespacename.svc.cluster.local in Kubernetes, maybe localhost in a developer-desktop environment.  You need to make sure this is configurable, most straightforwardly via an environment variable.

ContentLicense: CC BY-SA 4.0


问:
How to return specific properties of objects in form of array in javascript
I have a function that takes an array of dog objects and returns an array of the specific properties</p>

```<code>The code that I have tried
function Owner(dogs) {
     dogs.map(value => {
     if (value.breed === 'GermanShepherd') {
         return value.owner;
 }
}
</code>```

答:
One option is using reduce() and check if the breed if same with search variable, if it is, use concat() to add to the accumulator.

let arr = [{"name":"Beatrice","breed":"Lurcher","owner":"Tom"},{"name":"Max","breed":"GermanShepherd","owner":"Malcolm"},{"name":"Poppy","breed":"GermanShepherd","owner":"Vikram"}];
let search = 'GermanShepherd';

let result = arr.reduce((c, v) => v.breed === search ? c.concat(v.owner) : c, []);

console.log(result);```
</div>
</div>
</p>

<hr>

<p>You can also use <code>filter</code> and <code>map</code> combo.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = [{"name":"Beatrice","breed":"Lurcher","owner":"Tom"},{"name":"Max","breed":"GermanShepherd","owner":"Malcolm"},{"name":"Poppy","breed":"GermanShepherd","owner":"Vikram"}]
let search = 'GermanShepherd';

let result = arr.filter(o => o.breed === search).map(o => o.owner);

console.log(result);</code>```

Body:
I have a function that takes an array of dog objects and returns an array of the specific properties

The code that I have tried
function Owner(dogs) {
     dogs.map(value => {
     if (value.breed === 'GermanShepherd') {
         return value.owner;
 }
}

Body:
One option is using reduce() and check if the breed if same with search variable, if it is, use concat() to add to the accumulator.

let arr = [{"name":"Beatrice","breed":"Lurcher","owner":"Tom"},{"name":"Max","breed":"GermanShepherd","owner":"Malcolm"},{"name":"Poppy","breed":"GermanShepherd","owner":"Vikram"}];
let search = 'GermanShepherd';

let result = arr.reduce((c, v) => v.breed === search ? c.concat(v.owner) : c, []);

console.log(result);

You can also use filter and map combo.

let arr = [{"name":"Beatrice","breed":"Lurcher","owner":"Tom"},{"name":"Max","breed":"GermanShepherd","owner":"Malcolm"},{"name":"Poppy","breed":"GermanShepherd","owner":"Vikram"}]
let search = 'GermanShepherd';

let result = arr.filter(o => o.breed === search).map(o => o.owner);

console.log(result);


问:
get value from location.href="javascript:someFunction()"?
Is is possible to get the value returned by a function, by triggering that function with location.href='javascript:someFunction()?

```<code>/* in some script */

function someFunction(action) {
   console.log('triggered');
   return 'Received';
}

/* in another script and another level */
var returned = location.href='javascript:someFunction()';

// Is it possible to get the returned value this way?
</code>```

I know there are other solutions and possibilities, but I'm looking for a simple answer, is it possible to receive the returned values like that or not, and if yes, how?

I appreciate your kind replies.

EDIT:

Top level page:

```<code>function someFunction() {
   var collectionEvent = new CustomEvent("PageEvent", {detail: {data:lotsOfData}});
   window.dispatchEvent(collectionEvent);
}
</code>```

Sandbox:

```<code>var data;
window.addEventListener("PageEvent", function(event) {
    data = event.detail.lotsOfData;
}, false);
</code>```

So far so good, now I can trigger:

```<code>window.href = "javascript:someFunction()";
setTimeOut(function() {
   doTheMainFunction(data);
}, 2000);
</code>```

That's the work around I don't like, because I don't know how much time does someFunction take to get the data from the main window object and pass to the sandbox, so I couldn't make a promise.

Thanks.

答:
If I understand your question well, then you can store assigning the result of the function into a variable:</p>

```<code>/* in some script */

function someFunction(action) {
   console.log('triggered');
   return 'Received';
}

/* in another script and another level */
var returned = `location.href='${someFunction()}'`;

// Is it possible to get the returned value this way?
</code>```

Body:
Is is possible to get the value returned by a function, by triggering that function with location.href='javascript:someFunction()?

/* in some script */

function someFunction(action) {
   console.log('triggered');
   return 'Received';
}

/* in another script and another level */
var returned = location.href='javascript:someFunction()';

// Is it possible to get the returned value this way?

I know there are other solutions and possibilities, but I'm looking for a simple answer, is it possible to receive the returned values like that or not, and if yes, how?

I appreciate your kind replies.

EDIT:

Top level page:

function someFunction() {
   var collectionEvent = new CustomEvent("PageEvent", {detail: {data:lotsOfData}});
   window.dispatchEvent(collectionEvent);
}

Sandbox:

var data;
window.addEventListener("PageEvent", function(event) {
    data = event.detail.lotsOfData;
}, false);

So far so good, now I can trigger:

window.href = "javascript:someFunction()";
setTimeOut(function() {
   doTheMainFunction(data);
}, 2000);

That's the work around I don't like, because I don't know how much time does someFunction take to get the data from the main window object and pass to the sandbox, so I couldn't make a promise.

Thanks.

Body:
If I understand your question well, then you can store assigning the result of the function into a variable:

/* in some script */

function someFunction(action) {
   console.log('triggered');
   return 'Received';
}

/* in another script and another level */
var returned = `location.href='${someFunction()}'`;

// Is it possible to get the returned value this way?


问:
Click event on a slider goes at the end of the array
I am trying to create a simple slider using javascript.
So far, here is my code :

html:

```<code>  <div class="carousel-container">

    <div class="slides-container">
      <div class="slide">
        <img src="assets/images/image-1.jpg" alt="">
      </div>
      <div class="slide">
        <img src="assets/images/image-3.jpg" alt="">
      </div>
      <div class="slide">
        <img src="assets/images/image-2.jpg" alt="">
      </div>
      <div class="slide">
        <img src="assets/images/image-3.jpg" alt="">
      </div>
    </div>

  </div>

  <div class="carousel-nav">
    <button class="button-previous">Previous</button>
    <button class="button-next">Next</button>
  </div>
</code>```

Js :

```<code>    const slides = document.querySelectorAll('.slide')
    const slidesContainer = document.querySelector('.slides-container')
    const slidesCount = slides.length
    const slideWidth = slides[0].clientWidth

    const prevButton = document.querySelector('.button-previous')
    const nextButton = document.querySelector('.button-next')

    function nextSlide(slide) {
      for (slide = 0; slide < slidesCount; slide++) {
        slidesContainer.style.transform = 'translateX(-' + (slide * slideWidth) + 'px)'
      }
    }

    nextButton.addEventListener('click', function() {
      nextSlide()
    })
</code>```

The issue I have is that when I click on the next button, the slider goes all the way at the end of my array, thus skipping all the images in between.

What would be the best way to have my for loop stop at each image and go again when the button is clicked?

答:
The reason it is skipping to the end with each click is: the for() loop. You are cycling through all of the slides — generating a new translateX coordinate with each pass – on every click. Leaving you with the last value every time.

The answer CheapGamer gave defines a pattern to avoid the for() loop trap by keeping track of the current “slide” index outside of the nextSlide() handler.

```<code>let current = 0; // <- independent index reference

function nextSlide(slide) {
      if (current < slidesCount) {
        slidesContainer.style.transform = 'translateX(-' + (current * slideWidth) + 'px)';
        current++;  // <- increment the index
      }
}
// I changed the `slide` reference in `(slide * slideWidth)` to `current`  to reflect the intent of the code
</code>```

This takes care of incrementing you through the carousel until current equals 3. (The slide argument in nextSlide(slide) isn’t necessary.)

Body:
I am trying to create a simple slider using javascript.
So far, here is my code :

html:

    <button class="button-previous">Previous</button>
    <button class="button-next">Next</button>

Js :

    const slides = document.querySelectorAll('.slide')
    const slidesContainer = document.querySelector('.slides-container')
    const slidesCount = slides.length
    const slideWidth = slides[0].clientWidth

    const prevButton = document.querySelector('.button-previous')
    const nextButton = document.querySelector('.button-next')

    function nextSlide(slide) {
      for (slide = 0; slide < slidesCount; slide++) {
        slidesContainer.style.transform = 'translateX(-' + (slide * slideWidth) + 'px)'
      }
    }

    nextButton.addEventListener('click', function() {
      nextSlide()
    })

The issue I have is that when I click on the next button, the slider goes all the way at the end of my array, thus skipping all the images in between.

What would be the best way to have my for loop stop at each image and go again when the button is clicked?

Body:
The reason it is skipping to the end with each click is: the for() loop. You are cycling through all of the slides — generating a new translateX coordinate with each pass – on every click. Leaving you with the last value every time.

The answer CheapGamer gave defines a pattern to avoid the for() loop trap by keeping track of the current “slide” index outside of the nextSlide() handler.

let current = 0; // <- independent index reference

function nextSlide(slide) {
      if (current < slidesCount) {
        slidesContainer.style.transform = 'translateX(-' + (current * slideWidth) + 'px)';
        current++;  // <- increment the index
      }
}
// I changed the `slide` reference in `(slide * slideWidth)` to `current`  to reflect the intent of the code

This takes care of incrementing you through the carousel until current equals 3. (The slide argument in nextSlide(slide) isn’t necessary.)


问:
Radio Button with default selection in Django
I had the same doubt of radio button in model file.

I want it to be a compulsory/required field with default selection to "No".

Fields available would be - Yes/No. Any suggestions.

```<code>B_CHOICES = [('P','Positive'),('N','Negative')]
Tag_Type = models.CharField(choices=B_CHOICES, max_length=128)
</code>```

Here's my form and model code-

Form -

```<code><form id="ant_form" name="ant_form" method="POST" action="#">{% csrf_token %}

<input name="r_user" type="checkbox" value="{{user.id}}" />  {{user.username}}

<input type="radio" name="txt{{user.id}}" value="P" > </input>
    P Comment
<input type="radio" name="txt{{user.id}}" value="N" > </input>
    N Comment

<textarea style="height: auto" rows="1" id="txt{{user.id}}" name="comment_{{user.id}}" cols="50">
</textarea>
<br>
</li>
{% endfor %}
</ul>
</div>

{% endif %} {# users #}

</form>
</code>```

Model -

```<code>class r(models.Model):

BCHOICES = [('P','P'),('N','N'),]

tag_type = models.CharField(max_length=2, default=Negative, choices=BCHOICES)
</code>```

答:
You can set the default to 'N':

```<code>from django.db import models

B_CHOICES = [('P','Positive'),('N','Negative')]

class MyModel(models.Model):
    tag_type = models.CharField(choices=B_CHOICES, max_length=128<b>, default='N'</b>)</code>```

When you render a ModelForm for the given MyModel, then the HTML will look like:

```<code><select name="tag_type" id="id_tag_type">
  <option value="P">Positive</option>
  <option value="N" <b>selected</b>>Negative</option>
</select></code>```

Body:
I had the same doubt of radio button in model file.

I want it to be a compulsory/required field with default selection to "No".

Fields available would be - Yes/No. Any suggestions.

B_CHOICES = [('P','Positive'),('N','Negative')]
Tag_Type = models.CharField(choices=B_CHOICES, max_length=128)

Here's my form and model code-

Form -

<form id="ant_form" name="ant_form" method="POST" action="#">{% csrf_token %}

<input name="r_user" type="checkbox" value="{{user.id}}" />  {{user.username}}

<input type="radio" name="txt{{user.id}}" value="P" > </input>
    P Comment
<input type="radio" name="txt{{user.id}}" value="N" > </input>
    N Comment

<textarea style="height: auto" rows="1" id="txt{{user.id}}" name="comment_{{user.id}}" cols="50">
</textarea>

{% endfor %}

{% endif %} {# users #}

</form>

Model -

class r(models.Model):

BCHOICES = [('P','P'),('N','N'),]

tag_type = models.CharField(max_length=2, default=Negative, choices=BCHOICES)

Body:
You can set the default to 'N':

from django.db import models

B_CHOICES = [('P','Positive'),('N','Negative')]

class MyModel(models.Model):
    tag_type = models.CharField(choices=B_CHOICES, max_length=128, default='N')

When you render a ModelForm for the given MyModel, then the HTML will look like:

<select name="tag_type" id="id_tag_type">
  <option value="P">Positive</option>
  <option value="N" selected>Negative</option>
</select>


问:
Xcode Swift am/pm time to 24 hour format
I am trying to convert an am/pm format time to a 24 hour format time

```<code>6:35 PM to 18:35
</code>```

I tried this piece of code on playground but it doesn't seem to
work if I put the time alone

```<code>let dateAsString = "02/12/15, 6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH"
let date = dateFormatter.dateFromString(dateAsString) //returns nil
</code>```

Does anyone know how to accomplish this?

答:
Swift 3 *

Code to convert 12 hours (i.e. AM and PM) to 24 hours format which includes-

Hours:Minutes:Seconds:AM/PM to Hours:Minutes:Seconds

```<code>func timeConversion24(time12: String) -> String {
    let dateAsString = time12
    let df = DateFormatter()
    df.dateFormat = "hh:mm:ssa"

    let date = df.date(from: dateAsString)
    df.dateFormat = "HH:mm:ss"

    let time24 = df.string(from: date!)
    print(time24)
    return time24
}
</code>```

Input

07:05:45PM

Output

19:05:45

Similarly

Code to convert 24 hours to 12 hours (i.e. AM and PM) format which includes-

Hours:Minutes:Seconds to Hours:Minutes:Seconds:AM/PM

```<code>func timeConversion12(time24: String) -> String {
    let dateAsString = time24
    let df = DateFormatter()
    df.dateFormat = "HH:mm:ss"

    let date = df.date(from: dateAsString)
    df.dateFormat = "hh:mm:ssa"

    let time12 = df.string(from: date!)
    print(time12)
    return time12
}
</code>```

Input

19:05:45

Output

07:05:45PM

Body:
I am trying to convert an am/pm format time to a 24 hour format time

6:35 PM to 18:35

I tried this piece of code on playground but it doesn't seem to
work if I put the time alone

let dateAsString = "02/12/15, 6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH"
let date = dateFormatter.dateFromString(dateAsString) //returns nil

Does anyone know how to accomplish this?

Body:
Swift 3 *

Code to convert 12 hours (i.e. AM and PM) to 24 hours format which includes-

Hours:Minutes:Seconds:AM/PM to Hours:Minutes:Seconds

func timeConversion24(time12: String) -> String {
    let dateAsString = time12
    let df = DateFormatter()
    df.dateFormat = "hh:mm:ssa"

    let date = df.date(from: dateAsString)
    df.dateFormat = "HH:mm:ss"

    let time24 = df.string(from: date!)
    print(time24)
    return time24
}

Input

07:05:45PM

Output

19:05:45

Similarly

Code to convert 24 hours to 12 hours (i.e. AM and PM) format which includes-

Hours:Minutes:Seconds to Hours:Minutes:Seconds:AM/PM

func timeConversion12(time24: String) -> String {
    let dateAsString = time24
    let df = DateFormatter()
    df.dateFormat = "HH:mm:ss"

    let date = df.date(from: dateAsString)
    df.dateFormat = "hh:mm:ssa"

    let time12 = df.string(from: date!)
    print(time12)
    return time12
}

Input

19:05:45

Output

07:05:45PM


问:
Print largest and smallest number in python
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.

I am having problem in printing the largest and smallest number. Its printing incorrect number by the approach below:

```<code>largest = None
smallest = None
list1 = []
while True:
    num = input("Enter a number: ")
    if num == "done" : break
    try:
        val = int(num)
        if int(num):
            list1.append(num)
    except:
        print("Invalid input")
print("Maximum is " + max(list1))
print("Minimum is " + min(list1))
</code>```

I am entering numbers as 7, 2, bob, 10, and 4.

Its printing output as:
Invalid input
Maximum is 7
Minimum is 10

While the output I am looking for is:
Invalid input
Maximum is 10
Minimum is 2

答:
without using a list, you need Two value to keep track of max and min value of user input. use try and except to handle case when user enter a non numerical input other than 'done'.

Fast and better approach than using a list store value,sort data and and then get the final result

```<code>import sys

min_val = sys.maxsize
max_val = -sys.maxsize-1

flag = True
while flag:
    user_input = input()
    if user_input == 'done':
        flag = False
    else:
        try:
            user_input = int(user_input)
            if user_input>max_val:
                max_val = user_input
            if user_input<min_val:
                min_val = user_input
        except ValueError:
            print('Enter a Valid Number')

print('Maximum Value is {}'.format(max_val))
print('Minimum value is {}'.format(min_val))
</code>```

Body:
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.

I am having problem in printing the largest and smallest number. Its printing incorrect number by the approach below:

largest = None
smallest = None
list1 = []
while True:
    num = input("Enter a number: ")
    if num == "done" : break
    try:
        val = int(num)
        if int(num):
            list1.append(num)
    except:
        print("Invalid input")
print("Maximum is " + max(list1))
print("Minimum is " + min(list1))

I am entering numbers as 7, 2, bob, 10, and 4.

Its printing output as:
Invalid input
Maximum is 7
Minimum is 10

While the output I am looking for is:
Invalid input
Maximum is 10
Minimum is 2

Body:
without using a list, you need Two value to keep track of max and min value of user input. use try and except to handle case when user enter a non numerical input other than 'done'.

Fast and better approach than using a list store value,sort data and and then get the final result

import sys

min_val = sys.maxsize
max_val = -sys.maxsize-1

flag = True
while flag:
    user_input = input()
    if user_input == 'done':
        flag = False
    else:
        try:
            user_input = int(user_input)
            if user_input>max_val:
                max_val = user_input
            if user_input<min_val:
                min_val = user_input
        except ValueError:
            print('Enter a Valid Number')

print('Maximum Value is {}'.format(max_val))
print('Minimum value is {}'.format(min_val))


问:
tagName is null or not an object -- error msg in IE7 using latest version of jQuery (1.2.6)
has anyone else seen this error message. a quick check with google doesn't show me much.</p>

答:
If you're only seeing it in IE, it could be a bug with the DivX web plugin:

http://drupal.org/node/1038058

Issue is confirmed on the DivX site, which says "Fixed in the next release" (April 2011).

http://labs.divx.com/node/16824

Essentially, the bug is that DivX replaces the el.appendChild() function with an intercept that tries to lowercase the tagname, but doesn't bother checking to see if it is a text node.  This will break jQuery if you try to do something like $('body').append('hi!'). Additionally, it fails to return the element, which breaks SWFObject, for one.

The workaround is to make sure that you never call append() with a a text node, or with multiple top level elements.  If you are appending a series of items:

```<code>  append($('<div>hi</div><div>there</div>'))
</code>```

make sure you wrap them in a top level div to avoid the implied text node:

```<code>  append($('<div><div>hi</div><div>there</div></div>'))
</code>```

Here's a full workaround for appendChild being broken, the same approach can be used for insertBefore and replaceChild which share the bug.  The Divx JS is inserted some time after the page is loaded, so you may want to poll for this.

```<code>window.fixDivxPlayerBug = function () {
    var b = document.getElementsByTagName('body')[0];
    if ( window['ReplaceVideoElements'] && ! b.appendChildDivx ){
        b.appendChildDivx = b.appendChild;
        b.appendChild = function (el) {
            if( el.tagName == null) {
                var wrap = document.createElement('div');
                wrap.appendChild(el);
                b.appendChildDivx(wrap);
            }
            else {
                b.appendChildDivx(el);
            }
            return el;
        };
    }
};
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you're only seeing it in IE, it could be a bug with the DivX web plugin:

http://drupal.org/node/1038058

Issue is confirmed on the DivX site, which says "Fixed in the next release" (April 2011).

http://labs.divx.com/node/16824

Essentially, the bug is that DivX replaces the el.appendChild() function with an intercept that tries to lowercase the tagname, but doesn't bother checking to see if it is a text node.  This will break jQuery if you try to do something like $('body').append('hi!'). Additionally, it fails to return the element, which breaks SWFObject, for one.

The workaround is to make sure that you never call append() with a a text node, or with multiple top level elements.  If you are appending a series of items:

  append($('<div>hi</div><div>there</div>'))

make sure you wrap them in a top level div to avoid the implied text node:

  append($('<div><div>hi</div><div>there</div></div>'))

Here's a full workaround for appendChild being broken, the same approach can be used for insertBefore and replaceChild which share the bug.  The Divx JS is inserted some time after the page is loaded, so you may want to poll for this.

window.fixDivxPlayerBug = function () {
    var b = document.getElementsByTagName('body')[0];
    if ( window['ReplaceVideoElements'] && ! b.appendChildDivx ){
        b.appendChildDivx = b.appendChild;
        b.appendChild = function (el) {
            if( el.tagName == null) {
                var wrap = document.createElement('div');
                wrap.appendChild(el);
                b.appendChildDivx(wrap);
            }
            else {
                b.appendChildDivx(el);
            }
            return el;
        };
    }
};

ContentLicense: CC BY-SA 3.0


问:
Is LCS in Python just the intersection function in terms of length?
I was trying to otpimze a code that returns the length of the Longest Common Substring between two strings and realized that the insersection function returns pretty much the same. Am I correct?

a = input()
b = input()
print (len(set(a).intersection(b)))
```

答:
No, because the intersection of your words will break the individual letters into elements of a list. For example,

```<code>a = 'abcd'
b = 'dcba'
</code>```

becomes

```<code>a = ['a', 'b', 'c', 'd']
b = ['d', 'c', 'b', 'a']
</code>```

The length of the intersection will be 4, but that is not correct for your case since 'abcd' and 'dcba' have no common substring longer than length 1.

Also, using set on a word will remove any duplicate letters in your word, which will also mess up searching for common substrings.

What you would need to do instead is something like split the two words into lists all possible substrings, like what is done in this post. Then you can do an intersection of those lists and take the element of greatest length.

Body:
No, because the intersection of your words will break the individual letters into elements of a list. For example,

a = 'abcd'
b = 'dcba'

becomes

a = ['a', 'b', 'c', 'd']
b = ['d', 'c', 'b', 'a']

The length of the intersection will be 4, but that is not correct for your case since 'abcd' and 'dcba' have no common substring longer than length 1.

Also, using set on a word will remove any duplicate letters in your word, which will also mess up searching for common substrings.

What you would need to do instead is something like split the two words into lists all possible substrings, like what is done in this post. Then you can do an intersection of those lists and take the element of greatest length.


问:
Unexpected token error in mat-checkbox angular
```<code><div *ngFor="let bellNotification of earlierBellNotifications">
    <mat-checkbox (change)="updateNotificationEventStatus(bellNotification.key, $event)"
      [(ngModel)]="bellNotification.status==='READ'" (click)="$event.stopPropagation()" class="md-18">
      <span class="wd-notification-event-checkbox" i18n>MARK AS READ</span>
    </mat-checkbox>
</div>
</code>```

When trying to load page, I get the following error:

Uncaught Error: Template parse errors: Parser Error: Unexpected token
  '=' at column 33 in [bellNotification.status==='READ'=$event] in
  ng:///AppSharedModule/BellNotificationComponent.html@43:12 ("

  ][(ngModel)]="bellNotification.status==='READ'" (click)="$event.stopPropagation()" class="md-18">
      "): ng:///AppSharedModule/BellNotificationComponent.html@43:12

I tried replacing it with a function from typescript, I still get similar error.

I tried replacing it with a value from typescript, it worked, but it cannot be dynamically updated as it just comes from ts and is not dependent on the for loop iterator.

Can somebody help me point out the mistake in the syntax I am using.

I am new to Angular. Reference links are greatly appreciated.

答:
The conditional binding in [(ngModel)] expression will not work (I have never used like this)!

You can use [checked] attribute to check/uncheck the checkbox with the condition like:

```<code><div *ngFor="let bellNotification of earlierBellNotifications">
    <mat-checkbox (change)="updateNotificationEventStatus(bellNotification.key, $event)"
        \/\/\/
      [checked]="bellNotification.status === 'READ'" (click)="$event.stopPropagation()" class="md-18">
      <span class="wd-notification-event-checkbox" i18n>MARK AS READ</span>
    </mat-checkbox>
</div>
</code>```

Working_Demo

Body:
    <mat-checkbox (change)="updateNotificationEventStatus(bellNotification.key, $event)"
      [(ngModel)]="bellNotification.status==='READ'" (click)="$event.stopPropagation()" class="md-18">
      MARK AS READ
    </mat-checkbox>

When trying to load page, I get the following error:

Uncaught Error: Template parse errors: Parser Error: Unexpected token
  '=' at column 33 in [bellNotification.status==='READ'=$event] in
  ng:///AppSharedModule/BellNotificationComponent.html@43:12 ("

  ][(ngModel)]="bellNotification.status==='READ'" (click)="$event.stopPropagation()" class="md-18">
      "): ng:///AppSharedModule/BellNotificationComponent.html@43:12

I tried replacing it with a function from typescript, I still get similar error.

I tried replacing it with a value from typescript, it worked, but it cannot be dynamically updated as it just comes from ts and is not dependent on the for loop iterator.

Can somebody help me point out the mistake in the syntax I am using.

I am new to Angular. Reference links are greatly appreciated.

Body:
The conditional binding in [(ngModel)] expression will not work (I have never used like this)!

You can use [checked] attribute to check/uncheck the checkbox with the condition like:

<div *ngFor="let bellNotification of earlierBellNotifications">
    <mat-checkbox (change)="updateNotificationEventStatus(bellNotification.key, $event)"
        \/\/\/
      [checked]="bellNotification.status === 'READ'" (click)="$event.stopPropagation()" class="md-18">
      <span class="wd-notification-event-checkbox" i18n>MARK AS READ</span>
    </mat-checkbox>
</div>

Working_Demo


问:
Rails Errno::EACCES Permission Denied
Rails 3.1 Passenger on Apache Development environment
When I go to access the index (i.e. GET) for a route I get:

```<code>Errno::EACCES in Crb_agendas#index

Showing /var/www/crbagenda/app/views/layouts/application.html.erb where line #5 raised:

Permission denied - /var/www/crbagenda/tmp/cache/assets/E2C

Extracted source (around line #5):

2: <html>
3: <head>
4:   <title>CrbAgendas</title>
5:   <%= stylesheet_link_tag "application" %>
6:   <%= javascript_include_tag "application" %>
7:   <%= csrf_meta_tags %>
8: </head>

Rails.root: /var/www/crbagenda
</code>```

When I go to the path mentioned (/var/www/crbagenda/tmp/cache/assets/E2C) there is no E2C folder and root (what apache is running as) owns the assets dir... not sure what I did wrong here.... or what else I could show to help.

答: On windows just open your cmd as Administrator and execute your gem install "lib" command

Title: Rails Errno::EACCES Permission Denied

Body:
Rails 3.1 Passenger on Apache Development environment
When I go to access the index (i.e. GET) for a route I get:

Errno::EACCES in Crb_agendas#index

Showing /var/www/crbagenda/app/views/layouts/application.html.erb where line #5 raised:

Permission denied - /var/www/crbagenda/tmp/cache/assets/E2C

Extracted source (around line #5):

2:
3:
4:   <title>CrbAgendas</title>
5:   <%= stylesheet_link_tag "application" %>
6:   <%= javascript_include_tag "application" %>
7:   <%= csrf_meta_tags %>
8:

Rails.root: /var/www/crbagenda

When I go to the path mentioned (/var/www/crbagenda/tmp/cache/assets/E2C) there is no E2C folder and root (what apache is running as) owns the assets dir... not sure what I did wrong here.... or what else I could show to help.


问:
Django raw query giving same result on all models
I have 3 models Product, Photo, and ProductLikeDilike. I am performing left outer join on all the 3 models. First I am joining Product with Photo and then the resultant table(temp) I am joining with ProductLikeDilike. Below is the raw sql.

Note: olx is the name of django app.

```<code>data = Product.objects.raw('select * from (select
    olx_product.id,olx_product.name,olx_photo.file,olx_photo.cover_photo_flag
    from olx_product left outer join olx_photo on
    (olx_product.id=olx_photo.reference_id_id) where
    olx_photo.cover_photo_flag="yes" or olx_photo.cover_photo_flag is null) as
    temp left outer join olx_productlikedislike on
    (temp.id=olx_productlikedislike.product_id_id and
    olx_productlikedislike.product_liked_by_id_id=2)')

for x in data:
  print(x.name)
</code>```

What I want to understand that when I use any of the above 3 models to run the raw sql why I am getting the same result i.e.

When I do

```<code>data = Product.objects.raw('select *.....')
for x in data:
  print(x.name)
</code>```

or

```<code>data = Photo.objects.raw('select *......')
for x in data:
  print(x.name)
</code>```

or

```<code>data = ProductLikeDislike.raw('select *.....')
for x in data:
  print(x.name)
</code>```

I am getting the same result. Why?
Please help me to understand this.

Below is the models.py file

```<code>from django.db import models
from django.urls import reverse
from django.dispatch import receiver
from django.contrib.auth.models import User

    class Product(models.Model):
        category = models.ForeignKey(Category ,on_delete=models.CASCADE)
        name = models.CharField(max_length = 200, db_index = True)
        slug = models.SlugField(max_length = 200, db_index = True)
        description = models.TextField(blank = True)
        price = models.DecimalField(max_digits = 10, decimal_places = 2 )#Not used FloatField to avoid rounding issues
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)

        contact= models.BigIntegerField(default=None,blank=True, null=True)
        created_by = models.CharField(max_length = 200, default=None,blank=True, null=True)
        uploaded_by_id = models.IntegerField(default=0)
        status = models.IntegerField(default=0) # 0-->Active,1-->Inactive
        mark_as_sold = models.IntegerField(default=0) # 0-->not sold,1-->sold

        def get_absolute_url(self):
            return reverse('olx:edit_product', kwargs={'pk': self.pk})

        class Meta:
            ordering = ('-created',)
            index_together = (('id','slug'),)# we want to query product by id and slug using together index to improve performance

        def __str__(self):
            return self.name

    class Photo(models.Model):

        reference_id = models.ForeignKey(Product, null=True,on_delete=models.CASCADE)
        photo_type = models.CharField(max_length = 70, db_index = True)
        file = models.FileField(upload_to='photos/',default='NoImage.jpg')
        cover_photo_flag = models.CharField(default=0,max_length = 5, db_index = True)
        uploaded_at = models.DateTimeField(auto_now_add=True)
        uploaded_by_id = models.IntegerField(default=0)
        status = models.IntegerField(default=0) # 0-->Active,1-->Inactive

        class Meta:
            ordering = ('-uploaded_at',)

    class ProductLikeDislike(models.Model):
        product_id = models.ForeignKey(Product,models.SET_DEFAULT,default=0)
        product_liked_by_id = models.ForeignKey(User,models.SET_DEFAULT,default=0)
        status = models.BooleanField(default=False)
</code>```

And Please also show me how to write it in pure Django way if possible?

答:
Something like this:

```<code>    user_i_care_about = User.objects.get(username='user2')
    productlikedislike_set = models.Prefetch('productlikedislike_set',
                                             ProductLikeDislike.objects.select_related('product_liked_by') \
                                                               .filter(product_liked_by=user_i_care_about) \
                                                               .order_by('id'))
    photo_set = models.Prefetch('photo_set', Photo.objects.all())  # this is here incase you need to a select_related()

    products = Product.objects.prefetch_related(photo_set, productlikedislike_set) \
                              .filter(models.Q(photo__cover_photo_flag='yes') | models.Q(photo__isnull=True)) \
                              .filter(productlikedislike__product_liked_by=user_i_care_about)
</code>```

Then you can use:

```<code>for product in products:
    for pic in product.photo_set.all():
        print(x.file.name)
    # every product here WILL be liked by the user
</code>```

if your models look something like this:

```<code> class Product(models.Model):
    # category = models.ForeignKey(Category, on_delete=models.CASCADE)  # TODO: uncomment, didnt want to model this out
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)  # Not used FloatField to avoid rounding issues  # this is correct, no need to explain this, anyonw that works with django, gets this.
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    contact = models.BigIntegerField(default=None,blank=True, null=True)
    created_by = models.CharField(max_length=200, default=None, blank=True, null=True)
    uploaded_by_id = models.IntegerField(default=0)  # TODO: use ForeignKey(User) here!!!
    status = models.IntegerField(default=0)  # 0-->Active,1-->Inactive  # TODO: learn to use `choices`
    mark_as_sold = models.IntegerField(default=0)  # 0-->not sold,1-->sold  # TODO: there is something called `BooleanField` use it!

    class Meta:
        ordering = ('-created',)
        index_together = (('id', 'slug'),)  # we want to query product by id and slug using together index to improve performance

    def get_absolute_url(self):
        return reverse('olx:edit_product', kwargs={'pk': self.pk})

    def __str__(self):
        return self.name

class Photo(models.Model):

    product = models.ForeignKey(Product, null=True,on_delete=models.CASCADE, db_column='reference_id')
    photo_type = models.CharField(max_length=70, db_index=True)
    file = models.FileField(upload_to='photos/', default='NoImage.jpg')
    cover_photo_flag = models.CharField(default=0, max_length=5, db_index=True)  # TODO: learn to use `choices`, and you use "yes" / "no" -- and the default is 0 -- FIX THIS!!
    uploaded_at = models.DateTimeField(auto_now_add=True)
    uploaded_by_id = models.IntegerField(default=0)  # TODO: use ForeignKey(User) here!!!
    status = models.IntegerField(default=0)  # 0-->Active,1-->Inactive  # TODO: learn to use `choices` -- perhaps just call this "is_active" and make it a bool

    class Meta:
        ordering = ('-uploaded_at',)

class ProductLikeDislike(models.Model):
    product = models.ForeignKey(Product, models.SET_DEFAULT, default=0)  # TODO: default=0?? this is pretty bad. models.ForeignKey(Product, models.SET_NULL, null=True) is much better
    product_liked_by = models.ForeignKey(User, models.SET_DEFAULT, default=0, db_column='product_liked_by_id')  # TODO: default=0?? this is pretty bad. models.ForeignKey(ForeignKey, models.SET_NULL, null=True) is much better
    status = models.BooleanField(default=False)  # TODO: rename, bad name. try something like "liked" / "disliked" OR go with IntegerField(choices=((0, 'Liked'), (1, 'Disliked')) if you have more than 2 values.
</code>```

A full example WITH tests can be seen here: https://gist.github.com/kingbuzzman/05ed095d8f48c3904e217e56235af54a

Body:
I have 3 models Product, Photo, and ProductLikeDilike. I am performing left outer join on all the 3 models. First I am joining Product with Photo and then the resultant table(temp) I am joining with ProductLikeDilike. Below is the raw sql.

Note: olx is the name of django app.

data = Product.objects.raw('select * from (select
    olx_product.id,olx_product.name,olx_photo.file,olx_photo.cover_photo_flag
    from olx_product left outer join olx_photo on
    (olx_product.id=olx_photo.reference_id_id) where
    olx_photo.cover_photo_flag="yes" or olx_photo.cover_photo_flag is null) as
    temp left outer join olx_productlikedislike on
    (temp.id=olx_productlikedislike.product_id_id and
    olx_productlikedislike.product_liked_by_id_id=2)')

for x in data:
  print(x.name)

What I want to understand that when I use any of the above 3 models to run the raw sql why I am getting the same result i.e.

When I do

data = Product.objects.raw('select *.....')
for x in data:
  print(x.name)

or

data = Photo.objects.raw('select *......')
for x in data:
  print(x.name)

or

data = ProductLikeDislike.raw('select *.....')
for x in data:
  print(x.name)

I am getting the same result. Why?
Please help me to understand this.

Below is the models.py file

from django.db import models
from django.urls import reverse
from django.dispatch import receiver
from django.contrib.auth.models import User

    class Product(models.Model):
        category = models.ForeignKey(Category ,on_delete=models.CASCADE)
        name = models.CharField(max_length = 200, db_index = True)
        slug = models.SlugField(max_length = 200, db_index = True)
        description = models.TextField(blank = True)
        price = models.DecimalField(max_digits = 10, decimal_places = 2 )#Not used FloatField to avoid rounding issues
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)

        contact= models.BigIntegerField(default=None,blank=True, null=True)
        created_by = models.CharField(max_length = 200, default=None,blank=True, null=True)
        uploaded_by_id = models.IntegerField(default=0)
        status = models.IntegerField(default=0) # 0-->Active,1-->Inactive
        mark_as_sold = models.IntegerField(default=0) # 0-->not sold,1-->sold

        def get_absolute_url(self):
            return reverse('olx:edit_product', kwargs={'pk': self.pk})

        class Meta:
            ordering = ('-created',)
            index_together = (('id','slug'),)# we want to query product by id and slug using together index to improve performance

        def __str__(self):
            return self.name

    class Photo(models.Model):

        reference_id = models.ForeignKey(Product, null=True,on_delete=models.CASCADE)
        photo_type = models.CharField(max_length = 70, db_index = True)
        file = models.FileField(upload_to='photos/',default='NoImage.jpg')
        cover_photo_flag = models.CharField(default=0,max_length = 5, db_index = True)
        uploaded_at = models.DateTimeField(auto_now_add=True)
        uploaded_by_id = models.IntegerField(default=0)
        status = models.IntegerField(default=0) # 0-->Active,1-->Inactive

        class Meta:
            ordering = ('-uploaded_at',)

    class ProductLikeDislike(models.Model):
        product_id = models.ForeignKey(Product,models.SET_DEFAULT,default=0)
        product_liked_by_id = models.ForeignKey(User,models.SET_DEFAULT,default=0)
        status = models.BooleanField(default=False)

And Please also show me how to write it in pure Django way if possible?

Body:
Something like this:

    user_i_care_about = User.objects.get(username='user2')
    productlikedislike_set = models.Prefetch('productlikedislike_set',
                                             ProductLikeDislike.objects.select_related('product_liked_by') \
                                                               .filter(product_liked_by=user_i_care_about) \
                                                               .order_by('id'))
    photo_set = models.Prefetch('photo_set', Photo.objects.all())  # this is here incase you need to a select_related()

    products = Product.objects.prefetch_related(photo_set, productlikedislike_set) \
                              .filter(models.Q(photo__cover_photo_flag='yes') | models.Q(photo__isnull=True)) \
                              .filter(productlikedislike__product_liked_by=user_i_care_about)

Then you can use:

for product in products:
    for pic in product.photo_set.all():
        print(x.file.name)
    # every product here WILL be liked by the user

if your models look something like this:

 class Product(models.Model):
    # category = models.ForeignKey(Category, on_delete=models.CASCADE)  # TODO: uncomment, didnt want to model this out
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)  # Not used FloatField to avoid rounding issues  # this is correct, no need to explain this, anyonw that works with django, gets this.
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    contact = models.BigIntegerField(default=None,blank=True, null=True)
    created_by = models.CharField(max_length=200, default=None, blank=True, null=True)
    uploaded_by_id = models.IntegerField(default=0)  # TODO: use ForeignKey(User) here!!!
    status = models.IntegerField(default=0)  # 0-->Active,1-->Inactive  # TODO: learn to use `choices`
    mark_as_sold = models.IntegerField(default=0)  # 0-->not sold,1-->sold  # TODO: there is something called `BooleanField` use it!

    class Meta:
        ordering = ('-created',)
        index_together = (('id', 'slug'),)  # we want to query product by id and slug using together index to improve performance

    def get_absolute_url(self):
        return reverse('olx:edit_product', kwargs={'pk': self.pk})

    def __str__(self):
        return self.name

class Photo(models.Model):

    product = models.ForeignKey(Product, null=True,on_delete=models.CASCADE, db_column='reference_id')
    photo_type = models.CharField(max_length=70, db_index=True)
    file = models.FileField(upload_to='photos/', default='NoImage.jpg')
    cover_photo_flag = models.CharField(default=0, max_length=5, db_index=True)  # TODO: learn to use `choices`, and you use "yes" / "no" -- and the default is 0 -- FIX THIS!!
    uploaded_at = models.DateTimeField(auto_now_add=True)
    uploaded_by_id = models.IntegerField(default=0)  # TODO: use ForeignKey(User) here!!!
    status = models.IntegerField(default=0)  # 0-->Active,1-->Inactive  # TODO: learn to use `choices` -- perhaps just call this "is_active" and make it a bool

    class Meta:
        ordering = ('-uploaded_at',)

class ProductLikeDislike(models.Model):
    product = models.ForeignKey(Product, models.SET_DEFAULT, default=0)  # TODO: default=0?? this is pretty bad. models.ForeignKey(Product, models.SET_NULL, null=True) is much better
    product_liked_by = models.ForeignKey(User, models.SET_DEFAULT, default=0, db_column='product_liked_by_id')  # TODO: default=0?? this is pretty bad. models.ForeignKey(ForeignKey, models.SET_NULL, null=True) is much better
    status = models.BooleanField(default=False)  # TODO: rename, bad name. try something like "liked" / "disliked" OR go with IntegerField(choices=((0, 'Liked'), (1, 'Disliked')) if you have more than 2 values.

A full example WITH tests can be seen here: https://gist.github.com/kingbuzzman/05ed095d8f48c3904e217e56235af54a


问:
Exit from while loop which started inside a async method
How to break the while loop which inside an async method. Please refer below code

I have tried many ways but none of them worked for me

```<code>async void TotalTimer(string time)
{
    while (true)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(time);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        await Task.Delay(1000);

        if (string.IsNullOrEmpty(time))
        {
            break;
        }
    }
}
</code>```

I need to stop and exit from the loop

Updated code:

```<code>async Task TotalTimer(CancellationToken token)
{
    var intime = await App.Database.GetRecentIn();
    InTime = DateTime.Parse(intime.datetime).ToString("hh:mm tt");

    while (!token.IsCancellationRequested)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(intime.datetime);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        Console.WriteLine(TotalTime); // to see it's working
        await Task.Delay(1000);

        if (token.IsCancellationRequested)
        {
            break;
        }
    }
}

void StatCounting()
{
    var cts = new CancellationTokenSource();
   _= TotalTimer(cts.Token);
}

void StopCounting()
{
    var cts = new CancellationTokenSource();
    cts.Cancel();
   _= TotalTimer(cts.Token);

    _=Finalize();
}
</code>```

答:
Thanks for your effort guys. I have figure out a way to stop the loop. I have defined boolean and checked it within the while loop to break the loop. Its most likely @Enigmativitys answer. </p>

```<code>bool hasToStop = false;
while (true)
            {
                TimeSpan timesp = DateTime.Now - DateTime.Parse(intime.datetime);
                TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
                Console.WriteLine(TotalTime); // to see it's working
                await Task.Delay(1000);

                if (hasToStop)
                {
                    Console.WriteLine("Stoped");
                    break;
                }
            }
</code>```

Body:
How to break the while loop which inside an async method. Please refer below code

I have tried many ways but none of them worked for me

async void TotalTimer(string time)
{
    while (true)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(time);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        await Task.Delay(1000);

        if (string.IsNullOrEmpty(time))
        {
            break;
        }
    }
}

I need to stop and exit from the loop

Updated code:

async Task TotalTimer(CancellationToken token)
{
    var intime = await App.Database.GetRecentIn();
    InTime = DateTime.Parse(intime.datetime).ToString("hh:mm tt");

    while (!token.IsCancellationRequested)
    {
        TimeSpan timesp = DateTime.Now - DateTime.Parse(intime.datetime);
        TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
        Console.WriteLine(TotalTime); // to see it's working
        await Task.Delay(1000);

        if (token.IsCancellationRequested)
        {
            break;
        }
    }
}

void StatCounting()
{
    var cts = new CancellationTokenSource();
   _= TotalTimer(cts.Token);
}

void StopCounting()
{
    var cts = new CancellationTokenSource();
    cts.Cancel();
   _= TotalTimer(cts.Token);

    _=Finalize();
}

Body:
Thanks for your effort guys. I have figure out a way to stop the loop. I have defined boolean and checked it within the while loop to break the loop. Its most likely @Enigmativitys answer.

bool hasToStop = false;
while (true)
            {
                TimeSpan timesp = DateTime.Now - DateTime.Parse(intime.datetime);
                TotalTime = timesp.Hours + " : " + timesp.Minutes + " : " + timesp.Seconds;
                Console.WriteLine(TotalTime); // to see it's working
                await Task.Delay(1000);

                if (hasToStop)
                {
                    Console.WriteLine("Stoped");
                    break;
                }
            }


问:
Getting data from a range of values in jquery
I'm trying to get a range of numbers depending on what the user inputs.
I have customer.js which has the customer name and shoe size and what I would like is to get a range of shoe sizes depending
on what the user puts in.

For example. A user puts in the first textbox 5 and in the second textbox 9 I want the customers that is between 5 and 9,
but also including 5 and 9 to be displayed.

I've only gotten as far as this.

my html

```<code><form id="shoe_size">
    <label for="size">Enter sizes</label>
    <input type="text" name="size1" class="size1">
    <input type="text" name="size2" class="size2">
    <input type="submit" value="Search" class="submit">
</form>
</code>```

my jquery

```<code>$('#shoe_size').on('submit', function(){
    var size1 = $('.size1').val();
    var size2 = $('.size2').val();

    $('.table tr').each(function(){
        var size = 'false';
        $(this).each(function(){
            if(size1 <= size2){
                found = 'true';
            }
        })

        if(size == 'true'){
            $(this).show();
        }else{
            $(this).hide();
        }
    });
});
</code>```

答:
I know, the question has been answered. I just wanted to play around with a slighly shorter approach without a submit button:

// quickly generate some sample data ...
var shoes=[[4,'wht','dda'],
[4,'red','aaa'],[7,'blk','aba'],
[5,'blu','ca'],[4,'red','db'],
[9,'grn','z'],[8,'yel','g']];
$('.shoetable tbody').append('
'
+shoes.map(sh=>sh.join('	')).join('

')+'
');

// and now: do the magic ...
$('input').keyup(()=>{
  var mi=$('.size1').val()-0||0;
  var ma=$('.size2').val()-0||1000;
  $('.shoetable tbody tr:gt(0)').each((i,tr)=>{
      var s=$('td:eq(0)',tr).text()-0;
      $(tr).toggle(s>=mi&&s<=ma);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="shoe_size">
<label for="size">Show sizes between</label>
<input type="text" name="size1" class="size1" size="3"> and
<input type="text" name="size2" class="size2" size="3">
</form>
<table class="shoetable"><tr>
 <th>size</th><th>color</th><th>model</th>
</tr></table></code>```

Body:
I'm trying to get a range of numbers depending on what the user inputs.
I have customer.js which has the customer name and shoe size and what I would like is to get a range of shoe sizes depending
on what the user puts in.

For example. A user puts in the first textbox 5 and in the second textbox 9 I want the customers that is between 5 and 9,
but also including 5 and 9 to be displayed.

I've only gotten as far as this.

my html

<form id="shoe_size">
    Enter sizes
    <input type="text" name="size1" class="size1">
    <input type="text" name="size2" class="size2">
    <input type="submit" value="Search" class="submit">
</form>

my jquery

$('#shoe_size').on('submit', function(){
    var size1 = $('.size1').val();
    var size2 = $('.size2').val();

    $('.table tr').each(function(){
        var size = 'false';
        $(this).each(function(){
            if(size1 <= size2){
                found = 'true';
            }
        })

        if(size == 'true'){
            $(this).show();
        }else{
            $(this).hide();
        }
    });
});

Body:
I know, the question has been answered. I just wanted to play around with a slighly shorter approach without a submit button:

// quickly generate some sample data ...
var shoes=[[4,'wht','dda'],
[4,'red','aaa'],[7,'blk','aba'],
[5,'blu','ca'],[4,'red','db'],
[9,'grn','z'],[8,'yel','g']];
$('.shoetable tbody').append('<tr><td>'
+shoes.map(sh=>sh.join('</td><td>')).join('</td></tr><tr><td>')+'</td></tr>');

// and now: do the magic ...
$('input').keyup(()=>{
  var mi=$('.size1').val()-0||0;
  var ma=$('.size2').val()-0||1000;
  $('.shoetable tbody tr:gt(0)').each((i,tr)=>{
      var s=$('td:eq(0)',tr).text()-0;
      $(tr).toggle(s>=mi&&s<=ma);
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="shoe_size">
<label for="size">Show sizes between</label>
<input type="text" name="size1" class="size1" size="3"> and
<input type="text" name="size2" class="size2" size="3">
</form>
<table class="shoetable"><tr>
 <th>size</th><th>color</th><th>model</th>
</tr></table>


问:
Angular service null?
I have created a project in angular 7, and I have copied some code from former angular projects. First I make a very simple service:

```<code>import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
import { HttpClient,HttpErrorResponse} from  '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private  httpClient:  HttpClient) {

  }

  getValues():Observable<string[]>{
    var url = `${environment.apiUrl}/api/values`;
    return  this.httpClient.get<string[]>(url);
  }

  getTest():Observable<string[]>{
    var url = `${environment.apiUrl}/api/test`;
    return  this.httpClient.get<string[]>(url);
  }
}
</code>```

Then I just simply call it from a component:

```<code>import { Component, Inject, OnInit } from '@angular/core';
import { ApiService } from '../../api.service';

@Component({
  templateUrl: 'fleet.component.html'
})
export class FleetComponent implements OnInit {
  constructor(private  apiService:  ApiService) {}

  ngOnInit(): void {
    this.apiService.getValues()
    .subscribe(
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        alert(error);
      },
      () => {
        // 'onCompleted' callback.
        // No errors, route to new page here
      }
    );
  }
}
</code>```

Hovever this.apiService is null? Am i missing something here? I can see I don't have any imports or declarations in my old project.

All help is appreciated

Error:

ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[HttpClient]:
    StaticInjectorError(Platform: core)[HttpClient]:
      NullInjectorError: No provider for HttpClient!
  Error: StaticInjectorError(AppModule)[HttpClient]:
    StaticInjectorError(Platform: core)[HttpClient]:
      NullInjectorError: No provider for HttpClient!
      at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:8896)
      at resolveToken (core.js:9141)
      at tryResolveToken (core.js:9085)
      at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:8982)
      at resolveToken (core.js:9141)
      at tryResolveToken (core.js:9085)
      at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:8982)
      at resolveNgModuleDep (core.js:21218)
      at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:21907)
      at injectInjectorOnly (core.js:1774)
      at resolvePromise (zone.js:831)
      at resolvePromise (zone.js:788)
      at zone.js:892
      at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
      at Object.onInvokeTask (core.js:17290)
      at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
      at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
      at drainMicroTaskQueue (zone.js:601)

答:
```<code>import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}
</code>```

Title: Angular service null?

Body:
I have created a project in angular 7, and I have copied some code from former angular projects. First I make a very simple service:

import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
import { HttpClient,HttpErrorResponse} from  '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private  httpClient:  HttpClient) {

  }

  getValues():Observable<string[]>{
    var url = `${environment.apiUrl}/api/values`;
    return  this.httpClient.get<string[]>(url);
  }

  getTest():Observable<string[]>{
    var url = `${environment.apiUrl}/api/test`;
    return  this.httpClient.get<string[]>(url);
  }
}

Then I just simply call it from a component:

import { Component, Inject, OnInit } from '@angular/core';
import { ApiService } from '../../api.service';

@Component({
  templateUrl: 'fleet.component.html'
})
export class FleetComponent implements OnInit {
  constructor(private  apiService:  ApiService) {}

  ngOnInit(): void {
    this.apiService.getValues()
    .subscribe(
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        alert(error);
      },
      () => {
        // 'onCompleted' callback.
        // No errors, route to new page here
      }
    );
  }
}

Hovever this.apiService is null? Am i missing something here? I can see I don't have any imports or declarations in my old project.

All help is appreciated

Error:

ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[HttpClient]:
    StaticInjectorError(Platform: core)[HttpClient]:
      NullInjectorError: No provider for HttpClient!
  Error: StaticInjectorError(AppModule)[HttpClient]:
    StaticInjectorError(Platform: core)[HttpClient]:
      NullInjectorError: No provider for HttpClient!
      at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:8896)
      at resolveToken (core.js:9141)
      at tryResolveToken (core.js:9085)
      at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:8982)
      at resolveToken (core.js:9141)
      at tryResolveToken (core.js:9085)
      at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:8982)
      at resolveNgModuleDep (core.js:21218)
      at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:21907)
      at injectInjectorOnly (core.js:1774)
      at resolvePromise (zone.js:831)
      at resolvePromise (zone.js:788)
      at zone.js:892
      at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
      at Object.onInvokeTask (core.js:17290)
      at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
      at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
      at drainMicroTaskQueue (zone.js:601)


问:
Pythonic way of handling a python code for handling NAN and NAT columns
I'm having a large data set with multiple columns, in each of these columns there are 4 separate columns.

For ease the columns in Dataframe are US.A, US.B, US.C, BR.A, BR.B, BR.C
Now if column US.B is blank only then fill all US related column with "-" similarly if BR.B is blank then fill BR related columns with "-".

For this I'm using Python 3 and pandas I have made a code to run it but not particularly satisfied by the way it looks and was wondering if there is an easier way of handling this problem.

```<code>import pandas as pd

###Splitting the data set

df1 = df.drop(['D','E','F'], axis=1)
df2 = df.drop(['A', 'B','C'], axis=1)

###Now I tackle them individually

df1 = df1.astype(str)
df1 = df1[df1['US.B'].isnull()]
df1 = df1f.fillna(value="-")

df2 = df2.astype(str)
df2 = df2[df2['BR.B'].isnull()]
df2 = df2.fillna(value="-")

merge = pd.concat([df1, df2])
</code>```

Now the reason I covert the DataFrame to string is because for some reason the date columns which has "Nat" is giving me trouble during fillna. Now here it looks neat but I dealing with a huge data set and this repeats multiple times foe me to achieve the result.

Data:

```<code>1   US.A    US.B    US.C      BR.A     BR.B    BR.C
2   Foo     123  01-01-2018     Foo     324     03-05-2017
3   Bar     124  02-01-2018     Bar     325     04-05-2017
4   Foo     125  03-01-2018
5   Bar     126  04-01-2018     Bar     327     06-05-2017
6                               Foo     328     07-05-2017
7   Bar     128  06-01-2018     Bar     400     08-05-2017
8           100  07-01-2018     Foo     330
</code>```

Result:

```<code>1   US.A    US.B    US.C      BR.A     BR.B    BR.C
2   Foo     123  01-01-2018     Foo     324     03-05-2017
3   Bar     124  02-01-2018     Bar     325     04-05-2017
4   Foo     125  03-01-2018      -       -          -
5   Bar     126  04-01-2018     Bar     327     06-05-2017
6   -        -     -            Foo     328     07-05-2017
7   Bar     128  06-01-2018     Bar     400     08-05-2017
8           100  07-01-2018     Foo     330

</code>```

Body:
I'm having a large data set with multiple columns, in each of these columns there are 4 separate columns.

For ease the columns in Dataframe are US.A, US.B, US.C, BR.A, BR.B, BR.C
Now if column US.B is blank only then fill all US related column with "-" similarly if BR.B is blank then fill BR related columns with "-".

For this I'm using Python 3 and pandas I have made a code to run it but not particularly satisfied by the way it looks and was wondering if there is an easier way of handling this problem.

import pandas as pd

###Splitting the data set

df1 = df.drop(['D','E','F'], axis=1)
df2 = df.drop(['A', 'B','C'], axis=1)

###Now I tackle them individually

df1 = df1.astype(str)
df1 = df1[df1['US.B'].isnull()]
df1 = df1f.fillna(value="-")

df2 = df2.astype(str)
df2 = df2[df2['BR.B'].isnull()]
df2 = df2.fillna(value="-")

merge = pd.concat([df1, df2])

Now the reason I covert the DataFrame to string is because for some reason the date columns which has "Nat" is giving me trouble during fillna. Now here it looks neat but I dealing with a huge data set and this repeats multiple times foe me to achieve the result.

Data:

1   US.A    US.B    US.C      BR.A     BR.B    BR.C
2   Foo     123  01-01-2018     Foo     324     03-05-2017
3   Bar     124  02-01-2018     Bar     325     04-05-2017
4   Foo     125  03-01-2018
5   Bar     126  04-01-2018     Bar     327     06-05-2017
6                               Foo     328     07-05-2017
7   Bar     128  06-01-2018     Bar     400     08-05-2017
8           100  07-01-2018     Foo     330

Result:

1   US.A    US.B    US.C      BR.A     BR.B    BR.C
2   Foo     123  01-01-2018     Foo     324     03-05-2017
3   Bar     124  02-01-2018     Bar     325     04-05-2017
4   Foo     125  03-01-2018      -       -          -
5   Bar     126  04-01-2018     Bar     327     06-05-2017
6   -        -     -            Foo     328     07-05-2017
7   Bar     128  06-01-2018     Bar     400     08-05-2017
8           100  07-01-2018     Foo     330

Body:
You can try the below approach:

df_US=df.filter(like='US')
df_BR=df.filter(like='BR')

pd.concat([df_US.mask(df_US['US.B'].isna(),'-'),df_BR.mask(df_BR['BR.B'].isna(),'-')],axis=1)

  US.A US.B                 US.C BR.A BR.B                 BR.C
0  Foo  123  2018-01-01 00:00:00  Foo  324  2017-05-03 00:00:00
1  Bar  124  2018-01-02 00:00:00  Bar  325  2017-05-04 00:00:00
2  Foo  125  2018-01-03 00:00:00    -    -                    -
3  Bar  126  2018-01-04 00:00:00  Bar  327  2017-05-06 00:00:00
4    -    -                    -  Foo  328  2017-05-07 00:00:00
5  Bar  128  2018-01-06 00:00:00  Bar  400  2017-05-08 00:00:00
6  NaN  100  2018-01-07 00:00:00  Foo  330                  NaT


问:
Dax Finding date based on Criteria calculated Column
I couldn't find an answer for my issue elsewhere, so trying my luck here.

I have sales table and my final result should determine if there were sales made for same person in specific period of time, for example within 7 business days. for example:

For ID 123 I have to flag it that sale for products A,B,C where within specified period.

For ID 1234 only sales of products A and B meet the criteria product C was sold in irrelevant time frame.

I've created a date table with indicators that determine for each date if the date is a working day, but i am struggling to calculate the relevant last working day

For example: I need that for 01/01/2019 i will get 10/01/2019 date, based on NUMOFDAYS and FinalWorkday = TRUE, which basically means that i have to count NUMOFDAYS times TRUE statement for each date and return corresponding date.

After that step done I think that it would be pretty easy for me to determine if the sale for a person was made in specific time frame.

If someone can give me direction for that much appreciated

Thank you in advance

答: This issue can be solved by the following, since three are non-working days/holidays we can filter them out via POWERQUERY, than add an Index Column and Another column Which is basically Index column + Number of days wanted, then simply merge duplicate of dates query on Index+number of days wanted column on Index column. And we get the correct date</p>


问:
Protocol Buffers In C#: How Are Boxed Value Types Handled
In the following examples:

```<code>public class RowData
{
    public object[] Values;
}

public class FieldData
{
    public object Value;
}
</code>```

I am curious as how either protobuf-net or dotnet-protobufs would handle such classes.  I am more familiar with protobuf-net, so what I actually have is:

```<code>[ProtoContract]
public class RowData
{
    [ProtoMember(1)]
    public object[] Values;
}
[ProtoContract]
public class FieldData
{
    [ProtoMember(1)]
    public object Value;
}
</code>```

However I get an error saying "No suitable Default Object encoding found".  Is there an easy way to treat these classes, that I am just not aware of?

To elaborate more on the use case:

This is a scaled down version of a data class used in remoting.  So essentially it looks like this:

```<code>FieldData data = new FieldData();
data.Value = 8;

remoteObject.DoSomething(data);
</code>```

Note: I've omitted the ISerializable implementation for simplicity, but it is as you'd expect.

答:
(updated)

Right; figured it out... the main problem in my sample above was the value-getters; they were throwing exceptions. There were also some library glitches (now fixed).

However, the simplest approach is Nullable<T> pass-thru properties:

```<code>    [ProtoMember(1)]
    private int? ValueInt32
    {
        get { return Get<int>(); }
        set { Value = value; }
    }
</code>```

etc, with:

```<code>    private T? Get<T>() where T : struct
    {
        return (Value != null && Value is T) ? (T?)Value : (T?)null;
    }
</code>```

Both this and the *Specified approach have been tested, and now work fine.

OwnerDisplayName: Greg Dean

Body:
In the following examples:

public class RowData
{
    public object[] Values;
}

public class FieldData
{
    public object Value;
}

I am curious as how either protobuf-net or dotnet-protobufs would handle such classes.  I am more familiar with protobuf-net, so what I actually have is:

[ProtoContract]
public class RowData
{
    [ProtoMember(1)]
    public object[] Values;
}
[ProtoContract]
public class FieldData
{
    [ProtoMember(1)]
    public object Value;
}

However I get an error saying "No suitable Default Object encoding found".  Is there an easy way to treat these classes, that I am just not aware of?

To elaborate more on the use case:

This is a scaled down version of a data class used in remoting.  So essentially it looks like this:

FieldData data = new FieldData();
data.Value = 8;

remoteObject.DoSomething(data);

Note: I've omitted the ISerializable implementation for simplicity, but it is as you'd expect.

LastEditorDisplayName: Greg Dean

Body:
(updated)

Right; figured it out... the main problem in my sample above was the value-getters; they were throwing exceptions. There were also some library glitches (now fixed).

However, the simplest approach is Nullable<T> pass-thru properties:

    [ProtoMember(1)]
    private int? ValueInt32
    {
        get { return Get<int>(); }
        set { Value = value; }
    }

etc, with:

    private T? Get<T>() where T : struct
    {
        return (Value != null && Value is T) ? (T?)Value : (T?)null;
    }

Both this and the *Specified approach have been tested, and now work fine.

OwnerDisplayName: Marc Gravell

LastEditorDisplayName: Marc Gravell


问:
type casting to a dynamic array
Given the following:

```<code>Type
  TSomeTypeArray = array of SomeType;

var
  anArray: array of SomeType;

function GetSomeTypeArray: TSomeTypeArray;
</code>```

I want to write anArray = GetSomeTypeArray(); but the compiler does not like it.
Without changing the type of anArray or the return type of GetSomeTypeArrayhow can I typecast TSomeTypeArray to array of SomeType?

答:
You can't. You need to declare anArray as of type TSomeTypeArray, then it should work.

Alternatively, you could store the result into another array of type TSomeTypeArray then call SetLength on anArray to the length of the returned array. And finally loop through the two arrays setting the elements of anArray to the elements of the returned array.

Title: type casting to a dynamic array

Body:
Given the following:

Type
  TSomeTypeArray = array of SomeType;

var
  anArray: array of SomeType;

function GetSomeTypeArray: TSomeTypeArray;

I want to write anArray = GetSomeTypeArray(); but the compiler does not like it.
Without changing the type of anArray or the return type of GetSomeTypeArrayhow can I typecast TSomeTypeArray to array of SomeType?


问:
Parsing & converting nested xml in python
I have below xml data.

```<code><transaction>
        <date>20190415</date>
        <ticket>303434037</ticket>
        <value>15</value>
        <notenders>01</notenders>
        <tenderdetail>
            <tendertype>00</tendertype>
            <tenderamt>15</tenderamt>
        </tenderdetail>
        <item>
            <receipeno>00001096</receipeno>
            <price>7</price>
            <qty>0001</qty>
            <items>
                <item>
                    <receipeno>00000786</receipeno>
                    <price>8</price>
                    <qty>0001</qty>
                    <items>
                        <item>
                            <receipeno>00000599</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                        <item>
                            <receipeno>00000605</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                        <item>
                            <receipeno>00000608</receipeno>
                            <price>0</price>
                            <qty>0004</qty>
                        </item>
                    </items>
                </item>
                <item>
                    <receipeno>10000043</receipeno>
                    <price>0</price>
                    <qty>0001</qty>
                </item>
                <item>
                    <receipeno>00000381</receipeno>
                    <price>7</price>
                    <qty>0001</qty>
                    <items>
                    <item>
                            <receipeno>00000607</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                    </items>
                </item>
            </items>
        </item>
   </transaction>
</code>```

I need to convert this to a table format. the issues is there are many nested branches inside each tag. eg many <item> & <items> tags. irrespective of the nested-ness. I need to list down the data one below he other.

my desired output is as follows

```<code> +----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+
|   date   | ticket | value | notenders | tendertype | tenderamt | receipeno | price | qty |
+----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+
| 20190101 |  12345 |    15 |         1 |          0 |        15 |      1096 |     7 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       786 |     8 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       599 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       605 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       608 |     0 |   4 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       143 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       381 |     7 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       607 |     0 |   1 |
+----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+
</code>```

I'm new to python & XML parsing. Hence, kindly, direct me to solve this.
...

答:
You can try the following code to get all data from nested XML File, but i think there is an elegant way to achieve the result:

```<code>import pandas as pd, numpy as np
import xml.etree.ElementTree as ET

xml_data = 'your xml data'

# Prepare for the list of variable to save XML data
date=[]
ticket=[]
value=[]
notenders=[]
tendertype=[]
tenderamt=[]
receipeno=[]
price=[]
qty=[]

# Parse the XML File to get the desired data
root = ET.fromstring(xml_data)
# Get header data from XML (date, ticket, value, notenders, tenderdetail)
date.append(root.find('date').text)
ticket.append(root.find('ticket').text)
value.append(root.find('value').text)
notenders.append(int(root.find('notenders').text))
nested_node0=root.findall('tenderdetail')
for child0 in nested_node0:
    tendertype.append(int(child0.find('tendertype').text))
    tenderamt.append(int(child0.find('tenderamt').text))
# Get all data under first item tag
nested_node1 = root.findall('item') #1
for child in nested_node1:
    receipeno.append(int(child.find('receipeno').text))
    price.append(int(child.find('price').text))
    qty.append(int(child.find('qty').text))

    # Get all data under first items tag
    nested_node2 = child.findall('items') #2
    for child2 in nested_node2:
        # Get all data under second item tag
        nested_node3 = child2.findall('item') #3
        for child3 in nested_node3:
            receipeno.append(int(child3.find('receipeno').text))
            price.append(int(child3.find('price').text))
            qty.append(int(child3.find('qty').text))
            # Get all data under second items tag
            nested_node4 = child3.findall('items') #4
            for child4 in nested_node4:
                # Get all data under third item tag
                nested_node5 = child4.findall('item') #5
                for child5 in nested_node5:
                    receipeno.append(int(child5.find('receipeno').text))
                    price.append(int(child5.find('price').text))
                    qty.append(int(child5.find('qty').text))

# Make the same length of every list of data with the max length
date.extend([np.nan]*(len(receipeno)-len(date)))
ticket.extend([np.nan]*(len(receipeno)-len(ticket)))
value.extend([np.nan]*(len(receipeno)-len(value)))
notenders.extend([np.nan]*(len(receipeno)-len(notenders)))
tendertype.extend([np.nan]*(len(receipeno)-len(tendertype)))
tenderamt.extend([np.nan]*(len(receipeno)-len(tenderamt)))
data={'date':date,
      'ticket':ticket,
      'value':value,
      'notenders':notenders,
      'tendertype':tendertype,
      'tenderamt':tenderamt,
      'receipeno': receipeno,
      'price': price,
      'qty':qty}

# Create DataFrame from data
df = pd.DataFrame(data)
df = df.fillna(method='ffill')
df
</code>```

Output:

Hope this can help you.

Body:
I have below xml data.

<transaction>
        <date>20190415</date>
        <ticket>303434037</ticket>
        <value>15</value>
        <notenders>01</notenders>
        <tenderdetail>
            <tendertype>00</tendertype>
            <tenderamt>15</tenderamt>
        </tenderdetail>
        <item>
            <receipeno>00001096</receipeno>
            <price>7</price>
            <qty>0001</qty>
            <items>
                <item>
                    <receipeno>00000786</receipeno>
                    <price>8</price>
                    <qty>0001</qty>
                    <items>
                        <item>
                            <receipeno>00000599</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                        <item>
                            <receipeno>00000605</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                        <item>
                            <receipeno>00000608</receipeno>
                            <price>0</price>
                            <qty>0004</qty>
                        </item>
                    </items>
                </item>
                <item>
                    <receipeno>10000043</receipeno>
                    <price>0</price>
                    <qty>0001</qty>
                </item>
                <item>
                    <receipeno>00000381</receipeno>
                    <price>7</price>
                    <qty>0001</qty>
                    <items>
                    <item>
                            <receipeno>00000607</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                    </items>
                </item>
            </items>
        </item>
   </transaction>

I need to convert this to a table format. the issues is there are many nested branches inside each tag. eg many <item> & <items> tags. irrespective of the nested-ness. I need to list down the data one below he other.

my desired output is as follows

 +----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+
|   date   | ticket | value | notenders | tendertype | tenderamt | receipeno | price | qty |
+----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+
| 20190101 |  12345 |    15 |         1 |          0 |        15 |      1096 |     7 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       786 |     8 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       599 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       605 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       608 |     0 |   4 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       143 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       381 |     7 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       607 |     0 |   1 |
+----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+

I'm new to python & XML parsing. Hence, kindly, direct me to solve this.
...

Body:
You can try the following code to get all data from nested XML File, but i think there is an elegant way to achieve the result:

import pandas as pd, numpy as np
import xml.etree.ElementTree as ET

xml_data = 'your xml data'

# Prepare for the list of variable to save XML data
date=[]
ticket=[]
value=[]
notenders=[]
tendertype=[]
tenderamt=[]
receipeno=[]
price=[]
qty=[]

# Parse the XML File to get the desired data
root = ET.fromstring(xml_data)
# Get header data from XML (date, ticket, value, notenders, tenderdetail)
date.append(root.find('date').text)
ticket.append(root.find('ticket').text)
value.append(root.find('value').text)
notenders.append(int(root.find('notenders').text))
nested_node0=root.findall('tenderdetail')
for child0 in nested_node0:
    tendertype.append(int(child0.find('tendertype').text))
    tenderamt.append(int(child0.find('tenderamt').text))
# Get all data under first item tag
nested_node1 = root.findall('item') #1
for child in nested_node1:
    receipeno.append(int(child.find('receipeno').text))
    price.append(int(child.find('price').text))
    qty.append(int(child.find('qty').text))

    # Get all data under first items tag
    nested_node2 = child.findall('items') #2
    for child2 in nested_node2:
        # Get all data under second item tag
        nested_node3 = child2.findall('item') #3
        for child3 in nested_node3:
            receipeno.append(int(child3.find('receipeno').text))
            price.append(int(child3.find('price').text))
            qty.append(int(child3.find('qty').text))
            # Get all data under second items tag
            nested_node4 = child3.findall('items') #4
            for child4 in nested_node4:
                # Get all data under third item tag
                nested_node5 = child4.findall('item') #5
                for child5 in nested_node5:
                    receipeno.append(int(child5.find('receipeno').text))
                    price.append(int(child5.find('price').text))
                    qty.append(int(child5.find('qty').text))

# Make the same length of every list of data with the max length
date.extend([np.nan]*(len(receipeno)-len(date)))
ticket.extend([np.nan]*(len(receipeno)-len(ticket)))
value.extend([np.nan]*(len(receipeno)-len(value)))
notenders.extend([np.nan]*(len(receipeno)-len(notenders)))
tendertype.extend([np.nan]*(len(receipeno)-len(tendertype)))
tenderamt.extend([np.nan]*(len(receipeno)-len(tenderamt)))
data={'date':date,
      'ticket':ticket,
      'value':value,
      'notenders':notenders,
      'tendertype':tendertype,
      'tenderamt':tenderamt,
      'receipeno': receipeno,
      'price': price,
      'qty':qty}

# Create DataFrame from data
df = pd.DataFrame(data)
df = df.fillna(method='ffill')
df

Output:

Hope this can help you.


问:
override default font using @font-face
We want to modify default font in HTML using @font-face

```<code>@font-face {
    font-family: Times;
    font-style: normal;
    font-weight: 400;
    src: local('serif');
}
</code>```

in the above code we want to override Times font to serif, but above code is not working and Times font is getting used all the time instead of serif

答:
Try this example, it works for me -- https://jsfiddle.net/gbk4rLw3/16/. However,  it doesn't seem to work if you try to switch a font with a generic font type such as serif or sans-serif, but any other web-safe font seems to work.

Test code is here as well.

HTML

```<code><div class="test">
TESTING
</div>
</code>```

CSS

```<code>.test{
  font-family: Times;
}

@font-face {
    font-family: Times;
    font-style: normal;
    font-weight: 400;
    src: local("Impact"); /* Try replacing with Arial, Comic Sans MS, etc....*/
    }                          /*Doesn't seem to work with generic font types (serif,                                     sans-serif)*/
</code>```

If you want a serif font, try using "Courier New".

Title: override default font using @font-face

Body:
We want to modify default font in HTML using @font-face

@font-face {
    font-family: Times;
    font-style: normal;
    font-weight: 400;
    src: local('serif');
}

in the above code we want to override Times font to serif, but above code is not working and Times font is getting used all the time instead of serif

Body:
Try this example, it works for me -- https://jsfiddle.net/gbk4rLw3/16/. However,  it doesn't seem to work if you try to switch a font with a generic font type such as serif or sans-serif, but any other web-safe font seems to work.

Test code is here as well.

HTML

<div class="test">
TESTING
</div>

CSS

.test{
  font-family: Times;
}

@font-face {
    font-family: Times;
    font-style: normal;
    font-weight: 400;
    src: local("Impact"); /* Try replacing with Arial, Comic Sans MS, etc....*/
    }                          /*Doesn't seem to work with generic font types (serif,                                     sans-serif)*/

If you want a serif font, try using "Courier New".


问:
How to fix 'args is not defined' error in Node.js?
by wanting to create a musical bot, I quickly noticed by ending coded that the bot does not start for an error that is indicated below the code. Thank you for enlightening me as possible.

Thanks to help me

```<code>switch (args[0].tolowerCase()) {
  case "play":
    if (!args[1]) {
      message.channel.send("Indiquez le __lien__ s'il vous plaît !");
      return;
   }

if(!message.member.voiceChannel) {
  message.channel.send("Vous devez vous trouvez dans un salon **vocal**
!");
  return;

    }

    if(!servers[message.guild.id]) servers[message.guild.id] = {
      queue : []
    }

   var server = servers[message.guild.id]

    server.queue.push(args[1]);

    if(!message.guild.voiceConnection)
message.member.voiceChannel.join().then(function(connection) {
  play(connection, message);
    })
    break;
  case "skip" :
    var server = servers[message.guild.id];

    if (server.dispatcher) server.dispatcher.end();
    break;
  case "stop" :
    var servers = servers[message.guild.id];

    if (message.guild.voiceConnection)
    message.guild.voiceConnection.disconnect();
        break;
  default:
    message.channel.send("La commande saisie est invalide !");
}
</code>```

This is the console log.

```<code>ReferenceError: args is not defined
    at Object.<anonymous> (C:\Users\Thomas\Desktop\Nolosha
 Bot\index.js:170:1)
</code>```

答:
Welcome to Stack Overflow.

The error you receive is saying that you haven't declared the variable args, but you're trying to use it anyway. Make sure that you have set args prior to using it.

const args = message.content.trim().split(/ +/g);
```

This code takes the message content, removes any whitespace on the beginning or end, and then splits it up into pieces by spaces, returning an array. Keep in mind that it can't be redefined within the same block because it's a constant.

Body:
by wanting to create a musical bot, I quickly noticed by ending coded that the bot does not start for an error that is indicated below the code. Thank you for enlightening me as possible.

Thanks to help me

switch (args[0].tolowerCase()) {
  case "play":
    if (!args[1]) {
      message.channel.send("Indiquez le __lien__ s'il vous plaît !");
      return;
   }

if(!message.member.voiceChannel) {
  message.channel.send("Vous devez vous trouvez dans un salon **vocal**
!");
  return;

    }

    if(!servers[message.guild.id]) servers[message.guild.id] = {
      queue : []
    }

   var server = servers[message.guild.id]

    server.queue.push(args[1]);

    if(!message.guild.voiceConnection)
message.member.voiceChannel.join().then(function(connection) {
  play(connection, message);
    })
    break;
  case "skip" :
    var server = servers[message.guild.id];

    if (server.dispatcher) server.dispatcher.end();
    break;
  case "stop" :
    var servers = servers[message.guild.id];

    if (message.guild.voiceConnection)
    message.guild.voiceConnection.disconnect();
        break;
  default:
    message.channel.send("La commande saisie est invalide !");
}

This is the console log.

ReferenceError: args is not defined
    at Object.<anonymous> (C:\Users\Thomas\Desktop\Nolosha
 Bot\index.js:170:1)

Body:
Welcome to Stack Overflow.

The error you receive is saying that you haven't declared the variable args, but you're trying to use it anyway. Make sure that you have set args prior to using it.

const args = message.content.trim().split(/ +/g);

This code takes the message content, removes any whitespace on the beginning or end, and then splits it up into pieces by spaces, returning an array. Keep in mind that it can't be redefined within the same block because it's a constant.