问:
javascript merge to array with name
I am new in JS. It is a simple task but find it is hard to solve. I tried many methods includingconcat,push,$.merge
Here is an example

```<code>var a=[]
var b=[]
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"
</code>```

I want to get a result like [a:"b", c:"d", e:"f", g:"h"],
Here is some method I have tried

a.concat(b)get []

a.push(b) get 1

$.merge(a,b) get [0:[e:"f", g:"h"],a:"b",c:"d"]

I don't know where to go, Please help

答:
The biggest problem you're running into right now is that you are trying to use an array as an object, so first when you're initializing a and b you should use curly braces instead. And then to merge them, you can use the spread operator: ....

All of that culminates into this:

let a = {};
let b = {};
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"

a = {...a, ...b}
```

Title: javascript merge to array with name

Body:
I am new in JS. It is a simple task but find it is hard to solve. I tried many methods includingconcat,push,$.merge
Here is an example

var a=[]
var b=[]
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"

I want to get a result like [a:"b", c:"d", e:"f", g:"h"],
Here is some method I have tried

a.concat(b)get []

a.push(b) get 1

$.merge(a,b) get [0:[e:"f", g:"h"],a:"b",c:"d"]

I don't know where to go, Please help


来源: stackexchange

问:
What are data breakpoints?
I just came to know that there are data breakpoints. I have worked for the last 5 years in C++ using Visual Studio, and I have never used data breakpoints.

Can someone throw some light on what data breakpoints are, when to use them and how to use them with VS?

As per my understanding we can set a data breakpoint when we want to check for changes to a variable's value. In this case, we can set a data breakpoint with a condition on the variable value.

Any other examples?

答:
Definition:

Data breakpoints allow you to break
  execution when the value stored at a
  specified memory location changes.

From MSDN: How to: Set a Data Breakpoint:

How to Set a Memory Change Breakpoint

From the Debug Menu, choose New Breakpoint and click New Data Breakpoint

—or—

in the Breakpoints window Menu, click the New dropdown and choose New Data Breakpoint.

The New Breakpoint dialog box appears.

In the Address box, enter a memory address or expression that evaluates to a memory address. For example, &foo to break when the contents of variable foo change.

In the Byte Count box, enter the number of bytes you want the debugger to watch. For example, if you enter 4, the debugger will watch the four bytes starting at &foo and break if any of those bytes change value.

Click OK.

ContentLicense: CC BY-SA 2.5

Title: What are data breakpoints?

LastEditorDisplayName: MarkJ

OwnerDisplayName: Daniel L

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Daniel L


问:
Angular - How to make a button on click with a function that is not on the component?
So, I have a function called functionSave(). It is in the functionSave.ts file. I wanted to call it on my-component.html. They're both on the same folder. Is it possible to call it?</p>

答:
It is possible, just import it like so:

My functionSave.ts file.

export function doSomething(value: any): any {
         // do something
        }
```

<p>my component class:</p>

<pre class="lang-js prettyprint-override"><code>// import your function from functionSave
import { doSomething } from './functionSave';

@Component({})
class MyComponent {

  // save it in the component class
  public doSomething = doSomething;

}
</code>```

And finally call it in the template:

 <element (click)="doSomething()"></element>
```

ContentLicense: CC BY-SA 4.0

Body:
It is possible, just import it like so:

My functionSave.ts file.

export function doSomething(value: any): any {
         // do something
        }

my component class:

// import your function from functionSave
import { doSomething } from './functionSave';

@Component({})
class MyComponent {

  // save it in the component class
  public doSomething = doSomething;

}

And finally call it in the template:

 <element (click)="doSomething()"></element>


问:
Check if value equals 0 regardless of decimal values?
I'm balancing the sigma of a Gaussian kernel. I desire to break the while loop once the first index of the array is equal to 0.(any decimal value).

I found that simply trying to match 0 won't match if the value also contains any decimals like 0.000013301.

```<code>var gaussianKernel1d = (function() {
    var sqr2pi = Math.sqrt(2 * Math.PI);

    return function gaussianKernel1d(size, sigma) {
        'use strict';

        // ensure size is even and prepare variables
        var width = (size / 2) | 0,
            kernel = new Array(width * 2 + 1),
            norm = 1.0 / (sqr2pi * sigma),
            coefficient = 2 * sigma * sigma,
            total = 0,
            x;

        // set values and increment total
        for (x = -width; x <= width; x++) {
            total += kernel[width + x] = norm * Math.exp((-x * x) / coefficient);
        }

        // divide by total to make sure the sum of all the values is equal to 1
        for (x = 0; x < kernel.length; x++) {
            kernel[x] /= total;
        }

        return kernel;
    };
})();

let i = 0.01;
let kernelArray = gaussianKernel1d(512, i);
while (kernelArray[0] === 0) {
    i = i + 0.01;
    kernelArray = gaussianKernel1d(512, i);
</code>```

Same is also true when using Array[0] !== 0.0)

How can I match any values in the dataset that equal 0 regardless of the decimal values? And without converting the array to integers.

答:
epascarello's solution is correct:

```<code>while (Math.floor(kernelArray[0]) === 0)
</code>```

That will continue looping as long as kernelArray[0] is a value >= 0 and < 1.

Or of course, the other obvious approach is just to write the equation in the description above:

```<code>while (kernelArray[0]) >= 0 && kernelArray[0] < 1)
</code>```

Body:
I'm balancing the sigma of a Gaussian kernel. I desire to break the while loop once the first index of the array is equal to 0.(any decimal value).

I found that simply trying to match 0 won't match if the value also contains any decimals like 0.000013301.

var gaussianKernel1d = (function() {
    var sqr2pi = Math.sqrt(2 * Math.PI);

    return function gaussianKernel1d(size, sigma) {
        'use strict';

        // ensure size is even and prepare variables
        var width = (size / 2) | 0,
            kernel = new Array(width * 2 + 1),
            norm = 1.0 / (sqr2pi * sigma),
            coefficient = 2 * sigma * sigma,
            total = 0,
            x;

        // set values and increment total
        for (x = -width; x <= width; x++) {
            total += kernel[width + x] = norm * Math.exp((-x * x) / coefficient);
        }

        // divide by total to make sure the sum of all the values is equal to 1
        for (x = 0; x < kernel.length; x++) {
            kernel[x] /= total;
        }

        return kernel;
    };
})();

let i = 0.01;
let kernelArray = gaussianKernel1d(512, i);
while (kernelArray[0] === 0) {
    i = i + 0.01;
    kernelArray = gaussianKernel1d(512, i);

Same is also true when using Array[0] !== 0.0)

How can I match any values in the dataset that equal 0 regardless of the decimal values? And without converting the array to integers.

Body:
epascarello's solution is correct:

while (Math.floor(kernelArray[0]) === 0)

That will continue looping as long as kernelArray[0] is a value >= 0 and < 1.

Or of course, the other obvious approach is just to write the equation in the description above:

while (kernelArray[0]) >= 0 && kernelArray[0] < 1)


问:
'NoneType' object is not iterable - issue with context in Django
I have this models.py:

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

    venue = models.ForeignKey(Venue, on_delete=models.CASCADE)
    event = models.ForeignKey('Event', on_delete=models.CASCADE)
    start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False)

    def __str__(self):
        return "%s" % (self.start_date_time)
</code>```

This is my context_processors.py:

```<code>def events(request):
    return
    {
        'next_events': dateEvent.objects.all(),
    }
</code>```

which is registered in my settings.py:

```<code>        'OPTIONS': {
            'context_processors': [
                'nms_app.context_processors.events'
</code>```

I'm getting

```<code>TypeError at /

'NoneType' object is not iterable
Exception Location:     /home/luca/python_ve/lib/python3.8/site-packages/django/template/context.py in bind_template, line 246
/usr/local/lib/python3.8/contextlib.py in __enter__

                return next(self.gen)

     …

▼ Local vars
Variable    Value
self

<contextlib._GeneratorContextManager object at 0x7fe90a3e7a90>
</code>```

when visiting any page of my website, and I can't understand why. Can someone help me finding the culprit? I can't see why dateEvent is NoneType; it is populated with valid data.

答:
I can't believe it; it was 'only' an indentation problem. This code in my context_processors.py:

```<code>def events(request):
    return {
            'next_events': dateEvent.objects.all()
    }
</code>```

works.

Body:
I have this models.py:

class dateEvent(models.Model):

    venue = models.ForeignKey(Venue, on_delete=models.CASCADE)
    event = models.ForeignKey('Event', on_delete=models.CASCADE)
    start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False)

    def __str__(self):
        return "%s" % (self.start_date_time)

This is my context_processors.py:

def events(request):
    return
    {
        'next_events': dateEvent.objects.all(),
    }

which is registered in my settings.py:

        'OPTIONS': {
            'context_processors': [
                'nms_app.context_processors.events'

I'm getting

TypeError at /

'NoneType' object is not iterable
Exception Location:     /home/luca/python_ve/lib/python3.8/site-packages/django/template/context.py in bind_template, line 246
/usr/local/lib/python3.8/contextlib.py in __enter__

                return next(self.gen)

     …

▼ Local vars
Variable    Value
self

<contextlib._GeneratorContextManager object at 0x7fe90a3e7a90>

when visiting any page of my website, and I can't understand why. Can someone help me finding the culprit? I can't see why dateEvent is NoneType; it is populated with valid data.

Body:
I can't believe it; it was 'only' an indentation problem. This code in my context_processors.py:

def events(request):
    return {
            'next_events': dateEvent.objects.all()
    }

works.


问:
Is it possible to `continue` a foreach loop while in a for loop?
Okay, so what I want to do should sound pretty simple. I have a method that checks every character in a string if it's a letter from a to m. I now have to continue a foreach loop, while in a for loop. Is there a possible way to do what I want to do?

```<code>public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if (c == (char)i)
            {
                // Here immediately continue the upper foreach loop, not the for loop
                continue;
            }
        }
        error++;
    }

    int length = s.Length;
    return error + "/" + length;
}
</code>```

If there's a character that's not in the range of  a to m, there should be 1 added to error. In the end, the function should return the number of errors and the number of total characters in the string, f.E: "3/17".

Edit

What I wanted to achieve is not possible. There are workarounds, demonstrated in BsdDaemon's answer, by using a temporary variable.

The other answers fix my issue directly, by simply improving my code.

答:
The continue will skip the further lines in that iterations and if you need to break out the loop use break.

```<code>public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if ('a' == (char)i)
            {
                break; // break the whole looping, continue will break only the iteration
            }
        }
        error++;
    }
    string length = Convert.ToString(s.Length);
    return error + "/" + length;
}
</code>```

Body:
Okay, so what I want to do should sound pretty simple. I have a method that checks every character in a string if it's a letter from a to m. I now have to continue a foreach loop, while in a for loop. Is there a possible way to do what I want to do?

public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if (c == (char)i)
            {
                // Here immediately continue the upper foreach loop, not the for loop
                continue;
            }
        }
        error++;
    }

    int length = s.Length;
    return error + "/" + length;
}

If there's a character that's not in the range of  a to m, there should be 1 added to error. In the end, the function should return the number of errors and the number of total characters in the string, f.E: "3/17".

Edit

What I wanted to achieve is not possible. There are workarounds, demonstrated in BsdDaemon's answer, by using a temporary variable.

The other answers fix my issue directly, by simply improving my code.

Body:
The continue will skip the further lines in that iterations and if you need to break out the loop use break.

public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if ('a' == (char)i)
            {
                break; // break the whole looping, continue will break only the iteration
            }
        }
        error++;
    }
    string length = Convert.ToString(s.Length);
    return error + "/" + length;
}


问:
Ionic 5: how to secure mobile app with Fingerprint AIO
I am using Fingerprint AIO to secure my mobile app, but I am a bit confused about what to do here. As far as I can tell, this library only expose 2 functions isAvailable() and show(). So I give it a try on my project:

```<code>  import { FingerprintAIO, FingerprintOptions } from '@ionic-native/fingerprint-aio/ngx';

  initFingerprint() {
    const opt: FingerprintOptions = {
      title: 'Fingerprint - FaceID authentication',
      subtitle: "It's quick and easy",
      description: '',
      fallbackButtonTitle: 'Use Pin',
      cancelButtonTitle: 'Cancel',
      disableBackup: false
    }
    this.faio.show(opt)
      .then((result) => {
        console.log(result)
        // What should I do here ???
      })
      .catch((error) => {
        console.log(error);
      })
  }
