问:
Control flow statements. How many years should pass until goal money
I would like to solve this task, but unfortunately, I stopped at this: Maybe I calculated in int but should in double?

Peter put money in the bank. The bank increases Peter's deposit by a percent every year. Peter wants to know how many years should pass until his deposit in the bank reaches his goal money.

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // write your code here
        Scanner myobject = new Scanner(System.in);
        double money = myobject.nextDouble();
        double percent = myobject.nextDouble();
        double goal = myobject.nextDouble();
        int years = -1;
        while (goal >= money) {
            money = money + money * (percent / 100);
            ++years;
        }
        System.out.println(years);
    }
}
</code>```

Test input: 100 15 120

Correct output: 2

Your code output: 1

答:
The problem with your code is that you have set years to -1 instead of 0. That is why your code outputs count one less than the expected count. I have updated your code accordingly to make it produce the expected output. Please find it below. Let me know if you have questions.</p>

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Stackoverflow_053120
{
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String args[]) throws NumberFormatException, IOException
    {
        int money = Integer.parseInt(in.readLine());
        int percent = Integer.parseInt(in.readLine());
        int goal = Integer.parseInt(in.readLine());

        int years = 0;
        while(money < goal)
        {
            money = (money * (100+percent)) / 100;
            years++;
        }
        System.out.println(years);
    }
}
</code>```

Body:
I would like to solve this task, but unfortunately, I stopped at this: Maybe I calculated in int but should in double?

Peter put money in the bank. The bank increases Peter's deposit by a percent every year. Peter wants to know how many years should pass until his deposit in the bank reaches his goal money.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // write your code here
        Scanner myobject = new Scanner(System.in);
        double money = myobject.nextDouble();
        double percent = myobject.nextDouble();
        double goal = myobject.nextDouble();
        int years = -1;
        while (goal >= money) {
            money = money + money * (percent / 100);
            ++years;
        }
        System.out.println(years);
    }
}

Test input: 100 15 120

Correct output: 2

Your code output: 1

Body:
The problem with your code is that you have set years to -1 instead of 0. That is why your code outputs count one less than the expected count. I have updated your code accordingly to make it produce the expected output. Please find it below. Let me know if you have questions.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Stackoverflow_053120
{
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String args[]) throws NumberFormatException, IOException
    {
        int money = Integer.parseInt(in.readLine());
        int percent = Integer.parseInt(in.readLine());
        int goal = Integer.parseInt(in.readLine());

        int years = 0;
        while(money < goal)
        {
            money = (money * (100+percent)) / 100;
            years++;
        }
        System.out.println(years);
    }
}


来源: stackexchange

问:
Maximum absolute difference of value and index sums of Four arrays
You are given four arrays A, B, C, D each of size N.

Find maximum value (M) of given below expression

```<code>M = max(|A[i] - A[j]| + |B[i] - B[j]| + |C[i] - C[j]| + |D[i] - D[j]| + |i -j|)
Where 1 <= i < j  <= N <br />
</code>```

and here |x| refers to the absolute value of x.

Constraints

```<code>2 <= N <= 10^5
1 <= Ai,Bi,Ci,Di <= 10^9
</code>```

Input: N,A,B,C,D

Output: M

Ex.-

```<code>Input-
5
5,7,6,3,9
7,9,2,7,5
1,9,9,3,3
8,4,1,10,5
</code>```

Output-

```<code>24
</code>```

Question picture

I have tried this way

```<code>def max_value(arr1,arr2,arr3,arr4, n):
    res = 0;
    # Iterating two for loop,
    # one for i and another for j.
    for i in range(n):
        for j in range(n):
            temp= abs(arr1[i] - arr1[j]) + abs(arr2[i] - arr2[j]) + abs(arr3[i] - arr3[j]) + abs(arr4[i] - arr4[j]) + abs(i - j)
            if res>temp:
                res = res
            else:
                res = temp
    return res;

</code>```

This is O(n^2).
But I want a better time complexity solution. This will not work for higher values of N.

Here is solution for single array

答:
Idea for faster solution

If you are only interested in the maximum of M you could search for the minimum and maximum value of A, B,C, D and i-j.Let's say i_Amax is the i index for the maximum of A.

Now you find the value of B[i_Amax], C[i_Amax].... and the same for i_Amin and calculate M with the differences of the max and min value.

You repeated the step before with the index for the maximum value of B, so i_Bmax and calculate M, you repeat until you gone through A,B,C,D and i-j

You now should have five terms and one of them should be the maximum

If you don't have a clear minimum or maximum you have to calculate the indeces for all the possible minimums and maximums.

I think it should find any maximum and is faster than n^2, especially for big n, but I have not implemented it myself, so you have to think it through to check whether I made a logical error and one can not find every maximum with that idea.

I hope that helps!

ContentLicense: CC BY-SA 4.0

Body:
You are given four arrays A, B, C, D each of size N.

Find maximum value (M) of given below expression

M = max(|A[i] - A[j]| + |B[i] - B[j]| + |C[i] - C[j]| + |D[i] - D[j]| + |i -j|)
Where 1 <= i < j  <= N

and here |x| refers to the absolute value of x.

Constraints

2 <= N <= 10^5
1 <= Ai,Bi,Ci,Di <= 10^9

Input: N,A,B,C,D

Output: M

Ex.-

Input-
5
5,7,6,3,9
7,9,2,7,5
1,9,9,3,3
8,4,1,10,5

Output-

24

Question picture

I have tried this way

def max_value(arr1,arr2,arr3,arr4, n):
    res = 0;
    # Iterating two for loop,
    # one for i and another for j.
    for i in range(n):
        for j in range(n):
            temp= abs(arr1[i] - arr1[j]) + abs(arr2[i] - arr2[j]) + abs(arr3[i] - arr3[j]) + abs(arr4[i] - arr4[j]) + abs(i - j)
            if res>temp:
                res = res
            else:
                res = temp
    return res;

This is O(n^2).
But I want a better time complexity solution. This will not work for higher values of N.

Here is solution for single array


问:
Use @Min(0) to validate an integer encounter NumberFormatException
In Oracle's document, it says @Min is used to check "The value of the field or property must be an integer value greater than or equal to the number in the value element." I use @Min(0) to validate my form input to positive integer or zero but encounter NumberFormatException when I input 1.2. (I use Spring Boot + Thymeleaf)

What am I doing wrong?

My Code:

```<code>@Min(value = 0, message = "need zero or positive integer")
private int qty;
</code>```

When I input -1, I got the message I want, but when I input 1.2, I got NumberFormatException:

```<code>Failed to convert property value of type java.lang.String to required type int for property qty; nested exception is java.lang.NumberFormatException: For input string: "1.2"
</code>```

答:
You can validate numbers like this.</p>

```<code>import javax.validation.constraints.NotNull;
import javax.validation.constraints.PositiveOrZero;
</code>```

```<code>@NotNull(message = "Prop must be not null.")
@PositiveOrZero(message = "Prop value should zero or positive.")
private Integer prop;

</code>```

Body:
In Oracle's document, it says @Min is used to check "The value of the field or property must be an integer value greater than or equal to the number in the value element." I use @Min(0) to validate my form input to positive integer or zero but encounter NumberFormatException when I input 1.2. (I use Spring Boot + Thymeleaf)

What am I doing wrong?

My Code:

@Min(value = 0, message = "need zero or positive integer")
private int qty;

When I input -1, I got the message I want, but when I input 1.2, I got NumberFormatException:

Failed to convert property value of type java.lang.String to required type int for property qty; nested exception is java.lang.NumberFormatException: For input string: "1.2"

Body:
You can validate numbers like this.

import javax.validation.constraints.NotNull;
import javax.validation.constraints.PositiveOrZero;

@NotNull(message = "Prop must be not null.")
@PositiveOrZero(message = "Prop value should zero or positive.")
private Integer prop;


问:
How to generate a GUID in Oracle?
Is it possible to auto-generate a GUID into an Insert statement?

Also, what type of field should I use to store this GUID?

答:
I would recommend using Oracle's "dbms_crypto.randombytes" function.

Why?

This function returns a RAW value containing a cryptographically secure pseudo-random sequence of bytes, which can be used to generate random material for encryption keys.

select REGEXP_REPLACE(dbms_crypto.randombytes(16), '(.{8})(.{4})(.{4})(.{4})(.{12})', '\1-\2-\3-\4-\5') from dual;
```
<p>You should <strong>not</strong> use the function "sys_guid" because only one character changes.</p>
<pre class="lang-sql prettyprint-override"><code>ALTER TABLE locations ADD (uid_col RAW(16));

UPDATE locations SET uid_col = SYS_GUID();

SELECT location_id, uid_col FROM locations
   ORDER BY location_id, uid_col;

LOCATION_ID UID_COL
----------- ----------------------------------------------------------------
       1000 09F686761827CF8AE040578CB20B7491
       1100 09F686761828CF8AE040578CB20B7491
       1200 09F686761829CF8AE040578CB20B7491
       1300 09F68676182ACF8AE040578CB20B7491
       1400 09F68676182BCF8AE040578CB20B7491
       1500 09F68676182CCF8AE040578CB20B7491
</code>```

https://docs.oracle.com/database/121/SQLRF/functions202.htm#SQLRF06120

ContentLicense: CC BY-SA 3.0

Title: How to generate a GUID in Oracle?

Body:
I would recommend using Oracle's "dbms_crypto.randombytes" function.

Why?

This function returns a RAW value containing a cryptographically secure pseudo-random sequence of bytes, which can be used to generate random material for encryption keys.

select REGEXP_REPLACE(dbms_crypto.randombytes(16), '(.{8})(.{4})(.{4})(.{4})(.{12})', '\1-\2-\3-\4-\5') from dual;

You should not use the function "sys_guid" because only one character changes.

