问:
Django validate answer for specific question
Overview:
    I want to build a Question-Answer website, where the user has to enter the correct answer for each question. I have made 3 models for this:

```<code>class ProblemSet(models.Model):
    id = models.IntegerField(primary_key=True)

class Problem(models.Model):
    id = models.IntegerField(primary_key=True)
    problem_set = models.ForeignKey(ProblemSet, on_delete=models.CASCADE)
    question = models.TextField()
    solution = models.TextField()

class Solve(models.Model):
    username = models.ForeignKey(User, on_delete=models.CASCADE)
    problem_set = models.ForeignKey(ProblemSet, on_delete=models.CASCADE)
    problem_id = models.ForeignKey(Problem, on_delete= models.CASCADE)
</code>```

In solve model, if there is any entry that means that particular user has solved that problem_id.
So, I have utilized the generic Form View:

```<code>class IndexView(FormView):
    form_class = ProblemForm
    template_name = 'home/index.html'
    success_url = reverse_lazy('index')

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        if self.request.user.is_authenticated:
            inner_qs = "fetch ids that are solved from Solve model"

            problem_obj = Problem.objects\
                            .exclude(id__in=inner_qs)\
                            .order_by('id').first()

        else:
            #do something

        context['question'] = problem_obj.question
        return context
</code>```

The problem form is:

```<code>from django import forms

class ProblemForm(forms.Form):
    solution = forms.CharField(widget=forms.TextInput())
</code>```

How do I validate that the user is inputting the correct answer? I do get the value of solution field in def form_valid(self, form) function but how should I deal with it? Should i pass question_id in context and query the database in form_valid, or should i pass solution itself to context and access context data in form_valid() method to prevent double query but in this method I am not sure if this is secure as I don't want solution to be passed to client.

Is there any elegant way of doing this?

P.S. After user entered solution is compared to the one in database for that question, I add an entry in the Solve table denoting that this particular user has solved the question id.

答:
The FormView is processing two separate requests: First the GET request when the student fetches the form with a question to answer. Then the POST request when the student submits her answer to the question.

Now HTTP is stateless so somehow you need to keep track of the question that was presented in the first request so you know which question was answered when receiving the POST request.

The easiest way I would say is to actually include the question_id in the form itself, as a hidden input field. There's not real security issue here: The question_id can be manipulated by the student even though it's hidden, but what's the point?

So this is what I would do:

Add problem as a ModelChoiceField with a HiddenInput widget to your ProblemForm.

```<code>problem = forms.ModelChoiceField(queryset=Problem.objects.all(), widget=forms.HiddenInput())
</code>```

Set an initial value for the problem in the get_inital() method of your IndexView:

```<code>def get_problem(self):  # use also in get_context_data() to add the question
    if hasattr(self, 'problem'):
        return self.problem
    if self.request.user.is_authenticated:
        inner_qs = "fetch ids that are solved from Solve model"
        self.problem = Problem.objects\
                        .exclude(id__in=inner_qs)\
                        .order_by('id').first()
        return self.problem

def get_initial(self):
    initial = super().get_initial()
    initial['problem'] = self.get_problem()}
    return initial
</code>```

When the form gets submitted and is valid, you'll see that form.cleaned_data['problem'] is the submitted problem. So you can use that in the form_valid() method:

```<code>def form_valid(self, form):
    problem = form.cleaned_data['problem']
    # check that it hasn't been solved by the user already
    if problem.answer == form.cleaned_data['solution']:
        # create solve object for the user
    return redirect(...)
</code>```

The alternative would be to not include it in the form but refetch the problem in form_valid (note that the problem is fetched in the above method as well, when the form maps the submitted problem_id to the actual problem instance to populate its cleaned_data).

Body:
Overview:
    I want to build a Question-Answer website, where the user has to enter the correct answer for each question. I have made 3 models for this:

class ProblemSet(models.Model):
    id = models.IntegerField(primary_key=True)

class Problem(models.Model):
    id = models.IntegerField(primary_key=True)
    problem_set = models.ForeignKey(ProblemSet, on_delete=models.CASCADE)
    question = models.TextField()
    solution = models.TextField()

class Solve(models.Model):
    username = models.ForeignKey(User, on_delete=models.CASCADE)
    problem_set = models.ForeignKey(ProblemSet, on_delete=models.CASCADE)
    problem_id = models.ForeignKey(Problem, on_delete= models.CASCADE)

In solve model, if there is any entry that means that particular user has solved that problem_id.
So, I have utilized the generic Form View:

class IndexView(FormView):
    form_class = ProblemForm
    template_name = 'home/index.html'
    success_url = reverse_lazy('index')

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        if self.request.user.is_authenticated:
            inner_qs = "fetch ids that are solved from Solve model"

            problem_obj = Problem.objects\
                            .exclude(id__in=inner_qs)\
                            .order_by('id').first()

        else:
            #do something

        context['question'] = problem_obj.question
        return context

The problem form is:

from django import forms

class ProblemForm(forms.Form):
    solution = forms.CharField(widget=forms.TextInput())

How do I validate that the user is inputting the correct answer? I do get the value of solution field in def form_valid(self, form) function but how should I deal with it? Should i pass question_id in context and query the database in form_valid, or should i pass solution itself to context and access context data in form_valid() method to prevent double query but in this method I am not sure if this is secure as I don't want solution to be passed to client.

Is there any elegant way of doing this?

P.S. After user entered solution is compared to the one in database for that question, I add an entry in the Solve table denoting that this particular user has solved the question id.

Body:
The FormView is processing two separate requests: First the GET request when the student fetches the form with a question to answer. Then the POST request when the student submits her answer to the question.

Now HTTP is stateless so somehow you need to keep track of the question that was presented in the first request so you know which question was answered when receiving the POST request.

The easiest way I would say is to actually include the question_id in the form itself, as a hidden input field. There's not real security issue here: The question_id can be manipulated by the student even though it's hidden, but what's the point?

So this is what I would do:

Add problem as a ModelChoiceField with a HiddenInput widget to your ProblemForm.

problem = forms.ModelChoiceField(queryset=Problem.objects.all(), widget=forms.HiddenInput())

Set an initial value for the problem in the get_inital() method of your IndexView:

def get_problem(self):  # use also in get_context_data() to add the question
    if hasattr(self, 'problem'):
        return self.problem
    if self.request.user.is_authenticated:
        inner_qs = "fetch ids that are solved from Solve model"
        self.problem = Problem.objects\
                        .exclude(id__in=inner_qs)\
                        .order_by('id').first()
        return self.problem

def get_initial(self):
    initial = super().get_initial()
    initial['problem'] = self.get_problem()}
    return initial

When the form gets submitted and is valid, you'll see that form.cleaned_data['problem'] is the submitted problem. So you can use that in the form_valid() method:

def form_valid(self, form):
    problem = form.cleaned_data['problem']
    # check that it hasn't been solved by the user already
    if problem.answer == form.cleaned_data['solution']:
        # create solve object for the user
    return redirect(...)

The alternative would be to not include it in the form but refetch the problem in form_valid (note that the problem is fetched in the above method as well, when the form maps the submitted problem_id to the actual problem instance to populate its cleaned_data).


来源: stackexchange

问:
VS Code: "Breakpoint ignored because generated code not found" error
I have looked everywhere and I still have issue debugging TypeScript inside VS Code. I have read this thread but still I am not able to hit my breakpoints placed inside a TypeScript file, hitting the breakpoints in .js files all works fine.

So here is the simplest "hello world" project I have set up.

app.ts:

```<code>var message: string = "Hello World";

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

tsconfig.json

```<code>{
    "compilerOptions": {
        "target": "es5",
        "sourceMap": true
    }
}
</code>```

launch.json

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/app.js",
            "stopOnEntry": false,
            "args": [],
            "cwd": "${workspaceRoot}",
            "preLaunchTask": null,
            "runtimeExecutable": null,
            "runtimeArgs": [
                "--nolazy"
            ],
            "env": {
                "NODE_ENV": "development"
            },
            "externalConsole": false,
            "sourceMaps": true,
            "outDir": null
        }
    ]
}
</code>```

I have generated the js.map files by running the tsc --sourcemap app.ts command.

After all of those steps when I set a breakpoint on the console.log(message); row and launch the program (F5) from the "Debug" tab that breakpoint is grayed out saying "Breakpoint ignored because generated code not found (source map problem?)." I attached a screenshot of what I am observing:

What am I missing?

Edit:

Hi, I am still stuck on this. I managed to make one sample project that was hitting the break points but after I tried to copy that project to a different location on my HDD the break points again became gray and were not hit. What I did different in this test project was to use inline sourcemaps by compiling the TypeScript files with tsc app.ts --inlinesourcemap

I uploaded the mentioned sample project to GitHub so you can take a look at it here.

答:
I changed my config in launch.json for:

{
      "name": "Debug tests in Chrome",
      "type": "chrome",
      "request": "attach",
      "port": 9222,
      "sourceMaps": true,
      "sourceMapPathOverrides": {
        "*": "${webRoot}/*"
      },
      "webRoot": "${workspaceRoot}"
    }

before was:

{
      "name": "Debug tests in Chrome",
      "type": "chrome",
      "request": "attach",
      "port": 9222,
      "sourceMaps": true,
      "webRoot": "${workspaceRoot}"
    }

Include '"sourceMapPathOverrides"' was my solution

ContentLicense: CC BY-SA 3.0

Body:
I have looked everywhere and I still have issue debugging TypeScript inside VS Code. I have read this thread but still I am not able to hit my breakpoints placed inside a TypeScript file, hitting the breakpoints in .js files all works fine.

So here is the simplest "hello world" project I have set up.

app.ts:

var message: string = "Hello World";

console.log(message);

tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "sourceMap": true
    }
}

launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/app.js",
            "stopOnEntry": false,
            "args": [],
            "cwd": "${workspaceRoot}",
            "preLaunchTask": null,
            "runtimeExecutable": null,
            "runtimeArgs": [
                "--nolazy"
            ],
            "env": {
                "NODE_ENV": "development"
            },
            "externalConsole": false,
            "sourceMaps": true,
            "outDir": null
        }
    ]
}

I have generated the js.map files by running the tsc --sourcemap app.ts command.

After all of those steps when I set a breakpoint on the console.log(message); row and launch the program (F5) from the "Debug" tab that breakpoint is grayed out saying "Breakpoint ignored because generated code not found (source map problem?)." I attached a screenshot of what I am observing:

What am I missing?

Edit:

Hi, I am still stuck on this. I managed to make one sample project that was hitting the break points but after I tried to copy that project to a different location on my HDD the break points again became gray and were not hit. What I did different in this test project was to use inline sourcemaps by compiling the TypeScript files with tsc app.ts --inlinesourcemap

I uploaded the mentioned sample project to GitHub so you can take a look at it here.

ContentLicense: CC BY-SA 4.0