</code>```

The function above works fine, but what should I do in the then() callback? How can I tell my server that this user already authenticated successfully with their finger (or face)?

My assumption is that I need to encrypt their username and password in a text file then decrypt it later if they successfully authenticated and send that information to my server. But this seems like a lot of thing to do.

P/s: Here the library: https://github.com/NiklasMerz/cordova-plugin-fingerprint-aio

答:
Use this style instead:

```<code>this.faio.show(opt, successCallback, errorCallback);

function successCallback(){
  alert("Authentication successful");
}

function errorCallback(error){
  alert("Authentication invalid " + error.message);
}
</code>```

in success logically you have to unlock the app and navigate forward, and in error, you should prevent it and request pin or fingerprint again.

Body:
I am using Fingerprint AIO to secure my mobile app, but I am a bit confused about what to do here. As far as I can tell, this library only expose 2 functions isAvailable() and show(). So I give it a try on my project:

  import { FingerprintAIO, FingerprintOptions } from '@ionic-native/fingerprint-aio/ngx';

  initFingerprint() {
    const opt: FingerprintOptions = {
      title: 'Fingerprint - FaceID authentication',
      subtitle: "It's quick and easy",
      description: '',
      fallbackButtonTitle: 'Use Pin',
      cancelButtonTitle: 'Cancel',
      disableBackup: false
    }
    this.faio.show(opt)
      .then((result) => {
        console.log(result)
        // What should I do here ???
      })
      .catch((error) => {
        console.log(error);
      })
  }

The function above works fine, but what should I do in the then() callback? How can I tell my server that this user already authenticated successfully with their finger (or face)?

My assumption is that I need to encrypt their username and password in a text file then decrypt it later if they successfully authenticated and send that information to my server. But this seems like a lot of thing to do.

P/s: Here the library: https://github.com/NiklasMerz/cordova-plugin-fingerprint-aio

Body:
Use this style instead:

this.faio.show(opt, successCallback, errorCallback);

function successCallback(){
  alert("Authentication successful");
}

function errorCallback(error){
  alert("Authentication invalid " + error.message);
}

in success logically you have to unlock the app and navigate forward, and in error, you should prevent it and request pin or fingerprint again.


问:
How to use tf.data.Dataset.interleave() in TF 2 with a custom function?
I'm using TF 2.2 and I'm trying to use tf.data to create a pipeline.

The following works fine:

def load_image(filePath, label):

    print('Loading File: {}' + filePath)
    raw_bytes = tf.io.read_file(filePath)
    image = tf.io.decode_image(raw_bytes, expand_animations = False)

    return image, label

# TrainDS Pipeline
trainDS = getDataset()
trainDS = trainDS.shuffle(size['train'])
trainDS = trainDS.map(load_image, num_parallel_calls=AUTOTUNE)

for d in trainDS:
    print('Image: {} - Label: {}'.format(d[0], d[1]))
```

<p>I would like to use the <code>load_image()</code> with the <code>Dataset.interleave()</code>. Then I tried:</p>

<pre class="lang-py prettyprint-override"><code># TrainDS Pipeline
trainDS = getDataset()
trainDS = trainDS.shuffle(size['train'])
trainDS = trainDS.interleave(lambda x, y: load_image_with_label(x, y), cycle_length=4)

for d in trainDS:
    print('Image: {} - Label: {}'.format(d[0], d[1]))
</code>```

But I'm getting the following error:

```<code>Exception has occurred: TypeError
`map_func` must return a `Dataset` object. Got <class 'tuple'>
  File "/data/dev/train_daninhas.py", line 44, in <module>
    trainDS = trainDS.interleave(lambda x, y: load_image_with_label(x, y), cycle_length=4)
</code>```

How can I adapt my code to have the Dataset.interleave() working with the load_image() to read the images in parallel ?

答:
As the error suggests, you need to modify the load_image so that it return a Dataset object, I have shown an example with two images on how to go about doing it in tensorflow 2.2.0:

```<code>import tensorflow as tf
filenames = ["./img1.jpg", "./img2.jpg"]
labels = ["A", "B"]

def load_image(filePath, label):
    print('Loading File: {}' + filePath)
    raw_bytes = tf.io.read_file(filePath)
    image = tf.io.decode_image(raw_bytes, expand_animations = False)
    return tf.data.Dataset.from_tensors((image, label))

dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
dataset = dataset.interleave(lambda x, y: load_image(x, y), cycle_length=4)

for i in dataset.as_numpy_iterator():
    image = i[0]
    label = i[1]
    print(image.shape)
    print(label.decode())

# (275, 183, 3)
# A
# (275, 183, 3)
# B
</code>```

Body:
I'm using TF 2.2 and I'm trying to use tf.data to create a pipeline.

The following works fine:

def load_image(filePath, label):

    print('Loading File: {}' + filePath)
    raw_bytes = tf.io.read_file(filePath)
    image = tf.io.decode_image(raw_bytes, expand_animations = False)

    return image, label

# TrainDS Pipeline
trainDS = getDataset()
trainDS = trainDS.shuffle(size['train'])
trainDS = trainDS.map(load_image, num_parallel_calls=AUTOTUNE)

for d in trainDS:
    print('Image: {} - Label: {}'.format(d[0], d[1]))

I would like to use the load_image() with the Dataset.interleave(). Then I tried:

# TrainDS Pipeline
trainDS = getDataset()
trainDS = trainDS.shuffle(size['train'])
trainDS = trainDS.interleave(lambda x, y: load_image_with_label(x, y), cycle_length=4)

for d in trainDS:
    print('Image: {} - Label: {}'.format(d[0], d[1]))

But I'm getting the following error:

Exception has occurred: TypeError
`map_func` must return a `Dataset` object. Got <class 'tuple'>
  File "/data/dev/train_daninhas.py", line 44, in <module>
    trainDS = trainDS.interleave(lambda x, y: load_image_with_label(x, y), cycle_length=4)

How can I adapt my code to have the Dataset.interleave() working with the load_image() to read the images in parallel ?

Body:
As the error suggests, you need to modify the load_image so that it return a Dataset object, I have shown an example with two images on how to go about doing it in tensorflow 2.2.0:

import tensorflow as tf
filenames = ["./img1.jpg", "./img2.jpg"]
labels = ["A", "B"]

def load_image(filePath, label):
    print('Loading File: {}' + filePath)
    raw_bytes = tf.io.read_file(filePath)
    image = tf.io.decode_image(raw_bytes, expand_animations = False)
    return tf.data.Dataset.from_tensors((image, label))

dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
dataset = dataset.interleave(lambda x, y: load_image(x, y), cycle_length=4)

for i in dataset.as_numpy_iterator():
    image = i[0]
    label = i[1]
    print(image.shape)
    print(label.decode())

# (275, 183, 3)
# A
# (275, 183, 3)
# B


问:
Best way to create Python function with multiple options?
I've defined a bunch of custom functions and find a lot of them include some identical or similar blocks of code (e.g. just including slightly different strings or arguments). So something like:

```<code>def func1(a, b, c):
    some_identical_code
    some_similar_code
    more_identical_code
    some_unique_code
    final_similar_code

# similarly for func2, func3...
</code>```

I would like to try to combine these into a single function that takes an additional 'setting' argument, both because the functions are obviously related and to make the code more compact. The obvious but inelegant flow for this would be something like:

```<code>def func(a, b, c, setting):
    # setting = '1', '2', etc.

    some identical code

    if setting == '1':
        similar_code_1
    elif setting == '2':
        similar_code_2
    # etc. for other settings options

    more_identical_code

    if setting == '1':
        unique_code_1
        final_similar_code_1
    elif setting == '2':
        unique_code_2
        final_similar_code_2
    # etc. for other settings options