ALTER TABLE locations ADD (uid_col RAW(16));

UPDATE locations SET uid_col = SYS_GUID();

SELECT location_id, uid_col FROM locations
   ORDER BY location_id, uid_col;

LOCATION_ID UID_COL
----------- ----------------------------------------------------------------
       1000 09F686761827CF8AE040578CB20B7491
       1100 09F686761828CF8AE040578CB20B7491
       1200 09F686761829CF8AE040578CB20B7491
       1300 09F68676182ACF8AE040578CB20B7491
       1400 09F68676182BCF8AE040578CB20B7491
       1500 09F68676182CCF8AE040578CB20B7491

https://docs.oracle.com/database/121/SQLRF/functions202.htm#SQLRF06120


问:
Get info from server-side to my front-end side
I am using on my back-end node.js and in my front-end a regular js. I was trying to send info from my server by this line:

```<code>res.status(200).send({ message: "Hello!" });
</code>```

I tried a few codes in my client-side. in the code below I didn't get the message.

```<code>var request = new XMLHttpRequest();

request.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        console.log(request);
    }
};

request.open('GET', 'http://localhost:3000/newUser');
request.send();
</code>```

this is what I got in my console:

XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
  onabort: null
  onerror: null
  onload: null
  onloadend: null
  onloadstart: null
  onprogress: null
  onreadystatechange: ƒ ()
  arguments: null
  caller: null
  length: 0
  name: ""
  prototype: {constructor: ƒ}
  proto: ƒ ()
  [[FunctionLocation]]: newUser.js:111
  [[Scopes]]: Scopes[2]
  ontimeout: null
  readyState: 4
  response: "
  responseText: "
  responseType: ""
  responseURL: "http://localhost:3000/newUser"
  responseXML: null
  status: 200
  statusText: "OK"
  timeout: 0
  upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, download: > null, …}
  withCredentials: false
  proto: XMLHttpRequest

I have also tried to use POST instead of GET but I didn't get anything from the console.
Is there any other way to get the massage from the server to my client?

答:
Try with this example</p>

```<code>fetch('http://dummy.restapiexample.com/api/v1/employees',{
    method:'GET'
}).then(response => response.json()).then((value)=>{
    console.log(value)
}).catch(error=>{
    console.log(error);
})
</code>```

Body:
I am using on my back-end node.js and in my front-end a regular js. I was trying to send info from my server by this line:

res.status(200).send({ message: "Hello!" });

I tried a few codes in my client-side. in the code below I didn't get the message.

var request = new XMLHttpRequest();

request.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        console.log(request);
    }
};

request.open('GET', 'http://localhost:3000/newUser');
request.send();

this is what I got in my console:

XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
  onabort: null
  onerror: null
  onload: null
  onloadend: null
  onloadstart: null
  onprogress: null
  onreadystatechange: ƒ ()
  arguments: null
  caller: null
  length: 0
  name: ""
  prototype: {constructor: ƒ}
  proto: ƒ ()
  [[FunctionLocation]]: newUser.js:111
  [[Scopes]]: Scopes[2]
  ontimeout: null
  readyState: 4
  response: "
  responseText: "
  responseType: ""
  responseURL: "http://localhost:3000/newUser"
  responseXML: null
  status: 200
  statusText: "OK"
  timeout: 0
  upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, download: > null, …}
  withCredentials: false
  proto: XMLHttpRequest

I have also tried to use POST instead of GET but I didn't get anything from the console.
Is there any other way to get the massage from the server to my client?

Body:
Try with this example

fetch('http://dummy.restapiexample.com/api/v1/employees',{
    method:'GET'
}).then(response => response.json()).then((value)=>{
    console.log(value)
}).catch(error=>{
    console.log(error);
})


问:
Django access to model Properties Dynamically
I'm very new to Django so this question might be very basic.

I have a model called UserScores, which contains 16 different score properties, each representing a user score based on the game he/she has played.

when a user plays a game and finish it, the score he gets in that game should be added to the related property in his/her UserScores object. so the code looks like this:

```<code>if game_name == "game_1":
  self.game1_score += score
elif game_name == "game_2":
  self.game2_score += score
...
</code>```

in php I used to run a code like this:

```<code>obj.{game_name} += score
</code>```

so no matter what the game name was, the correct property was edited,

Now my question is that,

Is there a dynamic way to access properties on a Django model objects?

答:
You can use getattr/setattr to achieve what you want. For example, to set the field value:</p>
```<code>old_value = getattr(obj, field_name)
setattr(obj, field_name, old_value + score)
</code>```

Body:
I'm very new to Django so this question might be very basic.

I have a model called UserScores, which contains 16 different score properties, each representing a user score based on the game he/she has played.

when a user plays a game and finish it, the score he gets in that game should be added to the related property in his/her UserScores object. so the code looks like this:

if game_name == "game_1":
  self.game1_score += score
elif game_name == "game_2":
  self.game2_score += score
...

in php I used to run a code like this:

obj.{game_name} += score

so no matter what the game name was, the correct property was edited,

Now my question is that,

Is there a dynamic way to access properties on a Django model objects?

Body:
You can use getattr/setattr to achieve what you want. For example, to set the field value:

old_value = getattr(obj, field_name)
setattr(obj, field_name, old_value + score)


问:
Pandas Dataframe: Find the index of maximum value for each column using idxmax()
I have a dataframe 156 x 9 with no null values and I am trying to find the index of the maximum value of each column. I tried the following

```<code>    country_list = []
    keys = []
    for i in range(len(col)):
        country = df.loc[df[col[i]].idxmax()]['Country or region']
        country_list.append(country)
        keys.append(col[i])
</code>```

The columns available are

```<code>In[65]:df.columns
Out[65]:
Index(['Overall rank', 'Country or region', 'Score', 'GDP per capita',
       'Social support', 'Healthy life expectancy',
       'Freedom to make life choices', 'Generosity',
       'Perceptions of corruption'],
      dtype='object')
</code>```

But I got the error of for using idxmax TypeError: reduction operation 'argmax' not allowed for this dtype

Any help appreciated, thank you!

答:
You can try this :-

```<code>import numpy as np

col_names = df.columns
max_val_index = []

for col in col_names:
    max_val_index.append(np.argmax(df[col]))

</code>```

The max index value will be stored in max_val_index

Body:
I have a dataframe 156 x 9 with no null values and I am trying to find the index of the maximum value of each column. I tried the following

    country_list = []
    keys = []
    for i in range(len(col)):
        country = df.loc[df[col[i]].idxmax()]['Country or region']
        country_list.append(country)
        keys.append(col[i])

The columns available are

In[65]:df.columns
Out[65]:
Index(['Overall rank', 'Country or region', 'Score', 'GDP per capita',
       'Social support', 'Healthy life expectancy',
       'Freedom to make life choices', 'Generosity',
       'Perceptions of corruption'],
      dtype='object')

But I got the error of for using idxmax TypeError: reduction operation 'argmax' not allowed for this dtype

Any help appreciated, thank you!

Body:
You can try this :-

import numpy as np

col_names = df.columns
max_val_index = []

for col in col_names:
    max_val_index.append(np.argmax(df[col]))

The max index value will be stored in max_val_index


问:
How do you enter data in PlistBuddy
I am trying to change a data value with PlistBuddy and can't figure it out.

/usr/libexec/PlistBuddy -c "Set :Kernel:Emulate:Cpuid1Mask AAAAAAAAAAAAAAACAAAAAA==" ~/Desktop/test.plist

Instead of writing the data I want, when I view the file, I get: QUFBQUFBQUFBQUFBQUFBQ0FBQUFBQT09

I have played with hex, dec, bin, everything I can think of, but it never writes correctly.
I have been searching everywhere, and there's nothing I can find that explains how to do it. Everything is on entering strings, and nothing tells how to enter data, or it's format.

I need to change that value back and forth from AAAAAAAAAAAAAAACAAAAAA== to AAAAAAAAAAAAAAAAAAAAAA==

I tried printing it to see the output, so I could see the format, but it's blank in terminal.

Anyone know how to do it?

答:
I figured it out.
Both defaults and PlistBuddy cannot do it.
plutil works fine without corrupting the data string.</p>

Title: How do you enter data in PlistBuddy


问:
Running a set function name in multiple Powershell scripts
I am building a testing framework for my current development team. One thing that I'd like to let them do is create a Powershell script to run their tests. The system is a database deploy system, so to test it they will need to potentially run some set-up code, then the deploy will be kicked off, then they will run some check code at the end.

Since the deploy takes awhile I'd like to have the framework handle that once for all of the tests. So, the basic flow is:

```<code>Run test #1 set-up
Run test #2 set-up
Run test #3 set-up
Run the deploy process
Run the code to confirm that test #1 passed
Run the code to confirm that test #2 passed
Run the code to confirm that test #3 passed
</code>```

I figured that I would have the framework always call a function called "setup" (or something similar) in all of the Powershell scripts in a particular directory. If no "setup" function exists that's ok and it shouldn't error out. Then I would run the deploy and then run the other functions in the Powershell scripts.

Given a directory listing, how could I cycle through each Powershell script and run these functions?

Thanks for any guidance!

答:
this will recurse through the given folder and execute all the setup.ps1 scripts it finds.

```<code>Get-ChildItem D:\test -Recurse | where { $_.name -eq "setup.ps1" }| foreach {
   "Executing $($_.Fullname)"
    Invoke-Expression "$($_.Fullname) -setup -Verbose"
}
</code>```

It doesn't accept parameters though....

If you just wanted to go one folder deep this will do the job:

```<code>Get-ChildItem D:\test | where{$_.psiscontainer}|foreach {
    Get-ChildItem $_.fullname | where { $_.name -eq "setup.ps1" }| foreach {
       "Executing $($_.Fullname)"
       Invoke-Expression "$($_.Fullname) -setup -Verbose"
    }
}
</code>```