问:
HTTP 500 error launcing ASP.NET 3.0 application
I have just upgraded our ASP.NET Core 2.2 web application to 3.0. It builds and deploys fine. The problem is when I go to run it from our IIS server. This was running perfectly fine as a Core 2.2 web app, but now fails since upgrading to Core 3.0.

When I launch the web app from the commandline there are no reported errors.

When I launch the application from the browser the Windows logs indicate that the app started correctly.

The app then fails with an HTTP 500 error. Here are the IIS log entries.

We're using Windows Server 2012 R2 with IIS 8.5.9600.16384

The app appears to start correctly but then fails with an HTTP 500 error. Has anyone else seen this or something similar? Any ideas how to diagnose / fix the problem?

UPDATE

I've attached the VS 2019 debugger to the deployed app via the w3wp.exe process and it's not even hitting any of the middleware (I have a breakpoint at Startup() in Startup.cs).

I've tried changing the application pool settings e.g. identity, .NET version but to no avail.

When I launch the site from the web server I get the following error message which doesn't really tell me anything.

I can't see what's causing the problem.

答: .NET Core 3.0 uses the in-process hosting model by default. You may need to upgrade the .NET Core Hosting Bundle.</p>


问:
What does a lock statement do under the hood?
I see that for using objects which are not thread safe we wrap the code with a lock like this:

```<code>private static readonly Object obj = new Object();

lock (obj)
{
    // thread unsafe code
}
</code>```

So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?

What is the performance impact because of using locks?

答: Locks will block other threads from executing the code contained in the lock block.  The threads will have to wait until the thread inside the lock block has completed and the lock is released.  This does have a negative impact on performance in a multithreaded environment.  If you do need to do this you should make sure the code within the lock block can process very quickly.  You should try to avoid expensive activities like accessing a database etc.</p>

Body:
I see that for using objects which are not thread safe we wrap the code with a lock like this:

private static readonly Object obj = new Object();

lock (obj)
{
    // thread unsafe code
}

So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?

What is the performance impact because of using locks?


问:
How to convert a list to json in python
have a list with values

```<code>test = ["mark","will","john"]

</code>```

using for loop how to convert this into JSON like this

```<code>test =[{"name":"mark"},{"name":"john"},{"name":"will"}]
</code>```

Tried this

```<code>for i in test :
    print({"name":i})

</code>```

答:
```<code>>>> test = ["mark","will","john"]
>>> final=[]
>>> for i in test:
    d=dict()
    d['name']=i
    final.append(d)
>>> final

>>>[{'name': 'mark'}, {'name': 'will'}, {'name': 'john'}]
</code>```

Title: How to convert a list to json in python

Body:
have a list with values

test = ["mark","will","john"]

using for loop how to convert this into JSON like this

test =[{"name":"mark"},{"name":"john"},{"name":"will"}]

Tried this

for i in test :
    print({"name":i})


问:
Iterate over two Pytorch tensors at once?
I have two Pytorch tensors (really, just 1-D lists), t1 and t2. Is it possible to iterate over them in parallel, i.e. do something like

for a,b in zip(t1,t2)
?

Thanks.

答:
To zip tensors in PyTorch into one use torch.stack with dim=1

Example

```<code>t1 = torch.tensor([1, 2, 3])
t2 = torch.tensor([10, 20, 30])
t3 = torch.tensor([100, 200, 300])

res = torch.stack((t1, t2, t3), dim=1)
#output
#tensor([[  1,  10, 100],
#        [  2,  20, 200],
#        [  3,  30, 300]])
</code>```

Body:
To zip tensors in PyTorch into one use torch.stack with dim=1

Example

t1 = torch.tensor([1, 2, 3])
t2 = torch.tensor([10, 20, 30])
t3 = torch.tensor([100, 200, 300])

res = torch.stack((t1, t2, t3), dim=1)
#output
#tensor([[  1,  10, 100],
#        [  2,  20, 200],
#        [  3,  30, 300]])


问:
Faster alternatives to csv and pandas
I have data augmentation code which requires appending to csv file. Data is in order of millions. It takes 2-3 days. Are there any faster alternatives? How fast is HDF5 in case where we need append operations in order of millions?

Edit: code: for reference only

```<code>def insert_data(directory, annotated_csv, output_csv):
    data = pd.read_csv(annotated_csv)
    data.to_csv(output_csv,index = False)
    counter = 0
    print("number of files: ", len(os.listdir(directory)))

    datachunk = []

    for fname in glob.glob(directory + '/*jpg'):

        fname = fname.split('/')[-1]

        counter = counter + 1

        if counter % 10000 == 0:
            df_tmp = pd.DataFrame(data=datachunk, columns=data.columns)

            df_tmp.to_csv(output_csv,mode = 'a', index = False, header=False)

            datachunk = []

            print("counter: "+ str(counter))

        try:
            ofile = fname.split("-")[0]
            flabel = "'" + fname.split("-")[3] + "'"

            ofile = ofile +'.jpg'

            BB, MB, SB = get_all_bb(data, ofile)

            BB[0] = fname
            MB[0] = fname
            SB[0] = fname

            BB[7] = flabel
            MB[7] = flabel
            SB[7] = flabel

            datachunk.append(BB)
            datachunk.append(MB)
            datachunk.append(SB)

        except:
            print("Exception on"+ str(fname))
            pass

    df_tmp = pd.DataFrame(data=datachunk, columns=data.columns)
    df_tmp.to_csv(output_csv,mode = 'a', index = False, header=False)
    print("counter: "+ str(counter))
</code>```

This code just gives a glimpse of what's happening.

答:
Using simple pandas will only utilize a single core of your CPU for computation.

The solution:

You could use multiprocessing combined with pandas in order to speed up this append computation. Using multiprocessing, you will be able to reduce the processing time depending on the number of cores of your CPU. The higher the number of cores of your machine, the lesser the processing time.

A sample implementation of multiprocessing using pandas can be referred from this link: http://datumorphism.com/til/programming/pandas/pandas-parallel-multiprocessing/

For more detailed explanation, you could refer to :
https://towardsdatascience.com/make-your-own-super-pandas-using-multiproc-1c04f41944a1

Title: Faster alternatives to csv and pandas

Body:
I have data augmentation code which requires appending to csv file. Data is in order of millions. It takes 2-3 days. Are there any faster alternatives? How fast is HDF5 in case where we need append operations in order of millions?

Edit: code: for reference only

def insert_data(directory, annotated_csv, output_csv):
    data = pd.read_csv(annotated_csv)
    data.to_csv(output_csv,index = False)
    counter = 0
    print("number of files: ", len(os.listdir(directory)))

    datachunk = []

    for fname in glob.glob(directory + '/*jpg'):

        fname = fname.split('/')[-1]

        counter = counter + 1

        if counter % 10000 == 0:
            df_tmp = pd.DataFrame(data=datachunk, columns=data.columns)

            df_tmp.to_csv(output_csv,mode = 'a', index = False, header=False)

            datachunk = []

            print("counter: "+ str(counter))

        try:
            ofile = fname.split("-")[0]
            flabel = "'" + fname.split("-")[3] + "'"

            ofile = ofile +'.jpg'

            BB, MB, SB = get_all_bb(data, ofile)

            BB[0] = fname
            MB[0] = fname
            SB[0] = fname

            BB[7] = flabel
            MB[7] = flabel
            SB[7] = flabel

            datachunk.append(BB)
            datachunk.append(MB)
            datachunk.append(SB)

        except:
            print("Exception on"+ str(fname))
            pass

    df_tmp = pd.DataFrame(data=datachunk, columns=data.columns)
    df_tmp.to_csv(output_csv,mode = 'a', index = False, header=False)
    print("counter: "+ str(counter))

This code just gives a glimpse of what's happening.


问:
Slice an array with spaces in bash
I want to use a key-value storage in bash, and then access the elements and work with them. I have the following code so far, which finds the key in the storage, but can't extract the values from the array without interpreting the spaces.

A straight forward solution to this (since I know there will be three values for each key) is to access those directly, but surely there must be a way to slice the array properly.

```<code># the array is a key: value storage, the keys do not contain spaces, but the values might
# there are always three values for each key, but the number of words in them is unknown
services=("key1" "some values" "another_value" "a lot of values"
          "key2" "other values" "simple_value2" "a lot of values here"
          "key3" "something else here" "another_value3" "whatever")

# this should look for the given value in the array and return the key and respective values if its found
function find_key () {
    arr=("${@:2}")
    len=$(( ${#arr[@]} -1 ))
    for i in $(seq 0 4 "$len")
    do
    if [[ ${arr[$i]} == "$1" ]] ; then
        # this should get the i'th element and 4 following elements (the values), which works correctly
        result="${arr[*]:$i:4}"
        # at this point result is just a regular array and there is no way to separate the values again

        # this prints just one line with all words
        for x in "${result[@]}"; do
            echo "element: '$x'"
        done

        # I want to return the array ("key" "value 1" "value 2" "the third value") from here to work with it later
        echo "${result[@]}"
        return 0
    fi
    done
    return 1
}

key_and_values="$(find_key "key2" "${services[@]}")"
echo "${key_and_values[@]}"
</code>```

The output is:

```<code>element: 'key2 other values simple_value2 a lot of values here'
key2 other values simple_value2 a lot of values here
</code>```

And I am looking for:

```<code>element: 'key2'
element: 'other values'
element: 'simple_value2'
element: 'a lot of values here'
key2 other values simple_value2 a lot of values here
</code>```

答:
Change:

```<code>result="${arr[*]:$i:4}"
</code>```

into an array:

```<code>result=("${arr[@]:$i:4}")
</code>```

There are some problems with your script:

"${key_and_values[@]}" - key_and_values is not an array, it's a normal variable.

echo "${result[@]}" will work abnormally when for example result[0]='-n'. Use printf "%s\n" "${result[@]}" | paste -sd ' ' or similar.

I think I would go with something along:

```<code>find_key() {
    arr=("${@:2}")
    for ((i=0; i < ${#arr[@]}; i+=4)); do
        if [[ ${arr[$i]} == "$1" ]] ; then
            printf "%s\0" "${arr[@]:$i:4}"
            return 0
        fi
    done
    return 1
}

readarray -d '' -t key_and_values < <(find_key "key2" "${services[@]}")
printf "element: %s\n" "${key_and_values[@]}"
printf "%s\n" "${key_and_values[@]}" | paste -sd' '
</code>```

Title: Slice an array with spaces in bash

Body:
I want to use a key-value storage in bash, and then access the elements and work with them. I have the following code so far, which finds the key in the storage, but can't extract the values from the array without interpreting the spaces.

A straight forward solution to this (since I know there will be three values for each key) is to access those directly, but surely there must be a way to slice the array properly.

# the array is a key: value storage, the keys do not contain spaces, but the values might
# there are always three values for each key, but the number of words in them is unknown
services=("key1" "some values" "another_value" "a lot of values"
          "key2" "other values" "simple_value2" "a lot of values here"
          "key3" "something else here" "another_value3" "whatever")