</code>```

How can I do something like this more elegantly? Is there a standard way to do it?

One option I'm trying is to use dictionaries built into the function to parse the similar code blocks:

```<code>def func(a, b, c, setting):
    # setting = '1', '2', etc.
    simdict = {'1': '_1', '2': '_2' ...}

    some identical code
    similar_code(simdict[setting])
    more_identical_code

    if setting == '1':
        unique_code_1
    elif setting == '2':
        unique_code_2
    # etc. for other settings options

    final_similar_code(simdict[setting])
</code>```

This helps but 1) I'm not sure if it's good design and 2) it only helps so much when the identical vs. similar vs. unique code is very interspersed.

答:
Use a function to generate functions from the shared code. Say part of your shared code adds a constant to a value that's passed in:

```<code>def adder(n):
  def addTo(x):
    return x + n
  return addTo
</code>```

Then, you need an adder that adds 2 and one that adds 4:

```<code>add2 = adder(2)
print(add2(2)) # Prints 4

add4 = adder(4)
print(add4(2)) # Prints 6
</code>```

Body:
I've defined a bunch of custom functions and find a lot of them include some identical or similar blocks of code (e.g. just including slightly different strings or arguments). So something like:

def func1(a, b, c):
    some_identical_code
    some_similar_code
    more_identical_code
    some_unique_code
    final_similar_code

# similarly for func2, func3...

I would like to try to combine these into a single function that takes an additional 'setting' argument, both because the functions are obviously related and to make the code more compact. The obvious but inelegant flow for this would be something like:

def func(a, b, c, setting):
    # setting = '1', '2', etc.

    some identical code

    if setting == '1':
        similar_code_1
    elif setting == '2':
        similar_code_2
    # etc. for other settings options

    more_identical_code

    if setting == '1':
        unique_code_1
        final_similar_code_1
    elif setting == '2':
        unique_code_2
        final_similar_code_2
    # etc. for other settings options

How can I do something like this more elegantly? Is there a standard way to do it?

One option I'm trying is to use dictionaries built into the function to parse the similar code blocks:

def func(a, b, c, setting):
    # setting = '1', '2', etc.
    simdict = {'1': '_1', '2': '_2' ...}

    some identical code
    similar_code(simdict[setting])
    more_identical_code

    if setting == '1':
        unique_code_1
    elif setting == '2':
        unique_code_2
    # etc. for other settings options

    final_similar_code(simdict[setting])

This helps but 1) I'm not sure if it's good design and 2) it only helps so much when the identical vs. similar vs. unique code is very interspersed.

Body:
Use a function to generate functions from the shared code. Say part of your shared code adds a constant to a value that's passed in:

def adder(n):
  def addTo(x):
    return x + n
  return addTo

Then, you need an adder that adds 2 and one that adds 4:

add2 = adder(2)
print(add2(2)) # Prints 4

add4 = adder(4)
print(add4(2)) # Prints 6


问:
How to get the dashboard address from the Dask scheduler
When starting a dask distributed local cluster, you can set a random port or address for the dashboard_address.

If you later get the scheduler object. Is there a way to extract the address of the dashboard.

I have this:

```<code>cluster = dask.distributed.LocalCluster(scheduler_port=0,
                                        dashboard_address='localhost:0')
scheduler = dask.distributed.Client(cluster, set_as_default=False)
scheduler_info = scheduler.scheduler_info()
logger.info('Scheduler: %s', scheduler_info['address'])
logger.info('Status Port: %s', scheduler_info['services']['dashboard'])
</code>```

But that only gets the port of the dashboard, not the IP of the dashboard. If I were to put the dashboard address on a separate IP other than the scheduler, seems like it would be difficult to know what IP it was bound to.

答:
<pre class="lang-py prettyprint-override"><code># if you have the cluster object
cluster.dashboard_link

# or if you have a client
client.dashboard_link
</code>```

Body:
When starting a dask distributed local cluster, you can set a random port or address for the dashboard_address.

If you later get the scheduler object. Is there a way to extract the address of the dashboard.

I have this:

cluster = dask.distributed.LocalCluster(scheduler_port=0,
                                        dashboard_address='localhost:0')
scheduler = dask.distributed.Client(cluster, set_as_default=False)
scheduler_info = scheduler.scheduler_info()
logger.info('Scheduler: %s', scheduler_info['address'])
logger.info('Status Port: %s', scheduler_info['services']['dashboard'])

But that only gets the port of the dashboard, not the IP of the dashboard. If I were to put the dashboard address on a separate IP other than the scheduler, seems like it would be difficult to know what IP it was bound to.


问:
Symfony2 custom console command not working
I created a new Class in src/MaintenanceBundle/Command, named it GreetCommand.php and put the following code in it:

```<code><?php

namespace SK2\MaintenanceBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GreetCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('maintenance:greet')
            ->setDescription('Greet someone')
            ->addArgument('name', InputArgument::OPTIONAL, 'Who do you want to greet?')
            ->addOption('yell', null, InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input->getArgument('name');
        if ($name) {
            $text = 'Hello '.$name;
        } else {
            $text = 'Hello';
        }

        if ($input->getOption('yell')) {
            $text = strtoupper($text);
        }

        $output->writeln($text);
    }
}

?>
</code>```

And tried to call it via

app/console maintenance:greet Fabien

But i always get the following error:

[InvalidArgumentException]
  There are no commands defined in the "maintenance" namespace.

Any ideas?

答:
I had this same error when I tried to test my command execution with PHPUnit.

This was due to a wrong class import :

```<code>use Symfony\Component\Console\Application;
</code>```

should be

```<code>use Symfony\Bundle\FrameworkBundle\Console\Application;
</code>```

cf. Other stack thread

Body:
I created a new Class in src/MaintenanceBundle/Command, named it GreetCommand.php and put the following code in it:

<?php

namespace SK2\MaintenanceBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GreetCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('maintenance:greet')
            ->setDescription('Greet someone')
            ->addArgument('name', InputArgument::OPTIONAL, 'Who do you want to greet?')
            ->addOption('yell', null, InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input->getArgument('name');
        if ($name) {
            $text = 'Hello '.$name;
        } else {
            $text = 'Hello';
        }

        if ($input->getOption('yell')) {
            $text = strtoupper($text);
        }

        $output->writeln($text);
    }
}

?>

And tried to call it via

app/console maintenance:greet Fabien

But i always get the following error:

[InvalidArgumentException]
  There are no commands defined in the "maintenance" namespace.

Any ideas?

Body:
I had this same error when I tried to test my command execution with PHPUnit.

This was due to a wrong class import :

use Symfony\Component\Console\Application;

should be

use Symfony\Bundle\FrameworkBundle\Console\Application;

cf. Other stack thread


问:
changing the index according to click
I'm trying to make an image play each time i click it, i have two songs and two images at the moment.
every time i click an image only one of the songs play because the index is 0 right now.
I want a different song to play according to the image i'm clicking (i might add more pictures in the future so i was looking for a solution that doesn't involve changing the JS).
is there anything i can write in the index (instead of 0) that would change according to the image i'm clicking?

HTML:

```<code><section id="imgsound">
<div class="imageCircle">
    <div id="bird">
        <img id="birdImg" class="circle" src="images/bird.jpg">
        <audio id="birdAudio" class="audio"><source src="sounds/bird.mp3" type="audio/mpeg"></audio>
    </div>
</div>
<div class="imageCircle">
    <div id="stream">
        <img id="streamImg" class="circle" src="images/stream.jpg">
        <audio id="birdAudio" class="audio"><source src="sounds/stream.mp3" type="audio/mpeg">   </audio>
    </div>
</div>
</code>```

JS:

```<code>var audio;
function playAudio(){
    if (audio == false){
        $(this).css({"transform":"rotate(-360deg)"});
        $(".audio")[0].play();
        audio = true;
    }else{
        $(this).css({"transform":"rotate(360deg)"});
        $(".audio")[0].pause();
        audio = false;
    }
}
$(".imageCircle").click(playAudio);
</code>```

答: You should consult event.target for this. With it, you can get information of the element, that triggered the event. For example you can get the id or other attributes of the node from it.</p>

Title: changing the index according to click

Body:
I'm trying to make an image play each time i click it, i have two songs and two images at the moment.
every time i click an image only one of the songs play because the index is 0 right now.
I want a different song to play according to the image i'm clicking (i might add more pictures in the future so i was looking for a solution that doesn't involve changing the JS).
is there anything i can write in the index (instead of 0) that would change according to the image i'm clicking?

HTML:

        <audio id="birdAudio" class="audio"><source src="sounds/bird.mp3" type="audio/mpeg"></audio>

        <audio id="birdAudio" class="audio"><source src="sounds/stream.mp3" type="audio/mpeg">   </audio>

JS:

var audio;
function playAudio(){
    if (audio == false){
        $(this).css({"transform":"rotate(-360deg)"});
        $(".audio")[0].play();
        audio = true;
    }else{
        $(this).css({"transform":"rotate(360deg)"});
        $(".audio")[0].pause();
        audio = false;
    }
}
$(".imageCircle").click(playAudio);


问:
How does this particular Python recursion work? Why the result value becomes 1, 3, 6, 10, 15, 21?
Could you explain step by step, why the result value becomes 1, 3, 6, 10, 15, 21?</p>

```<code>def recursion(number):
    if(number > 0):
      result = number + recursion(number - 1)
      print(result)
    else:
      result = 0
    return result

print("\n\nRecursion Example Results")
recursion(6)
</code>```

答:
Looks like this function is returning the sum of consecutive numbers up to a certain value. Before you look at the code and try to understand it, you need to breakdown the problem:

Let's take some variable sumUpTo6 = 6 + 5 + 4 .... 0 which is the sum of numbers up to 6. Then let's take another variable sumUpTo7 = 7 + 6 + 5 + 4 ... 0 which is the sum of numbers up to 7. Notice now, that I can rewrite sumUpTo7 as sumUpTo7 = 7 + sumUpTo6

Now if we replace these variables with calls to your function:

If recursion(6) gives me the sum of numbers up to 6,

Then recursion(7) = 7 + recursion(6)

And more generally speaking, recursion(number) = number + recursion(number-1)

But what about when we reach recursion(0)? Well this is called the base case, and we want recursion(0) = 0 (because the sum of numbers up to 0 is 0).