It's irritated me a little that the parameters didn't work - I wonder if using the Invoke-Command could work for that. I haven't got time to try now, unless anyone else figures it out I'll have a look later.

Here's the script i used for setup.ps1

```<code>[cmdletbinding()]
Param()

function setup() {

    Write-Verbose "In setup 1"
    Write-Output "Done setup 1"

}

setup
</code>```

HTH

Body:
I am building a testing framework for my current development team. One thing that I'd like to let them do is create a Powershell script to run their tests. The system is a database deploy system, so to test it they will need to potentially run some set-up code, then the deploy will be kicked off, then they will run some check code at the end.

Since the deploy takes awhile I'd like to have the framework handle that once for all of the tests. So, the basic flow is:

Run test #1 set-up
Run test #2 set-up
Run test #3 set-up
Run the deploy process
Run the code to confirm that test #1 passed
Run the code to confirm that test #2 passed
Run the code to confirm that test #3 passed

I figured that I would have the framework always call a function called "setup" (or something similar) in all of the Powershell scripts in a particular directory. If no "setup" function exists that's ok and it shouldn't error out. Then I would run the deploy and then run the other functions in the Powershell scripts.

Given a directory listing, how could I cycle through each Powershell script and run these functions?

Thanks for any guidance!

Body:
this will recurse through the given folder and execute all the setup.ps1 scripts it finds.

Get-ChildItem D:\test -Recurse | where { $_.name -eq "setup.ps1" }| foreach {
   "Executing $($_.Fullname)"
    Invoke-Expression "$($_.Fullname) -setup -Verbose"
}

It doesn't accept parameters though....

If you just wanted to go one folder deep this will do the job:

Get-ChildItem D:\test | where{$_.psiscontainer}|foreach {
    Get-ChildItem $_.fullname | where { $_.name -eq "setup.ps1" }| foreach {
       "Executing $($_.Fullname)"
       Invoke-Expression "$($_.Fullname) -setup -Verbose"
    }
}

It's irritated me a little that the parameters didn't work - I wonder if using the Invoke-Command could work for that. I haven't got time to try now, unless anyone else figures it out I'll have a look later.

Here's the script i used for setup.ps1

[cmdletbinding()]
Param()

function setup() {

    Write-Verbose "In setup 1"
    Write-Output "Done setup 1"

}

setup

HTH


问:
Make bigger svg circle
I have an example of svg circle. But I dont know how to make bigger it in radius. I need this example cuz there are border-gradient with transperent inside. And I need not six parts, I need 12 parts. Please can somebody help me with it?

  <svg style="margin-top: 100px" width="300" height="300">
    <linearGradient id="linearColors1" x1="0" y1="0" x2="1" y2="1">
       <stop offset="0%" stop-color="#01E400"></stop>
       <stop offset="100%" stop-color="#FEFF01"></stop>
    </linearGradient>
    <linearGradient id="linearColors2" x1="0.5" y1="0" x2="0.5" y2="1">
       <stop offset="0%" stop-color="#FEFF01"></stop>
       <stop offset="100%" stop-color="#FF7E00"></stop>
    </linearGradient>
    <linearGradient id="linearColors3" x1="1" y1="0" x2="0" y2="1">
       <stop offset="0%" stop-color="#FF7E00"></stop>
       <stop offset="100%" stop-color="#FB0300"></stop>
    </linearGradient>
    <linearGradient id="linearColors4" x1="1" y1="1" x2="0" y2="0">
       <stop offset="0%" stop-color="#FB0300"></stop>
       <stop offset="100%" stop-color="#9B004A"></stop>
    </linearGradient>
    <linearGradient id="linearColors5" x1="0.5" y1="1" x2="0.5" y2="0">
       <stop offset="0%" stop-color="#9B004A"></stop>
       <stop offset="100%" stop-color="#7D0022"></stop>
    </linearGradient>
    <linearGradient id="linearColors6" x1="0" y1="1" x2="1" y2="0">
       <stop offset="0%" stop-color="#7D0022"></stop>
       <stop offset="100%" stop-color="#01E400"></stop>
    </linearGradient>
   <path d="M150 10 a120 120 0 0 1 103.9230 60"
        fill="none" stroke="url(#linearColors1)" stroke-width="20" />
  <path d="M253.9230 70 a120 120 0 0 1 0 120"
        fill="none" stroke="url(#linearColors2)" stroke-width="20" />
  <path d="M253.9230 190 a120 120 0 0 1 -103.9230 60"
        fill="none" stroke="url(#linearColors3)" stroke-width="20" />
  <path d="M150 250 a120 120 0 0 1 -103.9230 -60"
        fill="none" stroke="url(#linearColors4)" stroke-width="20" />
  <path d="M46.077 190 a120 120 0 0 1 0 -120"
        fill="none" stroke="url(#linearColors5)" stroke-width="20" />
  <path d="M46.077 70 a120 120 0 0 1 103.9230 -60"
        fill="none" stroke="url(#linearColors6)" stroke-width="20" />
</svg>

