问:
Weird filter for function definition in Ocaml
Sorry for this noob question but I have this function definition :

```<code>let f x = function
    | 0 -> 0
    | y -> 1;;
</code>```

I understand that f is a function of x,y but why does it give :

0 if y = 0

1 if y = 1

Indeed according to the filter, should not f(0,1) give 0 since 0 -> 0 ?

答:
The function syntax defines an anonymous function taking a single argument, and pattern matches on that argument. There are any number of places in OCaml where this can be useful. Given that OCaml is a highly pragmatic programming language, its inclusion makes sense.

The naming of the patterns doesn't particularly matter, except that you want to be careful not to shadow other values already bound to the same name.

Consider:

```<code>let f x =
  function
  | 0 -> 0
  | x = x + x
</code>```

If we evaluate f 4 5 we get 10 rather than 9 because x now is bound to the value 5 which we passed in. By using a different name in the pattern, we avoid this.

```<code>let f x =
  function
  | 0 -> 0
  | y = x + y
</code>```

Now, in this case it would have been far more straightforward to just write:

```<code>let f x y =
  match y with
  | 0 -> 0
  | y = x + y
</code>```

Or:

```<code>let f x y =
  if y = 0 then 0
  else x + y
</code>```

But let's say we wanted to pass an anonymous function to List.map to map a list of integers to new values, where 1, 2, or 3 are 0 and anything else is multiplied by two:

```<code>let lst = [4; 8; 1; 9; 3] in
List.map (fun x -> match x with 1 | 2 | 3 -> 0 | _ -> x * 2) lst
</code>```

The function syntax cleans this up a bit:

```<code>let lst = [4; 8; 1; 9; 3] in
List.map (function 1 | 2 | 3 -> 0 | x -> x * 2) lst
</code>```

Or:

```<code>let lst = [4; 8; 1; 9; 3] in
let f = function 1 | 2 | 3 -> 0 | x -> x * 2 in
List.map f lst
</code>```

Body:
Sorry for this noob question but I have this function definition :

let f x = function
    | 0 -> 0
    | y -> 1;;

I understand that f is a function of x,y but why does it give :

0 if y = 0

1 if y = 1

Indeed according to the filter, should not f(0,1) give 0 since 0 -> 0 ?

Body:
The function syntax defines an anonymous function taking a single argument, and pattern matches on that argument. There are any number of places in OCaml where this can be useful. Given that OCaml is a highly pragmatic programming language, its inclusion makes sense.

The naming of the patterns doesn't particularly matter, except that you want to be careful not to shadow other values already bound to the same name.

Consider:

let f x =
  function
  | 0 -> 0
  | x = x + x

If we evaluate f 4 5 we get 10 rather than 9 because x now is bound to the value 5 which we passed in. By using a different name in the pattern, we avoid this.

let f x =
  function
  | 0 -> 0
  | y = x + y

Now, in this case it would have been far more straightforward to just write:

let f x y =
  match y with
  | 0 -> 0
  | y = x + y

Or:

let f x y =
  if y = 0 then 0
  else x + y

But let's say we wanted to pass an anonymous function to List.map to map a list of integers to new values, where 1, 2, or 3 are 0 and anything else is multiplied by two:

let lst = [4; 8; 1; 9; 3] in
List.map (fun x -> match x with 1 | 2 | 3 -> 0 | _ -> x * 2) lst

The function syntax cleans this up a bit:

let lst = [4; 8; 1; 9; 3] in
List.map (function 1 | 2 | 3 -> 0 | x -> x * 2) lst

Or:

let lst = [4; 8; 1; 9; 3] in
let f = function 1 | 2 | 3 -> 0 | x -> x * 2 in
List.map f lst


来源: stackexchange

问:
No output in VS Code when running tests
I'm running an XUnit test-ptoject in VS Code with the .NET Core Test Explorer extension. I'm trying to write output during the tests but nothing is working. I've tried writing output in different ways, but can't see any output anywhere. Has anyone managed to see output in vs code somehow while running tests?

Here is a small example class:

```<code>using Xunit;
using Xunit.Abstractions;
using System.Diagnostics;

public class TestClass
{

    private ITestOutputHelper _output;

    public TestClass(ITestOutputHelper output)
    {
        _output = output;
    }

    [Fact]
    public void Test2()
    {
        _output.WriteLine("Hello");
        Debug.WriteLine("Hello");
        Console.WriteLine("Hello");
    }
}
</code>```

答:
Output only shows if the test fails.

If you need to to see your output, you can (temporarily) add this line at the end of the test:

```<code>Assert.False(true, "Fail on purpose");
</code>```

If you're running in VS Code, the test output will be visible in the "OUTPUT" tab when you set the source to "Test Explorer (Test runner output)" in the drop-down on the right.

ContentLicense: CC BY-SA 4.0

Title: No output in VS Code when running tests

Body:
I'm running an XUnit test-ptoject in VS Code with the .NET Core Test Explorer extension. I'm trying to write output during the tests but nothing is working. I've tried writing output in different ways, but can't see any output anywhere. Has anyone managed to see output in vs code somehow while running tests?

Here is a small example class:

using Xunit;
using Xunit.Abstractions;
using System.Diagnostics;

public class TestClass
{

    private ITestOutputHelper _output;

    public TestClass(ITestOutputHelper output)
    {
        _output = output;
    }

    [Fact]
    public void Test2()
    {
        _output.WriteLine("Hello");
        Debug.WriteLine("Hello");
        Console.WriteLine("Hello");
    }
}

Body:
Output only shows if the test fails.

If you need to to see your output, you can (temporarily) add this line at the end of the test:

Assert.False(true, "Fail on purpose");

If you're running in VS Code, the test output will be visible in the "OUTPUT" tab when you set the source to "Test Explorer (Test runner output)" in the drop-down on the right.


问:
from tkinter import * doesnt work anymore
I have been working on a project and everything was alright until I got this error:

```<code>File "D:\python\TKinter\amihaiRatson.py", line 1, in <module>
    from tkinter import *
  File "C:\Users\amiha\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2472, in <module>
    class Grid:
  File "C:\Users\amiha\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2493, in Grid
    self.tk.call(
NameError: name 'self' is not defined
</code>```

tkinter module suddenly not working..

答:
you can use

```<code>import tkinter
</code>```

or you can also use import tkinter as tk if you code is like test = tk.Label() and not test = tkinter.Label()

Body:
I have been working on a project and everything was alright until I got this error:

File "D:\python\TKinter\amihaiRatson.py", line 1, in <module>
    from tkinter import *
  File "C:\Users\amiha\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2472, in <module>
    class Grid:
  File "C:\Users\amiha\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2493, in Grid
    self.tk.call(
NameError: name 'self' is not defined

tkinter module suddenly not working..

Body:
you can use

import tkinter

or you can also use import tkinter as tk if you code is like test = tk.Label() and not test = tkinter.Label()


问:
Warning: Received `false` for a non-boolean attribute. How do I pass a boolean for a custom boolean attribute?
```<code>Warning: Received `false` for a non-boolean attribute `comingsoon`.

If you want to write it to the DOM, pass a string instead:
comingsoon="false" or comingsoon={value.toString()}.
</code>```

How do I pass a boolean in a custom attribute for React?

I'm using styled-components and passing the attribute through the component. Here is a picture of how I'm passing the attr.

passing boolean custom attr as "comingsoon"

styled-components css props

答: This warning can be caused also if the property of styled component has the name existing in HTML. For example I had such issue when named property wrap. After renaming warning disappeared.

Body:
Warning: Received `false` for a non-boolean attribute `comingsoon`.

If you want to write it to the DOM, pass a string instead:
comingsoon="false" or comingsoon={value.toString()}.

How do I pass a boolean in a custom attribute for React?

I'm using styled-components and passing the attribute through the component. Here is a picture of how I'm passing the attr.

passing boolean custom attr as "comingsoon"

styled-components css props


问:
Python N-Queen solution explanation
I was going through this really neat solution for n-queen problem from Elements of Programming Interviews, Recursion chapter, but can't seem to understand a particular piece of code. If someone can explain the logic here, it would be really helpful. If condition for checking conflicts is something I am trying to wrap my head around here but to no success.</p>
```<code>def n_queens(n: int) -> List[List[int]]:
    def solve_n_queens(row):
        if row == n:
            # All queens are legally placed.
            result.append(col_placement.copy())
            return
        for col in range(n):
            # Test if a newly place queen will conflict any earlier queens place before
            # I am struggling to make sense of this if condition
            if all(abs(c - col) not in (0, row - i)
                for i, c in enumerate(col_placement[:row])):
                    col_placement[row] = col
                    solve_n_queens(row + 1)

    result: List[List[int]] = []
    col_placement = [0] * n
    solve_n_queens(0)
    return result
</code>```

答:
The test at the bottom checks each previous queen placement to see:

if the previous queen column placement == current column placement

if the slope: abs(current column - previous column)/(current row - previous row) == 1

To clarify, let's change the variable names and the test, containing two comparisons for each previous row, is now written:

```<code>if all(abs(prev_col - curr_col) not in (0, curr_row - prev_row)
            for prev_row, prev_col in enumerate(col_placement[:row])):
</code>```

above is prev_col - curr_col != 0 #queens are not in the same column

For 2., since a chess board is a square, all diagonal slopes will equal one. A slope of one can be tested by insuring delta y = delta x.  For example 2/2 = 1, so 2 == 2.

For the rewritten test above, the test is: abs(prev_col - curr_col) != curr_row - prev_row.  abs() for the columns insures both diagonal directions are tested; abs() is not needed for rows since curr_row is the last row added.

```<code>        # Test if a newly place queen will conflict any earlier queens place before
        # I am struggling to make sense of this if condition
        if all(abs(c - col) not in (0, row - i)
            for i, c in enumerate(col_placement[:row])):
</code>```

Title: Python N-Queen solution explanation

Body:
I was going through this really neat solution for n-queen problem from Elements of Programming Interviews, Recursion chapter, but can't seem to understand a particular piece of code. If someone can explain the logic here, it would be really helpful. If condition for checking conflicts is something I am trying to wrap my head around here but to no success.

def n_queens(n: int) -> List[List[int]]:
    def solve_n_queens(row):
        if row == n:
            # All queens are legally placed.
            result.append(col_placement.copy())
            return
        for col in range(n):
            # Test if a newly place queen will conflict any earlier queens place before
            # I am struggling to make sense of this if condition
            if all(abs(c - col) not in (0, row - i)
                for i, c in enumerate(col_placement[:row])):
                    col_placement[row] = col
                    solve_n_queens(row + 1)

    result: List[List[int]] = []
    col_placement = [0] * n
    solve_n_queens(0)
    return result

Body:
The test at the bottom checks each previous queen placement to see:

if the previous queen column placement == current column placement

if the slope: abs(current column - previous column)/(current row - previous row) == 1

To clarify, let's change the variable names and the test, containing two comparisons for each previous row, is now written:

if all(abs(prev_col - curr_col) not in (0, curr_row - prev_row)
            for prev_row, prev_col in enumerate(col_placement[:row])):

above is prev_col - curr_col != 0 #queens are not in the same column

For 2., since a chess board is a square, all diagonal slopes will equal one. A slope of one can be tested by insuring delta y = delta x.  For example 2/2 = 1, so 2 == 2.

For the rewritten test above, the test is: abs(prev_col - curr_col) != curr_row - prev_row.  abs() for the columns insures both diagonal directions are tested; abs() is not needed for rows since curr_row is the last row added.

        # Test if a newly place queen will conflict any earlier queens place before
        # I am struggling to make sense of this if condition
        if all(abs(c - col) not in (0, row - i)
            for i, c in enumerate(col_placement[:row])):


问:
extract bit in Ruby Integers
I need to get the n-th bit of an Integer, either signed or unsigned, in Ruby.

```<code>x = 123 # that is 1111011
n = 2   # bit 2 is ...0
</code>```

The following piece of code doesn't work in the general case:

```<code>x.to_s(2)[-(n+1)] #0 good! but...
</code>```

because of negative numbers not represented as 2-complement:

```<code>-123.to_s(2) # "-1111011"
</code>```

So how to proceed?

答:
You could try the  Bindata lib.

There is a function to represent an integer's binary representation as a string, and after that, you can do what you like with it.

ContentLicense: CC BY-SA 3.0

Title: extract bit in Ruby Integers

Body:
I need to get the n-th bit of an Integer, either signed or unsigned, in Ruby.

x = 123 # that is 1111011
n = 2   # bit 2 is ...0

The following piece of code doesn't work in the general case:

x.to_s(2)[-(n+1)] #0 good! but...

because of negative numbers not represented as 2-complement:

-123.to_s(2) # "-1111011"

So how to proceed?


问:
Recursive search JSON/DICT in Python 3
I am realizing in Python 3 some APIs that allow me to receive information about a school based on the class code. But I would like to know how I get the information through the class code.
Example:
I enter the code GF528S and I want the program to tell me the class (3C INF), the address (Address 1, Milan), and if possible also the name of the school (Test School 1) and the previous keys. Thanks in advance! Of course I use a JSON structure:

```<code>{
    "schools": {
         "Lombardia": {
            "Milano": {
                "Milano": {
                    "Test School 1": {
                        "sedi": {
                            "0": {
                                "indirizzo": "Address 1, Milan",
                                "classi": {
                                    "INFORMATICA E TELECOMUNICAZIONI": {
                                        "3C INF": "GF528S"
                                    }
                                }
                            },
                            "1": {
                                "indirizzo": "Address 2, Milan",
                                "classi": {
                                    "INFORMATICA E TELECOMUNICAZIONI": {
                                        "1A IT": "HKPV5P",
                                        "2A IT": "QL3J3K",
                                        "3A INF": "X4E35C",
                                        "3A TEL": "ZAA7LC"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

When I get the values from my database they are converted to a python dictionary if it helps!
After a series of tests thanks to your answers, I found that the for in .items() is blocked when it shows the indirizzo field:
In particular, it cannot search in these dictionaries:

```<code>{'classi': {'INFORMATICA E TELECOMUNICAZIONI': {'3C INF': 'GF528S'}}, 'indirizzo': 'Address 1, Milan'}
{'classi': {'INFORMATICA E TELECOMUNICAZIONI': {'1A IT': 'HKPV5P', '2A IT': 'QL3J3K', '3A INF': 'X4E35C', '3A TEL': 'ZAA7LC'}}, 'indirizzo': 'Address 2, Milan'}
</code>```

I think the problem is precisely the indirizzo field. If you want to do the for first, it can be saved in a variable and deleted from the json:

```<code>del val ["address"]
</code>```

The problem is that then I can't associate the address with the class.
Code:

```<code>def dictionary_check(input):
    indirizzo = ""
    for key,value in input.items():
        if isinstance(value, dict):
            dictionary_check(value)
        else:
            for i in value:
                indirizzo += i["indirizzo"]
                del i['indirizzo']
                for x, y in i.items():
                    for z, j in y.items():
                        for a in j.items():
                            if a[1] == "HKPV5P":
                                print(indirizzo)
                                print("Classe: " + a[0])
</code>```

答:
```<code>search_key = "GF528S"
def recursive_search(dct,keys):
    for key,value in dct.items():
        if key == search_key:
            print(keys,value)
        if type(value) == dict:
            recursive_search(value,[*keys,key])
recursive_search(dinput_dict,[])
</code>```

Title: Recursive search JSON/DICT in Python 3

Body:
I am realizing in Python 3 some APIs that allow me to receive information about a school based on the class code. But I would like to know how I get the information through the class code.
Example:
I enter the code GF528S and I want the program to tell me the class (3C INF), the address (Address 1, Milan), and if possible also the name of the school (Test School 1) and the previous keys. Thanks in advance! Of course I use a JSON structure:

{
    "schools": {
         "Lombardia": {
            "Milano": {
                "Milano": {
                    "Test School 1": {
                        "sedi": {
                            "0": {
                                "indirizzo": "Address 1, Milan",
                                "classi": {
                                    "INFORMATICA E TELECOMUNICAZIONI": {
                                        "3C INF": "GF528S"
                                    }
                                }
                            },
                            "1": {
                                "indirizzo": "Address 2, Milan",
                                "classi": {
                                    "INFORMATICA E TELECOMUNICAZIONI": {
                                        "1A IT": "HKPV5P",
                                        "2A IT": "QL3J3K",
                                        "3A INF": "X4E35C",
                                        "3A TEL": "ZAA7LC"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

When I get the values from my database they are converted to a python dictionary if it helps!
After a series of tests thanks to your answers, I found that the for in .items() is blocked when it shows the indirizzo field:
In particular, it cannot search in these dictionaries:

{'classi': {'INFORMATICA E TELECOMUNICAZIONI': {'3C INF': 'GF528S'}}, 'indirizzo': 'Address 1, Milan'}
{'classi': {'INFORMATICA E TELECOMUNICAZIONI': {'1A IT': 'HKPV5P', '2A IT': 'QL3J3K', '3A INF': 'X4E35C', '3A TEL': 'ZAA7LC'}}, 'indirizzo': 'Address 2, Milan'}

I think the problem is precisely the indirizzo field. If you want to do the for first, it can be saved in a variable and deleted from the json:

del val ["address"]

The problem is that then I can't associate the address with the class.
Code:

def dictionary_check(input):
    indirizzo = ""
    for key,value in input.items():
        if isinstance(value, dict):
            dictionary_check(value)
        else:
            for i in value:
                indirizzo += i["indirizzo"]
                del i['indirizzo']
                for x, y in i.items():
                    for z, j in y.items():
                        for a in j.items():
                            if a[1] == "HKPV5P":
                                print(indirizzo)
                                print("Classe: " + a[0])


问:
How can I separate the information in one column of the table I have into 3 separate columns?
For example, one column of the table I have is like this

```<code>HGVS.Consequence
    Lys10Arg
    Lys10Lys
    LeullLeu
    Phe12Ser
    Phe12Cys
    lle13Leu
    lle13Val
    lle13Phe
    Thr15Pro
</code>```

And I want a table like this.

```<code>Mutation  Ref  Change Position
lle13Val  lle   Val      13
lle13Phe  lle   Phe      13
Thr15Pro  Thr   Pro      15
</code>```

答:
Code

Here is a base R way with substr.

sepfun <- function(x){
  s1 <- substr(x, 1, 3)
  s2 <- substr(x, 4, 5)
  s3 <- substring(x, 6)
  y <- do.call(cbind.data.frame, list(s1, s3, s2))
  names(y) <- c("Ref", "Change", "Position")
  cbind(Mutation = x, y)
}

sepfun(df1$HGVS.Consequence)
#>   Mutation Ref Change Position
#> 1 Lys10Arg Lys    Arg       10
#> 2 Lys10Lys Lys    Lys       10
#> 3 LeullLeu Leu    Leu       ll
#> 4 Phe12Ser Phe    Ser       12
#> 5 Phe12Cys Phe    Cys       12
#> 6 lle13Leu lle    Leu       13
#> 7 lle13Val lle    Val       13
#> 8 lle13Phe lle    Phe       13
#> 9 Thr15Pro Thr    Pro       15
```
<p><sup>Created on 2022-02-13 by the reprex package (v2.0.1)</sup></p>
<h2>Data</h2>
<pre class="lang-r prettyprint-override"><code>HGVS.Consequence<-scan(text = '
Lys10Arg
Lys10Lys
LeullLeu
Phe12Ser
Phe12Cys
lle13Leu
lle13Val
lle13Phe
Thr15Pro
', sep = "\n", what = character())
df1 <- data.frame(HGVS.Consequence)
</code>```

Created on 2022-02-13 by the reprex package (v2.0.1)

Body:
For example, one column of the table I have is like this

HGVS.Consequence
    Lys10Arg
    Lys10Lys
    LeullLeu
    Phe12Ser
    Phe12Cys
    lle13Leu
    lle13Val
    lle13Phe
    Thr15Pro

And I want a table like this.

Mutation  Ref  Change Position
lle13Val  lle   Val      13
lle13Phe  lle   Phe      13
Thr15Pro  Thr   Pro      15

Body:
Code

Here is a base R way with substr.

sepfun <- function(x){
  s1 <- substr(x, 1, 3)
  s2 <- substr(x, 4, 5)
  s3 <- substring(x, 6)
  y <- do.call(cbind.data.frame, list(s1, s3, s2))
  names(y) <- c("Ref", "Change", "Position")
  cbind(Mutation = x, y)
}

sepfun(df1$HGVS.Consequence)
#>   Mutation Ref Change Position
#> 1 Lys10Arg Lys    Arg       10
#> 2 Lys10Lys Lys    Lys       10
#> 3 LeullLeu Leu    Leu       ll
#> 4 Phe12Ser Phe    Ser       12
#> 5 Phe12Cys Phe    Cys       12
#> 6 lle13Leu lle    Leu       13
#> 7 lle13Val lle    Val       13
#> 8 lle13Phe lle    Phe       13
#> 9 Thr15Pro Thr    Pro       15

Created on 2022-02-13 by the reprex package (v2.0.1)

Data

HGVS.Consequence<-scan(text = '
Lys10Arg
Lys10Lys
LeullLeu
Phe12Ser
Phe12Cys
lle13Leu
lle13Val
lle13Phe
Thr15Pro
', sep = "\n", what = character())
df1 <- data.frame(HGVS.Consequence)

Created on 2022-02-13 by the reprex package (v2.0.1)


问:
How to merge two json array which has same value in react native in a javascript
I have a two json objects. i need to merge those in a single object which has same id.

Example

```<code> const [orderdetails, setOrderdetails] = useState([]);
  const [ordertracking, setOrdertracking] = useState([]);

  useEffect(() => {
    fetch('first api')
      .then((response) => response.json())
      .then((json) => setOrderdetails(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    fetch('second api')
      .then((response) => response.json())
      .then((json) => setOrdertracking(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);
</code>```

Sample data

First api response in orderdetails

```<code>{
    "statusCode": "200",
    "message": "success",
    "content": [
         { subject_id: 711, topics: ["Test", "Test2"] },
         { subject_id: 712, topics: ["topic1", "Topic2"] }
]
}
</code>```

Second api response in ordertracking

```<code>{
        "statusCode": "200",
        "message": "success",
        "content": [
              {subject_id: 711, subject_name: "Science"},
               {subject_id: 712, subject_name: "Maths"}
    ]
    }
</code>```

I want the merged result to be:

```<code>const result = [
  {
    subject_id: "711",
    subjectName: "Science",
    topics: [ "Test", "Test2" ]
  },
  {
    subject_id: "712",
    subjectName: "Maths",
    topics: [ "topic1", "Topic2" ]
  }
];
</code>```

As you can see there are two api response in a josn format I need to merge those json object which is inside a content which has same 'subject_id'  and rest of the values as a single data.

I need a solution in javascript for my react native app if you can suggest me a react native code

答:
You can just use ForEach loop and Find method to do that...

const res1 = {
  statusCode: '200',
  message: 'success',
  content: [
    { subject_id: 711, topics: ['Test', 'Test2'] },
    { subject_id: 712, topics: ['topic1', 'Topic2'] },
  ],
};

const res2 = {
  statusCode: '200',
  message: 'success',
  content: [
    { subject_id: 711, subject_name: 'Science' },
    { subject_id: 712, subject_name: 'Maths' },
  ],
};

let result = [
  // {
  //   subject_id: "711",
  //   subjectName: "Science",
  //   topics: [ "Test", "Test2" ]
  // },
  // {
  //   subject_id: "712",
  //   subjectName: "Maths",
  //   topics: [ "topic1", "Topic2" ]
  // }
];

res1.content.forEach((item) => {
  result.push({
    subject_id: item.subject_id,
    topics: item.topics,
    subject_name: res2.content.find(
      (elem) => elem.subject_id == item.subject_id
    ).subject_name,
  });
});

console.log(result);```

Body:
I have a two json objects. i need to merge those in a single object which has same id.

Example

 const [orderdetails, setOrderdetails] = useState([]);
  const [ordertracking, setOrdertracking] = useState([]);

  useEffect(() => {
    fetch('first api')
      .then((response) => response.json())
      .then((json) => setOrderdetails(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    fetch('second api')
      .then((response) => response.json())
      .then((json) => setOrdertracking(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

Sample data

First api response in orderdetails

{
    "statusCode": "200",
    "message": "success",
    "content": [
         { subject_id: 711, topics: ["Test", "Test2"] },
         { subject_id: 712, topics: ["topic1", "Topic2"] }
]
}

Second api response in ordertracking

{
        "statusCode": "200",
        "message": "success",
        "content": [
              {subject_id: 711, subject_name: "Science"},
               {subject_id: 712, subject_name: "Maths"}
    ]
    }

I want the merged result to be:

const result = [
  {
    subject_id: "711",
    subjectName: "Science",
    topics: [ "Test", "Test2" ]
  },
  {
    subject_id: "712",
    subjectName: "Maths",
    topics: [ "topic1", "Topic2" ]
  }
];

As you can see there are two api response in a josn format I need to merge those json object which is inside a content which has same 'subject_id'  and rest of the values as a single data.

I need a solution in javascript for my react native app if you can suggest me a react native code


问:
Require One of a Set of Fields in SQL
I have an entity, let's call 'machine', which has a group of entities from which it takes its name. At least one of these fields is required, but more than one can be set. So in the example below, if the host name and IP is not set, then the service tag should be. I am using Propel 1.5 as an ORM.

```<code>machine:
  id: ~
  hostname:    {type: varchar(255)}
  ip:          {type: varchar(255)}
  service_tag: {type: varchar(255)}
</code>```

An article on multi-column constraints makes me wonder if it would be possible to add something like required(hostname, mac, service_tag). If this is the case, how would I accomplish this in .yml form for Propel?

答: I think its not possible with symfony and propel. But you can set up your symfony form that it requires one of the three columns.</p>

Title: Require One of a Set of Fields in SQL

Body:
I have an entity, let's call 'machine', which has a group of entities from which it takes its name. At least one of these fields is required, but more than one can be set. So in the example below, if the host name and IP is not set, then the service tag should be. I am using Propel 1.5 as an ORM.

machine:
  id: ~
  hostname:    {type: varchar(255)}
  ip:          {type: varchar(255)}
  service_tag: {type: varchar(255)}

An article on multi-column constraints makes me wonder if it would be possible to add something like required(hostname, mac, service_tag). If this is the case, how would I accomplish this in .yml form for Propel?


问:
react js rendering blank [age with no errors on console
So basically I have a navbar that switches between routes. When the page loads, it goes to my localhost by default but doesn't actually render the App component it's being given. I believe the problem is within the navbar as the app renders other components when the Nav component is not included. Please assist me if you can.

code to the questions is given below:
app.js

```<code>    import React from 'react';
import './App.css';
import Nav from './components/Navbar/navbar';
import Content from './components/Header/firstsec';
import Grid from './components/secondsec/secondsec';
import Footer from './components/footer/footer';
import Sign from './components/signin/signin';
import Trend from './components/trending/trending';

function App() {
  return (
      <div>
       <Nav/>
     <Content />
     <Grid />
     <Footer />
     <Sign />
     <Trend />
     </div>

  );
}

export default App;
</code>```

navbar.js

```<code>    import React from "react";
import {
  BrowserRouter as Router,
  Route,
  Routes,
  Link} from "react-router-dom";
import Content from "../Header/firstsec";
import Grid from "../secondsec/secondsec";
import Trend from "../trending/trending";
import Sign from "../signin/signin";
import { Component } from "react/cjs/react.development";

export default class Nav extends Component{
  render(){
    return (
    <Router>
    <div>
      <nav className="bg-gradient-to-r from-blue-300 to to-purple-500 via-black">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-6">
          <div className="flex items-center justify-between h-36">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <img
                  className="h-8 w-8"
                  src="https://tailwindui.com/img/logos/workflow-mark-indigo-500.svg"
                  alt="Workflow"
                />
              </div>
              <div className="hidden md:block">
                <div className="ml-10 flex items-baseline space-x-4">
                  <Nav.Link as={Link} to ={"/"}

                    className=" hover:bg-gray-700 text-white px-3 py-2 rounded-md text-sm font-medium"
                  >
                    Bloow
                  </Nav.Link>
                  <Nav.Link as={Link} to ={"/Content"}
                    className="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium">
                    Bloow TV
                  </Nav.Link>

                  <Nav.Link as={Link} to ={"/Grid"}
                    className="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium"
                  >
                    Bloow Music
                  </Nav.Link>

                  <Nav.Link as={Link} to ={"/Trending"}
                    className="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium"
                  >
                    Trending
                  </Nav.Link>
                  <div>
                  <Nav.Link as={Link} to ={"/Sign"}
                    className="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium"
                  >
                    Sign in
                  </Nav.Link>

                  </div>
              </div>
            </div>
            <div className="-mr-2 flex md:hidden">
              <button
                type="button"
                className="bg-gray-800 inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-white hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white"
                aria-controls="mobile-menu"
                aria-expanded="false"
              >
                <span className="sr-only">Open main menu</span>

                <svg
                  className="block h-6 w-6"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  aria-hidden="true"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M4 6h16M4 12h16M4 18h16"
                  />
                </svg>

                <svg
                  className="hidden h-6 w-6"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  aria-hidden="true"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M6 18L18 6M6 6l12 12"
                  />
                </svg>
              </button>
            </div>
          </div>
        </div>
        </div>

        <div className="md:hidden" id="mobile-menu">
          <div className="px-2 pt-2 pb-3 space-y-1 sm:px-3">
            <Nav.Link as={Link} to ={"/home"}
              className="hover:bg-gray-700 text-white block px-3 py-2 rounded-md font-medium text-5xl"
            >
              Bloow
            </Nav.Link>

            <Nav.Link as={Link} to ={"/Content"}

              className="text-gray-300 hover:bg-gray-700 hover:text-white block px-3 py-2 rounded-md text-base font-medium"
            >
              Bloow TV
            </Nav.Link>

            <Nav.Link as={Link} to ={"/Grid"}
              className="text-gray-300 hover:bg-gray-700 hover:text-white block px-3 py-2 rounded-md text-base font-medium"
            >
              Bloow Music
            </Nav.Link>

            <Nav.Link as={Link} to ={"/Trending"}
              className="text-gray-300 hover:bg-gray-700 hover:text-white block px-3 py-2 rounded-md text-base font-medium"
            >
              Trending
            </Nav.Link>

            <Nav.Link as={Link} to ={"/Sign"}
              className="text-gray-300 hover:bg-gray-700 hover:text-white block px-3 py-2 rounded-md text-base font-medium"
            >
              Sign in
            </Nav.Link>
          </div>
        </div>
      </nav>
    </div>
    <div>
      <Routes>
        <Route path="/" Component ={Content} />
        <Route path="/Content" Component ={Content}>
        </Route>
        <Route path="/Grid" Component ={Grid}>
          <Grid />
        </Route>
        <Route path="/Trending" Component={Trend}>
          <Trend />
        </Route>
        <Route path="/Sign" Component={Sign}>
          <Sign />
        </Route>
      </Routes>

    </div>
    </Router>
  );

}
}

</code>```

答:
Try replace

```<code><Route path="/Sign" Component={Sign}>
</code>```

by

```<code><Route path="/Sign" component={Sign}>
</code>```

Body:
So basically I have a navbar that switches between routes. When the page loads, it goes to my localhost by default but doesn't actually render the App component it's being given. I believe the problem is within the navbar as the app renders other components when the Nav component is not included. Please assist me if you can.

code to the questions is given below:
app.js

    import React from 'react';
import './App.css';
import Nav from './components/Navbar/navbar';
import Content from './components/Header/firstsec';
import Grid from './components/secondsec/secondsec';
import Footer from './components/footer/footer';
import Sign from './components/signin/signin';
import Trend from './components/trending/trending';

function App() {
  return (

     <Content />
     <Grid />

     <Sign />
     <Trend />

  );
}

export default App;

navbar.js

    import React from "react";
import {
  BrowserRouter as Router,
  Route,
  Routes,
  Link} from "react-router-dom";
import Content from "../Header/firstsec";
import Grid from "../secondsec/secondsec";
import Trend from "../trending/trending";
import Sign from "../signin/signin";
import { Component } from "react/cjs/react.development";

export default class Nav extends Component{
  render(){
    return (
    <Router>

                    Bloow

                    Bloow TV

                    Bloow Music

                    Trending

                    Sign in

              <button
                type="button"
                className="bg-gray-800 inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-white hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white"
                aria-controls="mobile-menu"
                aria-expanded="false"
              >
                Open main menu

                <svg
                  className="block h-6 w-6"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  aria-hidden="true"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M4 6h16M4 12h16M4 18h16"
                  />
                </svg>

                <svg
                  className="hidden h-6 w-6"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  aria-hidden="true"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M6 18L18 6M6 6l12 12"
                  />
                </svg>
              </button>

              Bloow

              Bloow TV

              Bloow Music

              Trending

              Sign in

      <Routes>
        <Route path="/" Component ={Content} />
        <Route path="/Content" Component ={Content}>
        </Route>
        <Route path="/Grid" Component ={Grid}>
          <Grid />
        </Route>
        <Route path="/Trending" Component={Trend}>
          <Trend />
        </Route>
        <Route path="/Sign" Component={Sign}>
          <Sign />
        </Route>
      </Routes>

    </Router>
  );

}
}

Body:
Try replace

<Route path="/Sign" Component={Sign}>

by

<Route path="/Sign" component={Sign}>


问:
Why Is My Django Post Request Sending Incorrectly Parsed My List of Dictionaries?
Here is my Django view:

```<code>def sendMail(request):
    url = 'https://example.com/example'
    dictwithlist = request.FILES['dictwithlist']
    parsed = json.load(dictwithlist)

    // the log file shows that the lists are intact after json.loads
    logip(request, json.loads(parsed))
    x = requests.post(url, json.loads(clockoutJSON))
return HttpResponse(status=204)
</code>```

If I just send parsed data my express server receives an empty dict, {}. When I log the json.loads(parsed) I find good data, with the lists intact. When the data gets to the other side though, the dictionaries inside the nested list are all removed, replaced by only strings of their keys.

I tried using headers as described here: Sending list of dicts as value of dict with requests.post going wrong but I just get 500 errors. I don't know if I'm formatting the headers wrong or not. (because the code has line spacing and I'm copying it)

Can anyone help me understand why this is failing? I need that list to get through with its dictionaries intact.

答:
I believe you may need to use dumps rather than loads when sending the request:

x = requests.post(url, json.dumps(parsed))
```
<p>Alternatively if you're using the python <code>requests</code> library you can send json as a dict as below:</p>
<pre class="lang-py prettyprint-override"><code>response = requests.post(url=url, json=parsed)
</code>```

Body:
Here is my Django view:

def sendMail(request):
    url = 'https://example.com/example'
    dictwithlist = request.FILES['dictwithlist']
    parsed = json.load(dictwithlist)

    // the log file shows that the lists are intact after json.loads
    logip(request, json.loads(parsed))
    x = requests.post(url, json.loads(clockoutJSON))
return HttpResponse(status=204)

If I just send parsed data my express server receives an empty dict, {}. When I log the json.loads(parsed) I find good data, with the lists intact. When the data gets to the other side though, the dictionaries inside the nested list are all removed, replaced by only strings of their keys.

I tried using headers as described here: Sending list of dicts as value of dict with requests.post going wrong but I just get 500 errors. I don't know if I'm formatting the headers wrong or not. (because the code has line spacing and I'm copying it)

Can anyone help me understand why this is failing? I need that list to get through with its dictionaries intact.

Body:
I believe you may need to use dumps rather than loads when sending the request:

x = requests.post(url, json.dumps(parsed))

Alternatively if you're using the python requests library you can send json as a dict as below:

response = requests.post(url=url, json=parsed)


答:
```<code>tidyr::extract(df, HGVS.Consequence,
     c('Ref', 'Position', 'Change'), '(\\D+)(\\d+)(\\D+)', remove = FALSE)
</code>```

Title: How can I separate the information in one column of the table I have into 3 separate columns?


问:
MySQL REGEXP matching positive numbers
I have a column varchar[25] with this data inside :

886,-886

-886

0,-1234

1234

(empty)

0

the numbers might change in size from a 1 digit to a n digits.
and I need to be able to pull any row that has at least one positive number in it

I was thinking that something like

```<code>REGEXP '[^-,][0-9]+'
</code>```

but this pulls -886 as 88 matches the regexp

答:
I was able to figure out the best solution:

```<code>`COL` NOT LIKE  '%-%'
</code>```

I forgot to mention that the column might also contain words like:

all,-886

none,886

0,1,2,3,none

0

etc...

Title: MySQL REGEXP matching positive numbers

Body:
I have a column varchar[25] with this data inside :

886,-886

-886

0,-1234

1234

(empty)

0

the numbers might change in size from a 1 digit to a n digits.
and I need to be able to pull any row that has at least one positive number in it

I was thinking that something like

REGEXP '[^-,][0-9]+'

but this pulls -886 as 88 matches the regexp

Body:
I was able to figure out the best solution:

`COL` NOT LIKE  '%-%'

I forgot to mention that the column might also contain words like:

all,-886

none,886

0,1,2,3,none

0

etc...


问:
Is it possible to build this header layout using Flexbox CSS?
I've been trying to figure out how to make this layout possible in CSS Flexbox, so far cannot figure out a way to make it work that doesn't involve hiding a duplicate  to show only on desktop. Is this possible to do using Flexbox?

Image example of what I'm trying to achieve:

答:
A solution in grid would be a lot nicer and this is a working example the breakpoint for mobile version happens in 800px,

I suggest you read the Grid Area Template system it make these kind of layouts in very modern and nice way

.parent{
  width: 100%;
  height:100vh;
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas: "blue red""blue red""green green";
  gap: 10px;
}

.blue{
  grid-area: blue;
  width: 200px;
  background: blue;
}

.red{
  grid-area: red;
  width: 100%;
  background: red;
}

.green{
  grid-area: green;
  width: 100%;
  height: 100%;
  background: green;
}

@media screen and (max-width: 800px){
  .parent{
 grid-template-areas:    "blue red"
                         "blue green";
     grid-template-rows: 1fr 1fr;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="red"></div>
  <div class="green"></div>
  <div class="blue"></div>
</div></code>```

Body:
A solution in grid would be a lot nicer and this is a working example the breakpoint for mobile version happens in 800px,

I suggest you read the Grid Area Template system it make these kind of layouts in very modern and nice way

.parent{
  width: 100%;
  height:100vh;
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas: "blue red""blue red""green green";
  gap: 10px;
}

.blue{
  grid-area: blue;
  width: 200px;
  background: blue;
}

.red{
  grid-area: red;
  width: 100%;
  background: red;
}

.green{
  grid-area: green;
  width: 100%;
  height: 100%;
  background: green;
}

@media screen and (max-width: 800px){
  .parent{
 grid-template-areas:    "blue red"
                         "blue green";
     grid-template-rows: 1fr 1fr;
  }
}

<div class="parent">
  <div class="red"></div>
  <div class="green"></div>
  <div class="blue"></div>
</div>


答:
Using tidyr::separate and tidying the ordering / names with dplyr:

tidyr::separate(data   = df,
                col    = HGVS.Consequence,
                into   = c("Ref", "Position", "Change"),
                sep    = c(3, 5, 8),
                remove = FALSE) |>
  dplyr::select(1, 2, 4, 3) |>
  dplyr::rename(mutation = HGVS.Consequence)

#>   mutation Ref Change Position
#> 1 Lys10Arg Lys    Arg       10
#> 2 Lys10Lys Lys    Lys       10
#> 3 LeullLeu Leu    Leu       ll
#> 4 Phe12Ser Phe    Ser       12
#> 5 Phe12Cys Phe    Cys       12
#> 6 lle13Leu lle    Leu       13
#> 7 lle13Val lle    Val       13
#> 8 lle13Phe lle    Phe       13
#> 9 Thr15Pro Thr    Pro       15

```


问:
What should I configure SVN to ignore in my Delphi projects?
What files should I tell Tortoise SVN to ignore when committing to a repository?

In particular I am interested in practical information such as whether to include such files as *.dproj.2007 etc that seem to appear but may not be needed.

答:
The official Emba answer is here:

https://docwiki.embarcadero.com/RADStudio/Sydney/en/File_Extensions_of_Files_Generated_by_RAD_Studio

At time of this writing, I believe this list of types to be incomplete (example: there is no mention of Android .obb files), but the wiki format allows suggestions, and the page does appear to be updated.

You could also look at this:

https://delphi.fandom.com/wiki/Delphi_File_Extensions

although it seems to be less than complete, and not updated very often (Example: no mention of android-related files at all.)


问:
Convert hex value to decimal in C but keep getting incorrect value, plus too few argument error when calling func
Hello I am trying to convert a hex value into the decimal form but for some reason the result I'm getting each time is negative and completely incorrect. Additionally I would like to take that decimal number and then convert it into it binary value. I have created func's for both but have run into the problem of "too few arguments" when calling my bin() func. If somebody could point me in the right direction and explain what I am doing wrong I would sincerely appreciate it.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define arraysize 20

int decimal() {

    int i = 0, val, len;
    char hex1[arraysize];
    long long dec = 0, base = 1;

    len = strlen(hex1);

    for (i = len--;i >= 0; i--) {
        if (hex1[1] >= '0' && hex1[i] <= '9') {
            dec += (hex1[i] - 48) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'A' && hex1[i] <= 'F') {
            dec += (hex1[i] - 55) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'a' && hex1[i] <= 'f') {
            dec += (hex1[i] - 87) * base;
            base *= 16;
        }
    }
    printf("Your decimal value is: %lld\n",dec);
    return 0;
}

int bin(long long dec) {

    int a[10], i;

    for (i = 0; dec > 0; i++) {
        a[i] = dec % 2;
        dec = dec / 2;
    }
    printf("\nThe binary value is: ");
    for (i = i - 1; i >= 0; i--) {
        printf("%d", a[i]);
    }
    return 0;
}

int main() {

    char hex1[arraysize];

    printf("Enter your HEX value: ");
    fflush(stdin);
    fgets(hex1, arraysize, stdin);

    decimal(hex1);
    bin();
}
</code>```

答:
There are multiple problems in your code:

hex1 should be passed as an argument to decimal(). As posted, your code has undefined behavior because hex1 is an uninitialized local array.

i = len-- initializes i to the value of len, hence one position too far. Use i = len - 1 instead.

if (hex1[1] >= '0' && hex1[i] <= '9') uses hex[1] instead of hex[i]

you should use expressions with character constants '0', ('A' - 10) and ('a' - 10) instead of hard coded magical values 48, 55 and 87.

the array a is too short in function bin(). You should give it a length of at least 64.

the argument in bin() should have unsigned long long type.

fflush(stdin); has undefined behavior.

Here is a modified version:

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

unsigned long long decimal(const char *hex) {
    unsigned long long dec = 0;
    int i, c;

    for (i = 0; (c = hex[i]) != '\0'; i++) {
        if (c >= '0' && c <= '9') {
            dec = dec * 16 + (c - '0');
        } else
        if (c >= 'A' && c <= 'F') {
            dec = dec * 16 + (c - 'A' + 10);
        } else
        if (c >= 'a' && c <= 'f') {
            dec = dec * 16 + (c - 'a' + 10);
        }
    }
    return dec;
}

void bin(unsigned long long dec) {
    char a[65];
    int i;

    a[64] = '\0';
    for (i = 63;; i--) {
        a[i] = '0' + dec % 2;
        dec = dec / 2;
        if (dec == 0)
            break;
    }
    printf("The binary value is: %s\n", a);
}

int main() {
    char hex1[20];

    printf("Enter your HEX value: ");
    if (fgets(hex1, sizeof hex1, stdin)) {
        unsigned long long dec = decimal(hex1);
        printf("Your decimal value is: %llu\n", dec);
        bin(dec);
    }
    return 0;
}
</code>```

Body:
Hello I am trying to convert a hex value into the decimal form but for some reason the result I'm getting each time is negative and completely incorrect. Additionally I would like to take that decimal number and then convert it into it binary value. I have created func's for both but have run into the problem of "too few arguments" when calling my bin() func. If somebody could point me in the right direction and explain what I am doing wrong I would sincerely appreciate it.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define arraysize 20

int decimal() {

    int i = 0, val, len;
    char hex1[arraysize];
    long long dec = 0, base = 1;

    len = strlen(hex1);

    for (i = len--;i >= 0; i--) {
        if (hex1[1] >= '0' && hex1[i] <= '9') {
            dec += (hex1[i] - 48) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'A' && hex1[i] <= 'F') {
            dec += (hex1[i] - 55) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'a' && hex1[i] <= 'f') {
            dec += (hex1[i] - 87) * base;
            base *= 16;
        }
    }
    printf("Your decimal value is: %lld\n",dec);
    return 0;
}

int bin(long long dec) {

    int a[10], i;

    for (i = 0; dec > 0; i++) {
        a[i] = dec % 2;
        dec = dec / 2;
    }
    printf("\nThe binary value is: ");
    for (i = i - 1; i >= 0; i--) {
        printf("%d", a[i]);
    }
    return 0;
}

int main() {

    char hex1[arraysize];

    printf("Enter your HEX value: ");
    fflush(stdin);
    fgets(hex1, arraysize, stdin);

    decimal(hex1);
    bin();
}

Body:
There are multiple problems in your code:

hex1 should be passed as an argument to decimal(). As posted, your code has undefined behavior because hex1 is an uninitialized local array.

i = len-- initializes i to the value of len, hence one position too far. Use i = len - 1 instead.

if (hex1[1] >= '0' && hex1[i] <= '9') uses hex[1] instead of hex[i]

you should use expressions with character constants '0', ('A' - 10) and ('a' - 10) instead of hard coded magical values 48, 55 and 87.

the array a is too short in function bin(). You should give it a length of at least 64.

the argument in bin() should have unsigned long long type.

fflush(stdin); has undefined behavior.

Here is a modified version:

#include <stdio.h>

unsigned long long decimal(const char *hex) {
    unsigned long long dec = 0;
    int i, c;

    for (i = 0; (c = hex[i]) != '\0'; i++) {
        if (c >= '0' && c <= '9') {
            dec = dec * 16 + (c - '0');
        } else
        if (c >= 'A' && c <= 'F') {
            dec = dec * 16 + (c - 'A' + 10);
        } else
        if (c >= 'a' && c <= 'f') {
            dec = dec * 16 + (c - 'a' + 10);
        }
    }
    return dec;
}

void bin(unsigned long long dec) {
    char a[65];
    int i;

    a[64] = '\0';
    for (i = 63;; i--) {
        a[i] = '0' + dec % 2;
        dec = dec / 2;
        if (dec == 0)
            break;
    }
    printf("The binary value is: %s\n", a);
}

int main() {
    char hex1[20];

    printf("Enter your HEX value: ");
    if (fgets(hex1, sizeof hex1, stdin)) {
        unsigned long long dec = decimal(hex1);
        printf("Your decimal value is: %llu\n", dec);
        bin(dec);
    }
    return 0;
}


问:
R and Rstudio Docker vs Binder
My problem is that I can't use R-studio at my work place as the IT does not support it  . I want to use R and R-studio that installed on my personnel laptop on my company laptop ( using a modern browser which is behind firewall ) . Some of the options   I am thinking of two two things

should I need to  build  a docker for R and R-studio (I see base images are already available) , I am mostly interested in basic  R , Dplyr  (haven ,xporter, and Reticulate ) packages .

Should I have to use a binder .  I am not technical person and my programming skills are very limited can any one suggest me way .

What exactly are the difference between using Docker option vs Binder ?
I know I can use R-Studio online and get my work done but with the new paid account I am running out of project hours and very slow sometimes . Thanks in advance

答:
Here are some examples beyond the modern RStudio MyBinder example:

https://github.com/fomightez/pythonista_skewedf

https://github.com/fomightez/r_phylogenetics_worshop

https://github.com/fomightez/chapter7/tree/master/binder

The modern RStudio MyBinder example has been set as a template on GitHub so you can use

The first one is for a special use of a package not on conda. And I started that one from square one.

The other two were converted from content by others to aid in making them Binder-ready.

You essentially list everything you need from conda in the environment.yml along with the appropriate channels.  If you need special stuff not on conda, you need the other configuration files included there.

Getting everything working can take some iterations on adding things, letting the image get built, and testing your libraries are available. Although you seem to think your situation is not overly complex.

The binder launch badges you see are just images where you modify the URL to point the MyBinder federation site at your repository. Look at the URL and you should see the pattern where you put studio at the end of the URL pointing at your repo. The form at MyBinder.org site can help with this; however, most often it is easier to just adapt a working launch badge's code copied from elsewhere. The form isn't set up at this time for making the URLs for launching to RStudio.

Download anything useful your create in a running session. The sessions timeout after 10 minutes, although RStudio usually keeps them active.

Lack of Persistence and limited memory, storage, & power can be drawbacks.   The inherent reproducibility and portability are advantages.

MyBinder.org doesn't work with private repos. If you have code you don't want to share, you can upload it to the temporary session, using the repo for specifying the environment. You could host a private binderhub that does allow the use of private git repositories; however, that is probably overkill for your use case and exceed your ability level at this time.

GitHub isn't the only place to host repositories that can be pointed at the MyBinder system. If you go to the MyBinder.org page and click where it says 'GitHub' on the left side of the top line of the form, you can see a list of the sources at which you can host a repository and point the system to build an image and launch a container with that specified image.

Building the image from a source repository takes some minutes the first time. Once the image is built though on the service, launch is typically less than 30 seconds. Each time you make a change on the source repo, a build is necessary. Some changes don't cause the new build to be as long as the initial one as some optimizing is done to only build what is necessary after a change. Keep in mind there are several members of the federation around the workd and if traffic on the internet gets sent to where the built image isn't yet available, it will be built from scratch again first.

The Holepunch project is out there to offer some help for users working in the R ecosystem; however, with the R-Conda system that is now integrated into MyBinder it is pretty much as easy to do it the way I described. Last I knew, the Holepunch route makes a Dockerfile that isn't as easy to troubleshoot as using the current the R-Conda system route. Dockerfiles are essentially a last ditch configuration file that MyBinder can handle. The reason being the other configuration files are much easier and don't require knowing Dockerfile syntax. MyBinder aims to offer the ability to take advantage of Docker offering containers with a specified environment without users needing to know anything about Docker.

There is a Binder Help category for posting to get help at the Jupyter Discourse Forum. Some other examples of posts already there may help you troubleshoot.

Notice of a common pitfall

Most of the the configuration files for making a repository Binder-ready are simply text and can be edited right in the GitHub browser interface, without need to git or even cloning the repo locally.

Last I knew, there are two exceptions to this. The postBuild and start configuration files have settings that allow them to be run as scripts and these get altered in a way they no longer work if you edit them via the GitHub browser interface. (This was my experience when last I tried. Your mileage may vary or things may have changed now.) To edit those, you have to have git available on a system you have and pull one from some other source. Then edit that on your machine that has git working & add it your repo and push it back up from your local computer.

(If this is a problem, you can post in the Jupyter Discourse Forum Binder help category and you and I could coordinate where I fork and edit those files in your repo to your specifications and then make a pull request to update your source of the fork with those changes.)

Title: R and Rstudio Docker vs Binder


问:
How to upload more than 1000 entries using LOAD DATA INFILE?
I'm trying to import an csv file to my database table, the origin of this file was a previous database with the same structure. My issue is that it imports only 1000 rows instead of the whole 62k+ file. The script i'm using is:</p>
```<code>LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/covid19.csv'
INTO TABLE covid19.covid19
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(id,date,iso2,iso3,country,continent,cases,deaths,population);
</code>```

答:
Some clients have a option, where they reduce the number of returned Rows with a LIMIT 1000.

You should check, how many rows you actually have with

```<code>SELECT COUNT(*) FROM covid19.covid19;
</code>```

You should see the actual number of inserted rows, as the command didn't show any warnungs or errors.

Body:
I'm trying to import an csv file to my database table, the origin of this file was a previous database with the same structure. My issue is that it imports only 1000 rows instead of the whole 62k+ file. The script i'm using is:

LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/covid19.csv'
INTO TABLE covid19.covid19
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(id,date,iso2,iso3,country,continent,cases,deaths,population);

Body:
Some clients have a option, where they reduce the number of returned Rows with a LIMIT 1000.

You should check, how many rows you actually have with

SELECT COUNT(*) FROM covid19.covid19;

You should see the actual number of inserted rows, as the command didn't show any warnungs or errors.


问:
Alternative to psutil.Process(pid).name
I have measured the performance of psutil.Process(pid).name and it turns out that it is more than ten times slower than for example psutil.Process(pid).exe. Because the last one of these functions requires different privileges over the path, I cannot just just extract the filename from the path. My question is: Are there any alternatives to psutil.Process(pid).name, which does the same?

答:
You mentioned this is for windows.  I took a look at what psutil does for windows.  It looks like psutil.Process().name is using the windows tool help API.  If you look at psutil's Process code and trace .name, it goes to get_name() in process_info.c.  It is looping through all the pids on your system until it finds the one you're looking for.  I think this may be a limitation of the toolhelp API.  But this is why it's slower than .exe, which uses a different API path, that (as you pointed out), requires additional privilege.

The solution I came up with is to use ctypes and ctypes.windll to call the windows ntapi directly.  It only needs PROCESS_QUERY_INFORMATION, which is different than PROCESS_ALL_ACCESS:

```<code>import ctypes
import os.path

# duplicate the UNICODE_STRING structure from the windows API

class UNICODE_STRING(ctypes.Structure):
    _fields_ = [
      ('Length', ctypes.c_short),
      ('MaximumLength', ctypes.c_short),
      ('Buffer', ctypes.c_wchar_p)
    ]

# args

pid = 8000 # put your pid here

# define some constants; from windows API reference

MAX_TOTAL_PATH_CHARS = 32767
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_IMAGE_FILE_NAME = 27

# open handles

ntdll = ctypes.windll.LoadLibrary('ntdll.dll')
process = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION,
  False, pid)

# allocate memory

buflen = (((MAX_TOTAL_PATH_CHARS + 1) * ctypes.sizeof(ctypes.c_wchar)) +
  ctypes.sizeof(UNICODE_STRING))
buffer = ctypes.c_char_p(' ' * buflen)

# query process image filename and parse for process "name"

ntdll.NtQueryInformationProcess(process, PROCESS_IMAGE_FILE_NAME, buffer,
  buflen, None)
pustr = ctypes.cast(buffer, ctypes.POINTER(UNICODE_STRING))
print os.path.split(pustr.contents.Buffer)[-1]

# cleanup

ctypes.windll.kernel32.CloseHandle(process)
ctypes.windll.kernel32.FreeLibrary(ntdll._handle)
</code>```

Title: Alternative to psutil.Process(pid).name

Body:
You mentioned this is for windows.  I took a look at what psutil does for windows.  It looks like psutil.Process().name is using the windows tool help API.  If you look at psutil's Process code and trace .name, it goes to get_name() in process_info.c.  It is looping through all the pids on your system until it finds the one you're looking for.  I think this may be a limitation of the toolhelp API.  But this is why it's slower than .exe, which uses a different API path, that (as you pointed out), requires additional privilege.

The solution I came up with is to use ctypes and ctypes.windll to call the windows ntapi directly.  It only needs PROCESS_QUERY_INFORMATION, which is different than PROCESS_ALL_ACCESS:

import ctypes
import os.path

# duplicate the UNICODE_STRING structure from the windows API

class UNICODE_STRING(ctypes.Structure):
    _fields_ = [
      ('Length', ctypes.c_short),
      ('MaximumLength', ctypes.c_short),
      ('Buffer', ctypes.c_wchar_p)
    ]

# args

pid = 8000 # put your pid here

# define some constants; from windows API reference

MAX_TOTAL_PATH_CHARS = 32767
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_IMAGE_FILE_NAME = 27

# open handles

ntdll = ctypes.windll.LoadLibrary('ntdll.dll')
process = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION,
  False, pid)

# allocate memory

buflen = (((MAX_TOTAL_PATH_CHARS + 1) * ctypes.sizeof(ctypes.c_wchar)) +
  ctypes.sizeof(UNICODE_STRING))
buffer = ctypes.c_char_p(' ' * buflen)

# query process image filename and parse for process "name"

ntdll.NtQueryInformationProcess(process, PROCESS_IMAGE_FILE_NAME, buffer,
  buflen, None)
pustr = ctypes.cast(buffer, ctypes.POINTER(UNICODE_STRING))
print os.path.split(pustr.contents.Buffer)[-1]

# cleanup

ctypes.windll.kernel32.CloseHandle(process)
ctypes.windll.kernel32.FreeLibrary(ntdll._handle)


问:
django-cookiecutter, docker-compose run: can't type in terminal
I'm having an issue with a project started with django cookiecutter.

To verify that the issue was not with my project, I'm testing on a blank django cookiecutter project.

The issue is that when I run:

```<code>docker-compose -f production.yml run --rm django python manage.py createsuperuser
</code>```

I get the prompt but can't type in the terminal.

Same thing when I run:

```<code>docker-compose -f production.yml run --rm django python manage.py shell
</code>```

I get the shell prompt, but I can't type.

The app is running on a machine on DigitalOcean created with the docker-machine create command.

Any thoughts on what the issue could be and how I could debug this?

答:
bash can be accessed inside the docker container using the following command.

```<code>docker-compose -f production.yml exec django bash
</code>```

This will give you full access to the container of your django server.
There you can run all your normal django commands with full interactivity.

Create Superuser

python manage.py createsuperuser
```
<p><strong>For Local ENV</strong></p>
```docker-compose -f local.yml exec django bash
```

Body:
I'm having an issue with a project started with django cookiecutter.

To verify that the issue was not with my project, I'm testing on a blank django cookiecutter project.

The issue is that when I run:

docker-compose -f production.yml run --rm django python manage.py createsuperuser

I get the prompt but can't type in the terminal.

Same thing when I run:

docker-compose -f production.yml run --rm django python manage.py shell

I get the shell prompt, but I can't type.

The app is running on a machine on DigitalOcean created with the docker-machine create command.

Any thoughts on what the issue could be and how I could debug this?

Body:
bash can be accessed inside the docker container using the following command.

docker-compose -f production.yml exec django bash

This will give you full access to the container of your django server.
There you can run all your normal django commands with full interactivity.

Create Superuser

python manage.py createsuperuser

For Local ENV

docker-compose -f local.yml exec django bash


问:
Flutter [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'FirebaseAuthException' is not a subtype of type 'String'
Hi developers, I am getting this issue

```<code>W/System  ( 7624): Ignoring header X-Firebase-Locale because its value was null.
E/flutter ( 7624): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'FirebaseAuthException' is not a subtype of type 'String'
E/flutter ( 7624): #0      CubitApp.userRegestration.<anonymous closure> (package:shoping_app/lib/shared/cubit/appcubit.dart:172:29)
E/flutter ( 7624): #1      _rootRunUnary (dart:async/zone.dart:1434:47)
E/flutter ( 7624): #2      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 7624): #3      _FutureListener.handleError (dart:async/future_impl.dart:177:22)
E/flutter ( 7624): #4      Future._propagateToListeners.handleError (dart:async/future_impl.dart:778:47)
E/flutter ( 7624): #5      Future._propagateToListeners (dart:async/future_impl.dart:799:13)
E/flutter ( 7624): #6      Future._completeError (dart:async/future_impl.dart:609:5)
E/flutter ( 7624): #7      _completeOnAsyncError (dart:async-patch/async_patch.dart:272:13)
E/flutter ( 7624): #8      FirebaseAuth.createUserWithEmailAndPassword (package:firebase_auth/src/firebase_auth.dart)
E/flutter ( 7624): <asynchronous suspension>
</code>```

on my flutter app when I was tried to create FirebaseAuth.instance.createUserWithEmailAndPassword

and this is the function that I wrote:

```<code>void create_Account({
    required String firstName,
    required String lastName,
    required String userName,
    required String address1,
    required String address2,
    required String phone,
    required String email,
    required String passWord,
}){
  emit(RegisterLodingState());
  FirebaseAuth.instance.createUserWithEmailAndPassword(
      email: email,
      password: passWord,
  ).then((value) {
    emit(RegisterSuccessedState());
    print(value.user!.email);
    print(value.user!.uid);

  }).catchError((err){
    emit(RegisterErrorState(err));
    print('Error when Login :$err');
  });
</code>```

and this code when I call the function:

```<code>ConditionalBuilder(
                      condition: true,
                      builder: (context) => defaultButton(
                        function: () {
                          if (formKey.currentState!.validate()) {
                            cubit.create_Account(
                                firstName:firstNameController.text,
                                lastName: lastNameController.text,
                                userName: userNameController.text,
                                address1:addressOneController.text,
                                address2:addressTwoController.text,
                                phone: phoneNumberController.text,
                                email: phoneNumberController.text,
                                passWord: passwordController.text,
                            );
                          }
                        },
                        text: 'Sign Up',
                      ),
                      fallback: (context) => const Center(
                          child: CircularProgressIndicator()),
                    ),
</code>```

Note:
my emulator device is already connected with the internet and although I tried a physical device but the same problem.

答:
You are trying to cast a FirebaseAuthException to a String which is incorrect so change this line:

```<code>print('Error when Login :$err');
</code>```

to this:

```<code>print('Error when Login :${err.message}');
</code>```

Also, take a look at this document to find out more about error handling in firebase.

Body:
Hi developers, I am getting this issue

W/System  ( 7624): Ignoring header X-Firebase-Locale because its value was null.
E/flutter ( 7624): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'FirebaseAuthException' is not a subtype of type 'String'
E/flutter ( 7624): #0      CubitApp.userRegestration.<anonymous closure> (package:shoping_app/lib/shared/cubit/appcubit.dart:172:29)
E/flutter ( 7624): #1      _rootRunUnary (dart:async/zone.dart:1434:47)
E/flutter ( 7624): #2      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 7624): #3      _FutureListener.handleError (dart:async/future_impl.dart:177:22)
E/flutter ( 7624): #4      Future._propagateToListeners.handleError (dart:async/future_impl.dart:778:47)
E/flutter ( 7624): #5      Future._propagateToListeners (dart:async/future_impl.dart:799:13)
E/flutter ( 7624): #6      Future._completeError (dart:async/future_impl.dart:609:5)
E/flutter ( 7624): #7      _completeOnAsyncError (dart:async-patch/async_patch.dart:272:13)
E/flutter ( 7624): #8      FirebaseAuth.createUserWithEmailAndPassword (package:firebase_auth/src/firebase_auth.dart)
E/flutter ( 7624): <asynchronous suspension>

on my flutter app when I was tried to create FirebaseAuth.instance.createUserWithEmailAndPassword

and this is the function that I wrote:

void create_Account({
    required String firstName,
    required String lastName,
    required String userName,
    required String address1,
    required String address2,
    required String phone,
    required String email,
    required String passWord,
}){
  emit(RegisterLodingState());
  FirebaseAuth.instance.createUserWithEmailAndPassword(
      email: email,
      password: passWord,
  ).then((value) {
    emit(RegisterSuccessedState());
    print(value.user!.email);
    print(value.user!.uid);

  }).catchError((err){
    emit(RegisterErrorState(err));
    print('Error when Login :$err');
  });

and this code when I call the function:

ConditionalBuilder(
                      condition: true,
                      builder: (context) => defaultButton(
                        function: () {
                          if (formKey.currentState!.validate()) {
                            cubit.create_Account(
                                firstName:firstNameController.text,
                                lastName: lastNameController.text,
                                userName: userNameController.text,
                                address1:addressOneController.text,
                                address2:addressTwoController.text,
                                phone: phoneNumberController.text,
                                email: phoneNumberController.text,
                                passWord: passwordController.text,
                            );
                          }
                        },
                        text: 'Sign Up',
                      ),
                      fallback: (context) => const Center(
                          child: CircularProgressIndicator()),
                    ),

Note:
my emulator device is already connected with the internet and although I tried a physical device but the same problem.

Body:
You are trying to cast a FirebaseAuthException to a String which is incorrect so change this line:

print('Error when Login :$err');

to this:

print('Error when Login :${err.message}');

Also, take a look at this document to find out more about error handling in firebase.


问:
How do I display a decimal value to 2 decimal places?
When displaying the value of a decimal currently with .ToString(), it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places.

Do I use a variation of .ToString() for this?

答:
```<code>        var arr = new List<int>() { -4, 3, -9, 0, 4, 1 };
        decimal result1 = arr.Where(p => p > 0).Count();
        var responseResult1 = result1 / arr.Count();
        decimal result2 = arr.Where(p => p < 0).Count();
        var responseResult2 = result2 / arr.Count();
        decimal result3 = arr.Where(p => p == 0).Count();
        var responseResult3 = result3 / arr.Count();
        Console.WriteLine(String.Format("{0:#,0.000}", responseResult1));
        Console.WriteLine(String.Format("{0:#,0.0000}", responseResult2));
        Console.WriteLine(String.Format("{0:#,0.00000}", responseResult3));
</code>```

you can put as many 0 as you want.

OwnerDisplayName: wows

Body:
        var arr = new List<int>() { -4, 3, -9, 0, 4, 1 };
        decimal result1 = arr.Where(p => p > 0).Count();
        var responseResult1 = result1 / arr.Count();
        decimal result2 = arr.Where(p => p < 0).Count();
        var responseResult2 = result2 / arr.Count();
        decimal result3 = arr.Where(p => p == 0).Count();
        var responseResult3 = result3 / arr.Count();
        Console.WriteLine(String.Format("{0:#,0.000}", responseResult1));
        Console.WriteLine(String.Format("{0:#,0.0000}", responseResult2));
        Console.WriteLine(String.Format("{0:#,0.00000}", responseResult3));

you can put as many 0 as you want.


问:
Constructor and destructor in c++ when using the pimpl idiom
I come from Java that has a different way in handling what's private and has to be hided regarding a class implementation and it also has a garbage collector which means there is no need for a destructor.

I learned the basics of how to implement a class in c++ but I need to better understand how to implement a class, in particular the constructor and destructor, when using the pimpl idiom.

hpp file:

```<code>class MyClass{
public:
  MyClass();
  MyClass(std::vector<int>& arr);
  ~MyClass();

private:
  struct Impl;
  Impl* pimpl;
};
</code>```

cpp file:

```<code>#include "MyClass.hpp"
using namespace std;

struct MyClass::Impl{
  vector<int> arr;
  int var;
};
</code>```

I wrote the sample code of a class I need to work on(which means I can't change the way the pimpl idiom is used) using the pimpl idiom and I'm looking for an answer to these questions:

How do I implement the constructor to create an empty instance of MyClass?

```<code>MyClass::MyClass(){}
</code>```

How do I implement the constructor to create an instance of MyClass with these arguments?

```<code>MyClass::MyClass(vector<int>& arr,int var){}
</code>```

How do I implement the destructor?

```<code>MyClass::~MyClass(){}
</code>```

EDIT:

How I would do it:

```<code>MyClass::MyClass(): pimpl(new Impl) {}

MyClass::MyClass(vector<int>& arr,int var): pimpl(new Impl) {
  pimpl->arr=arr;
  pimpl->var=var;
}

MyClass::~MyClass(){
  delete pimpl;
}

</code>```

答:
This is an example of a correct way to implement PIMPL idiom in modern C++:

foo.hpp

#pragma once

#include <memory>

class Foo {
public:
  Foo();
  ~Foo();

  Foo(Foo const &) = delete;
  Foo &operator=(Foo const &) = delete;

  Foo(Foo &&) noexcept;
  Foo &operator=(Foo &&) noexcept;

  void bar();

private:
  class impl;
  std::unique_ptr<impl> pimpl_;
};
```
<p>foo.cpp:</p>
```#include "foo.hpp"

#include <iostream>

class Foo::impl {
public:
  impl() = default;
  ~impl() = default;

  impl(impl const &) = default;
  impl &operator=(impl const &) = default;

  impl(impl &&) noexcept = default;
  impl &operator=(impl &&) noexcept = default;

  void bar() { std::cout << "bar" << std::endl; }
};

Foo::Foo() : pimpl_(new impl{}) {}
Foo::~Foo() = default;

Foo::Foo(Foo &&) noexcept = default;
Foo &Foo::operator=(Foo &&) noexcept = default;

void Foo::bar() { pimpl_->bar(); }
```
<p>main.cpp:</p>
<pre class="lang-cpp prettyprint-override"><code>#include "foo.hpp"

int main(int argc, char const *argv[]) {
  Foo foo;
  foo.bar();
  return 0;
}
</code>```

There are a few words that are to be said:

use a smart pointer (unique or shared) to hold reference(s) to 'impl' object. It'll help you like in JAVA control number of references to an underlying object. In this example, as just Foo class is gone 'impl' is automatically destroyed, there is no need to manually watch the lifetime of the 'impl' object

'impl' MUST be always completely declared and defined in *.cpp file (or bunch of files) or internal *.hpp and/or *.cpp files so that a user of your front class (i.e., in this example 'Foo') that aggregates 'impl' is impossible to see any changes and content of your 'impl' class, that is why PIMPL idiom exists: to persist the interface of the front class for a user and all the changes mostly shall be done in the hidden 'impl' class

The destructor of the front class MUST be always defined in *.cpp file since the compiler must know how to destroy the 'impl' that is not seen thoroughly from the *.hpp file where a front class is declared

The special functions with rvalue-references (move-ctor and move-assignment operator) MUST also be defined in *.cpp file due to the same reason as in the previous clause

Body:
I come from Java that has a different way in handling what's private and has to be hided regarding a class implementation and it also has a garbage collector which means there is no need for a destructor.

I learned the basics of how to implement a class in c++ but I need to better understand how to implement a class, in particular the constructor and destructor, when using the pimpl idiom.

hpp file:

class MyClass{
public:
  MyClass();
  MyClass(std::vector<int>& arr);
  ~MyClass();

private:
  struct Impl;
  Impl* pimpl;
};

cpp file:

#include "MyClass.hpp"
using namespace std;

struct MyClass::Impl{
  vector<int> arr;
  int var;
};

I wrote the sample code of a class I need to work on(which means I can't change the way the pimpl idiom is used) using the pimpl idiom and I'm looking for an answer to these questions:

How do I implement the constructor to create an empty instance of MyClass?

MyClass::MyClass(){}

How do I implement the constructor to create an instance of MyClass with these arguments?

MyClass::MyClass(vector<int>& arr,int var){}

How do I implement the destructor?

MyClass::~MyClass(){}

EDIT:

How I would do it:

MyClass::MyClass(): pimpl(new Impl) {}

MyClass::MyClass(vector<int>& arr,int var): pimpl(new Impl) {
  pimpl->arr=arr;
  pimpl->var=var;
}

MyClass::~MyClass(){
  delete pimpl;
}

Body:
This is an example of a correct way to implement PIMPL idiom in modern C++:

foo.hpp

#pragma once

#include <memory>

class Foo {
public:
  Foo();
  ~Foo();

  Foo(Foo const &) = delete;
  Foo &operator=(Foo const &) = delete;

  Foo(Foo &&) noexcept;
  Foo &operator=(Foo &&) noexcept;

  void bar();

private:
  class impl;
  std::unique_ptr<impl> pimpl_;
};

foo.cpp:

#include "foo.hpp"

#include <iostream>

class Foo::impl {
public:
  impl() = default;
  ~impl() = default;

  impl(impl const &) = default;
  impl &operator=(impl const &) = default;

  impl(impl &&) noexcept = default;
  impl &operator=(impl &&) noexcept = default;

  void bar() { std::cout << "bar" << std::endl; }
};

Foo::Foo() : pimpl_(new impl{}) {}
Foo::~Foo() = default;

Foo::Foo(Foo &&) noexcept = default;
Foo &Foo::operator=(Foo &&) noexcept = default;

void Foo::bar() { pimpl_->bar(); }

main.cpp:

#include "foo.hpp"

int main(int argc, char const *argv[]) {
  Foo foo;
  foo.bar();
  return 0;
}

There are a few words that are to be said:

use a smart pointer (unique or shared) to hold reference(s) to 'impl' object. It'll help you like in JAVA control number of references to an underlying object. In this example, as just Foo class is gone 'impl' is automatically destroyed, there is no need to manually watch the lifetime of the 'impl' object

'impl' MUST be always completely declared and defined in *.cpp file (or bunch of files) or internal *.hpp and/or *.cpp files so that a user of your front class (i.e., in this example 'Foo') that aggregates 'impl' is impossible to see any changes and content of your 'impl' class, that is why PIMPL idiom exists: to persist the interface of the front class for a user and all the changes mostly shall be done in the hidden 'impl' class

The destructor of the front class MUST be always defined in *.cpp file since the compiler must know how to destroy the 'impl' that is not seen thoroughly from the *.hpp file where a front class is declared

The special functions with rvalue-references (move-ctor and move-assignment operator) MUST also be defined in *.cpp file due to the same reason as in the previous clause


问:
How do I pass a Treeview's SelectedItem to another command?
I created a treeview in WPF MVVM with a hierarchical DAtaTemplate property.

Outside of the Treeview, I have an "EDIT" button. On press of edit button I want to pass the Treeview's selectedItem to the RelayCommand in the viewmodel.

I am implementing the same functionality within the TreeviewItem on double click of the node. However I want to know what is the best way to accomplish this outside.

My code structure is as follows

MainView -> MainViewModel

StateViewItem -> StateViewModel (HierarchicalDataTemplate inheriting from TreeViewItemViewModel)

RegionViewItem -> RegionViewModel (DataTemplate inheriting from TreeViewItemViewModel)

The RegionViewModel handles the double click for the node and accomplishes the Edit functionality.

However the "EDIT" button is outside of the treeview, how do I pass the selected RegionViewItem to the Command bound so I can load it for editing?

thanks in advance for help

答:
Code below is ONLY for guidance purposes for MVVM. It may / may not compile.

Way 1:

Assuming that your TreeViewItemViewModel is the base item level view model data context for all tree view items in your tree, add a writeable property in TreeViewItemViewModel called IsSelected. Dont forget to notify property changes in IsSelected's Setter.

In your XAML Tree View add the following in the Style targetted for the TreeViewItem ....

```<code>  <TreeView.Resources>
      <Style TargetType="{x:Type TreeViewItem}">
          <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
      </Style>
  </TreeView.Resources>
</code>```

This way when any TreeView gets selected, ONLY its own TreeViewItemViewModel's IsSelected property will be true and rest all tree view items will be false. So the task left would be to find the selected TreeViewItemViewModel object from the hierarchy of object bound to the ItemsSource of the TreeView.

Way 2:

Have an attached property for a TreeViewItem and handle its MouseDown event. Check if the 'IsSelected' value of the TreeViewItem is true and extract its data context which will be the selected TreeViewItemViewModel.

```<code>  <TreeView.Resources>
      <Style TargetType="{x:Type TreeViewItem}">
          <Setter Property="local:MyAttachedBehavior.HandleMouseDown" Value="true" />
      </Style>
  </TreeView.Resources>
</code>```

in the static HandleMouseDownPropertyChanged() dependency property changed method, handle the MouseDown event on the (TreeViewItem)sender ...

```<code>  ((TreeViewItem)sender).MouseDown += TreeViewMouseDownEventHandler;

  private static TreeViewMouseDownEventHandler(object sender, MouseButtonEventArgs e)
  {
      var treeViewItem = (TreeViewItem)sender;
      if (treeViewItem.IsSelected)
      {
            var mySelectedItem = treeViewItem.DataContext as TreeViewItemViewModel;
      }
  }
</code>```

Pass this selected `TreeViewItemViewModel' instance as the required selected item to your routine.

Let me know if this helps.

Body:
Code below is ONLY for guidance purposes for MVVM. It may / may not compile.

Way 1:

Assuming that your TreeViewItemViewModel is the base item level view model data context for all tree view items in your tree, add a writeable property in TreeViewItemViewModel called IsSelected. Dont forget to notify property changes in IsSelected's Setter.

In your XAML Tree View add the following in the Style targetted for the TreeViewItem ....

  <TreeView.Resources>
      <Style TargetType="{x:Type TreeViewItem}">
          <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
      </Style>
  </TreeView.Resources>

This way when any TreeView gets selected, ONLY its own TreeViewItemViewModel's IsSelected property will be true and rest all tree view items will be false. So the task left would be to find the selected TreeViewItemViewModel object from the hierarchy of object bound to the ItemsSource of the TreeView.

Way 2:

Have an attached property for a TreeViewItem and handle its MouseDown event. Check if the 'IsSelected' value of the TreeViewItem is true and extract its data context which will be the selected TreeViewItemViewModel.

  <TreeView.Resources>
      <Style TargetType="{x:Type TreeViewItem}">
          <Setter Property="local:MyAttachedBehavior.HandleMouseDown" Value="true" />
      </Style>
  </TreeView.Resources>

in the static HandleMouseDownPropertyChanged() dependency property changed method, handle the MouseDown event on the (TreeViewItem)sender ...

  ((TreeViewItem)sender).MouseDown += TreeViewMouseDownEventHandler;

  private static TreeViewMouseDownEventHandler(object sender, MouseButtonEventArgs e)
  {
      var treeViewItem = (TreeViewItem)sender;
      if (treeViewItem.IsSelected)
      {
            var mySelectedItem = treeViewItem.DataContext as TreeViewItemViewModel;
      }
  }

Pass this selected `TreeViewItemViewModel' instance as the required selected item to your routine.

Let me know if this helps.


问:
How to install latest phpmyadmin on ubuntu nginx server
I have installed phpmyadmin on ubuntu server using php81,

When i access the phpmyadmin on my browser I kept getting deprecation notice as shown below

Deprecation Notice in ./libraries/classes/Url.php#221
 http_build_query(): Passing null to parameter #2 ($numeric_prefix) of type string is deprecated

```

I'm running ubuntu 20.04

Following lots of research, I found out that the only way out is to install phpmyadmin 5 which is currently the latest version

But the problem is that following this answer

sudo apt-get install phpmyadmin=5.1.1

Gives the following error

E: Version '5.1.1' for 'phpmyadmin' was not found

Is there anything I can do to get the latest phpmyadmin on my ubuntu server

答:
As far as i can seee the latest version for phpmyadmin available for focal (Ubuntu 20.04) is 4.9.5: https://packages.ubuntu.com/focal/phpmyadmin

You could do any of the following:

Disable error reporting for notices in php so the notice doesn't come up(How do I turn off PHP Notices?)

Try to manually install the latest version of phpmyadmin(https://www.phpmyadmin.net/)

Install an older version of php and run phpmyadmin on that(https://www.digitalocean.com/community/tutorials/how-to-run-multiple-php-versions-on-one-server-using-apache-and-php-fpm-on-ubuntu-18-04)

Body:
I have installed phpmyadmin on ubuntu server using php81,

When i access the phpmyadmin on my browser I kept getting deprecation notice as shown below

Deprecation Notice in ./libraries/classes/Url.php#221
 http_build_query(): Passing null to parameter #2 ($numeric_prefix) of type string is deprecated

I'm running ubuntu 20.04

Following lots of research, I found out that the only way out is to install phpmyadmin 5 which is currently the latest version

But the problem is that following this answer

sudo apt-get install phpmyadmin=5.1.1

Gives the following error

E: Version '5.1.1' for 'phpmyadmin' was not found

Is there anything I can do to get the latest phpmyadmin on my ubuntu server


问:
Jupyter Notebook's File and Kernel menus disappear
I have an issue where my File and Kernel menus initially show while the notebook is loading, then disappear once the notebook is loaded.

I should be seeing this:

but instead I see this:

It used to work correctly. I am not sure what could have changed to make these menus disappear.

Thanks for any help with this.

答: I had exactly the same problem a few days ago, also a kernel error popped out. The error said that there was a problem with path to ArcGIS software, which I had installed couple of weeks earlier. After I uninstalled ArcGIS (I didn't need it anymore) my jupyter came back to normal.</p>


问:
Java regex issues with an exact token
In my Java app I have a "template string", say, "This record's name is : %%%NAME%%%."

I want to loop through a list and for each iteration, print out a "customized version" of this template that string-replaces the %%%NAME%%% token for a meaningful value.  For instance:

```<code>List<String> strNamesList = getNamesSomehow();
String strTemplate = "This record's name is : %%%NAME%%%.";
String strCustomized = "";
for(int i = 0; i < strNamesList.size(); i++)
{
    strCustomized = strTemplate.replaceFirst(strSomeRegex, strNamesList.get(i));
    System.out.println(strCustomized);
}
</code>```

Per usual, I am choking on the strSomeRegex. I simply need a regex that will match for the exact phrase:

%%%NAME%%%

I have Googled, Binged, Wikipediaed and more. Searches for "match regex on exact" (and their likes) turn back all sorts of things, none of which help me with this token that has punctuation (percentage signs) in it.

Regexes are just one of those things that get me every time, and this is my last resort.

Thanks to any kind StackOverflowers who can point me in the right direction!

答:
If the percent signs are your only issue, backslash is used to escape special characters in regex.

So your pattern should be \%\%\%NAME\%\%\%

Which means in Java, one would write:

```<code>String patternString = "\\%\\%\\%NAME\\%\\%\\%";
</code>```

EDIT: Wait, but is % a regex special character? I assumed it was, but the following code worked for me:

```<code>Pattern p = Pattern.compile("%%%NAME%%%");
Matcher m = p.matcher("This record's name is : %%%NAME%%%.");
System.out.println(m.replaceFirst("Bob")); //prints "This record's name is : Bob."
</code>```

I don't see % mentioned anywhere in the documentation: http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

Am I missing something here?

Title: Java regex issues with an exact token

Body:
In my Java app I have a "template string", say, "This record's name is : %%%NAME%%%."

I want to loop through a list and for each iteration, print out a "customized version" of this template that string-replaces the %%%NAME%%% token for a meaningful value.  For instance:

List<String> strNamesList = getNamesSomehow();
String strTemplate = "This record's name is : %%%NAME%%%.";
String strCustomized = "";
for(int i = 0; i < strNamesList.size(); i++)
{
    strCustomized = strTemplate.replaceFirst(strSomeRegex, strNamesList.get(i));
    System.out.println(strCustomized);
}

Per usual, I am choking on the strSomeRegex. I simply need a regex that will match for the exact phrase:

%%%NAME%%%

I have Googled, Binged, Wikipediaed and more. Searches for "match regex on exact" (and their likes) turn back all sorts of things, none of which help me with this token that has punctuation (percentage signs) in it.

Regexes are just one of those things that get me every time, and this is my last resort.

Thanks to any kind StackOverflowers who can point me in the right direction!

Body:
If the percent signs are your only issue, backslash is used to escape special characters in regex.

So your pattern should be \%\%\%NAME\%\%\%

Which means in Java, one would write:

String patternString = "\\%\\%\\%NAME\\%\\%\\%";

EDIT: Wait, but is % a regex special character? I assumed it was, but the following code worked for me:

Pattern p = Pattern.compile("%%%NAME%%%");
Matcher m = p.matcher("This record's name is : %%%NAME%%%.");
System.out.println(m.replaceFirst("Bob")); //prints "This record's name is : Bob."

I don't see % mentioned anywhere in the documentation: http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

Am I missing something here?


问:
Partial match between 2 column and output yes, no in another column

Trying to do a partial match between the two columns and generate Yes or No if they do have a partial match on the third column

答:
So, for the names given, you'd expect three "Yes" answers - for Trelleborg and Moog?

You could try this: get the first word from column B, and see if it's present in column A.

To get the first word, find the first space.

```<code>=FIND(" ", @B:B)
</code>```

Get that many letters (minus 1 for the space) from B:

```<code>=LEFT(@B:B,FIND(" ", @B:B)-1)
</code>```

Find that word in column A. Use SEARCH not FIND for a case-insensitive search:

```<code>=SEARCH(LEFT(@B:B,FIND(" ", @B:B)-1),@A:A)
</code>```

This will give a number or an error. Let's make that be FALSE or TRUE:

```<code>=ISERROR(SEARCH(LEFT(@B:B,FIND(" ", @B:B)-1),@A:A))
</code>```

Finally let's turn that into "No" (is true, an error, no match found) or "Yes" (if false, not an error, match found)

```<code>=IF(ISERROR(SEARCH(LEFT(@B:B,FIND(" ", @B:B)-1),@A:A)),"No","Yes")
</code>```

Body:
So, for the names given, you'd expect three "Yes" answers - for Trelleborg and Moog?

You could try this: get the first word from column B, and see if it's present in column A.

To get the first word, find the first space.

=FIND(" ", @B:B)

Get that many letters (minus 1 for the space) from B:

=LEFT(@B:B,FIND(" ", @B:B)-1)

Find that word in column A. Use SEARCH not FIND for a case-insensitive search:

=SEARCH(LEFT(@B:B,FIND(" ", @B:B)-1),@A:A)

This will give a number or an error. Let's make that be FALSE or TRUE:

=ISERROR(SEARCH(LEFT(@B:B,FIND(" ", @B:B)-1),@A:A))

Finally let's turn that into "No" (is true, an error, no match found) or "Yes" (if false, not an error, match found)

=IF(ISERROR(SEARCH(LEFT(@B:B,FIND(" ", @B:B)-1),@A:A)),"No","Yes")


问:
How does one disable SourceDestCheck when creating instances with AWS CLI
It should be possible to disable SourceDestCheck since it is documented
"SourceDestCheck -> (boolean)"

but using run-instances with

```<code>aws ec2 run-instances ...
--SourceDestCheck false
</code>```

or

```<code>--sourceDestCheck=false
</code>```

Fails with
Unknown options: --SourceDestCheck, false

It seems I can run it later with a modify command

```<code>aws ec2 modify-instance-attribute --resource=$INSTANCE_ID --no-source-dest-check
</code>```

but it should be possible to set that at instantiation. I just can't figure out the actual syntax.

答:
I know this is old but I ran into the same issue today and solved it this way.  In the resource block of your terraform file add:

```<code>provisioner "local-exec" {
    command = "aws ec2 modify-instance-attribute --no-source-dest-check --instance-id ${self.id}"
}
</code>```

assuming you have the was cli tools installed.

Body:
It should be possible to disable SourceDestCheck since it is documented
"SourceDestCheck -> (boolean)"

but using run-instances with

aws ec2 run-instances ...
--SourceDestCheck false

or

--sourceDestCheck=false

Fails with
Unknown options: --SourceDestCheck, false

It seems I can run it later with a modify command

aws ec2 modify-instance-attribute --resource=$INSTANCE_ID --no-source-dest-check

but it should be possible to set that at instantiation. I just can't figure out the actual syntax.

Body:
I know this is old but I ran into the same issue today and solved it this way.  In the resource block of your terraform file add:

provisioner "local-exec" {
    command = "aws ec2 modify-instance-attribute --no-source-dest-check --instance-id ${self.id}"
}

assuming you have the was cli tools installed.