So now let's put this all into code:

```<code>def recursion(number):                           # `number` here is the number we want to add up to
    if (number > 0):                             # if `number` is greater than 0, we can use the number below it to get the answer
        result = number + recursion(number-1)    # we use the logic above
        print(result)                            # show the result on the command line
    else:                                        # if `number` is not greater than 0, then it must be less than or equal to 0
        result = 0                               # in this case the sum up to number will be 0
    return result                                # pass the result up to the caller
</code>```

The call to recursion(6) will run something like this:

We call recursion(6)

6 is greater than 0. So we call recursion(6-1) which is recursion(5) and we will add 6 to this. We don't print anything yet because we wait for recursion(5) to finish.

5 is greater than 0. So we call recursion(4). Nothing printed yet.

4 is greater than 0. So we call recursion(3). Nothing printed yet.

3 is greater than 0. So we call recursion(2). Nothing printed yet.

2 is greater than 0. So we call recursion(1). Nothing printed yet.

1 is greater than 0. So we call recursion(0). Nothing printed yet.

0 is not greater than 0, so we return 0. We don't print anything here

So for recursion recursion(1) we got 1 + 0 (from previous line) so we print 1 and return 1

For recursion(2) we got 2 + 1 (from previous line) so we print and return 3

For recursion(3) we got 3 + 3 so we print and return 6

For recursion(4) we got 4 + 6 so we print and return 10

For recursion(5) we got 5 + 10 so we print and return 15

... you get the idea

I added some print statements to the code below to make it easier to understand:

Run this with different numbers...

```<code>def recursion(number):
    if(number > 0):
      print("{} is greater than 0".format(number))
      print("Calling recursion({}-1)\n".format(number))
      previous_result = recursion(number - 1)
      print("recursion({}-1) gave {}".format(number, previous_result))
      result = number + previous_result
      print("returning {} + {} = {}\n".format(number, previous_result, result))
    else:
      print("Hit 0! Returning 0\n")
      result = 0
    return result

print("\n\nRecursion Example Results\n\n")
recursion(6)
</code>```

Body:
Could you explain step by step, why the result value becomes 1, 3, 6, 10, 15, 21?

def recursion(number):
    if(number > 0):
      result = number + recursion(number - 1)
      print(result)
    else:
      result = 0
    return result

print("\n\nRecursion Example Results")
recursion(6)

Body:
Looks like this function is returning the sum of consecutive numbers up to a certain value. Before you look at the code and try to understand it, you need to breakdown the problem:

Let's take some variable sumUpTo6 = 6 + 5 + 4 .... 0 which is the sum of numbers up to 6. Then let's take another variable sumUpTo7 = 7 + 6 + 5 + 4 ... 0 which is the sum of numbers up to 7. Notice now, that I can rewrite sumUpTo7 as sumUpTo7 = 7 + sumUpTo6

Now if we replace these variables with calls to your function:

If recursion(6) gives me the sum of numbers up to 6,

Then recursion(7) = 7 + recursion(6)

And more generally speaking, recursion(number) = number + recursion(number-1)

But what about when we reach recursion(0)? Well this is called the base case, and we want recursion(0) = 0 (because the sum of numbers up to 0 is 0).

So now let's put this all into code:

def recursion(number):                           # `number` here is the number we want to add up to
    if (number > 0):                             # if `number` is greater than 0, we can use the number below it to get the answer
        result = number + recursion(number-1)    # we use the logic above
        print(result)                            # show the result on the command line
    else:                                        # if `number` is not greater than 0, then it must be less than or equal to 0
        result = 0                               # in this case the sum up to number will be 0
    return result                                # pass the result up to the caller

The call to recursion(6) will run something like this:

We call recursion(6)

6 is greater than 0. So we call recursion(6-1) which is recursion(5) and we will add 6 to this. We don't print anything yet because we wait for recursion(5) to finish.

5 is greater than 0. So we call recursion(4). Nothing printed yet.

4 is greater than 0. So we call recursion(3). Nothing printed yet.

3 is greater than 0. So we call recursion(2). Nothing printed yet.

2 is greater than 0. So we call recursion(1). Nothing printed yet.

1 is greater than 0. So we call recursion(0). Nothing printed yet.

0 is not greater than 0, so we return 0. We don't print anything here

So for recursion recursion(1) we got 1 + 0 (from previous line) so we print 1 and return 1

For recursion(2) we got 2 + 1 (from previous line) so we print and return 3

For recursion(3) we got 3 + 3 so we print and return 6

For recursion(4) we got 4 + 6 so we print and return 10

For recursion(5) we got 5 + 10 so we print and return 15

... you get the idea

I added some print statements to the code below to make it easier to understand:

Run this with different numbers...

def recursion(number):
    if(number > 0):
      print("{} is greater than 0".format(number))
      print("Calling recursion({}-1)\n".format(number))
      previous_result = recursion(number - 1)
      print("recursion({}-1) gave {}".format(number, previous_result))
      result = number + previous_result
      print("returning {} + {} = {}\n".format(number, previous_result, result))
    else:
      print("Hit 0! Returning 0\n")
      result = 0
    return result

print("\n\nRecursion Example Results\n\n")
recursion(6)


问:
How can I return a specific element out of an array in Javascript?
Im trying to implement a Network discovery search which returns all devices that are linked with my local network.
My code so far looks like this:

```<code>const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  console.log(devices);
})
</code>```

And the returned array in the console looks like this:

```<code>[
  { name: '?', ip: '192.168.0.174', mac: '00:17:88:65:f4:4d' },
  { name: '?', ip: '192.168.0.222', mac: '80:be:05:73:bc:g5' },
  { name: '?', ip: '192.168.0.190', mac: '0c:fe:45:4d:b8:28' }
]
</code>```

So, I know the Mac Adress of the device im looking for already, my problem is, how can I search for the mac adress in the Array, and return the specific ip Adress of this device?
For example, I pass the mac adress "00:17:88:65:f4:4d" into a function, and the function should return "192.168.0.174" which I can save in a variable and work with in the following code.

I might be able to solve this with the find() function, but how can I tell the code, that I only want the ip adress, and not the full element of the array saved?
I thought about something like:

```<code>const ip = devices.find('00:17:88:65:f4:4d');
</code>```

But this would only return the full element, if the syntax was correct.

答:
Sorry, I was just replying with this answer but noticed Wais has already given the same answer above! here is an example using .forEach rather than a for loop though

let details = [
  { name: '?', ip: '192.168.0.174', mac: '00:17:88:65:f4:4d' },
  { name: '?', ip: '192.168.0.222', mac: '80:be:05:73:bc:g5' },
  { name: '?', ip: '192.168.0.190', mac: '0c:fe:45:4d:b8:28' }
]

details.forEach((item, index) => {
  if(item.mac === "80:be:05:73:bc:g5") {
    return item.ip;
  }
});```

Body:
Im trying to implement a Network discovery search which returns all devices that are linked with my local network.
My code so far looks like this:

const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  console.log(devices);
})

And the returned array in the console looks like this:

[
  { name: '?', ip: '192.168.0.174', mac: '00:17:88:65:f4:4d' },
  { name: '?', ip: '192.168.0.222', mac: '80:be:05:73:bc:g5' },
  { name: '?', ip: '192.168.0.190', mac: '0c:fe:45:4d:b8:28' }
]

So, I know the Mac Adress of the device im looking for already, my problem is, how can I search for the mac adress in the Array, and return the specific ip Adress of this device?
For example, I pass the mac adress "00:17:88:65:f4:4d" into a function, and the function should return "192.168.0.174" which I can save in a variable and work with in the following code.

I might be able to solve this with the find() function, but how can I tell the code, that I only want the ip adress, and not the full element of the array saved?
I thought about something like:

const ip = devices.find('00:17:88:65:f4:4d');

But this would only return the full element, if the syntax was correct.


问:
Visually move from one html element to another - Javascript
For context sake this a school work where I type text into input field and I get options from database that suggest items which have same letters as user has written. It has simple name database attached.

I receive AJAX response and make that into array of names.
I have ul element underneath search field and names which come from response I populate as li items in this ul list. This all works.
What I need is functionality when pressing up / down arrow keys to move from input field into those list items.

on my first try I chose to make datalist instead of ul and I populated datalist with option elements, this worked well as I could move from input to datalist options. However, further down the road I needed to attach event listeners to options which is not possible. Hence I then went to ul / li version.
I cant seem to be able to work out how can I switch from input element into li items.

what i have tryed:

I have eventlistener keydown on input field to check if DownArrow is pressed. This works. Then i tryed following (names is the id of ul).

```<code>let list = document.getElementById('names');
list.firstChild.focus();
list.firstChild.select();
</code>```

Here I get error that "list.firstChild.select is not a function" and im stuck.

link to current version

答:
Judging your code, the reason you get the error list.firstChild.select is not a function is because you try to use the focus() method on an element which does not have it. Basically, you can use it on an <input /> element, but it won't work on a
 item.

According to DOM level 2, only the following Elements have a focus method:

HTMLInputElement

HTMLSelectElement

HTMLTextAreaElement

HTMLAnchorElement

HTMLAreaElement

Body:
For context sake this a school work where I type text into input field and I get options from database that suggest items which have same letters as user has written. It has simple name database attached.

I receive AJAX response and make that into array of names.
I have ul element underneath search field and names which come from response I populate as li items in this ul list. This all works.
What I need is functionality when pressing up / down arrow keys to move from input field into those list items.

on my first try I chose to make datalist instead of ul and I populated datalist with option elements, this worked well as I could move from input to datalist options. However, further down the road I needed to attach event listeners to options which is not possible. Hence I then went to ul / li version.
I cant seem to be able to work out how can I switch from input element into li items.

what i have tryed:

I have eventlistener keydown on input field to check if DownArrow is pressed. This works. Then i tryed following (names is the id of ul).

let list = document.getElementById('names');
list.firstChild.focus();
list.firstChild.select();

Here I get error that "list.firstChild.select is not a function" and im stuck.

link to current version

Body:
Judging your code, the reason you get the error list.firstChild.select is not a function is because you try to use the focus() method on an element which does not have it. Basically, you can use it on an <input /> element, but it won't work on a <li> item.

According to DOM level 2, only the following Elements have a focus method:

HTMLInputElement

HTMLSelectElement

HTMLTextAreaElement

HTMLAnchorElement

HTMLAreaElement


问:
how to add rows to a data frame that are in another data frame by a column in pyspark
I have 2 dfs and i want to get the rows that in the second df to the first one.
but I want to add these rows only if the value in the cid column isnt in the first one .</p>

```<code>df1
x  y  z  cid
4  8  1  1
7  5  6  2
7  3  5  3