```

答:
This is how I would do it using svg: I am creating a arc representing the 12th part of a circle. Next I'm using the arc 12 times every time using a different gradient for the stroke.

In order to make a bigger circle you can either change the width of the svg element or in javascript change the r.

Of coarse you'll have to write the gradients you want for the arcs 7 to 11

const SVG_NS = "http://www.w3.org/2000/svg";
const SVG_XLINK = "http://www.w3.org/1999/xlink";
let r = 120;
let n = 12;
let a = 360/n;
let arad = 2*Math.PI/n
let points = []
let p1={
    x:r*Math.cos(0),
    y:r*Math.sin(0)
}
let p2={
    x:r*Math.cos(arad),
    y:r*Math.sin(arad)
}

  let path = document.createElementNS(SVG_NS, 'path');
  let d = `M${p1.x},${p1.y}A${r},${r} 0 0 1 ${p2.x},${p2.y}`;
  path.setAttributeNS(null,"d",d);
  path.setAttribute("id","thepath");
  theDefs.appendChild(path);

for(let i=0; i<n; i++){
  let use = document.createElementNS(SVG_NS, 'use');
  use.setAttributeNS(SVG_XLINK, 'xlink:href', '#thepath');
  use.setAttribute("stroke",`url(#linearColors${i})`)
  use.setAttribute("transform",`rotate(${a*i})`);
  svg.appendChild(use);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>use{stroke-width:20px;}</code>```

<svg id="svg" style="margin-top: 100px" viewBox="-150 -150 300 300" width="300">
<defs id="theDefs">
<linearGradient id="linearColors0" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#01E400"></stop>
<stop offset="100%" stop-color="#FEFF01"></stop>
</linearGradient>
<linearGradient id="linearColors1" x1="0.5" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#FEFF01"></stop>
<stop offset="100%" stop-color="#FF7E00"></stop>
</linearGradient>
<linearGradient id="linearColors2" x1="1" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#FF7E00"></stop>
<stop offset="100%" stop-color="#FB0300"></stop>
</linearGradient>
<linearGradient id="linearColors3" x1="1" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#FB0300"></stop>
<stop offset="100%" stop-color="#9B004A"></stop>
</linearGradient>
<linearGradient id="linearColors4" x1="0.5" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#9B004A"></stop>
<stop offset="100%" stop-color="#7D0022"></stop>
</linearGradient>
<linearGradient id="linearColors5" x1="0" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#7D0022"></stop>
<stop offset="100%" stop-color="#01E400"></stop>
</linearGradient>
<linearGradient id="linearColors6" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#01E400"></stop>
<stop offset="100%" stop-color="#FEFF01"></stop>
</linearGradient>
<linearGradient id="linearColors7" x1="0.5" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#FEFF01"></stop>
<stop offset="100%" stop-color="#FF7E00"></stop>
</linearGradient>
<linearGradient id="linearColors8" x1="1" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#FF7E00"></stop>
<stop offset="100%" stop-color="#FB0300"></stop>
</linearGradient>
<linearGradient id="linearColors9" x1="1" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#FB0300"></stop>
<stop offset="100%" stop-color="#9B004A"></stop>
</linearGradient>
<linearGradient id="linearColors10" x1="0.5" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#9B004A"></stop>
<stop offset="100%" stop-color="#7D0022"></stop>
</linearGradient>
<linearGradient id="linearColors11" x1="0" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#7D0022"></stop>
<stop offset="100%" stop-color="#01E400"></stop>
</linearGradient>
</defs>
</svg>```

Title: Make bigger svg circle

Body:
This is how I would do it using svg: I am creating a arc representing the 12th part of a circle. Next I'm using the arc 12 times every time using a different gradient for the stroke.

In order to make a bigger circle you can either change the width of the svg element or in javascript change the r.

Of coarse you'll have to write the gradients you want for the arcs 7 to 11

const SVG_NS = "http://www.w3.org/2000/svg";
const SVG_XLINK = "http://www.w3.org/1999/xlink";
let r = 120;
let n = 12;
let a = 360/n;
let arad = 2*Math.PI/n
let points = []
let p1={
    x:r*Math.cos(0),
    y:r*Math.sin(0)
}
let p2={
    x:r*Math.cos(arad),
    y:r*Math.sin(arad)
}

  let path = document.createElementNS(SVG_NS, 'path');
  let d = `M${p1.x},${p1.y}A${r},${r} 0 0 1 ${p2.x},${p2.y}`;
  path.setAttributeNS(null,"d",d);
  path.setAttribute("id","thepath");
  theDefs.appendChild(path);

for(let i=0; i<n; i++){
  let use = document.createElementNS(SVG_NS, 'use');
  use.setAttributeNS(SVG_XLINK, 'xlink:href', '#thepath');
  use.setAttribute("stroke",`url(#linearColors${i})`)
  use.setAttribute("transform",`rotate(${a*i})`);
  svg.appendChild(use);
}

use{stroke-width:20px;}

<svg id="svg" style="margin-top: 100px" viewBox="-150 -150 300 300" width="300">
<defs id="theDefs">
<linearGradient id="linearColors0" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#01E400"></stop>
<stop offset="100%" stop-color="#FEFF01"></stop>
</linearGradient>
<linearGradient id="linearColors1" x1="0.5" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#FEFF01"></stop>
<stop offset="100%" stop-color="#FF7E00"></stop>
</linearGradient>
<linearGradient id="linearColors2" x1="1" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#FF7E00"></stop>
<stop offset="100%" stop-color="#FB0300"></stop>
</linearGradient>
<linearGradient id="linearColors3" x1="1" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#FB0300"></stop>
<stop offset="100%" stop-color="#9B004A"></stop>
</linearGradient>
<linearGradient id="linearColors4" x1="0.5" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#9B004A"></stop>
<stop offset="100%" stop-color="#7D0022"></stop>
</linearGradient>
<linearGradient id="linearColors5" x1="0" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#7D0022"></stop>
<stop offset="100%" stop-color="#01E400"></stop>
</linearGradient>
<linearGradient id="linearColors6" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#01E400"></stop>
<stop offset="100%" stop-color="#FEFF01"></stop>
</linearGradient>
<linearGradient id="linearColors7" x1="0.5" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#FEFF01"></stop>
<stop offset="100%" stop-color="#FF7E00"></stop>
</linearGradient>
<linearGradient id="linearColors8" x1="1" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#FF7E00"></stop>
<stop offset="100%" stop-color="#FB0300"></stop>
</linearGradient>
<linearGradient id="linearColors9" x1="1" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#FB0300"></stop>
<stop offset="100%" stop-color="#9B004A"></stop>
</linearGradient>
<linearGradient id="linearColors10" x1="0.5" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#9B004A"></stop>
<stop offset="100%" stop-color="#7D0022"></stop>
</linearGradient>
<linearGradient id="linearColors11" x1="0" y1="1" x2="0" y2="1">
<stop offset="0%" stop-color="#7D0022"></stop>
<stop offset="100%" stop-color="#01E400"></stop>
</linearGradient>
</defs>
</svg>


问:
Getting error while running selenium with testng
I am new to automation programming. I am getting below error while running my firstprogram with TestNG in Selenium.

Could you please guide me?

The error I had:

```<code>[RemoteTestNG] detected TestNG version 6.14.3
System is opening browser
FAILED CONFIGURATION: @AfterMethod afterMethod
java.lang.NullPointerException
    at TestNG.afterMethod(TestNG.java:30)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:646)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

FAILED: verifytitle
java.lang.NoClassDefFoundError: com/google/common/collect/ImmutableMap
    at org.openqa.selenium.remote.service.DriverService$Builder.<init>(DriverService.java:259)
    at org.openqa.selenium.chrome.ChromeDriverService$Builder.<init>(ChromeDriverService.java:101)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:94)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at TestNG.verifytitle(TestNG.java:15)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.ClassNotFoundException: com.google.common.collect.ImmutableMap
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 30 more

===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
    Configuration Failures: 1, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
Configuration Failures: 1, Skips: 0
===============================================
</code>```

Code :

```<code>import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;

public class TestNG {

    WebDriver driver;
  @Test
  public void verifytitle()   {
      String path = "D:\\Automation\\chromedriver\\chromedriver.exe";
      System.setProperty("webdriver.chrome.driver", path) ;
      driver = new ChromeDriver();
      driver.get("https://www.google.com");

      System.out.println("Browser has opened google website");
      String currenttitle = driver.getTitle();
      System.out.println("Browser of title is " + currenttitle);
     }

  @BeforeMethod
  public void beforeMethod() {
      System.out.println("System is opening browser");
  }

  @AfterMethod
  public void afterMethod() {
      driver.close();
      System.out.println("Browser has closed browser");
  }

}
</code>```

答:
You are getting an exception java.lang.NoClassDefFoundError: com/google/common/collect/ImmutableMap. It means that you don't have Guava (which is a dependency for Selenium) on your classpath. Try using the following maven dependency in your pom.xml file and build your project.

```<code><dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.0.0-alpha-6</version>
</dependency>
</code>```

If the above doesn't work or solve your problem, then include the following dependency for guava directly in your pom as below. Note: Do not include both in your pom.xml

```<code><dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>19.0</version>
</dependency>
</code>```

If you don't use maven, you could download the above jars from https://mvnrepository.com/ and include it in your classpath.

Body:
I am new to automation programming. I am getting below error while running my firstprogram with TestNG in Selenium.

Could you please guide me?

The error I had:

[RemoteTestNG] detected TestNG version 6.14.3
System is opening browser
FAILED CONFIGURATION: @AfterMethod afterMethod
java.lang.NullPointerException
    at TestNG.afterMethod(TestNG.java:30)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:646)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

FAILED: verifytitle
java.lang.NoClassDefFoundError: com/google/common/collect/ImmutableMap
    at org.openqa.selenium.remote.service.DriverService$Builder.<init>(DriverService.java:259)
    at org.openqa.selenium.chrome.ChromeDriverService$Builder.<init>(ChromeDriverService.java:101)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:94)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at TestNG.verifytitle(TestNG.java:15)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.ClassNotFoundException: com.google.common.collect.ImmutableMap
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 30 more

===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
    Configuration Failures: 1, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
Configuration Failures: 1, Skips: 0
===============================================

Code :

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;

public class TestNG {

    WebDriver driver;
  @Test
  public void verifytitle()   {
      String path = "D:\\Automation\\chromedriver\\chromedriver.exe";
      System.setProperty("webdriver.chrome.driver", path) ;
      driver = new ChromeDriver();
      driver.get("https://www.google.com");

      System.out.println("Browser has opened google website");
      String currenttitle = driver.getTitle();
      System.out.println("Browser of title is " + currenttitle);
     }

  @BeforeMethod
  public void beforeMethod() {
      System.out.println("System is opening browser");
  }

  @AfterMethod
  public void afterMethod() {
      driver.close();
      System.out.println("Browser has closed browser");
  }

}

Body:
You are getting an exception java.lang.NoClassDefFoundError: com/google/common/collect/ImmutableMap. It means that you don't have Guava (which is a dependency for Selenium) on your classpath. Try using the following maven dependency in your pom.xml file and build your project.

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.0.0-alpha-6</version>
</dependency>

If the above doesn't work or solve your problem, then include the following dependency for guava directly in your pom as below. Note: Do not include both in your pom.xml

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>19.0</version>
</dependency>

If you don't use maven, you could download the above jars from https://mvnrepository.com/ and include it in your classpath.


问:
Search html table
I have a website that shows a table with data from a database, I'm trying to implement a search feature but can't get it to work.
The code for the search feature is mostly copied from a tutorial I watched, as I'm fairly new to coding. I have tried looking for spelling mistakes, missing brackets, etc, but couldn't get it to work.
So I'm hoping someone can tell me what I'm doing wrong :)

index.php:

```<code><!DOCTYPE html>

<html lang="en" dir="ltr">

  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
    <meta name="description" content="Inventar">
    <meta name="author" content="Martin Eide Bjørndal">
    <title>Ut</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="/src/css/style.css">
     <!-- jQuery library -->
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
  </head>

  <body>
    <button class="back" onclick="window.location='../'">
      <img src="/src/icons/back.png">
    </button> <!-- Tilbake knapp -->

    <div class="container-fluid" id="utskjekkcontainer">
      <div class="row justify-content-center">
        <div class="col-mv-10 bg-light mt-5 rounded p-3">
          <h1 class="text-primary p-2">Utskjekk</h1>
          <hr>
          <div class="form-inline">
            <label for="search" class="font-weight-bold lead text-dark">Søk</label>
            <input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">
          </div>
          <hr>
          <?php
            include "../src/fn/init.php";
            $stmt=$conn->prepare("SELECT * FROM inventar");
            $stmt->execute();
            $result=$stmt->get_result();
          ?>
          <table class="table table-hover table-light table-striped" id="table_data">
            <thead>
              <tr>
                <th>#</th>
                <th>Navn</th>
                <th>Antall</th>
                <th>Tilgjengelig</th>
                <th>Plassering</th>
                <th>Vekt (kg)</th>
                <th>Størrelse x y z (cm)</th>
                <th>Kommentar</th>
              </tr>
            </thead>
            <tbody>
              <?php while($row=$result->fetch_assoc()){ ?>
                <tr>
                  <td><?php echo $row["id"]; ?></td>
                  <td><?php echo $row["navn"]; ?></td>
                  <td><?php echo $row["antall"]; ?></td>
                  <td><?php echo $row["antall_tilgjengelig"]; ?></td>
                  <td><?php echo $row["plassering"]; ?></td>
                  <td><?php echo $row["vekt"]; ?></td>
                  <td><?php echo $row["størrelse"]; ?></td>
                  <td><?php echo $row["kommentar"]; ?></td>
                </tr>
              <?php } ?>
             </tbody>
           </table>
        </div>
      </div>
    </div>

    <script type="text/javascript">
      $(document).ready(function(){
        $('#search_text').keyup(function(){
          var search = $(this).val();
          $.ajax({
            url:'action.php',
            method:'post',
            data:{query:search},
            success:function(response){
              $('#table_data').html(response);
            }
          });
        });
      });
    </script>

  </body>

</html>
</code>```

action.php:

```<code>   <?php

    include "../src/fn/init.php";
    $output = "";

    if(isset($_POST["query"])){
        $search = $_POST["query"];
        $stmt = $conn->prepare("SELECT * FROM inventar WHERE navn LIKE CONCAT('%','?','%') OR id LIKE CONCAT('%','?','%') OR plassering LIKE CONCAT('%','?','%')");
        $stmt->bind_param("sss",$search, $search, $search);
    } else {
        $stmt=$conn->prepare("SELECT * FROM inventar");
    };
    $stmt->execute();
    $result=$stmt->get_result();

    if($result->num_rows>0){
        $output = "<thead>
                        <tr>
                            <th>#</th>
                            <th>Navn</th>
                            <th>Antall</th>
                            <th>Tilgjengelig</th>
                            <th>Plassering</th>
                            <th>Vekt (kg)</th>
                            <th>Størrelse x y z (cm)</th>
                            <th>Kommentar</th>
                        </tr>
                    </thead>
                    <tbody>";

        while($row=$result->fetch_assoc()){
            $output .= "
                <tr>
                    <td>".$row["id"]."</td>
                    <td>".$row["navn"]."</td>
                    <td>".$row["antall"]."</td>
                    <td>".$row["antall_tilgjengelig"]."</td>
                    <td>".$row["plassering"]."</td>
                    <td>".$row["vekt"]."</td>
                    <td>".$row["størrelse"]."</td>
                    <td>".$row["kommentar"]."</td>
                </tr>";
        };
        $output .= "</tbody>";
        echo $output;
    } else {
        echo "<h3> Found no match!</h3>";
    };

?>
</code>```

答:
you can use JQuery Table

```<code><script src="js/jquery-3.1.0.js"></script> <script src="js/jquery.dataTables.min.js"></script>
</code>```

and declare script like this to connect with ur table

`````

For more info, u can read this documentation https://datatables.net/

Title: Search html table

Body:
I have a website that shows a table with data from a database, I'm trying to implement a search feature but can't get it to work.
The code for the search feature is mostly copied from a tutorial I watched, as I'm fairly new to coding. I have tried looking for spelling mistakes, missing brackets, etc, but couldn't get it to work.
So I'm hoping someone can tell me what I'm doing wrong :)

index.php:

<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
    <meta name="description" content="Inventar">
    <meta name="author" content="Martin Eide Bjørndal">
    <title>Ut</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="/src/css/style.css">

    <button class="back" onclick="window.location='../'">

    </button>

Utskjekk

            Søk
            <input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">

          <?php
            include "../src/fn/init.php";
            $stmt=$conn->prepare("SELECT * FROM inventar");
            $stmt->execute();
            $result=$stmt->get_result();
          ?>

                #
                Navn
                Antall
                Tilgjengelig
                Plassering
                Vekt (kg)
                Størrelse x y z (cm)
                Kommentar

              <?php while($row=$result->fetch_assoc()){ ?>

                  <?php echo $row["id"]; ?>
                  <?php echo $row["navn"]; ?>
                  <?php echo $row["antall"]; ?>
                  <?php echo $row["antall_tilgjengelig"]; ?>
                  <?php echo $row["plassering"]; ?>
                  <?php echo $row["vekt"]; ?>
                  <?php echo $row["størrelse"]; ?>
                  <?php echo $row["kommentar"]; ?>

              <?php } ?>

action.php:

   <?php

    include "../src/fn/init.php";
    $output = "";

    if(isset($_POST["query"])){
        $search = $_POST["query"];
        $stmt = $conn->prepare("SELECT * FROM inventar WHERE navn LIKE CONCAT('%','?','%') OR id LIKE CONCAT('%','?','%') OR plassering LIKE CONCAT('%','?','%')");
        $stmt->bind_param("sss",$search, $search, $search);
    } else {
        $stmt=$conn->prepare("SELECT * FROM inventar");
    };
    $stmt->execute();
    $result=$stmt->get_result();

    if($result->num_rows>0){
        $output = "

                            #
                            Navn
                            Antall
                            Tilgjengelig
                            Plassering
                            Vekt (kg)
                            Størrelse x y z (cm)
                            Kommentar

";

        while($row=$result->fetch_assoc()){
            $output .= "

                    ".$row["id"]."
                    ".$row["navn"]."
                    ".$row["antall"]."
                    ".$row["antall_tilgjengelig"]."
                    ".$row["plassering"]."
                    ".$row["vekt"]."
                    ".$row["størrelse"]."
                    ".$row["kommentar"]."

";
        };
        $output .= "
";
        echo $output;
    } else {
        echo "
 Found no match!
";
    };

?>

Body:
you can use JQuery Table

<script src="js/jquery-3.1.0.js"></script> <script src="js/jquery.dataTables.min.js"></script>

and declare script like this to connect with ur table

`<script>
$(document).ready(function(){
    $('#table_data').DataTable();
});
</script>`

For more info, u can read this documentation https://datatables.net/


问:
Deinit UIImpactFeedbackGenerator
I init a UIImpactFeedbackGenerator with a timer with TimeInterval=1.0. After some seconds, I call the deinitHapticFeedback(), as described below and navigate to the next view controller, but the feedback doesn't stop and keeps occurring for about ten seconds after the new VC appears.

(Also, I tried calling deinitHapticFeedback() in viewWillDisappear(_ animated: Bool), but the same thing happens.)

Do you have any idea for a more optimal deinit function for a UIFeedbackGenerator ?

```<code>private var feedbackGenerator: UIImpactFeedbackGenerator? = nil

private func generateHapticFeedback() {
    feedbackGenerator = UIImpactFeedbackGenerator(style: .medium)
    feedbackGenerator?.prepare()
    DispatchQueue.main.async {
        self.feedbackGenerator?.impactOccurred()
    }
}

private func deinitHapticFeedback() {
    feedbackGenerator = nil
}
</code>```

Thanks in advance!

答:
You are creating a new UIImpactFeedbackGenerator every time generateHapticFeedback method is called. So even if you set feedbackGenerator to nil, a new object will be created at this line feedbackGenerator = UIImpactFeedbackGenerator(style: .medium).

Instead of setting feedbackGenerator to nil you have invalidate your timer. If you are using Timer class to schedule timer you can call invalidate method like this timer.invalidate().

```<code>private func deinitHapticFeedback() {
    timer.invalidate() // invalidate timer
}
</code>```

You can also restart the timer as well when view controller appears again (if required).

Title: Deinit UIImpactFeedbackGenerator

Body:
I init a UIImpactFeedbackGenerator with a timer with TimeInterval=1.0. After some seconds, I call the deinitHapticFeedback(), as described below and navigate to the next view controller, but the feedback doesn't stop and keeps occurring for about ten seconds after the new VC appears.

(Also, I tried calling deinitHapticFeedback() in viewWillDisappear(_ animated: Bool), but the same thing happens.)

Do you have any idea for a more optimal deinit function for a UIFeedbackGenerator ?

private var feedbackGenerator: UIImpactFeedbackGenerator? = nil

private func generateHapticFeedback() {
    feedbackGenerator = UIImpactFeedbackGenerator(style: .medium)
    feedbackGenerator?.prepare()
    DispatchQueue.main.async {
        self.feedbackGenerator?.impactOccurred()
    }
}

private func deinitHapticFeedback() {
    feedbackGenerator = nil
}

Thanks in advance!

Body:
You are creating a new UIImpactFeedbackGenerator every time generateHapticFeedback method is called. So even if you set feedbackGenerator to nil, a new object will be created at this line feedbackGenerator = UIImpactFeedbackGenerator(style: .medium).

Instead of setting feedbackGenerator to nil you have invalidate your timer. If you are using Timer class to schedule timer you can call invalidate method like this timer.invalidate().

private func deinitHapticFeedback() {
    timer.invalidate() // invalidate timer
}

You can also restart the timer as well when view controller appears again (if required).


问:
How can improve my text topic classifier?
I am developing a text topic classifier that can label sentences or small questions.
So far it can label around 30 known subjects.

Works well, but it begins to confuse similar questions with each other.

For example these 3 labels:

1) Label - backup_proxy_intranet:
How to set up a backup proxy for intranet app?
... and 140 similar questions containing 'backup proxy for intranet app'...

2) Label - smartphone_intranet:
How to use intranet app in my smartphone? and
... and 140 similar questions containing 'intranet app in my smartphone'...

3) Label - ticket_intranet: How to relate a ticket order with the intranet app?
... and 140 similar questions containing 'ticket order with the intranet app'...

After training these 3 always returns the label backup_proxy_intranet.
what can i do to separate them?

```<code>series = series.dropna()
series = shuffle(series)

X_stemmed = []
for x_t in series['phrase']:
    stemmed_text = [stemmer.stem(i) for i in word_tokenize(x_t)]
    X_stemmed.append(' '.join(stemmed_text))

x_normalized = []
for x_t in X_stemmed:
    temp_corpus=x_t.split(' ')
    corpus=[token for token in temp_corpus if token not in stops]
    x_normalized.append(' '.join(corpus))

X_train,X_test,y_train,y_test = train_test_split(x_normalized,series['target'],random_state=0,test_size=0.20)

vect = CountVectorizer(ngram_range=(1,3)).fit(X_train)
X_train_vectorized = vect.transform(X_train)

sampler = SMOTE()
model = make_pipeline(sampler, LogisticRegression())
print()
print("-->Model: ")
print(model)
print()
print("-->Training... ")
model.fit(X_train_vectorized,y_train)