# this should look for the given value in the array and return the key and respective values if its found
function find_key () {
    arr=("${@:2}")
    len=$(( ${#arr[@]} -1 ))
    for i in $(seq 0 4 "$len")
    do
    if [[ ${arr[$i]} == "$1" ]] ; then
        # this should get the i'th element and 4 following elements (the values), which works correctly
        result="${arr[*]:$i:4}"
        # at this point result is just a regular array and there is no way to separate the values again

        # this prints just one line with all words
        for x in "${result[@]}"; do
            echo "element: '$x'"
        done

        # I want to return the array ("key" "value 1" "value 2" "the third value") from here to work with it later
        echo "${result[@]}"
        return 0
    fi
    done
    return 1
}

key_and_values="$(find_key "key2" "${services[@]}")"
echo "${key_and_values[@]}"

The output is:

element: 'key2 other values simple_value2 a lot of values here'
key2 other values simple_value2 a lot of values here

And I am looking for:

element: 'key2'
element: 'other values'
element: 'simple_value2'
element: 'a lot of values here'
key2 other values simple_value2 a lot of values here

Body:
Change:

result="${arr[*]:$i:4}"

into an array:

result=("${arr[@]:$i:4}")

There are some problems with your script:

"${key_and_values[@]}" - key_and_values is not an array, it's a normal variable.

echo "${result[@]}" will work abnormally when for example result[0]='-n'. Use printf "%s\n" "${result[@]}" | paste -sd ' ' or similar.

I think I would go with something along:

find_key() {
    arr=("${@:2}")
    for ((i=0; i < ${#arr[@]}; i+=4)); do
        if [[ ${arr[$i]} == "$1" ]] ; then
            printf "%s\0" "${arr[@]:$i:4}"
            return 0
        fi
    done
    return 1
}

readarray -d '' -t key_and_values < <(find_key "key2" "${services[@]}")
printf "element: %s\n" "${key_and_values[@]}"
printf "%s\n" "${key_and_values[@]}" | paste -sd' '


问:
Kotlin: At which situations does implicit conversion happen?
I am a beginner in Kotlin.
I'm most familiar with Python, and I just read through the basic Java Tutorial https://docs.oracle.com/javase/tutorial/java/index.html before jumping into Kotlin.

A question came up in my mind while reading this section of the documentation of Kotlin

https://kotlinlang.org/docs/reference/basic-types.html#explicit-conversions

What I have understood from above section of the documentation is:

For assignments =, implicit type conversion happens. If the lefthand side's type is a supertype or same type of righthand side's type the code would compile. Otherwise it's a compile error. In case of Int and Long, they are both subtypes of Number but neither of them subtypes of each other, so the implicit conversion would not work. Therefore we need to use methods like .toLong() or .toInt() to explicitly convert them.

Then when I read the part

  ```<code>val l = 1L + 3 // Long + Int => Long
</code>```

I started wondering if implicit type conversion would be taking place in this situation.

The documentation says this has to do with the operator overloading.
How is this operator overloading implemented under the hood?
I tried to find the source code at Github https://github.com/JetBrains/kotlin/blob/master/core/builtins/native/kotlin/Primitives.kt ,
but here the functions are only declared but not implemented. Where can I find the implementations?

It seems that operation overloading does not actually perform type conversion. Do we just implementing all possible functions with same name but different parameter type signatures, so that the type is inferred, then the function with the matching signature is selected?

And the general question: In Kotlin, exactly at which situations does implicit conversion happen?

答:
For assignments =, implicit type conversion happens. If the lefthand side's type is a supertype or same type of righthand side's type the code would compile.

Assignments aren't special in this. More generally, if the expected type of an expression is a supertype or the same as actual type, the code compiles; it's just that the expected type for the right-hand side of an assignment is the left-hand side's type. I wouldn't say there is an implicit conversion inserted, but I don't think anything breaks if you see it that way.

Do we just implementing all possible functions with same name but different parameter type signatures, so that the type is inferred, then the function with the matching signature is selected?

Yes, exactly (for this case). If you want to support primitive types, you need to provide overloads for all of them.

So 1L + 3 is just a method call so far as the parsing and type-checking is concerned (`Long.plus(Int): Long specifically), no implicit conversion is involved. But these methods are built into the compiler to handle specially which is why you don't see an implementation.

It becomes two bytecode instructions i2l ("convert an int into a long") and ladd ("add two longs"), but that's not something you should probably care about yet, or for a long time.

And the general question: In Kotlin, exactly at which situations does implicit conversion happen?

Smart casts are the closest Kotlin has to implicit conversions but they are sufficiently different from i.c.s in other languages that I wouldn't use the name. So I'd say never.

Body:
I am a beginner in Kotlin.
I'm most familiar with Python, and I just read through the basic Java Tutorial https://docs.oracle.com/javase/tutorial/java/index.html before jumping into Kotlin.

A question came up in my mind while reading this section of the documentation of Kotlin

https://kotlinlang.org/docs/reference/basic-types.html#explicit-conversions

What I have understood from above section of the documentation is:

For assignments =, implicit type conversion happens. If the lefthand side's type is a supertype or same type of righthand side's type the code would compile. Otherwise it's a compile error. In case of Int and Long, they are both subtypes of Number but neither of them subtypes of each other, so the implicit conversion would not work. Therefore we need to use methods like .toLong() or .toInt() to explicitly convert them.

Then when I read the part

val l = 1L + 3 // Long + Int => Long

I started wondering if implicit type conversion would be taking place in this situation.

The documentation says this has to do with the operator overloading.
How is this operator overloading implemented under the hood?
I tried to find the source code at Github https://github.com/JetBrains/kotlin/blob/master/core/builtins/native/kotlin/Primitives.kt ,
but here the functions are only declared but not implemented. Where can I find the implementations?

It seems that operation overloading does not actually perform type conversion. Do we just implementing all possible functions with same name but different parameter type signatures, so that the type is inferred, then the function with the matching signature is selected?

And the general question: In Kotlin, exactly at which situations does implicit conversion happen?


问:
How to declare a dependency on an at-least version,maven
I have a my-api which depends on A-api.

And my client will dependent on A-api explictly , so I may propable need to declare this dependency as provided.

Rather than declare a hard-coded version dependeny on A-api at my my-api's pom, I want a lowest version, since A-api's team will garanteer that its Api will be compatable with the former one

my-api's pom:

```<code>            <dependency>
                <groupId>org.mygroup</groupId>
                <artifactId>A-api</artifactId>
                <version>a-at-least-version</version><!--I only want a lowest version that i need-->
                <scope>provided</scope><!--Should I declare it as provided? -->
            </dependency>
</code>```

my client will use our two api like:

```<code>        <!--Notice, my client will explicitly declare dependency on A-api, and this may be higher than what my-api dependent on. This api will update more frequently than my-api-->
            <dependency>
                <groupId>org.mygroup</groupId>
                <artifactId>A-api</artifactId>
                <version>may-be-a-newer-version</version>
            </dependency>

            <!--My client will also dependent on my-api with a statble version-->
            <dependency>
                <groupId>org.mygroup</groupId>
                <artifactId>my-api</artifactId>
                <version>one-version</version>
            </dependency>
</code>```

答:
Seems this question has already been answered via comments by @michaldo, but if you're hell-bent on doing it your way, you can use this notation.

<dependency>
    <groupId>org.mygroup</groupId>
    <artifactId>A-api</artifactId>
    <version>[x.y,)</version>
    <scope>provided</scope>
</dependency>
```

Please refer to the Maven docs on resolving version ranges.

Body:
I have a my-api which depends on A-api.

And my client will dependent on A-api explictly , so I may propable need to declare this dependency as provided.

Rather than declare a hard-coded version dependeny on A-api at my my-api's pom, I want a lowest version, since A-api's team will garanteer that its Api will be compatable with the former one

my-api's pom:

            <dependency>
                <groupId>org.mygroup</groupId>
                <artifactId>A-api</artifactId>
                <version>a-at-least-version</version>
                <scope>provided</scope>
            </dependency>

my client will use our two api like:

            <dependency>
                <groupId>org.mygroup</groupId>
                <artifactId>A-api</artifactId>
                <version>may-be-a-newer-version</version>
            </dependency>

            <dependency>
                <groupId>org.mygroup</groupId>
                <artifactId>my-api</artifactId>
                <version>one-version</version>
            </dependency>

Body:
Seems this question has already been answered via comments by @michaldo, but if you're hell-bent on doing it your way, you can use this notation.

<dependency>
    <groupId>org.mygroup</groupId>
    <artifactId>A-api</artifactId>
    <version>[x.y,)</version><!--I only want a lowest version that i need-->
    <scope>provided</scope><!--Should I declare it as provided? -->
</dependency>

Please refer to the Maven docs on resolving version ranges.


问:
Exclude pattern in RegExp match Golang
I need to extract a part of a string in Golang for a dashboard in Google Data Studio. This is the string:

```<code>ABC - What I need::Other Information I do not need
</code>```

To get the part between the hyphen and the first colon I have tried ([\\-].*[\\:]), which includes both, the hyphen and the colons.

That might be an easy question for more experienced RegExp users, but how do I match only the words in between?

答:
You may use this:

```<code>-(.*?):
</code>```

Here the first capture group is your desired result.
 Example

Sample Source: ( run here )

```<code>package main

import (
    "fmt"
    "regexp"
)

func main() {
    var re = regexp.MustCompile(`(?m)-(.*?):`)
    var str = `ABC - What I need::Other Information I do not need`
    rs:=re.FindStringSubmatch(str)
    fmt.Println(rs[1])

}
</code>```

Title: Exclude pattern in RegExp match Golang

Body:
I need to extract a part of a string in Golang for a dashboard in Google Data Studio. This is the string:

ABC - What I need::Other Information I do not need

To get the part between the hyphen and the first colon I have tried ([\\-].*[\\:]), which includes both, the hyphen and the colons.

That might be an easy question for more experienced RegExp users, but how do I match only the words in between?

Body:
You may use this:

-(.*?):

Here the first capture group is your desired result.
 Example

Sample Source: ( run here )

package main

import (
    "fmt"
    "regexp"
)

func main() {
    var re = regexp.MustCompile(`(?m)-(.*?):`)
    var str = `ABC - What I need::Other Information I do not need`
    rs:=re.FindStringSubmatch(str)
    fmt.Println(rs[1])

}


问:
Do I fit the scaler on X or X_train when I have train,dev and test sets?
Here is my data

```<code>X = X.reshape((-1, 784))
y = y.reshape((-1,1))
X_test = X_test.reshape((-1, 784))
y_test = y_test.reshape((-1,1))

X_train, X_val, y_train, y_val = train_test_split(X,
                                                  y,
                                                  test_size=0.1,
                                                  random_state=1)
</code>```

Do I fit the X or X_train in the .fit ?

```<code>scaler = MinMaxScaler()
scaler.fit(X_train)
</code>```

or

```<code>scaler = MinMaxScaler()
scaler.fit(X)
</code>```

The transform will be as follows

```<code>X_train = scaler.transform(X_train)
X_val = scaler.transform(X_val)
y_test = scaler.transform(y_test)
</code>```

答: You should use only the train data to avoid biasing and skewing. Some deeper explanation in this answer or in many other sources.</p>

Body:
Here is my data

X = X.reshape((-1, 784))
y = y.reshape((-1,1))
X_test = X_test.reshape((-1, 784))
y_test = y_test.reshape((-1,1))

X_train, X_val, y_train, y_val = train_test_split(X,
                                                  y,
                                                  test_size=0.1,
                                                  random_state=1)

Do I fit the X or X_train in the .fit ?

scaler = MinMaxScaler()
scaler.fit(X_train)

or

scaler = MinMaxScaler()
scaler.fit(X)

The transform will be as follows

X_train = scaler.transform(X_train)
X_val = scaler.transform(X_val)
y_test = scaler.transform(y_test)


问:
How to navigate in mobx store using react navigation?
I can use this.props.navigation from screen component to navigate. How should I do the similar in mobx store file? Or should I perform navigation in store?

I read the Navigating without the navigation prop article, but it seems only works for screen components, right?

Someone says use global variable to store a this.props.navigation reference and use it anywhere, but I don't like the idea...

答:
Send this one this.props.navigation as a parameter to the store. Then use as you use on the component side.

```<code>LoginStore.login(this.props.navigation)
</code>```

in the LoginStore

```<code>@action login = (navigation) => { navigation.navigate('Page');}
</code>```

Body:
Send this one this.props.navigation as a parameter to the store. Then use as you use on the component side.

LoginStore.login(this.props.navigation)

in the LoginStore

@action login = (navigation) => { navigation.navigate('Page');}


问:
Remove extra x axis lines in the middle from morris.js Line chart
I'm trying to create a Line Chart using morris.js but the chart is showing extra lines with float values. But I only need the chart to show 0 and 1 axis

This is my graph configuration

```<code>config = {
    data: graphData,
    xkey: 'x',
    ykeys: ['a','b'],
    parseTime: false,
    fillOpacity: 0.6,
    hideHover: 'auto',
    behaveLikeLine: true,
    resize: false,
    pointFillColors:['#ffffff'],
    pointStrokeColors: ['black'],
    lineColors:['red','orange'],
    hoverCallback: function(index, options, content, row) {
      return(content);
    },
    gridIntegers: true,
    ymax: 1,
    ymin: 0,

  };
config.element = 'line-chart';

$("#line-chart").empty();

Morris.Line(config);
</code>```

I'm only submitting 1 and 0 for the x axis.

```<code>[
    {
        "x": "2020-02-15 06:36:21",
        "a": 1,
        "b": 1
    },
    {
        "x": "2020-02-14 21:35:37",
        "a": 0,
        "b": 0
    }
]
</code>```

答:
The official latest version of Morris v0.5.1 doesn't have a gridIntegers parameter. It was added in a pull request and available in this version of Morris.

You can also use the latest official version of Morris and extend it to add this parameter like in my code snippet. Then, this parameter set to true like you tried should work as expected.

Please try the following snippet:

(function () {
    var $, MyMorris;

    MyMorris = window.MyMorris = {};
    $ = jQuery;

    MyMorris = Object.create(Morris);

    MyMorris.Grid.prototype.gridDefaults["gridIntegers"] = false;

    MyMorris.Grid.prototype.setData = function (data, redraw) {
        var e, idx, index, maxGoal, minGoal, ret, row, step, total, y, ykey, ymax, ymin, yval, _ref;
        if (redraw == null) {
            redraw = true;
        }
        this.options.data = data;
        if ((data == null) || data.length === 0) {
            this.data = [];
            this.raphael.clear();
            if (this.hover != null) {
                this.hover.hide();
            }
            return;
        }
        ymax = this.cumulative ? 0 : null;
        ymin = this.cumulative ? 0 : null;
        if (this.options.goals.length > 0) {
            minGoal = Math.min.apply(Math, this.options.goals);
            maxGoal = Math.max.apply(Math, this.options.goals);
            ymin = ymin != null ? Math.min(ymin, minGoal) : minGoal;
            ymax = ymax != null ? Math.max(ymax, maxGoal) : maxGoal;
        }
        this.data = (function () {
            var _i, _len, _results;
            _results = [];
            for (index = _i = 0, _len = data.length; _i < _len; index = ++_i) {
                row = data[index];
                ret = {
                    src: row
                };
                ret.label = row[this.options.xkey];
                if (this.options.parseTime) {
                    ret.x = Morris.parseDate(ret.label);
                    if (this.options.dateFormat) {
                        ret.label = this.options.dateFormat(ret.x);
                    } else if (typeof ret.label === 'number') {
                        ret.label = new Date(ret.label).toString();
                    }
                } else {
                    ret.x = index;
                    if (this.options.xLabelFormat) {
                        ret.label = this.options.xLabelFormat(ret);
                    }
                }
                total = 0;
                ret.y = (function () {
                    var _j, _len1, _ref, _results1;
                    _ref = this.options.ykeys;
                    _results1 = [];
                    for (idx = _j = 0, _len1 = _ref.length; _j < _len1; idx = ++_j) {
                        ykey = _ref[idx];
                        yval = row[ykey];
                        if (typeof yval === 'string') {
                            yval = parseFloat(yval);
                        }
                        if ((yval != null) && typeof yval !== 'number') {
                            yval = null;
                        }
                        if (yval != null) {
                            if (this.cumulative) {
                                total += yval;
                            } else {
                                if (ymax != null) {
                                    ymax = Math.max(yval, ymax);
                                    ymin = Math.min(yval, ymin);
                                } else {
                                    ymax = ymin = yval;
                                }
                            }
                        }
                        if (this.cumulative && (total != null)) {
                            ymax = Math.max(total, ymax);
                            ymin = Math.min(total, ymin);
                        }
                        _results1.push(yval);
                    }
                    return _results1;
                }).call(this);
                _results.push(ret);
            }
            return _results;
        }).call(this);
        if (this.options.parseTime) {
            this.data = this.data.sort(function (a, b) {
                return (a.x > b.x) - (b.x > a.x);
            });
        }
        this.xmin = this.data[0].x;
        this.xmax = this.data[this.data.length - 1].x;
        this.events = [];
        if (this.options.events.length > 0) {
            if (this.options.parseTime) {
                this.events = (function () {
                    var _i, _len, _ref, _results;
                    _ref = this.options.events;
                    _results = [];
                    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                        e = _ref[_i];
                        _results.push(Morris.parseDate(e));
                    }
                    return _results;
                }).call(this);
            } else {
                this.events = this.options.events;
            }
            this.xmax = Math.max(this.xmax, Math.max.apply(Math, this.events));
            this.xmin = Math.min(this.xmin, Math.min.apply(Math, this.events));
        }
        if (this.xmin === this.xmax) {
            this.xmin -= 1;
            this.xmax += 1;
        }
        this.ymin = this.yboundary('min', ymin);
        this.ymax = this.yboundary('max', ymax);
        if (this.ymin === this.ymax) {
            if (ymin) {
                this.ymin -= 1;
            }
            this.ymax += 1;
        }
        if (((_ref = this.options.axes) === true || _ref === 'both' || _ref === 'y') || this.options.grid === true) {
            if (this.options.ymax === this.gridDefaults.ymax && this.options.ymin === this.gridDefaults.ymin) {
                this.grid = this.autoGridLines(this.ymin, this.ymax, this.options.numLines);
                this.ymin = Math.min(this.ymin, this.grid[0]);
                this.ymax = Math.max(this.ymax, this.grid[this.grid.length - 1]);
            } else {
                step = (this.ymax - this.ymin) / (this.options.numLines - 1);
                if (this.options.gridIntegers) {
                    step = Math.max(1, Math.round(step));
                }
                this.grid = (function () {
                    var _i, _ref1, _ref2, _results;
                    _results = [];
                    for (y = _i = _ref1 = this.ymin, _ref2 = this.ymax; step > 0 ? _i <= _ref2 : _i >= _ref2; y = _i += step) {
                        _results.push(y);
                    }
                    return _results;
                }).call(this);
            }
        }
        this.dirty = true;
        if (redraw) {
            return this.redraw();
        }
    };
}).call(this);

var graphData = [
    { "x": "2020-02-15 06:36:21", "a": 1, "b": 1 },
    { "x": "2020-02-14 21:35:37", "a": 0, "b": 0 }
];

var config = {
    data: graphData,
    element: 'line-chart',
    xkey: 'x',
    ykeys: ['a','b'],
    parseTime: false,
    fillOpacity: 0.6,
    hideHover: 'auto',
    behaveLikeLine: true,
    resize: false,
    pointFillColors:['#ffffff'],
    pointStrokeColors: ['black'],
    lineColors:['red','orange'],
    labels: ['A', 'B'],
    gridIntegers: true,
    ymax: 1,
    ymin: 0
  };

$("#line-chart").empty();

Morris.Line(config);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css" rel="stylesheet" />

<div id="line-chart"></div></code>```

Note that you don't need your hoverCallback function if it stays like this. You should also add the labels parameter to define your labels.

Body:
I'm trying to create a Line Chart using morris.js but the chart is showing extra lines with float values. But I only need the chart to show 0 and 1 axis

This is my graph configuration

config = {
    data: graphData,
    xkey: 'x',
    ykeys: ['a','b'],
    parseTime: false,
    fillOpacity: 0.6,
    hideHover: 'auto',
    behaveLikeLine: true,
    resize: false,
    pointFillColors:['#ffffff'],
    pointStrokeColors: ['black'],
    lineColors:['red','orange'],
    hoverCallback: function(index, options, content, row) {
      return(content);
    },
    gridIntegers: true,
    ymax: 1,
    ymin: 0,

  };
config.element = 'line-chart';

$("#line-chart").empty();

Morris.Line(config);

I'm only submitting 1 and 0 for the x axis.

[
    {
        "x": "2020-02-15 06:36:21",
        "a": 1,
        "b": 1
    },
    {
        "x": "2020-02-14 21:35:37",
        "a": 0,
        "b": 0
    }
]

Body:
The official latest version of Morris v0.5.1 doesn't have a gridIntegers parameter. It was added in a pull request and available in this version of Morris.

You can also use the latest official version of Morris and extend it to add this parameter like in my code snippet. Then, this parameter set to true like you tried should work as expected.

Please try the following snippet:

(function () {
    var $, MyMorris;

    MyMorris = window.MyMorris = {};
    $ = jQuery;

    MyMorris = Object.create(Morris);

    MyMorris.Grid.prototype.gridDefaults["gridIntegers"] = false;

    MyMorris.Grid.prototype.setData = function (data, redraw) {
        var e, idx, index, maxGoal, minGoal, ret, row, step, total, y, ykey, ymax, ymin, yval, _ref;
        if (redraw == null) {
            redraw = true;
        }
        this.options.data = data;
        if ((data == null) || data.length === 0) {
            this.data = [];
            this.raphael.clear();
            if (this.hover != null) {
                this.hover.hide();
            }
            return;
        }
        ymax = this.cumulative ? 0 : null;
        ymin = this.cumulative ? 0 : null;
        if (this.options.goals.length > 0) {
            minGoal = Math.min.apply(Math, this.options.goals);
            maxGoal = Math.max.apply(Math, this.options.goals);
            ymin = ymin != null ? Math.min(ymin, minGoal) : minGoal;
            ymax = ymax != null ? Math.max(ymax, maxGoal) : maxGoal;
        }
        this.data = (function () {
            var _i, _len, _results;
            _results = [];
            for (index = _i = 0, _len = data.length; _i < _len; index = ++_i) {
                row = data[index];
                ret = {
                    src: row
                };
                ret.label = row[this.options.xkey];
                if (this.options.parseTime) {
                    ret.x = Morris.parseDate(ret.label);
                    if (this.options.dateFormat) {
                        ret.label = this.options.dateFormat(ret.x);
                    } else if (typeof ret.label === 'number') {
                        ret.label = new Date(ret.label).toString();
                    }
                } else {
                    ret.x = index;
                    if (this.options.xLabelFormat) {
                        ret.label = this.options.xLabelFormat(ret);
                    }
                }
                total = 0;
                ret.y = (function () {
                    var _j, _len1, _ref, _results1;
                    _ref = this.options.ykeys;
                    _results1 = [];
                    for (idx = _j = 0, _len1 = _ref.length; _j < _len1; idx = ++_j) {
                        ykey = _ref[idx];
                        yval = row[ykey];
                        if (typeof yval === 'string') {
                            yval = parseFloat(yval);
                        }
                        if ((yval != null) && typeof yval !== 'number') {
                            yval = null;
                        }
                        if (yval != null) {
                            if (this.cumulative) {
                                total += yval;
                            } else {
                                if (ymax != null) {
                                    ymax = Math.max(yval, ymax);
                                    ymin = Math.min(yval, ymin);
                                } else {
                                    ymax = ymin = yval;
                                }
                            }
                        }
                        if (this.cumulative && (total != null)) {
                            ymax = Math.max(total, ymax);
                            ymin = Math.min(total, ymin);
                        }
                        _results1.push(yval);
                    }
                    return _results1;
                }).call(this);
                _results.push(ret);
            }
            return _results;
        }).call(this);
        if (this.options.parseTime) {
            this.data = this.data.sort(function (a, b) {
                return (a.x > b.x) - (b.x > a.x);
            });
        }
        this.xmin = this.data[0].x;
        this.xmax = this.data[this.data.length - 1].x;
        this.events = [];
        if (this.options.events.length > 0) {
            if (this.options.parseTime) {
                this.events = (function () {
                    var _i, _len, _ref, _results;
                    _ref = this.options.events;
                    _results = [];
                    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                        e = _ref[_i];
                        _results.push(Morris.parseDate(e));
                    }
                    return _results;
                }).call(this);
            } else {
                this.events = this.options.events;
            }
            this.xmax = Math.max(this.xmax, Math.max.apply(Math, this.events));
            this.xmin = Math.min(this.xmin, Math.min.apply(Math, this.events));
        }
        if (this.xmin === this.xmax) {
            this.xmin -= 1;
            this.xmax += 1;
        }
        this.ymin = this.yboundary('min', ymin);
        this.ymax = this.yboundary('max', ymax);
        if (this.ymin === this.ymax) {
            if (ymin) {
                this.ymin -= 1;
            }
            this.ymax += 1;
        }
        if (((_ref = this.options.axes) === true || _ref === 'both' || _ref === 'y') || this.options.grid === true) {
            if (this.options.ymax === this.gridDefaults.ymax && this.options.ymin === this.gridDefaults.ymin) {
                this.grid = this.autoGridLines(this.ymin, this.ymax, this.options.numLines);
                this.ymin = Math.min(this.ymin, this.grid[0]);
                this.ymax = Math.max(this.ymax, this.grid[this.grid.length - 1]);
            } else {
                step = (this.ymax - this.ymin) / (this.options.numLines - 1);
                if (this.options.gridIntegers) {
                    step = Math.max(1, Math.round(step));
                }
                this.grid = (function () {
                    var _i, _ref1, _ref2, _results;
                    _results = [];
                    for (y = _i = _ref1 = this.ymin, _ref2 = this.ymax; step > 0 ? _i <= _ref2 : _i >= _ref2; y = _i += step) {
                        _results.push(y);
                    }
                    return _results;
                }).call(this);
            }
        }
        this.dirty = true;
        if (redraw) {
            return this.redraw();
        }
    };
}).call(this);

var graphData = [
    { "x": "2020-02-15 06:36:21", "a": 1, "b": 1 },
    { "x": "2020-02-14 21:35:37", "a": 0, "b": 0 }
];

var config = {
    data: graphData,
    element: 'line-chart',
    xkey: 'x',
    ykeys: ['a','b'],
    parseTime: false,
    fillOpacity: 0.6,
    hideHover: 'auto',
    behaveLikeLine: true,
    resize: false,
    pointFillColors:['#ffffff'],
    pointStrokeColors: ['black'],
    lineColors:['red','orange'],
    labels: ['A', 'B'],
    gridIntegers: true,
    ymax: 1,
    ymin: 0
  };

$("#line-chart").empty();

Morris.Line(config);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css" rel="stylesheet" />

<div id="line-chart"></div>

Note that you don't need your hoverCallback function if it stays like this. You should also add the labels parameter to define your labels.


问:
MongoDB - Can I use @TextIndexed and @Indexed on a field at the same time?
Is it possible to have both index and text index on the same column in MongoDB?

I want to query Question collection by country code (i.e. "US") and unwind related data in Country collection by country code as id.

Example code for Spring Data MongoDB / Kotlin:

```<code>@Document
data class Question(
    @Id val id: String,

    @TextIndexed
    @Indexed(name = "question_country_code_index")
    val countryCode: String
)
</code>```

答:
It is possible to apply both annotation to the very same property. The IndexResolver will then create two indexes.

```<code>{
    "v" : 2,
    "key" : {
        "_fts" : "text",
        "_ftsx" : 1
    },
    "name" : "Question_TextIndex",
    "ns" : "db.question",
    "weights" : {
        "textIndexedPropertyWithDefaultWeight" : 1
    },
    "language_override" : "language",
    "textIndexVersion" : 3
},
{
    "v" : 2,
    "key" : {
        "countryCode" : 1
    },
    "name" : "question_country_code_index",
    "ns" : "db.question",
    "collation" : {
        ...
    }
}
</code>```

Body:
Is it possible to have both index and text index on the same column in MongoDB?

I want to query Question collection by country code (i.e. "US") and unwind related data in Country collection by country code as id.

Example code for Spring Data MongoDB / Kotlin:

@Document
data class Question(
    @Id val id: String,

    @TextIndexed
    @Indexed(name = "question_country_code_index")
    val countryCode: String
)

Body:
It is possible to apply both annotation to the very same property. The IndexResolver will then create two indexes.

{
    "v" : 2,
    "key" : {
        "_fts" : "text",
        "_ftsx" : 1
    },
    "name" : "Question_TextIndex",
    "ns" : "db.question",
    "weights" : {
        "textIndexedPropertyWithDefaultWeight" : 1
    },
    "language_override" : "language",
    "textIndexVersion" : 3
},
{
    "v" : 2,
    "key" : {
        "countryCode" : 1
    },
    "name" : "question_country_code_index",
    "ns" : "db.question",
    "collation" : {
        ...
    }
}


问:
Unable to get Refresh token from Azure B2C
Can anyone please tell me the steps to get a refresh token from Azure B2C, although we already have authorization token from Azure B2C.

We are following below user flow for getting the active token from Azure B2C but we are not receiving Refresh Token

```<code>https://tenant.b2clogin.com/tenant.onmicrosoft.com/oauth2/v2.0/authorize?
client_id=feerer72-615a-4851-af2b-78786bhgg
&response_type=id_token+token
&redirect_uri=https%3A%2F%2Fjwt.ms
&scope=openid%20offline_access
&state=arbitrary_data_you_can_receive_in_the_response
&nonce=defaultNonce
&p=userflowName
</code>```

Description:
Have given all permissions on azure B2C tenant as shown in screenshots attached below:

So please can anyone tell me how can I receive refresh token in response so that I can use that refresh token for getting an another active token from Azure B2C without login in the user on Azure B2C.

NOTE:
Check the response given below:
We are getting Active Token but not receiving Refresh Token

```<code>{
  "typ": "JWT",
  "alg": "RS256",
  "kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk"
}.{
  "exp": 1582120656,
  "nbf": 1582034256,
  "ver": "1.0",
  "iss": "https://tenant.b2clogin.com/c9fabc17-7ff9-4cdf17-b175-945gfgdf9ac/v2.0/",
  "sub": "842e9ee3-28dfd02-4a29-ba95-b5228616e9fe",
  "aud": "fecd3e72-615a-4851-af2b-d2b5171735erer4d",
  "nonce": "defaultNonce",
  "iat": 1582034256,
  "auth_time": 1582034256,
  "oid": "898hfhfe3-2802-4a29-ba95-b5228616e9fe",
  "emails": [
    "nikhil.sharma@gmail.com"
  ],
  "tfp": "B2C_1_Sign_Up_Policy",
  "c_hash": "vAb2w438XDmZpZBzEYMcZ2rA"
}
</code>```

答:
Try using the following endpoint to make the same request and check if you get in the response the refresh token:

https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/oauth2/v2.0/token

If not, then potentially there is some misconfiguration with your AD B2C instance.

Body:
Can anyone please tell me the steps to get a refresh token from Azure B2C, although we already have authorization token from Azure B2C.

We are following below user flow for getting the active token from Azure B2C but we are not receiving Refresh Token

https://tenant.b2clogin.com/tenant.onmicrosoft.com/oauth2/v2.0/authorize?
client_id=feerer72-615a-4851-af2b-78786bhgg
&response_type=id_token+token
&redirect_uri=https%3A%2F%2Fjwt.ms
&scope=openid%20offline_access
&state=arbitrary_data_you_can_receive_in_the_response
&nonce=defaultNonce
&p=userflowName

Description:
Have given all permissions on azure B2C tenant as shown in screenshots attached below:

So please can anyone tell me how can I receive refresh token in response so that I can use that refresh token for getting an another active token from Azure B2C without login in the user on Azure B2C.

NOTE:
Check the response given below:
We are getting Active Token but not receiving Refresh Token

{
  "typ": "JWT",
  "alg": "RS256",
  "kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk"
}.{
  "exp": 1582120656,
  "nbf": 1582034256,
  "ver": "1.0",
  "iss": "https://tenant.b2clogin.com/c9fabc17-7ff9-4cdf17-b175-945gfgdf9ac/v2.0/",
  "sub": "842e9ee3-28dfd02-4a29-ba95-b5228616e9fe",
  "aud": "fecd3e72-615a-4851-af2b-d2b5171735erer4d",
  "nonce": "defaultNonce",
  "iat": 1582034256,
  "auth_time": 1582034256,
  "oid": "898hfhfe3-2802-4a29-ba95-b5228616e9fe",
  "emails": [
    "nikhil.sharma@gmail.com"
  ],
  "tfp": "B2C_1_Sign_Up_Policy",
  "c_hash": "vAb2w438XDmZpZBzEYMcZ2rA"
}


问:
Can tensorflow models be trained on images with larger resolution?
Need help on understanding whether Tensorflow models can be trained on larger resolutions like 4K resolution. I tried, but the training is not getting commenced, I hope because of some memory issue. Has anyone worked on the same?</p>

答:
In theory you can, there are no limitations on TensorFlow that prevent you from doing this.

But in practice, the limitation is GPU or system RAM. A 3840x2160 (4K) single-channel floating point feature map is around 32 MB of RAM, and generally a convolutional network uses multiple feature maps at each layer, from 96 to 512. For example, 128 4K feature maps would need around 1 GB of RAM, and then training using batches and keeping intermediate results for gradient computation, would require too much RAM.

If you look at input shapes to common ImageNet-trained neural networks, sizes are usually 224x224, 256x256, and the biggest I have seen is 600x600 for object detection networks like SSD and Faster R-CNN. These sizes are very far from a full 4K image.

TLDR. You should downscale your images to a manageable size.


问:
How do I include/exclude a JUnit 5 `ParameterizedTest` by name in Maven
I have a parameterized JUnit 5 test, e.g.

@EnumSource(Mode.class)
@ParameterizedTest void shouldRunWithMode(Mode mode) {
    ...
```

<p>I want to exclude one of the enum cases from running in Maven, as described here:</p>

<pre class="lang-xml prettyprint-override"><code><plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.2</version>
    <configuration>
        <test>!testpackage.SomeTest#shouldRunWithMode[3 three]</test>
    </configuration>
</plugin>
</code>```

The same thing without the ! would mean inclusion, i.e. execute only this test.

I played around with the exclude expression and the square brackets, but I didn't find a combination to make it work.

A demo project is on GitHub.

答:
I dug into the code and found that there is no code for it. It's obviously supported only on JUnit 4.

I reported it as a bug SUREFIRE-1753

Body:
I have a parameterized JUnit 5 test, e.g.

@EnumSource(Mode.class)
@ParameterizedTest void shouldRunWithMode(Mode mode) {
    ...

I want to exclude one of the enum cases from running in Maven, as described here:

<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.2</version>
    <configuration>
        <test>!testpackage.SomeTest#shouldRunWithMode[3 three]</test>
    </configuration>
</plugin>

The same thing without the ! would mean inclusion, i.e. execute only this test.

I played around with the exclude expression and the square brackets, but I didn't find a combination to make it work.

A demo project is on GitHub.


问:
Overflow: hidden with border radius not working on Safari
I have to make a button with a ::before hidden which shows on :hover. This animation is working great on Chrome, IE and Firefox, but i have a weird issue on Safari.

Overflow:hidden is working but without the border radius.

You should run the fiddle in safari to see this issue.

Thanks !

.btn{
  border-radius: 3rem;
  cursor: pointer;
  display: inline-block;
  font-size: 15px;
  font-weight: 400;
  font-family: arial;
  overflow: hidden;
  position: relative;
  padding: 0.8rem 2.5rem;
  text-decoration: none;
  }

.btn-primary{
  background-color: blue;
  border-color: blue;
  color: white;
}

.btn-primary::before{
  background-color: deeppink;
  border-radius: 50%;
  content: '';
  color: white;
  height: 100%;
  left: 100%;
  margin: 0;
  position: absolute;
  top: 0;
  transform-origin: 100% 50%;
  transform: scale3d(1, 1.4, 1);
  transition: all 300ms cubic-bezier(0.7,0,0.9,1);
  width: 20%;
}

.btn-primary:hover::before{
  transform: scale3d(1, 5, 1);
  width: 110%;
  left: -2%;
  z-index: 0;
}

.btn-primary span{
  position: relative;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <span>Button primary</span>
</code>```

答: will-change: transform; on element with overflow: hidden; solved issue for me

Body:
I have to make a button with a ::before hidden which shows on :hover. This animation is working great on Chrome, IE and Firefox, but i have a weird issue on Safari.

Overflow:hidden is working but without the border radius.

You should run the fiddle in safari to see this issue.

Thanks !

.btn{
  border-radius: 3rem;
  cursor: pointer;
  display: inline-block;
  font-size: 15px;
  font-weight: 400;
  font-family: arial;
  overflow: hidden;
  position: relative;
  padding: 0.8rem 2.5rem;
  text-decoration: none;
  }

.btn-primary{
  background-color: blue;
  border-color: blue;
  color: white;
}

.btn-primary::before{
  background-color: deeppink;
  border-radius: 50%;
  content: '';
  color: white;
  height: 100%;
  left: 100%;
  margin: 0;
  position: absolute;
  top: 0;
  transform-origin: 100% 50%;
  transform: scale3d(1, 1.4, 1);
  transition: all 300ms cubic-bezier(0.7,0,0.9,1);
  width: 20%;
}

.btn-primary:hover::before{
  transform: scale3d(1, 5, 1);
  width: 110%;
  left: -2%;
  z-index: 0;
}

.btn-primary span{
  position: relative;
  z-index: 1;
}

  Button primary


问:
This site can’t be reached http://127.0.0.1:8000/hello using Flask as web framework
I am trying to run a simple "hello world" code using flask version 1.1.1 and python 3.7. the server is running but the web page is not loading. Can anyone please help???

```<code>from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello_world():
    return "Hello world"

if __name__ == '__main__':
    app.run(host='127.0.0.1',port=8000, debug=True)
</code>```

Output is as below

But the web page(http://127.0.0.1:8000/hello) displays "This site can’t be reached"

答: make host =0.0.0.0 in app.run() and whatever port you will give it will work and if you will not give port in by default it will take 5000</p>

Body:
I am trying to run a simple "hello world" code using flask version 1.1.1 and python 3.7. the server is running but the web page is not loading. Can anyone please help???

from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello_world():
    return "Hello world"

if __name__ == '__main__':
    app.run(host='127.0.0.1',port=8000, debug=True)

Output is as below

But the web page(http://127.0.0.1:8000/hello) displays "This site can’t be reached"


问:
C# StreamWriter writes extra bytes to the Stream
```<code>var memStream = new MemoryStream();
using (var sw = new StreamWriter(memStream, Encoding.UTF8, 4194304 /* 4 MiB */, leaveOpen: true))
{
     var str = new string(Enumerable.Repeat(' ', 10240 /* 10 * KiB */).ToArray());
     Console.WriteLine(str.Length);
     Console.WriteLine(Encoding.UTF8.GetBytes(str).Length);
     sw.Write(str);
     sw.Flush();
     Console.WriteLine(memStream.Length);
}
// Output
// ---------
// 10240
// 10240
// 10243

// Output which I was expecting
// ---------
// 10240
// 10240
// 10240
</code>```

I checked the StreamWriter.Write(String) documentation on MSDN but I didn't find anything which mentions that this API can write extra bytes to the stream.
(MSDN Doc StreamWriter.Write).
I am using .NET Core 3.1, but I am guessing this behavior also holds for Core 2.0 and Framework although I have not explicitly tested my hypothesis for them. I read the StreamWriter documentation thoroughly, I don't find any mention of such a behavior. Is this a bug or expected behavior or am I missing something ?

答:
You could prevent the output of the BOM by creating a UTF8Encoding that should not emit an UTF8 identifier by using new UTF8Encoding(false):

```<code>var memStream = new MemoryStream();
using (var sw = new StreamWriter(memStream, new UTF8Encoding(false), 4194304 /* 4 MiB */, leaveOpen: true))
{
    var str = new string(Enumerable.Repeat(' ', 10240 /* 10 * KiB */).ToArray());
    Console.WriteLine(str.Length);
    Console.WriteLine(Encoding.UTF8.GetBytes(str).Length);
    sw.Write(str);
    sw.Flush();
    Console.WriteLine(memStream.Length);
}
</code>```

Body:
var memStream = new MemoryStream();
using (var sw = new StreamWriter(memStream, Encoding.UTF8, 4194304 /* 4 MiB */, leaveOpen: true))
{
     var str = new string(Enumerable.Repeat(' ', 10240 /* 10 * KiB */).ToArray());
     Console.WriteLine(str.Length);
     Console.WriteLine(Encoding.UTF8.GetBytes(str).Length);
     sw.Write(str);
     sw.Flush();
     Console.WriteLine(memStream.Length);
}
// Output
// ---------
// 10240
// 10240
// 10243

// Output which I was expecting
// ---------
// 10240
// 10240
// 10240

I checked the StreamWriter.Write(String) documentation on MSDN but I didn't find anything which mentions that this API can write extra bytes to the stream.
(MSDN Doc StreamWriter.Write).
I am using .NET Core 3.1, but I am guessing this behavior also holds for Core 2.0 and Framework although I have not explicitly tested my hypothesis for them. I read the StreamWriter documentation thoroughly, I don't find any mention of such a behavior. Is this a bug or expected behavior or am I missing something ?

Body:
You could prevent the output of the BOM by creating a UTF8Encoding that should not emit an UTF8 identifier by using new UTF8Encoding(false):

var memStream = new MemoryStream();
using (var sw = new StreamWriter(memStream, new UTF8Encoding(false), 4194304 /* 4 MiB */, leaveOpen: true))
{
    var str = new string(Enumerable.Repeat(' ', 10240 /* 10 * KiB */).ToArray());
    Console.WriteLine(str.Length);
    Console.WriteLine(Encoding.UTF8.GetBytes(str).Length);
    sw.Write(str);
    sw.Flush();
    Console.WriteLine(memStream.Length);
}


问:
Bound string value from ViewModel not updating in UI element
I have this TextBlock in XAML that its text property is bound to a viewmodel command.

```<code><TextBlock Text="{Binding SomeText}"></TextBlock>
</code>```

Meanwhile, the viewmodel looks like this:

```<code>\\ the text property
private string _someText = "";

public const string SomeTextPropertyName = "SomeText";
public string SomeText
{
    get
    {
        return _someText;
    }
    set
    {
        Set(SomeTextPropertyName, ref _someText, value);
    }
}

\\ the command that changes the string

private RelayCommand<string> _theCommand;

public RelayCommand<string> TheCommand
{
    get
    {
        return _theCommand
            ?? (_theCommand = new RelayCommand<string>(ExecuteTheCommand));
    }
}

private void ExecuteTheCommand(string somestring)
{
    _someText = "Please Change";
    \\ MessageBox.Show(SomeText);
}
</code>```

I can successfully call the TheCommand as I did able to call a MessageBox using that command from the triggering element. The SomeText value also change as shown in the commented MessageBox line. What am I doing wrong here, is there any silly mistake?

答:
You're setting the field _someText directly, which means you're by-passing the setter of the SomeText property. But that setter is calling the  Set(SomeTextPropertyName, ref _someText, value); method that is internally raising the PropertyChanged event.

That PropertyChanged event is necessary for the Data Binding, so that it knows the SomeText property was updated.

That means, instead of doing this:

```<code>private void ExecuteTheCommand(string somestring)
{
    _someText = "Please Change";
    \\ MessageBox.Show(SomeText);
}
</code>```

Just do this and it should work:

```<code>private void ExecuteTheCommand(string somestring)
{
    SomeText = "Please Change";
    \\ MessageBox.Show(SomeText);
}
</code>```

Body:
I have this TextBlock in XAML that its text property is bound to a viewmodel command.

<TextBlock Text="{Binding SomeText}"></TextBlock>

Meanwhile, the viewmodel looks like this:

\\ the text property
private string _someText = "";

public const string SomeTextPropertyName = "SomeText";
public string SomeText
{
    get
    {
        return _someText;
    }
    set
    {
        Set(SomeTextPropertyName, ref _someText, value);
    }
}

\\ the command that changes the string

private RelayCommand<string> _theCommand;

public RelayCommand<string> TheCommand
{
    get
    {
        return _theCommand
            ?? (_theCommand = new RelayCommand<string>(ExecuteTheCommand));
    }
}

private void ExecuteTheCommand(string somestring)
{
    _someText = "Please Change";
    \\ MessageBox.Show(SomeText);
}

I can successfully call the TheCommand as I did able to call a MessageBox using that command from the triggering element. The SomeText value also change as shown in the commented MessageBox line. What am I doing wrong here, is there any silly mistake?

Body:
You're setting the field _someText directly, which means you're by-passing the setter of the SomeText property. But that setter is calling the  Set(SomeTextPropertyName, ref _someText, value); method that is internally raising the PropertyChanged event.

That PropertyChanged event is necessary for the Data Binding, so that it knows the SomeText property was updated.

That means, instead of doing this:

private void ExecuteTheCommand(string somestring)
{
    _someText = "Please Change";
    \\ MessageBox.Show(SomeText);
}

Just do this and it should work:

private void ExecuteTheCommand(string somestring)
{
    SomeText = "Please Change";
    \\ MessageBox.Show(SomeText);
}


问:
sudo: docker-machine: command not found
who has ever tried following this tutorial about Docker Swarm?

https://docs.docker.com/get-started/part4/

There is a section called : Create a cluster. What I wanted to do was to create a couple of VMs using docker-machine. Since I use ubuntu16.0.4 so I used following commands to get VirtualBox.

```<code>sudo apt-get update
sudo apt-get install virtualbox-5.2
</code>```

After I installed VirtualBox, typed a command like :

docker-machine create --driver virtualbox myvm1

But it says :
sudo: docker-machine: command not found

So I typed another command to check if I have installed VirtualBox correctly.

sudo virtualbox version

This opens the Oracle VM VirtualBox Manager, which means I did install VirtualBox correctly , but not sure.

Could anyone help me with a proper solution?
Any help would be appreciated.

答: On MacOS installing with brew is the simplest solution: brew install docker-machine

Title: sudo: docker-machine: command not found

Body:
who has ever tried following this tutorial about Docker Swarm?

https://docs.docker.com/get-started/part4/

There is a section called : Create a cluster. What I wanted to do was to create a couple of VMs using docker-machine. Since I use ubuntu16.0.4 so I used following commands to get VirtualBox.

sudo apt-get update
sudo apt-get install virtualbox-5.2

After I installed VirtualBox, typed a command like :

docker-machine create --driver virtualbox myvm1

But it says :
sudo: docker-machine: command not found

So I typed another command to check if I have installed VirtualBox correctly.

sudo virtualbox version

This opens the Oracle VM VirtualBox Manager, which means I did install VirtualBox correctly , but not sure.

Could anyone help me with a proper solution?
Any help would be appreciated.


问:
How to create a destname which includes date and time at installation in Inno Set-up
I want to use the [Files] section to create a new file which has the format:

```<code>Program Name plus date plus time .fmpur
</code>```

I'd be grateful for any ideas.

答:
An alternative to TLama's example using a function to get the filename.</p>

```<code>[code]
function GetFileName(Dummy: String): String;
begin
    Result := SetupSetting("AppName") + " " + GetDateTimeString('dd-mm-yyyy hh-nn-ss', '-', ':') + ".fmpur";
end;

[Files]
Source: "MyProg.exe"; DestDir: "{app}"; DestName: "{code:GetFileName}"
</code>```

Body:
I want to use the [Files] section to create a new file which has the format:

Program Name plus date plus time .fmpur

I'd be grateful for any ideas.

Body:
An alternative to TLama's example using a function to get the filename.

[code]
function GetFileName(Dummy: String): String;
begin
    Result := SetupSetting("AppName") + " " + GetDateTimeString('dd-mm-yyyy hh-nn-ss', '-', ':') + ".fmpur";
end;

[Files]
Source: "MyProg.exe"; DestDir: "{app}"; DestName: "{code:GetFileName}"


问:
Collect data from object separated by comma and make themselves as individual object - Javascript
I have an array contening various objects. These objects contain data separated by comma. I would like to remove each of these data from Object and make them as an individual object (including same date):

```<code>Array = [3]
 0: Object { year: "march 2019", "turnover": 120, "employee": 1000, "cars":232 }
 1: Object { year: "april 2019", "turnover": 123, "employee": 1340, "cars":682 }
 2: Object { year: "june 2019", "turnover": 1343, "employee": 760, "cars": 4345 }

</code>```

my goal is to extract data from each object and make them object himself with the same date:

```<code>Array = [9]
 0: Object { year: "march 2019", "turnover": 120 }
 1: Object { year: "march 2019" , "employee": 1000 }
 2: Object { year: "march 2019", "cars":232 }
 3: Object { year: "april 2019", "turnover": 123 }
 4: Object { year: "april 2019", "employee": 1340 }
 5: Object { year: "april 2019","cars":682 }
 6: Object { year: "june 2019", "turnover": 1343 }
 7: Object { year: "june 2019", "employee": 760 }
 8: Object { year: "june 2019","cars": 4345 }

</code>```

I appreciate your help

Thanks

答:
```<code>var testarr = [{ year: "march 2019", "turnover": 120, "employee": 1000, "cars":232 },{ year: "march 2019", "turnover": 120, "employee": 1000, "cars":232 }]

var finalArr = [];
for(i=0;i<testarr.length;i++){

    for (key in testarr[i]){
        var yearjson = { "year" : testarr[i]["year"]}
        if(key != "year"){
            yearjson[key] = testarr[i][key]
            finalArr.push(yearjson)
        }
    }

}
console.log(finalArr)
</code>```

Body:
I have an array contening various objects. These objects contain data separated by comma. I would like to remove each of these data from Object and make them as an individual object (including same date):

Array = [3]
 0: Object { year: "march 2019", "turnover": 120, "employee": 1000, "cars":232 }
 1: Object { year: "april 2019", "turnover": 123, "employee": 1340, "cars":682 }
 2: Object { year: "june 2019", "turnover": 1343, "employee": 760, "cars": 4345 }

my goal is to extract data from each object and make them object himself with the same date:

Array = [9]
 0: Object { year: "march 2019", "turnover": 120 }
 1: Object { year: "march 2019" , "employee": 1000 }
 2: Object { year: "march 2019", "cars":232 }
 3: Object { year: "april 2019", "turnover": 123 }
 4: Object { year: "april 2019", "employee": 1340 }
 5: Object { year: "april 2019","cars":682 }
 6: Object { year: "june 2019", "turnover": 1343 }
 7: Object { year: "june 2019", "employee": 760 }
 8: Object { year: "june 2019","cars": 4345 }

I appreciate your help

Thanks


问:
Matlab function convertion to R
i'm trying to convert a code from MATLAB to R and find a difficulty in a otherwise easy convertion.

```<code>function [X1, X2, X3, X4] = example (A, B, C, D, E)

SOME STATEMENTS

END
</code>```

cant find how to input in my r code the X1,...,X4. My code is the following

```<code>example <- function(A, B, C, D, E){

SOME STATEMENTS

}
</code>```

How and where to insert the Xi's?

Also how to convert the MATLAB statement =% in R?

```<code>fprintf('A=%D, B=%E, C=%F,', A, B, C)
</code>```

答:
In R, you can put list(X1, X2, X3, X4) to the end of your function block. When you call the function example(A,B,C,D,D), the output will be in the format of list, i.e., list(X1, X2, X3, X4)

```<code>example <- function(A, B, C, D, E){

SOME STATEMENTS

list(X1, X2, X3, X4)
}
</code>```

Title: Matlab function convertion to R

Body:
i'm trying to convert a code from MATLAB to R and find a difficulty in a otherwise easy convertion.

function [X1, X2, X3, X4] = example (A, B, C, D, E)

SOME STATEMENTS

END

cant find how to input in my r code the X1,...,X4. My code is the following

example <- function(A, B, C, D, E){

SOME STATEMENTS

}

How and where to insert the Xi's?

Also how to convert the MATLAB statement =% in R?

fprintf('A=%D, B=%E, C=%F,', A, B, C)

Body:
In R, you can put list(X1, X2, X3, X4) to the end of your function block. When you call the function example(A,B,C,D,D), the output will be in the format of list, i.e., list(X1, X2, X3, X4)

example <- function(A, B, C, D, E){

SOME STATEMENTS

list(X1, X2, X3, X4)
}


问:
Difference between returning Void and () in a swift closure
Whats the difference between these closures?

```<code>let closureA: () -> ()
</code>```

and

```<code>let closureB: () -> Void
</code>```

答:
If you arrived here because you got an error such as Cannot convert value of type 'Void.Type' to specified type 'Void', then it might be useful to consider that:

() can mean two things:

() can be a type - the empty tuple type, which is the same as Void.

() can be a value - an empty tuple, which is the same as Void().

In my case I was looking to change () to Void, but this caused the error mentioned above. Solving it would either mean just keeping it as () or using Void(). The latter can be put in a global constant let void = Void() and then you can just use void. Whether this is a good practice / style, is up for debate.

Body:
Whats the difference between these closures?

let closureA: () -> ()

and

let closureB: () -> Void


问:
How do I pass a RegEx pattern to Pytesseract?
There seems to be two ways to go about this, none seem to work.

First, you can pass tessedit_char_whitelist, but that seems to work only with characters, not patterns:

```<code>import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Users\.../tesseract.exe'

pytesseract.image_to_string(img, config="-c tessedit_char_whitelist=.{5,15}\d{4,8}")
</code>```

That doesn't work, although you can whitelist characters as 'abcdefgh'.

The second way is this way. I have found the eng.user-patterns file, and entered my RegEx pattern, but I don't know how to set it so it's active. I guess it would be something like:

```<code>pytesseract.image_to_string(img, configfile="eng.user-patterns")
</code>```

However, pytesseract accepts no such argument.

答:
RegEx are not supported by tesseract and pytesseract can do nothing with it.
tessedit_char_whitelist and user-patterns are different parameter with different effects.</p>

Body:
There seems to be two ways to go about this, none seem to work.

First, you can pass tessedit_char_whitelist, but that seems to work only with characters, not patterns:

import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Users\.../tesseract.exe'

pytesseract.image_to_string(img, config="-c tessedit_char_whitelist=.{5,15}\d{4,8}")

That doesn't work, although you can whitelist characters as 'abcdefgh'.

The second way is this way. I have found the eng.user-patterns file, and entered my RegEx pattern, but I don't know how to set it so it's active. I guess it would be something like:

pytesseract.image_to_string(img, configfile="eng.user-patterns")

However, pytesseract accepts no such argument.


问:
How to transform a ellipse to a rect in Javascript
So I´m trying to code something that a shape transforms to another one, if a specific key is pressed. So far I´m stuck at the first shape. How can I write, that my "var musculus" changes to function flexor, or extensor on keyTyped?

var musculus;

function draw() {
  musculus = ellipse(30, 30, 20, 20);

  function keyTyped() {
    if (key === 'a') {
      musculus = flexor;
    } else if (key === 'b') {
      musculus = extensor;
    }
  }
}

function flexor() {
  ellipse(56, 46, 55, 55);
}

function extensor() {
  square(30, 20, 55, 20);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script></code>```

答:
Your code is close to working, you just need to make a few changes.

Remove the line musculus = ellipse(30, 30, 20, 20); in draw().

Draw is run every frame so musculus keeps getting set to ellipse(30, 30, 20, 20)

musculus is set but never used, add musculus; into draw() so it is used each on frame.

Move keyTyped() outside of draw() so P5js can see and use it.

keyTypes() is correct but you need to set musculus to the function not just the function name. Just add () to each function name. ie. musculus = flexor();

There are definitely a lot of improvements you can make to this script but you're off to a good start.

Fixed code

```<code>var musculus;

function draw() {
  musculus;
}

function keyTyped() {
  if (key === 'a') {
    musculus = flexor();
  } else if (key === 'b') {
    musculus = extensor();
  }
}

function flexor() {
  ellipse(56, 46, 55, 55);
}

function extensor() {
  square(30, 20, 55, 20);
}
</code>```

Better fix

In my re-write, I set the value of musculus to a word(aka. string) which is used in draw() to call the corresponding function in an if statement. I'm also using background('white') to clear the screen before drawing the new frame.

var musculus;

function draw() {
  background(255);
  if (musculus === 'flexor') {
    flexor();
  } else if (musculus === 'extensor') {
    extensor();
  }
}

function keyTyped() {
  if (key === 'a') {
    musculus = 'flexor';
  } else if (key === 'b') {
    musculus = 'extensor';
  }
}

function flexor() {
  ellipse(56, 46, 55, 55);
}

function extensor() {
  square(30, 20, 55, 20);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script></code>```

Body:
Your code is close to working, you just need to make a few changes.

Remove the line musculus = ellipse(30, 30, 20, 20); in draw().

Draw is run every frame so musculus keeps getting set to ellipse(30, 30, 20, 20)

musculus is set but never used, add musculus; into draw() so it is used each on frame.

Move keyTyped() outside of draw() so P5js can see and use it.

keyTypes() is correct but you need to set musculus to the function not just the function name. Just add () to each function name. ie. musculus = flexor();

There are definitely a lot of improvements you can make to this script but you're off to a good start.

Fixed code

var musculus;

function draw() {
  musculus;
}

function keyTyped() {
  if (key === 'a') {
    musculus = flexor();
  } else if (key === 'b') {
    musculus = extensor();
  }
}

function flexor() {
  ellipse(56, 46, 55, 55);
}

function extensor() {
  square(30, 20, 55, 20);
}

Better fix

In my re-write, I set the value of musculus to a word(aka. string) which is used in draw() to call the corresponding function in an if statement. I'm also using background('white') to clear the screen before drawing the new frame.

var musculus;

function draw() {
  background(255);
  if (musculus === 'flexor') {
    flexor();
  } else if (musculus === 'extensor') {
    extensor();
  }
}

function keyTyped() {
  if (key === 'a') {
    musculus = 'flexor';
  } else if (key === 'b') {
    musculus = 'extensor';
  }
}

function flexor() {
  ellipse(56, 46, 55, 55);
}

function extensor() {
  square(30, 20, 55, 20);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>


问:
How to create a random logical vector with specific numbers of TRUE / FALSE entries
I would like to create a logical vector that has 10 rows, with each row randomly assigned either TRUE or FALSE.  However, I want there to only be 3 FALSE and 7 TRUE.

Example of desired outcome (logical vector with three randomly assigned FALSE entries and 7 randomly assigned TRUE entries):

```<code>> vector
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "TRUE" "TRUE" "TRUE"
[10] "TRUE"
</code>```

I can create a logical vector of size 10 that has TRUE or FALSE, but I don't know how to specify I want three FALSE entries and 7 TRUE entries.

```<code>vector <- sample(x = c("TRUE","FALSE"), size = 10, replace = TRUE)
</code>```

This produces:

```<code>> train
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"
[10] "TRUE"
</code>```

Which has the incorrect number of TRUE and FALSE entries (4 TRUE and 6 FALSE).

答:
You can try this:

Approach1 :
Use prob parameter to give proportions for sample you select along with replace=TRUE in sample command. sample command doesn't guarantee the exact value of proportion, but for larger sample size it may give approximate proportions

```<code>x <- c(TRUE, FALSE)
sample(x,10 ,replace = TRUE, prob=c(.7, .3))
</code>```

Approach2:
    For a perfect proportion:

```<code>rep(c(TRUE, FALSE), times= c(7,3)) ## In case you want to have perfect proportion
    #if someone wanted to randomly shuffle then one cas use:
     rep(c(TRUE, FALSE), times= c(7,3))[order(runif(10))]
</code>```

Output:

```<code>> sample(x,10 ,replace = T, prob=c(.7, .3))
 [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
 [8]  TRUE  TRUE  TRUE
</code>```

Output:

```<code>rep(c(TRUE, FALSE), times= c(7,3))[order(runif(10))]
  [1]  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE
  [8]  TRUE  TRUE FALSE
</code>```

Body:
I would like to create a logical vector that has 10 rows, with each row randomly assigned either TRUE or FALSE.  However, I want there to only be 3 FALSE and 7 TRUE.

Example of desired outcome (logical vector with three randomly assigned FALSE entries and 7 randomly assigned TRUE entries):

> vector
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "TRUE" "TRUE" "TRUE"
[10] "TRUE"

I can create a logical vector of size 10 that has TRUE or FALSE, but I don't know how to specify I want three FALSE entries and 7 TRUE entries.

vector <- sample(x = c("TRUE","FALSE"), size = 10, replace = TRUE)

This produces:

> train
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"
[10] "TRUE"

Which has the incorrect number of TRUE and FALSE entries (4 TRUE and 6 FALSE).

Body:
You can try this:

Approach1 :
Use prob parameter to give proportions for sample you select along with replace=TRUE in sample command. sample command doesn't guarantee the exact value of proportion, but for larger sample size it may give approximate proportions

x <- c(TRUE, FALSE)
sample(x,10 ,replace = TRUE, prob=c(.7, .3))

Approach2:
    For a perfect proportion:

rep(c(TRUE, FALSE), times= c(7,3)) ## In case you want to have perfect proportion
    #if someone wanted to randomly shuffle then one cas use:
     rep(c(TRUE, FALSE), times= c(7,3))[order(runif(10))]

Output:

> sample(x,10 ,replace = T, prob=c(.7, .3))
 [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
 [8]  TRUE  TRUE  TRUE

Output:

rep(c(TRUE, FALSE), times= c(7,3))[order(runif(10))]
  [1]  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE
  [8]  TRUE  TRUE FALSE


问:
requests.packages.urllib3.exceptions.SSLError: [Error 2] no such file or directory
Have some code, it works with raw code but once i turned it into a executable with pyinstaller i get the requests.packages.urllib3.exceptions.SSLError: [Error 2] no such file or directory
it always works with raw code but not with pyinstaller

tried using requests from both python 2 and python3, tried on multiple PCs.

i expect it to execute the code when using a .exe with pyinstaller

答:
Finally I found a solution by using certifi to resolve the full path to the 'cacert.pem' cert. And use it in request:

import requests
import certifi

req_url = "https://jsonplaceholder.typicode.com/todos/1"
response = requests.get(req_url, timeout=10, verify=certifi.where()).json()
print(response)
```

If you use another cert or want to move to final binary it can be copied into pyinstaller too and use it into verify parameter.

Body:
Finally I found a solution by using certifi to resolve the full path to the 'cacert.pem' cert. And use it in request:

import requests
import certifi

req_url = "https://jsonplaceholder.typicode.com/todos/1"
response = requests.get(req_url, timeout=10, verify=certifi.where()).json()
print(response)

If you use another cert or want to move to final binary it can be copied into pyinstaller too and use it into verify parameter.


问:
Iterate through template parameter
I have a function that receives a template parameter.

```<code>template<class Container>
void function(const Container& object)
{
     //here i want to iterate through object and print them
}

int main()
{
     function(std::vector<int>{1,3,6,7});
     function(std::vector<std::vector<int>>{{1,2,3},{2,5,7}});
}
</code>```

Is it possible to do this in one function? Suppose the container argument will be integer.

答:
One example:</p>

```<code>template<class T>
void print(T const& object) {
    std::cout << object;
}

template<class... Args>
void print(std::vector<Args...> const& container) {
    for(auto const& element : container) {
        print(element);
        std::cout << ' ';
    }
    std::cout << '\n';
}

int main() {
     print(std::vector<int>{1,3,6,7});
     print(std::vector<std::vector<int>>{{1,2,3},{2,5,7}});
}
</code>```

Title: Iterate through template parameter

Body:
I have a function that receives a template parameter.

template<class Container>
void function(const Container& object)
{
     //here i want to iterate through object and print them
}

int main()
{
     function(std::vector<int>{1,3,6,7});
     function(std::vector<std::vector<int>>{{1,2,3},{2,5,7}});
}

Is it possible to do this in one function? Suppose the container argument will be integer.

Body:
One example:

template<class T>
void print(T const& object) {
    std::cout << object;
}

template<class... Args>
void print(std::vector<Args...> const& container) {
    for(auto const& element : container) {
        print(element);
        std::cout << ' ';
    }
    std::cout << '\n';
}

int main() {
     print(std::vector<int>{1,3,6,7});
     print(std::vector<std::vector<int>>{{1,2,3},{2,5,7}});
}