df2
x  y  z  cid
8  4  5  1
1  2  9  2
8  6  4  3
4  5  4  4

result:
x  y  z  cid
4  8  1  1
7  5  6  2
7  3  5  3
4  5  4  4
</code>```

答:
You can try below code.

```<code>from pyspark.sql.functions import *
# Create DataFrame df1
df1 = spark.createDataFrame([(4,8,1,1), (7,5,6,2), (7,3,5,3)], ["x", "y", "z", "cid"])

# Create DataFrame df2
df2 = spark.createDataFrame([(8,4,5,1), (1,2,9,2), (8,6,4,3), (4,5,4,4)], ["x", "y", "z", "cid"])

# Get the values from cid column from df1
col1 = df1.select(collect_set("cid")).collect()[0][0]

# Filter the dataframe df2 where cid values present in df2 but not in df1.
df3 = df2.filter(~df2["cid"].isin(col1))

# Union df1 and df3.
df4 = df1.union(df3)
df4.show()
</code>```

// Output

```<code>+---+---+---+---+
|  x|  y|  z|cid|
+---+---+---+---+
|  4|  8|  1|  1|
|  7|  5|  6|  2|
|  7|  3|  5|  3|
|  4|  5|  4|  4|
+---+---+---+---+
</code>```

I hope this helps.

Body:
I have 2 dfs and i want to get the rows that in the second df to the first one.
but I want to add these rows only if the value in the cid column isnt in the first one .

df1
x  y  z  cid
4  8  1  1
7  5  6  2
7  3  5  3

df2
x  y  z  cid
8  4  5  1
1  2  9  2
8  6  4  3
4  5  4  4

result:
x  y  z  cid
4  8  1  1
7  5  6  2
7  3  5  3
4  5  4  4

Body:
You can try below code.

from pyspark.sql.functions import *
# Create DataFrame df1
df1 = spark.createDataFrame([(4,8,1,1), (7,5,6,2), (7,3,5,3)], ["x", "y", "z", "cid"])

# Create DataFrame df2
df2 = spark.createDataFrame([(8,4,5,1), (1,2,9,2), (8,6,4,3), (4,5,4,4)], ["x", "y", "z", "cid"])

# Get the values from cid column from df1
col1 = df1.select(collect_set("cid")).collect()[0][0]

# Filter the dataframe df2 where cid values present in df2 but not in df1.
df3 = df2.filter(~df2["cid"].isin(col1))

# Union df1 and df3.
df4 = df1.union(df3)
df4.show()

// Output

+---+---+---+---+
|  x|  y|  z|cid|
+---+---+---+---+
|  4|  8|  1|  1|
|  7|  5|  6|  2|
|  7|  3|  5|  3|
|  4|  5|  4|  4|
+---+---+---+---+

I hope this helps.


问:
Apply CSS class to Pandas DataFrame using to_html
I'm having trouble applying "classes" argument with Pandas "to_html" method to style a DataFrame.

"classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table"
from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html

I am able to render a styled DataFrame like this (for example):

```<code>df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])

myhtml = df.style.set_properties(**{'font-size': '11pt', 'font-family': 'Calibri','border-collapse': 'collapse','border': '1px solid black'}).render()

with open('myhtml.html','w') as f:
    f.write(myhtml)
</code>```

How can I style html output from a DataFrame using "classes" with "to_html" like this:

```<code>df.to_html('myhtml.html',classes=<something here>)
</code>```

答:
I found the most precise, and frankly the easiest way of doing it is skipping the styling, to_html() etc. and converting the DF to a dictionary using the df.to_dict() method.

Specifically what gave me trouble, was displaying the styled pandas html in an outlook email, as it just wouldn't render properly with the css mess that pandas was producing.

iterate over the dict and generate the html there by simply wrapping keys/values in the tags that you need, adding classes etc. and concatenate this all into one string.
Then paste this str into a prepared template with a predefined css.

For convenience I found it's useful to export the same df twice, using .to_dict() and to_dict('index') to first fill in the columns and then work your way down row by row. Alternatively just have a list of relevant column names.

```<code>dict_data = [df.to_dict(), df.to_dict('index')]

return_str = '<table><tr>'

for key in dict_data[0].keys():
    return_str = return_str + '<th class="header">' + key + '</th>'

return_str = return_str + '</tr>'

for key in dict_data[1].keys():
    return_str = return_str + '<tr><th class="index">' + key + '</th>'
    for subkey in dict_data[1][key]:
        return_str = return_str + '<td>' + dict_data[1][key][subkey] + '</td>'

return_str = return_str + '</tr></table>'
</code>```

and then return_str goes into the template.

Body:
I'm having trouble applying "classes" argument with Pandas "to_html" method to style a DataFrame.

"classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table"
from: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html

I am able to render a styled DataFrame like this (for example):

df = pd.DataFrame([[1, 2], [1, 3], [4, 6]], columns=['A', 'B'])

myhtml = df.style.set_properties(**{'font-size': '11pt', 'font-family': 'Calibri','border-collapse': 'collapse','border': '1px solid black'}).render()

with open('myhtml.html','w') as f:
    f.write(myhtml)

How can I style html output from a DataFrame using "classes" with "to_html" like this:

df.to_html('myhtml.html',classes=<something here>)

Body:
I found the most precise, and frankly the easiest way of doing it is skipping the styling, to_html() etc. and converting the DF to a dictionary using the df.to_dict() method.

Specifically what gave me trouble, was displaying the styled pandas html in an outlook email, as it just wouldn't render properly with the css mess that pandas was producing.

iterate over the dict and generate the html there by simply wrapping keys/values in the tags that you need, adding classes etc. and concatenate this all into one string.
Then paste this str into a prepared template with a predefined css.

For convenience I found it's useful to export the same df twice, using .to_dict() and to_dict('index') to first fill in the columns and then work your way down row by row. Alternatively just have a list of relevant column names.

dict_data = [df.to_dict(), df.to_dict('index')]

return_str = '<table><tr>'

for key in dict_data[0].keys():
    return_str = return_str + '<th class="header">' + key + '</th>'

return_str = return_str + '</tr>'

for key in dict_data[1].keys():
    return_str = return_str + '<tr><th class="index">' + key + '</th>'
    for subkey in dict_data[1][key]:
        return_str = return_str + '<td>' + dict_data[1][key][subkey] + '</td>'

return_str = return_str + '</tr></table>'

and then return_str goes into the template.


问:
LINQ - Will FirstOrDefault() always return the same record?
if I have the following 'User' table

```<code>UserName UserID
-------- ------
abc      1
xyz      2
pqr      2

</code>```

and the following linq query:

```<code>_context.User.OrderByDescending(x => x.UserID).FirstOrDefault();
</code>```

will the result always be consistent?

as in will I always get either user with UserName 'xyz' or user with UserName 'pqr' or will it be random?

答:
In this case, it will not be random, after using OrderByDescending on UserID from table Users having duplicate UserID, the other dependent column will appear in the final list in the same order as it was in the User Table.

for eg.  If this was the order in the table

```<code>UserName UserID
-------- ------
abc      1
pqr      2
xyz      2
</code>```

and the following linq query:

```<code>_context.User.OrderByDescending(x => x.UserID).FirstOrDefault();
</code>```

Will give Output : user with pqr

Hope this helps.

Body:
if I have the following 'User' table

UserName UserID
-------- ------
abc      1
xyz      2
pqr      2

and the following linq query:

_context.User.OrderByDescending(x => x.UserID).FirstOrDefault();

will the result always be consistent?

as in will I always get either user with UserName 'xyz' or user with UserName 'pqr' or will it be random?

Body:
In this case, it will not be random, after using OrderByDescending on UserID from table Users having duplicate UserID, the other dependent column will appear in the final list in the same order as it was in the User Table.

for eg.  If this was the order in the table

UserName UserID
-------- ------
abc      1
pqr      2
xyz      2

and the following linq query:

_context.User.OrderByDescending(x => x.UserID).FirstOrDefault();

Will give Output : user with pqr

Hope this helps.


问:
In etcd v3.0.x, how do I request all keys with a given prefix?
In etcd 3.0.x, a new API was introduced, and I'm just reading up on it. One thing is unclear to me, in the RangeRequest object. In the description of the property range_end, it says:

If the range_end is one bit larger than the given key,
  then the range requests get the all keys with the prefix (the given key).

Here is the complete text, to provide some context:

```<code>// key is the first key for the range. If range_end is not given, the request only looks up key.
bytes key = 1;
// range_end is the upper bound on the requested range [key, range_end).
// If range_end is '\0', the range is all keys >= key.
// If the range_end is one bit larger than the given key,
// then the range requests get the all keys with the prefix (the given key).
// If both key and range_end are '\0', then range requests returns all keys.
bytes range_end = 2;
</code>```

My question is: What is meant by

If the range_end is one bit larger than the given key

? Does it mean that range_end is 1 bit longer than key? Does it mean it must be key+1 when interpreted as integer? If the latter, in which encoding?

答:
A great TypeScript example here: https://github.com/mixer/etcd3/blob/7691f9bf227841e268c3aeeb7461ad71872df878/src/util.ts#L25

work js example with TextEncoder/TextDecoder:

```<code>function endRangeForPrefix(value) {
    let textEncoder = new TextEncoder();
    let encodeValue = textEncoder.encode(value);

    for (let i = encodeValue.length - 1; i >= 0; i--) {
        if (encodeValue[i] < 0xff) {
            encodeValue[i]++;
            encodeValue = encodeValue.slice(0, i + 1);

            let textDecoder = new TextDecoder();
            let decode = textDecoder.decode(encodeValue);
            return decode;
        }
    }

    return '';
}
</code>```

Body:
In etcd 3.0.x, a new API was introduced, and I'm just reading up on it. One thing is unclear to me, in the RangeRequest object. In the description of the property range_end, it says:

If the range_end is one bit larger than the given key,
  then the range requests get the all keys with the prefix (the given key).

Here is the complete text, to provide some context:

// key is the first key for the range. If range_end is not given, the request only looks up key.
bytes key = 1;
// range_end is the upper bound on the requested range [key, range_end).
// If range_end is '\0', the range is all keys >= key.
// If the range_end is one bit larger than the given key,
// then the range requests get the all keys with the prefix (the given key).
// If both key and range_end are '\0', then range requests returns all keys.
bytes range_end = 2;

My question is: What is meant by

If the range_end is one bit larger than the given key

? Does it mean that range_end is 1 bit longer than key? Does it mean it must be key+1 when interpreted as integer? If the latter, in which encoding?

Body:
A great TypeScript example here: https://github.com/mixer/etcd3/blob/7691f9bf227841e268c3aeeb7461ad71872df878/src/util.ts#L25

work js example with TextEncoder/TextDecoder:

function endRangeForPrefix(value) {
    let textEncoder = new TextEncoder();
    let encodeValue = textEncoder.encode(value);

    for (let i = encodeValue.length - 1; i >= 0; i--) {
        if (encodeValue[i] < 0xff) {
            encodeValue[i]++;
            encodeValue = encodeValue.slice(0, i + 1);

            let textDecoder = new TextDecoder();
            let decode = textDecoder.decode(encodeValue);
            return decode;
        }
    }

    return '';
}


问:
php.ini wont work outside public_html directory
Just very quick question about php.ini file. I created my own on my php.ini file and it works fine if I put it inside my 'public_html' directory. However the problem is it can obviously be viewed in browser through HTTP requests.

So, I am trying to move it outside my 'public_html' directory however it does not seem to work when outside my 'public_html'.

I know I could perhaps set in my .htaccess the following to avoid it being read:

```<code><Files php.ini>
  Order allow,deny
  Deny from all