filename = '/var/www/html/python/intraope_bot/lib/textTopicClassifier.model'
pickle.dump(model,open(filename, 'wb'))
filename2 = '/var/www/html/python/intraope_bot/lib/textTopicClassifier.vector'
pickle.dump(vect,open(filename2, 'wb'))
</code>```

Best Regards!

答: I got best results using multinomial Naive bayes also from scikit learn</p>

Body:
I am developing a text topic classifier that can label sentences or small questions.
So far it can label around 30 known subjects.

Works well, but it begins to confuse similar questions with each other.

For example these 3 labels:

1) Label - backup_proxy_intranet:
How to set up a backup proxy for intranet app?
... and 140 similar questions containing 'backup proxy for intranet app'...

2) Label - smartphone_intranet:
How to use intranet app in my smartphone? and
... and 140 similar questions containing 'intranet app in my smartphone'...

3) Label - ticket_intranet: How to relate a ticket order with the intranet app?
... and 140 similar questions containing 'ticket order with the intranet app'...

After training these 3 always returns the label backup_proxy_intranet.
what can i do to separate them?

series = series.dropna()
series = shuffle(series)

X_stemmed = []
for x_t in series['phrase']:
    stemmed_text = [stemmer.stem(i) for i in word_tokenize(x_t)]
    X_stemmed.append(' '.join(stemmed_text))

x_normalized = []
for x_t in X_stemmed:
    temp_corpus=x_t.split(' ')
    corpus=[token for token in temp_corpus if token not in stops]
    x_normalized.append(' '.join(corpus))

X_train,X_test,y_train,y_test = train_test_split(x_normalized,series['target'],random_state=0,test_size=0.20)

vect = CountVectorizer(ngram_range=(1,3)).fit(X_train)
X_train_vectorized = vect.transform(X_train)

sampler = SMOTE()
model = make_pipeline(sampler, LogisticRegression())
print()
print("-->Model: ")
print(model)
print()
print("-->Training... ")
model.fit(X_train_vectorized,y_train)

filename = '/var/www/html/python/intraope_bot/lib/textTopicClassifier.model'
pickle.dump(model,open(filename, 'wb'))
filename2 = '/var/www/html/python/intraope_bot/lib/textTopicClassifier.vector'
pickle.dump(vect,open(filename2, 'wb'))

Best Regards!


问:
VB6 Get Folder Path when Right-Clicking with the mouse
I have created a very small project that consists of obtaining the path of a directory. for this I added a Textbox to the form which is the one that will show the collected path of the directory.

After compiling it I placed in: C:. and then I added it to the right-click mouse menu. but here comes my problem. my goal was to have my app to collect the path of the folder when ever I right-click and run my app in any folder I choose when right-clicking at it. for example: my documents, desktop, and so on. but instead my app always get the path where I placed it, in this case: C:.

I tried manually but I don't want to do it this way.
In this example I have to run my project first and then drog and drop a file from that folder into the textbox.

```<code>Private Sub Command1_Click()
   Dim strFullFilePath As String
   strFullFilePath = Text1.Text
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   Text2 = fso.GetParentFolderName(strFullFilePath)
End Sub

Private Sub Text1_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single)
   Text1 = Data.Files(1)
End Sub
</code>```

I will appreciate any suggestion. I've searched the site for the same question as mine, but I did not find any.

Thanks in advance
Regards

答:
Change the program's registration, adding "%V" at the end

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\Background\shell\Project\command] @="C:\\Project.exe" "%V"

Explorer will then pass the directory to you on the command line. You can read command line parameters using the Command() function in VB.

Private Sub Command1_Click()
   Dim strFullFilePath As String
   strFullFilePath = Text1.Text
   Text2 = Command()
End Sub
```

Body:
I have created a very small project that consists of obtaining the path of a directory. for this I added a Textbox to the form which is the one that will show the collected path of the directory.

After compiling it I placed in: C:. and then I added it to the right-click mouse menu. but here comes my problem. my goal was to have my app to collect the path of the folder when ever I right-click and run my app in any folder I choose when right-clicking at it. for example: my documents, desktop, and so on. but instead my app always get the path where I placed it, in this case: C:.

I tried manually but I don't want to do it this way.
In this example I have to run my project first and then drog and drop a file from that folder into the textbox.

Private Sub Command1_Click()
   Dim strFullFilePath As String
   strFullFilePath = Text1.Text
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   Text2 = fso.GetParentFolderName(strFullFilePath)
End Sub

Private Sub Text1_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single)
   Text1 = Data.Files(1)
End Sub

I will appreciate any suggestion. I've searched the site for the same question as mine, but I did not find any.

Thanks in advance
Regards


问:
Android-java- How to sort a list of objects by a certain value within the object
Im trying to sort through an arraylist of objects by a particular value within the object. What would be the best approach to do such a thing. Should I use Collections.sort() with some kind of comparator?

Im trying to sort a list of objects by a float value they hold in one of the variables.

EDIT:
This is what I have so far:

```<code>public class CustomComparator implements Comparator<Marker> {
    @Override
    public int compare(Mark o1, Mark o2) {
        return o1.getDistance().compareTo(o2.getDistance());
    }
}
</code>```

the error states: Cannot invoke compareTo(double) on the primitive type double.

Is it because a comparator cant return anything other than a certain type?

答:
For Kotlin, you can use this function

```<code>fun sortList(list: List<YourCustomPOJOClass?>) {

    //descending
    Collections.sort(
        list
    ) { o1, o2 -> Integer.valueOf(o1!!.intValueXYZ!!).compareTo(o2!!.intValueXYZ!!) }

//    //ascending
//    Collections.sort(
//        list
//    ) { o1, o2 -> Integer.valueOf(o2!!.intValueXYZ!!).compareTo(o1!!.intValueXYZ!!) }
}
</code>```

and just call it in your activity or fragment by

```<code>sortList(list)
</code>```

Body:
Im trying to sort through an arraylist of objects by a particular value within the object. What would be the best approach to do such a thing. Should I use Collections.sort() with some kind of comparator?

Im trying to sort a list of objects by a float value they hold in one of the variables.

EDIT:
This is what I have so far:

public class CustomComparator implements Comparator<Marker> {
    @Override
    public int compare(Mark o1, Mark o2) {
        return o1.getDistance().compareTo(o2.getDistance());
    }
}

the error states: Cannot invoke compareTo(double) on the primitive type double.

Is it because a comparator cant return anything other than a certain type?

Body:
For Kotlin, you can use this function

fun sortList(list: List<YourCustomPOJOClass?>) {

    //descending
    Collections.sort(
        list
    ) { o1, o2 -> Integer.valueOf(o1!!.intValueXYZ!!).compareTo(o2!!.intValueXYZ!!) }

//    //ascending
//    Collections.sort(
//        list
//    ) { o1, o2 -> Integer.valueOf(o2!!.intValueXYZ!!).compareTo(o1!!.intValueXYZ!!) }
}

and just call it in your activity or fragment by

sortList(list)


问:
Getting cannot get error on Postman for all my API's
I am developing a backend project using nodejs, express and mongoose. But when I try to test my endpoints on Postman I keep getting this error. I am new to nodejs so I am not quite sure what this means.

This is my main js file index.js

```<code>const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const apiRoute = require('./routes/api');
const adminRoute = require('./routes/admin');

mongoose.Promise = global.Promise;

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`listening to port ${port}`));
app.use(bodyParser.json());

app.use('/api', apiRoute);
app.use('/admin', adminRoute);

// As per Mongoose Documentation
const options = {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true,

    autoIndex: false, // Don't build indexes
    //reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
    //reconnectInterval: 500, // Reconnect every 500ms
    poolSize: 10, // Maintain up to 10 socket connections
    // If not connected, return errors immediately rather than waiting for reconnect
    bufferMaxEntries: 0,
    connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
    socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
    family: 4 // Use IPv4, skip trying IPv6
};

mongoose.connect('mongodb://localhost:27017/admin', options).then(
    () => {
        console.log('db connected');
    },
    (err) => {
        console.log('connection error');
    }
);
</code>```

This is /routes/api.js

```<code>const router = express.Router();
const Ticket = require('../models/Ticket');
const Joi = require('joi');
const { seatValidation, typeValidation } = require('../validation');

//View all tickets
router.get('/tickets', async (req, res) => {
    try {
        let tickets = await Ticket.find();
        res.json(tickets);
    } catch (error) {
        res.json({ message: error });
    }
});

//View Ticket Status
router.get('/status/seat/:seat', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { error } = seatValidation(req.params.seat);

    if (error) return res.status(404).send(error);

    try {
        let status = await Ticket.findOne({ seat: parseInt(req.params.seat) }).select('status');
        res.json(status);
    } catch (error) {
        res.json({ message: error });
    }
});

//View Details of person owning the ticket
router.get('/details/seat/:seat', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { error } = seatValidation(req.params.seat);

    if (error) return res.status(404).send(error);

    try {
        let status = await Ticket.findOne({ seat: parseInt(req.params.seat) })
            .select('status')
            .select('first_name')
            .select('last_name')
            .select('gender')
            .select('email')
            .select('mobile');
        res.json(status);
    } catch (error) {
        res.json({ message: error });
    }
});

// adding empty seats
router.post('/add', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { error } = seatValidation(req.body);

    if (error) return res.status(404).send(error);

    let ticket = new Ticket({
        seat: req.body.seat,
        status: 'open'
    });

    let ticketSaved = await ticket.save();
    try {
        res.json(ticketSaved);
    } catch (error) {
        res.json({ message: error });
    }
});

//View all open tickets
router.get('/tickets/open', async (req, res) => {
    try {
        let tickets = await Ticket.find({ status: 'open' });
        res.json(tickets);
    } catch (error) {
        res.json({ message: error });
    }
});

//View all closed tickets
router.get('/tickets/closed', async (req, res) => {
    try {
        let tickets = await Ticket.find({ status: 'close' });
        res.json(tickets);
    } catch (error) {
        res.json({ message: error });
    }
});

//Update the ticket status (open/close + adding user details)
router.put('/status/:seat/:type', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { seatError } = seatValidation(req.params.seat);

    if (seatError) return res.status(404).send(seatError);

    // input validation - type should be a string and should be 'open' or 'close'
    let { typeError } = typeValidation(req.params.type);

    if (typeError) return res.status(400).send(typeError);

    try {
        let type = req.params.type;
        if (type === 'open') {
            try {
                let ticket = await Ticket.updateOne(
                    { seat: req.params.seat },
                    {
                        $set: { status: 'open' },
                        $unset: { first_name: 1, last_name: 1, gender: 1, email: 1, mobile: 1 }
                    }
                );
                res.json(ticket);
            } catch (error) {
                res.json({ message: error });
            }
        } else if (type === 'close') {
            // input validation - type should be a string and should be 'open' or 'close'
            let ticketSchema = {
                first_name: Joi.string().min(3).required(),
                last_name: Joi.string().min(3).required(),
                gender: Joi.string().valid('M').valid('F').valid('U').required(),
                email: Joi.string().email().required(),
                mobile: Joi.number().integer().min(1000000000).max(9999999999).required()
            };

            let validation = Joi.validate(req.body, ticketSchema);

            if (validation.error) {
                res.status(400).send(validation.error);
                return;
            }

            try {
                let ticket = await Ticket.updateOne(
                    { seat: req.params.seat },
                    {
                        $set: {
                            status: 'close',
                            first_name: req.body.first_name,
                            last_name: req.body.last_name,
                            gender: req.body.gender,
                            email: req.body.email,
                            mobile: req.body.mobile
                        }
                    }
                );
                res.json(ticket);
            } catch (error) {
                res.json({ message: error });
            }
        }
    } catch (error) {
        res.json({ message: error });
    }
});

module.exports = router;
</code>```