</Files>
</code>```

However I do not want to do this as my php.ini can still get cached by Google if it's in the 'public_html' directory. Is there any suggestions to make it work outside my public_html?

I am running an Apache server. Thanks for any suggestions

答:
How is it that you php.ini came to be in a web server accessible folder? It is the first time I hear of such a situation.

I thought hard on how you managed to do this, and the only answer I came up with is that you created a vhost in php folder. If that is the case, create another vhost out of the php.ini path, and remove the offending vhost.  See this post for examples.

Body:
Just very quick question about php.ini file. I created my own on my php.ini file and it works fine if I put it inside my 'public_html' directory. However the problem is it can obviously be viewed in browser through HTTP requests.

So, I am trying to move it outside my 'public_html' directory however it does not seem to work when outside my 'public_html'.

I know I could perhaps set in my .htaccess the following to avoid it being read:

<Files php.ini>
  Order allow,deny
  Deny from all
</Files>

However I do not want to do this as my php.ini can still get cached by Google if it's in the 'public_html' directory. Is there any suggestions to make it work outside my public_html?

I am running an Apache server. Thanks for any suggestions


问:
Add items to an existing list mvc5
(I am a new developer)I have a list that I put in a viewBag to make a dropwdown in my view and I would like to add 3 elements to this list so that we can see them at the end of my dropdown. I make a timesheet for the employees and I have a dropdown of the projects that the person worked during the week and I would like to add at the end of the dropdown the 3 options "Vacancy", "Unplanned Absence", "Planned Absence" if the person has been on leave instead of working.

This is my request for the projects :

```<code>var projectAssignment = (from pa in db.ProjectAssignment
                                     join p in db.Projects on pa.ProjectId equals p.ID
                                     where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
                                     select new ProjectTimesheetList
                                     {
                                         ProjectName = p.ProjectName,
                                         ProjectId = pa.ProjectId
                                     });
ViewBag.ProjectTimeSHeet = projectAssignment;
</code>```

This is a the modal to add my timehseet and i want to put the 3 daysoff type at the end of dropdown, so in this case after "NatureBooker"

And this is my code of my dropdown:

```<code><select name="' + row + '_' + col + '" class="custom-select" id="tsCell_' + row + '_' + col + '" data-row="' + row + '" data-col="' + col + '">' +
                    '<option value="">----Select----</option>@Html.Raw(projsStr)</select>';
</code>```

SOLUTION:

```<code>var projectAssignment = (from pa in db.ProjectAssignment
                                     join p in db.Projects on pa.ProjectId equals p.ID
                                     where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
                                     select new ProjectTimesheetList
                                     {
                                         ProjectName = p.ProjectName,
                                         ProjectId = pa.ProjectId
                                     });

            List<ProjectTimesheetList> projectAssignments = projectAssignment.ToList();

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Vacancy",
                ProjectId = -1,
            });

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Unplanned Absence",
                ProjectId = -2,
            });

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Planned Absence",
                ProjectId = -3,
            });

            ViewBag.ProjectTimeSHeet = projectAssignments;
</code>```

And the result:

答:
```<code>var myOptions = {
    val1 : 'Vacancy',
    val2 : 'Unplanned Absence',
    val3 : 'Planned Absence',
};
var mySelect = $('#dropdownID');
$.each(myOptions, function(val, text) {
    mySelect.append(
        $('<option></option>').val(val).html(text)
    );
});
</code>```

through Javascript

```<code>  var ddl = document.getElementById("dropdownID");
   for ( let key in myOptions )
   {
        var option = document.createElement("OPTION");
        option.innerHTML = key
        option.value = myOptions[key]
        ddl.options.add(option);
    }
</code>```

Title: Add items to an existing list mvc5

Body:
(I am a new developer)I have a list that I put in a viewBag to make a dropwdown in my view and I would like to add 3 elements to this list so that we can see them at the end of my dropdown. I make a timesheet for the employees and I have a dropdown of the projects that the person worked during the week and I would like to add at the end of the dropdown the 3 options "Vacancy", "Unplanned Absence", "Planned Absence" if the person has been on leave instead of working.

This is my request for the projects :

var projectAssignment = (from pa in db.ProjectAssignment
                                     join p in db.Projects on pa.ProjectId equals p.ID
                                     where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
                                     select new ProjectTimesheetList
                                     {
                                         ProjectName = p.ProjectName,
                                         ProjectId = pa.ProjectId
                                     });
ViewBag.ProjectTimeSHeet = projectAssignment;

This is a the modal to add my timehseet and i want to put the 3 daysoff type at the end of dropdown, so in this case after "NatureBooker"

And this is my code of my dropdown:

<select name="' + row + '_' + col + '" class="custom-select" id="tsCell_' + row + '_' + col + '" data-row="' + row + '" data-col="' + col + '">' +
                    '<option value="">----Select----</option>@Html.Raw(projsStr)</select>';

SOLUTION:

var projectAssignment = (from pa in db.ProjectAssignment
                                     join p in db.Projects on pa.ProjectId equals p.ID
                                     where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
                                     select new ProjectTimesheetList
                                     {
                                         ProjectName = p.ProjectName,
                                         ProjectId = pa.ProjectId
                                     });

            List<ProjectTimesheetList> projectAssignments = projectAssignment.ToList();

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Vacancy",
                ProjectId = -1,
            });

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Unplanned Absence",
                ProjectId = -2,
            });

            projectAssignments.Add(new ProjectTimesheetList
            {
                ProjectName = "Planned Absence",
                ProjectId = -3,
            });

            ViewBag.ProjectTimeSHeet = projectAssignments;

And the result:

Body:
var myOptions = {
    val1 : 'Vacancy',
    val2 : 'Unplanned Absence',
    val3 : 'Planned Absence',
};
var mySelect = $('#dropdownID');
$.each(myOptions, function(val, text) {
    mySelect.append(
        $('<option></option>').val(val).html(text)
    );
});

through Javascript

  var ddl = document.getElementById("dropdownID");
   for ( let key in myOptions )
   {
        var option = document.createElement("OPTION");
        option.innerHTML = key
        option.value = myOptions[key]
        ddl.options.add(option);
    }


问:
JSON not reading escape symbols from DB
So, I got values from DB @Table that contains column with String value and json in it. But as I try to map it with ObjectMapper.writeValueAsString() all i get is this (Also implying that those escape symbols as backward slashes are in a string):

\"list\" [ \"key\":\"value\", ...  , \"key\":\"value\"] }

It also appears that @Entity class have other fields as that table columns, but they seem to map okay, without escape symbols inside a String

Any idea why that happens? Thanks in advance

答:
Try

```<code>String yourJson = "{Key:\\'aa'}";
String a = yourJson.replace("\\","");
System.out.println(a);
</code>```

Similar:
unclosed string literal error at compile time because it contains double quotes and pre tags of HTML

Title: JSON not reading escape symbols from DB

Body:
Try

String yourJson = "{Key:\\'aa'}";
String a = yourJson.replace("\\","");
System.out.println(a);

Similar:
unclosed string literal error at compile time because it contains double quotes and pre tags of HTML


问:
Running Elasticsearch within Gitlab CI as non-root user
Since version 6 it's not possible anymore to start Elasticsearch as a root user. Before that, there was es.insecure.allow.root flag which could be used for that. Now due to security reasons the ES team decided to disable that option completely.

The problem arises when you use Gitlab CI runner based on docker executor and you want to run Elasticsearch in it. script section of your CI job is executed by root user. Changing the user is not possible when using docker executor. Starting ES as root is not allowed. So how to fix that?

答:
I did not find an answer so I'm going to post  one here. I encountered this problem on my Ruby on Rails project so this example will be based on RoR. I had to run elasticsearch from the inside of RSpec and https://github.com/elastic/elasticsearch-ruby/tree/master/elasticsearch-extensions gem helped me with that. Configuring the gem is a bit out of the scope so I'm going to skip this part.

The key is to create a new non-root user inside the docker image you're using for Gitlab CI. This means using a custom image or updating your image if you're using a custom one already.

The following is the example that worked for me.

Dockerfile

```<code>FROM ruby:2.5.1-stretch

# install elasticsearch
RUN wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.5.2-amd64.deb
RUN wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.5.2-amd64.deb.sha512
RUN shasum -a 512 -c elasticsearch-7.5.2-amd64.deb.sha512
RUN dpkg -i elasticsearch-7.5.2-amd64.deb

# adjust ownership and permissions to make it possible to run elasticsearch as a custom user
RUN chmod -R 750 /usr/share/elasticsearch/bin
RUN chmod -R 770 /var/log/elasticsearch
RUN chown elasticsearch:elasticsearch -R /usr/share/elasticsearch
RUN chown elasticsearch:elasticsearch -R /var/log/elasticsearch
RUN chown elasticsearch:elasticsearch -R /var/lib/elasticsearch
RUN chown elasticsearch:elasticsearch -R /etc/default/elasticsearch
RUN chown elasticsearch:elasticsearch -R /etc/elasticsearch

# create a user and add it to elasticsearch group
RUN useradd non_root -m
RUN usermod -a -G elasticsearch non_root

# select this user to make it run gitlab script section instead of root
USER non_root
</code>```

.gitlab-ci.yml

```<code>image: your_image

your_job:
  script:
    # run elasticsearch here
</code>```

Body:
I did not find an answer so I'm going to post  one here. I encountered this problem on my Ruby on Rails project so this example will be based on RoR. I had to run elasticsearch from the inside of RSpec and https://github.com/elastic/elasticsearch-ruby/tree/master/elasticsearch-extensions gem helped me with that. Configuring the gem is a bit out of the scope so I'm going to skip this part.

The key is to create a new non-root user inside the docker image you're using for Gitlab CI. This means using a custom image or updating your image if you're using a custom one already.

The following is the example that worked for me.

Dockerfile

FROM ruby:2.5.1-stretch

# install elasticsearch
RUN wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.5.2-amd64.deb
RUN wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.5.2-amd64.deb.sha512
RUN shasum -a 512 -c elasticsearch-7.5.2-amd64.deb.sha512
RUN dpkg -i elasticsearch-7.5.2-amd64.deb

# adjust ownership and permissions to make it possible to run elasticsearch as a custom user
RUN chmod -R 750 /usr/share/elasticsearch/bin
RUN chmod -R 770 /var/log/elasticsearch
RUN chown elasticsearch:elasticsearch -R /usr/share/elasticsearch
RUN chown elasticsearch:elasticsearch -R /var/log/elasticsearch
RUN chown elasticsearch:elasticsearch -R /var/lib/elasticsearch
RUN chown elasticsearch:elasticsearch -R /etc/default/elasticsearch
RUN chown elasticsearch:elasticsearch -R /etc/elasticsearch

# create a user and add it to elasticsearch group
RUN useradd non_root -m
RUN usermod -a -G elasticsearch non_root

# select this user to make it run gitlab script section instead of root
USER non_root

.gitlab-ci.yml

image: your_image

your_job:
  script:
    # run elasticsearch here


问:
C#: How to keep track of the UID of messages between folders?
I'm moving messages from the inbox folder to a new folder. After a while I need to move some of these messages(not all) to a new folder. The problem with this is that everytime I move a message the uid changes. How can I do this without moving the wrong message?</p>

答:
If your server supports UIDPLUS (nearly all do), and you yourself are moving or copying the messages, the server will give you the new UID when you copy or move it in the COPYUID response.  You'll need to record this.

An example from the IMAP MOVE RFC6851:

```<code>   C: a UID MOVE 42:69 foo
   S: * OK [COPYUID 432432 42:69 1202:1229]
   S: * 22 EXPUNGE
   S: (more expunges)
   S: a OK Done
</code>```

The COPYUID response includes the UIDVALIDITY of the destination mail box, the UID set of the source messages, and the UID set of the destination messages.

If some other process is doing the moving, there's no way to guarantee the same message, and you'd have to track them based on their content (eg, the Message-ID header, the date time, a hash, etc.)

Body:
If your server supports UIDPLUS (nearly all do), and you yourself are moving or copying the messages, the server will give you the new UID when you copy or move it in the COPYUID response.  You'll need to record this.

An example from the IMAP MOVE RFC6851:

   C: a UID MOVE 42:69 foo
   S: * OK [COPYUID 432432 42:69 1202:1229]
   S: * 22 EXPUNGE
   S: (more expunges)
   S: a OK Done

The COPYUID response includes the UIDVALIDITY of the destination mail box, the UID set of the source messages, and the UID set of the destination messages.

If some other process is doing the moving, there's no way to guarantee the same message, and you'd have to track them based on their content (eg, the Message-ID header, the date time, a hash, etc.)


问:
Why is my input repeating multiple times?
I am currently making a project just for the sake of bettering my skills, but I have ran into a very confusing problem. When I run the first section, Encode, it all works properly and how I would like it to. But when I run the second section, Decode, it asks for a number between one and 12, and the message twice. Can anyone help me understand why this is occurring?</p>

```<code>import sys
import string
k = input('Enter keycode: ')
if k == '220997332':
    print('|E1-D12| |E2-D11||E3-D10| |E4-D9| |E5-D8| |E6-D7| |E7-D6| |E8-D5| |E9-D4| |E10-D3| |E11-D2| |E12-D1|')
    y = input('D for Decode |OR| E for Encode: ')
    if y == 'E' or 'e':
        x = input('Enter you message: ')
        z = input('Enter any number between 1-12: ')
        if z == '1':
            str1 = "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz,.?!:;"
            str1key ="QETUO{|ADGJL'ZCBM>WRIYP}SFHK:XVN!@#$%^&*()_+-=~`;][1490563"
            q = x.maketrans(str1, str1key)
            print(x.translate(q))
            sys.exit()
    if y == 'D' or 'd':
        X = input('Enter you message: ')
        Z = input('Enter any number between 1-12: ')
        if Z == '12':
            str12 ="QETUO{|ADGJL'ZCBM>WRIYP}SFHK:XVN!@#$%^&*()_+-=~`;][1490563"
            str12key = "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz,.?!:;"
            Q = X.maketrans(str12, str12key)
            print(x.translate(Q))
            sys.exit()
</code>```

答:
The problem is in the If condition. No matter what the user enters e or d or anything both the if blocks will be executed because the condition says that either (y=='E') should be true or ('e') should be true. and bool('e') is always true. The same happens with the next if block which is if (y=='D') or ('d').

To fix this you just need to correct the condition as if y=='E' or y=='e' and the same for the decoding.

For clearing your doubt, why it doesn't print message twice in encoding is because on the successful execution of encoding it runs sys.exit() which stops the program execution and skips rest of the code.

Hope this helps!!

Body:
I am currently making a project just for the sake of bettering my skills, but I have ran into a very confusing problem. When I run the first section, Encode, it all works properly and how I would like it to. But when I run the second section, Decode, it asks for a number between one and 12, and the message twice. Can anyone help me understand why this is occurring?

import sys
import string
k = input('Enter keycode: ')
if k == '220997332':
    print('|E1-D12| |E2-D11||E3-D10| |E4-D9| |E5-D8| |E6-D7| |E7-D6| |E8-D5| |E9-D4| |E10-D3| |E11-D2| |E12-D1|')
    y = input('D for Decode |OR| E for Encode: ')
    if y == 'E' or 'e':
        x = input('Enter you message: ')
        z = input('Enter any number between 1-12: ')
        if z == '1':
            str1 = "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz,.?!:;"
            str1key ="QETUO{|ADGJL'ZCBM>WRIYP}SFHK:XVN!@#$%^&*()_+-=~`;][1490563"
            q = x.maketrans(str1, str1key)
            print(x.translate(q))
            sys.exit()
    if y == 'D' or 'd':
        X = input('Enter you message: ')
        Z = input('Enter any number between 1-12: ')
        if Z == '12':
            str12 ="QETUO{|ADGJL'ZCBM>WRIYP}SFHK:XVN!@#$%^&*()_+-=~`;][1490563"
            str12key = "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz,.?!:;"
            Q = X.maketrans(str12, str12key)
            print(x.translate(Q))
            sys.exit()


问:
Create dbpedia subset and host it locally
I need to create and locally host a subset of dbpedia data which should only contain geographical information. Like of countries, rivers etc.

I found resources for setting up a Linked Data mirror from RDF dumps, but I cannot understand how to subset the data.

答: I created a SPARQL queries and dumped the results in RDF format, which later I was able to host locally by loading the data on a virtuoso server. For my use-case that was enough.</p>


问:
How do I add a string to each key of a dictionary?
I have a dictionary where each key is composed of a string eg. ['ba'] and each value is list of numbers eg. [1, 2, 3, 4,].

I would like to loop through each key and if the number is >= 100, I would like to add "D" in front of each number eg. 'D123, and if the number is <100, I would like to add "DI" to the front eg. 'DI45". I've written the following code but it doesn't change the dictionary.

```<code>def dict_change(dicto):
    for key,value in dicto.items():
        for numb in value:
            if numb >= 100:
                numb = 'D' + str(numb)
            else:
                numb = 'DI' + str(numb)
    return dicto

new_dict = dict_change(old_dict)
</code>```

Thank you! :)

答:
def dict_change(dicto):
    modified_dict = {}
    for key,value in dicto.items():
        key_tuple = tuple((('D' if no>100 else 'DI')+ str(no) for no in key))
        modified_dict[key_tuple] = value
    return modified_dict