This is schema /models/Ticket.js

```<code>const mongoose = require('mongoose');

const TicketSchema = mongoose.Schema({
    seat: Number,
    status: String,
    first_name: String,
    last_name: String,
    gender: String,
    email: String,
    mobile: Number
});

module.exports = mongoose.model('Ticket', TicketSchema);
</code>```

Can anyone help me out?

Here is the error from postman:
Postman screenshot

答:
In your index.js file you have specified route for apiRoute as /api and in the screenshot, it appears that you have missed that.
Please use the URL as localhost:3000/api/tickets
instead of just localhost:3000/tickets and it should work correctly.
As you can see as you have missed the /api part the express does not have the path you requested and is returning the status of 404 not found.

Body:
I am developing a backend project using nodejs, express and mongoose. But when I try to test my endpoints on Postman I keep getting this error. I am new to nodejs so I am not quite sure what this means.

This is my main js file index.js

const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const apiRoute = require('./routes/api');
const adminRoute = require('./routes/admin');

mongoose.Promise = global.Promise;

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`listening to port ${port}`));
app.use(bodyParser.json());

app.use('/api', apiRoute);
app.use('/admin', adminRoute);

// As per Mongoose Documentation
const options = {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true,

    autoIndex: false, // Don't build indexes
    //reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
    //reconnectInterval: 500, // Reconnect every 500ms
    poolSize: 10, // Maintain up to 10 socket connections
    // If not connected, return errors immediately rather than waiting for reconnect
    bufferMaxEntries: 0,
    connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
    socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
    family: 4 // Use IPv4, skip trying IPv6
};

mongoose.connect('mongodb://localhost:27017/admin', options).then(
    () => {
        console.log('db connected');
    },
    (err) => {
        console.log('connection error');
    }
);

This is /routes/api.js

const router = express.Router();
const Ticket = require('../models/Ticket');
const Joi = require('joi');
const { seatValidation, typeValidation } = require('../validation');

//View all tickets
router.get('/tickets', async (req, res) => {
    try {
        let tickets = await Ticket.find();
        res.json(tickets);
    } catch (error) {
        res.json({ message: error });
    }
});

//View Ticket Status
router.get('/status/seat/:seat', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { error } = seatValidation(req.params.seat);

    if (error) return res.status(404).send(error);

    try {
        let status = await Ticket.findOne({ seat: parseInt(req.params.seat) }).select('status');
        res.json(status);
    } catch (error) {
        res.json({ message: error });
    }
});

//View Details of person owning the ticket
router.get('/details/seat/:seat', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { error } = seatValidation(req.params.seat);

    if (error) return res.status(404).send(error);

    try {
        let status = await Ticket.findOne({ seat: parseInt(req.params.seat) })
            .select('status')
            .select('first_name')
            .select('last_name')
            .select('gender')
            .select('email')
            .select('mobile');
        res.json(status);
    } catch (error) {
        res.json({ message: error });
    }
});

// adding empty seats
router.post('/add', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { error } = seatValidation(req.body);

    if (error) return res.status(404).send(error);

    let ticket = new Ticket({
        seat: req.body.seat,
        status: 'open'
    });

    let ticketSaved = await ticket.save();
    try {
        res.json(ticketSaved);
    } catch (error) {
        res.json({ message: error });
    }
});

//View all open tickets
router.get('/tickets/open', async (req, res) => {
    try {
        let tickets = await Ticket.find({ status: 'open' });
        res.json(tickets);
    } catch (error) {
        res.json({ message: error });
    }
});

//View all closed tickets
router.get('/tickets/closed', async (req, res) => {
    try {
        let tickets = await Ticket.find({ status: 'close' });
        res.json(tickets);
    } catch (error) {
        res.json({ message: error });
    }
});

//Update the ticket status (open/close + adding user details)
router.put('/status/:seat/:type', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { seatError } = seatValidation(req.params.seat);

    if (seatError) return res.status(404).send(seatError);

    // input validation - type should be a string and should be 'open' or 'close'
    let { typeError } = typeValidation(req.params.type);

    if (typeError) return res.status(400).send(typeError);

    try {
        let type = req.params.type;
        if (type === 'open') {
            try {
                let ticket = await Ticket.updateOne(
                    { seat: req.params.seat },
                    {
                        $set: { status: 'open' },
                        $unset: { first_name: 1, last_name: 1, gender: 1, email: 1, mobile: 1 }
                    }
                );
                res.json(ticket);
            } catch (error) {
                res.json({ message: error });
            }
        } else if (type === 'close') {
            // input validation - type should be a string and should be 'open' or 'close'
            let ticketSchema = {
                first_name: Joi.string().min(3).required(),
                last_name: Joi.string().min(3).required(),
                gender: Joi.string().valid('M').valid('F').valid('U').required(),
                email: Joi.string().email().required(),
                mobile: Joi.number().integer().min(1000000000).max(9999999999).required()
            };

            let validation = Joi.validate(req.body, ticketSchema);

            if (validation.error) {
                res.status(400).send(validation.error);
                return;
            }

            try {
                let ticket = await Ticket.updateOne(
                    { seat: req.params.seat },
                    {
                        $set: {
                            status: 'close',
                            first_name: req.body.first_name,
                            last_name: req.body.last_name,
                            gender: req.body.gender,
                            email: req.body.email,
                            mobile: req.body.mobile
                        }
                    }
                );
                res.json(ticket);
            } catch (error) {
                res.json({ message: error });
            }
        }
    } catch (error) {
        res.json({ message: error });
    }
});

module.exports = router;

This is schema /models/Ticket.js

const mongoose = require('mongoose');

const TicketSchema = mongoose.Schema({
    seat: Number,
    status: String,
    first_name: String,
    last_name: String,
    gender: String,
    email: String,
    mobile: Number
});

module.exports = mongoose.model('Ticket', TicketSchema);

Can anyone help me out?

Here is the error from postman:
Postman screenshot


问:
Add title to a div in code behind is not appeared
I'm using Dialog popup from JQuery UI. I want to add a title to the popup and I found that only the title of the div should be filled.

When I write a constant value in the markup then the title is appeared, but when it's added in the code behind it is not appeared.

```<code>myDiv.Attributes["title"] = "some value";
</code>```

-

```<code><div id="myDiv" class="UsersDialogClass"
                       runat="server" style="display: none">
</code>```

Any idea!

答:
How about:

```<code>myDiv.Attributes.Add("title", "some value");
</code>```

with the fact it is on Page_Load event.

Body:
I'm using Dialog popup from JQuery UI. I want to add a title to the popup and I found that only the title of the div should be filled.

When I write a constant value in the markup then the title is appeared, but when it's added in the code behind it is not appeared.

myDiv.Attributes["title"] = "some value";

-

Any idea!

Body:
How about:

myDiv.Attributes.Add("title", "some value");

with the fact it is on Page_Load event.


问:
Restore MySQL InnoDb from *.frm files
I was working on my Mac when it crashed, the HDD got corrupted and cant be repaired unless formating, so i  recovered my DB data from OS X, i got all the folder , and now im trying to restore it in a windows computer while i repair the Mac.
I have tried several post here that says tha i just have to copy all the files to the data folder in the new MySQL instalment on windows , i already tried copying the db folder with the frm files and the ind files, then i copied the ibdata1 file and restarted the service but even so it didn't work , the i read that i had to copy also the ib_logfile0 and ib_logfile1 and so i did, but then the service didnt want to run.When i restore the original log it works but i can only see the tables in mysqlworkbench but i can't make querys to them because the log says that the tables doesnt exist even that i can see them.

Im using mysql 5.6 on windows 7 and mysqlworkbench.

Currently i have the *.frm files , the *.ibd files, the ibdata1, the ib_logfiles0 and 1 , that i rescued from my os x hdd, i copied all of them to the windows mysql installment and so the mysql service wont start.
Heres the current log when i try to start the service.

```<code> FROM CARLOSDESKTOP.err:

    2014-02-11 13:27:10  7108  Note  Plugin 'FEDERATED' is disabled.

          2014-02-11 13:27:10 3a8 InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.

    2014-02-11 13:27:10  7108  Note  InnoDB: Using atomics to ref count buffer pool pages

    2014-02-11 13:27:10  7108  Note  InnoDB: The InnoDB memory heap is disabled

    2014-02-11 13:27:10  7108  Note  InnoDB: Mutexes and rw_locks use Windows interlocked functions

    2014-02-11 13:27:10  7108  Note  InnoDB: Compressed tables use zlib 1.2.3

    2014-02-11 13:27:10  7108  Note  InnoDB: Not using CPU crc32 instructions

    2014-02-11 13:27:10  7108  Note  InnoDB: Initializing buffer pool, size = 8.0M

    2014-02-11 13:27:10  7108  Note  InnoDB: Completed initialization of buffer pool

    2014-02-11 13:27:10  7108  Note  InnoDB: Highest supported file format is Barracuda.

2014-02-11 13:27:12 - Server start done.

2014-02-11 13:27:12 - Status check of service 'MySQL56' returned start pending

2014-02-11 13:47:27 - Status check of service 'MySQL56' returned stopped

FROM CARLOSDESKTOP.err:

    2014-02-11 13:27:12  7108  Note  InnoDB: The log sequence numbers 8610473 and 8610473 in ibdata files do not match the log sequence number 13883013 in the ib_logfiles!

    2014-02-11 13:27:12  7108  Note  InnoDB: Database was not shutdown normally!

    2014-02-11 13:27:12  7108  Note  InnoDB: Starting crash recovery.

    2014-02-11 13:27:12  7108  Note  InnoDB: Reading tablespace information from the .ibd files...

    2014-02-11 13:27:13  7108  ERROR  InnoDB: space header page consists of zero bytes in tablespace .\demo\record.ibd (table demo/record)

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size:1024 Pages to analyze:64

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size: 1024, Possible space_id count:0

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size:2048 Pages to analyze:64

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size: 2048, Possible space_id count:0

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size:4096 Pages to analyze:32

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size: 4096, Possible space_id count:0

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size:8192 Pages to analyze:16

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size: 8192, Possible space_id count:0

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size:16384 Pages to analyze:8

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size: 16384, Possible space_id count:0

          InnoDB: Error: could not open single-table tablespace file .\demo\record.ibd

          InnoDB: We do not continue the crash recovery, because the table may become

          InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.

          InnoDB: To fix the problem and start mysqld:

          InnoDB: 1) If there is a permission problem in the file and mysqld cannot

          InnoDB: open the file, you should modify the permissions.

          InnoDB: 2) If the table is not needed, or you can restore it from a backup,

          InnoDB: then you can remove the .ibd file, and InnoDB will do a normal

          InnoDB: crash recovery and ignore that table.

          InnoDB: 3) If the file system or the disk is broken, and you cannot remove

          InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf

          InnoDB: and force InnoDB to continue crash recovery here.

2014-02-11 13:47:28 - Status check of service 'MySQL56' returned stopped

2014-02-11 13:47:28 - Starting server...

2014-02-11 13:48:29 - Status check of service 'MySQL56' returned start pending

2014-02-11 13:48:29 - Server start done.

2014-02-11 13:48:30 - Status check of service 'MySQL56' returned start pending
</code>```

答:
Process 1

Try to install mysql same version, if your crashed mysql version was 5.6 please install mysql 5.6.
brew install mysql@5.6

If following project fail try same things with mariadb. (In my case, by mariadb, I get back all database)

Before star, must stop mysql or mariadb. Use this command
brew services stop mysql or brew services stop mariadb

ibdata1 file copy from backup mysql folder and paste and replace it inside new installed mysql folder's ibdata1 (usr/local/var/mysql) or mamp/xampp mysql folder location.

ib_logfile0 and ib_logfile1 no need to replace first. If above process don't work, copy this file from backup mysql folder and replace. (In my case, i did not replace)

Now copy 1 database for test (for example : testdb) from backup mysql folder and paste it inside new installed mysql folder. In testdb must have .frm and .ibd file.

Restart mysql/mariadb (brew services start mysql) or (brew services start mariadb)

Login MySQL -> mysql -u root -p

If everything follow, mysql login successfully.

Now check database, SHOW DATABASES;

USE testdb;

SHOW TABLES;

SELECT * FROM testdbtable;

If there don't show any massage, then its successfully restore;

Process 2

If its not work, you have to install mysqlfrm (https://downloads.mysql.com/archives/utilities/)

To find database table schema. Open terminal or your command line with your backup mysql folder mysqlfrm --diagnostic /BACKUP/mysql/testdb > /RESTORE/testdb.sql

Open testdb.sql in notepad/sublime you will see all database table schema but not data just table :( anyway, follow following step carefully.

Add ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; end of every CREATE    TABLE....ENGINE=InnoDB otherwise table may not created.

Create new database "newtestdb" and run the command >> mysqldump -uroot -p --databases newtestdb > testdb.sql

It should create all database tables, Now if you check inside "newtestdb" you will see .frm and .ibd file.

Now again login mysql >> mysql -u root -p

SHOW DATABASES;
USE newtestdb;

Run this command one by one for all table, ALTER TABLE tablename DISCARD TABLESPACE; if you check newtestbd .ibd file will disapear.

Now Copy only .ibd file from backup database testdb folder and paste it in newtestdb.

Now run ALTER TABLE tablename IMPORT TABLESPACE;

Hope now you will get back your data.

Title: Restore MySQL InnoDb from *.frm files

Body:
I was working on my Mac when it crashed, the HDD got corrupted and cant be repaired unless formating, so i  recovered my DB data from OS X, i got all the folder , and now im trying to restore it in a windows computer while i repair the Mac.
I have tried several post here that says tha i just have to copy all the files to the data folder in the new MySQL instalment on windows , i already tried copying the db folder with the frm files and the ind files, then i copied the ibdata1 file and restarted the service but even so it didn't work , the i read that i had to copy also the ib_logfile0 and ib_logfile1 and so i did, but then the service didnt want to run.When i restore the original log it works but i can only see the tables in mysqlworkbench but i can't make querys to them because the log says that the tables doesnt exist even that i can see them.

Im using mysql 5.6 on windows 7 and mysqlworkbench.

Currently i have the *.frm files , the *.ibd files, the ibdata1, the ib_logfiles0 and 1 , that i rescued from my os x hdd, i copied all of them to the windows mysql installment and so the mysql service wont start.
Heres the current log when i try to start the service.

 FROM CARLOSDESKTOP.err:

    2014-02-11 13:27:10  7108  Note  Plugin 'FEDERATED' is disabled.

          2014-02-11 13:27:10 3a8 InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.

    2014-02-11 13:27:10  7108  Note  InnoDB: Using atomics to ref count buffer pool pages

    2014-02-11 13:27:10  7108  Note  InnoDB: The InnoDB memory heap is disabled

    2014-02-11 13:27:10  7108  Note  InnoDB: Mutexes and rw_locks use Windows interlocked functions

    2014-02-11 13:27:10  7108  Note  InnoDB: Compressed tables use zlib 1.2.3

    2014-02-11 13:27:10  7108  Note  InnoDB: Not using CPU crc32 instructions

    2014-02-11 13:27:10  7108  Note  InnoDB: Initializing buffer pool, size = 8.0M

    2014-02-11 13:27:10  7108  Note  InnoDB: Completed initialization of buffer pool

    2014-02-11 13:27:10  7108  Note  InnoDB: Highest supported file format is Barracuda.

2014-02-11 13:27:12 - Server start done.

2014-02-11 13:27:12 - Status check of service 'MySQL56' returned start pending

2014-02-11 13:47:27 - Status check of service 'MySQL56' returned stopped

FROM CARLOSDESKTOP.err:

    2014-02-11 13:27:12  7108  Note  InnoDB: The log sequence numbers 8610473 and 8610473 in ibdata files do not match the log sequence number 13883013 in the ib_logfiles!

    2014-02-11 13:27:12  7108  Note  InnoDB: Database was not shutdown normally!

    2014-02-11 13:27:12  7108  Note  InnoDB: Starting crash recovery.

    2014-02-11 13:27:12  7108  Note  InnoDB: Reading tablespace information from the .ibd files...

    2014-02-11 13:27:13  7108  ERROR  InnoDB: space header page consists of zero bytes in tablespace .\demo\record.ibd (table demo/record)

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size:1024 Pages to analyze:64

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size: 1024, Possible space_id count:0

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size:2048 Pages to analyze:64

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size: 2048, Possible space_id count:0

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size:4096 Pages to analyze:32

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size: 4096, Possible space_id count:0

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size:8192 Pages to analyze:16

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size: 8192, Possible space_id count:0

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size:16384 Pages to analyze:8

    2014-02-11 13:27:13  7108  Note  InnoDB: Page size: 16384, Possible space_id count:0

          InnoDB: Error: could not open single-table tablespace file .\demo\record.ibd

          InnoDB: We do not continue the crash recovery, because the table may become

          InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.

          InnoDB: To fix the problem and start mysqld:

          InnoDB: 1) If there is a permission problem in the file and mysqld cannot

          InnoDB: open the file, you should modify the permissions.

          InnoDB: 2) If the table is not needed, or you can restore it from a backup,

          InnoDB: then you can remove the .ibd file, and InnoDB will do a normal

          InnoDB: crash recovery and ignore that table.

          InnoDB: 3) If the file system or the disk is broken, and you cannot remove

          InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf

          InnoDB: and force InnoDB to continue crash recovery here.

2014-02-11 13:47:28 - Status check of service 'MySQL56' returned stopped

2014-02-11 13:47:28 - Starting server...

2014-02-11 13:48:29 - Status check of service 'MySQL56' returned start pending

2014-02-11 13:48:29 - Server start done.

2014-02-11 13:48:30 - Status check of service 'MySQL56' returned start pending