old_dict = {(110, 12, 13, 14, 15, 101): 'ba', (12, 126, -127, 128): 'pa'}
print(dict_change(old_dict))
```

<p>Output  </p>

```{('D110', 'DI12', 'DI13', 'DI14', 'DI15', 'D101'): 'ba', ('DI12', 'D126', 'DI-127', 'D128'): 'pa'}
```

Body:
I have a dictionary where each key is composed of a string eg. ['ba'] and each value is list of numbers eg. [1, 2, 3, 4,].

I would like to loop through each key and if the number is >= 100, I would like to add "D" in front of each number eg. 'D123, and if the number is <100, I would like to add "DI" to the front eg. 'DI45". I've written the following code but it doesn't change the dictionary.

def dict_change(dicto):
    for key,value in dicto.items():
        for numb in value:
            if numb >= 100:
                numb = 'D' + str(numb)
            else:
                numb = 'DI' + str(numb)
    return dicto

new_dict = dict_change(old_dict)

Thank you! :)

Body:
def dict_change(dicto):
    modified_dict = {}
    for key,value in dicto.items():
        key_tuple = tuple((('D' if no>100 else 'DI')+ str(no) for no in key))
        modified_dict[key_tuple] = value
    return modified_dict

old_dict = {(110, 12, 13, 14, 15, 101): 'ba', (12, 126, -127, 128): 'pa'}
print(dict_change(old_dict))

Output

{('D110', 'DI12', 'DI13', 'DI14', 'DI15', 'D101'): 'ba', ('DI12', 'D126', 'DI-127', 'D128'): 'pa'}


问:
How to create or verify ElementRangeIndexes in Marklogic from Flyway script
How to create or verify ElementRangeIndexes in Marklogic from Flyway script. It is a pain to remember the elementRangeIndex to be manually don eon every Marklogic DB we migrate.</p>

答:
You may be able to use the Flyway gradle plugin, to execute ml-gradle configuration scripts.

Alternatively, you can use gradle to execute curl commands and create the indexes using the MarkLogic Management API endpoints.

An example of using Curl to define an index taken from Learning the MarkLogic REST API:

```<code>curl -X PUT  --anyauth --user admin:admin --header "Content-Type:application/json" \
-d '{"word-positions": true,
     "element-word-positions": true,
     "range-element-index":
    [ { "scalar-type": "string",
        "namespace-uri": "",
        "localname": "SPEAKER",
        "collation": "http://marklogic.com/collation/",
        "range-value-positions": false,
        "invalid-values": "reject"
      },
      { "scalar-type": "string",
        "namespace-uri": "",
        "localname": "affiliation",
        "collation": "http://marklogic.com/collation/",
        "range-value-positions": false,
        "invalid-values": "reject"
      },
      { "scalar-type": "int",
        "namespace-uri": "",
        "localname": "contentRating",
        "collation": "",
        "range-value-positions": false,
        "invalid-values": "reject"
      },
      { "scalar-type": "unsignedLong",
        "namespace-uri": "http://marklogic.com/filter",
        "localname": "size",
        "collation": "",
        "range-value-positions": false,
        "invalid-values": "reject"
      },
      { "scalar-type": "string",
        "namespace-uri": "http://marklogic.com/filter",
        "localname": "Exposure_Time",
        "collation": "http://marklogic.com/collation/",
        "range-value-positions": false,
        "invalid-values": "reject"
      }]}' \
http://localhost:8002/manage/v2/databases/TutorialDB/properties
</code>```

Body:
You may be able to use the Flyway gradle plugin, to execute ml-gradle configuration scripts.

Alternatively, you can use gradle to execute curl commands and create the indexes using the MarkLogic Management API endpoints.

An example of using Curl to define an index taken from Learning the MarkLogic REST API:

curl -X PUT  --anyauth --user admin:admin --header "Content-Type:application/json" \
-d '{"word-positions": true,
     "element-word-positions": true,
     "range-element-index":
    [ { "scalar-type": "string",
        "namespace-uri": "",
        "localname": "SPEAKER",
        "collation": "http://marklogic.com/collation/",
        "range-value-positions": false,
        "invalid-values": "reject"
      },
      { "scalar-type": "string",
        "namespace-uri": "",
        "localname": "affiliation",
        "collation": "http://marklogic.com/collation/",
        "range-value-positions": false,
        "invalid-values": "reject"
      },
      { "scalar-type": "int",
        "namespace-uri": "",
        "localname": "contentRating",
        "collation": "",
        "range-value-positions": false,
        "invalid-values": "reject"
      },
      { "scalar-type": "unsignedLong",
        "namespace-uri": "http://marklogic.com/filter",
        "localname": "size",
        "collation": "",
        "range-value-positions": false,
        "invalid-values": "reject"
      },
      { "scalar-type": "string",
        "namespace-uri": "http://marklogic.com/filter",
        "localname": "Exposure_Time",
        "collation": "http://marklogic.com/collation/",
        "range-value-positions": false,
        "invalid-values": "reject"
      }]}' \
http://localhost:8002/manage/v2/databases/TutorialDB/properties


问:
onActivityResult() never called
I have a problem with onActivityResult() and setResult().

I started android development 1 week ago so sorry.

Could you help me?

here is a snippet of my code :

ListActivity function Click

```<code>    val myadapter = ItemAdapter();
    list_recycler_view.layoutManager = LinearLayoutManager(this)
    list_recycler_view.adapter = myadapter
    val me = this;
        myadapter.setOnItemClickListener(object : ItemAdapter.OnItemClickListener {
            override fun onItemClick(item: Item) {
                val intent = Intent(me, DetailActivity::class.java)
                intent.putExtra("item", item)
                startActivityForResult(intent, 2)
            }
        })
</code>```

List activity function onActivityResult

```<code>    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.d("reponse","coucou5");
        Log.d("reponse",requestCode.toString());
        Log.d("reponse",resultCode.toString());
        if (requestCode == 2 && resultCode == RESULT_OK) {

            val item = data?.getParcelableExtra<Item>("item") as Item
            Log.d("reponse-update",item.toString());
            if (item == null) {
                Toast.makeText(this, "Could not update! Error!", Toast.LENGTH_SHORT).show()
            }

            //ItemListViewModel.update(item);

        } else {
            Toast.makeText(this, "Note not saved!", Toast.LENGTH_SHORT).show()
        }
    }
</code>```

DetailActivity function on click

```<code>     btnSave.setOnClickListener{
            //other props
            item.gid = gid;
            item.distance = distance
            Log.d("reponse",item.toString());
            Log.d("reponse","coucou4");
            val returnIntent = intent
            returnIntent.putExtra("item", item)
            setResult(Activity.RESULT_OK, returnIntent)
            finish()
        }
</code>```

it seems that the onActivityResult() is never called

答:
Replace </p>

```<code>val returnIntent = intent
</code>```

<p>For </p>

```<code>val returnIntent = new Intent()
</code>```

Title: onActivityResult() never called

Body:
I have a problem with onActivityResult() and setResult().

I started android development 1 week ago so sorry.

Could you help me?

here is a snippet of my code :

ListActivity function Click

    val myadapter = ItemAdapter();
    list_recycler_view.layoutManager = LinearLayoutManager(this)
    list_recycler_view.adapter = myadapter
    val me = this;
        myadapter.setOnItemClickListener(object : ItemAdapter.OnItemClickListener {
            override fun onItemClick(item: Item) {
                val intent = Intent(me, DetailActivity::class.java)
                intent.putExtra("item", item)
                startActivityForResult(intent, 2)
            }
        })

List activity function onActivityResult

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.d("reponse","coucou5");
        Log.d("reponse",requestCode.toString());
        Log.d("reponse",resultCode.toString());
        if (requestCode == 2 && resultCode == RESULT_OK) {

            val item = data?.getParcelableExtra<Item>("item") as Item
            Log.d("reponse-update",item.toString());
            if (item == null) {
                Toast.makeText(this, "Could not update! Error!", Toast.LENGTH_SHORT).show()
            }

            //ItemListViewModel.update(item);

        } else {
            Toast.makeText(this, "Note not saved!", Toast.LENGTH_SHORT).show()
        }
    }

DetailActivity function on click

     btnSave.setOnClickListener{
            //other props
            item.gid = gid;
            item.distance = distance
            Log.d("reponse",item.toString());
            Log.d("reponse","coucou4");
            val returnIntent = intent
            returnIntent.putExtra("item", item)
            setResult(Activity.RESULT_OK, returnIntent)
            finish()
        }

it seems that the onActivityResult() is never called

Body:
Replace

val returnIntent = intent

For

val returnIntent = new Intent()


问:
Flutter test find by sub text
Is it possible to assert a test if the certain text is found either as full string match or as a sub string of other text?

I want the following test to pass as long as the string Foo is found anywhere, even as sub string of other strings. What should I change?

```<code>import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
  testWidgets('Find sub text', (WidgetTester tester) async {
    await tester.pumpWidget(Text('Error code is Foo', textDirection: TextDirection.ltr));
    expect(find.text('Error code is Foo'), findsOneWidget);
    expect(find.text('Foo'), findsOneWidget);
  });
}
</code>```

So far:

```<code>The following TestFailure object was thrown running a test:
  Expected: exactly one matching node in the widget tree
  Actual: _TextFinder:<zero widgets with text "Foo" (ignoring offstage widgets)>
   Which: means none were found but one was expected
</code>```

答:
Replace:

```<code>expect(find.text('Foo'), findsOneWidget);
</code>```

with:

```<code>expect(find.byWidgetPredicate((widget) {
  if (widget is Text) {
    final Text textWidget = widget;
    if (textWidget.data != null) return textWidget.data.contains('Foo');
    return textWidget.textSpan.toPlainText().contains('Foo');
  }
  return false;
}), findsOneWidget);
</code>```

You will first find Text widget, then check for substring in the Text string

Title: Flutter test find by sub text

Body:
Is it possible to assert a test if the certain text is found either as full string match or as a sub string of other text?

I want the following test to pass as long as the string Foo is found anywhere, even as sub string of other strings. What should I change?

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
  testWidgets('Find sub text', (WidgetTester tester) async {
    await tester.pumpWidget(Text('Error code is Foo', textDirection: TextDirection.ltr));
    expect(find.text('Error code is Foo'), findsOneWidget);
    expect(find.text('Foo'), findsOneWidget);
  });
}

So far:

The following TestFailure object was thrown running a test:
  Expected: exactly one matching node in the widget tree
  Actual: _TextFinder:<zero widgets with text "Foo" (ignoring offstage widgets)>
   Which: means none were found but one was expected

Body:
Replace:

expect(find.text('Foo'), findsOneWidget);

with:

expect(find.byWidgetPredicate((widget) {
  if (widget is Text) {
    final Text textWidget = widget;
    if (textWidget.data != null) return textWidget.data.contains('Foo');
    return textWidget.textSpan.toPlainText().contains('Foo');
  }
  return false;
}), findsOneWidget);

You will first find Text widget, then check for substring in the Text string