问:
Spacy: How to turn a verb into a noun?
How can I use Spacy to turn verbs into nouns? For example, the sentence

```<code>The shop is owned by the company.
</code>```

has the verb owned in passive voice. I want to turn it into owner using Spacy.

答:
spaCy has no feature to do this. NLG, or modifying the input text to make new text, is considered out of scope for spaCy.

Even if you used an NLG library I'm not sure there's any standard way to do the kind of transformation you want.

Also there's nothing wrong with passive voice.

Title: Spacy: How to turn a verb into a noun?

Body:
How can I use Spacy to turn verbs into nouns? For example, the sentence

The shop is owned by the company.

has the verb owned in passive voice. I want to turn it into owner using Spacy.


来源: stackexchange

问:
why am I not able to compare a space in string after splitting to a space?

def str_to_list(str):
    # Insert your code here
    new = list(str)
    for i in new:
        if i ==  or (i.isdigit() and int(i) > 5):
            new.remove(i)
    return new
```

I expect out to be ['d', 'o', 'l', 'l', 'a', 'r']

But I get [' ', 'd', 'o', 'l', 'l', 'a', 'r']

答:
try to write this code like

```<code>if i == " " or (i.is digit() and int(i)>5)
</code>```

Like this the space will evaluate like a string

ContentLicense: CC BY-SA 4.0

Body:
def str_to_list(str):
    # Insert your code here
    new = list(str)
    for i in new:
        if i ==  or (i.isdigit() and int(i) > 5):
            new.remove(i)
    return new

I expect out to be ['d', 'o', 'l', 'l', 'a', 'r']

But I get [' ', 'd', 'o', 'l', 'l', 'a', 'r']

Body:
try to write this code like

if i == " " or (i.is digit() and int(i)>5)

Like this the space will evaluate like a string


问:
How can I update/add new information to my local JSOn file in Flutter? (without creating any classes)
I made a small application, sort of like a library app where you can add books you've read. So, I have a local JSON file, which looks like this:

[
  {
    "name": "Harry Potter and the Deathly Hallows",
    "author": "J.K. Rowling",
    "rating": "4.5",
    "category": "Fantasy",
    "url": "some url"
  },
  {
    "name": "For Whom The Bell Tolls",
    "author": "E. Hemingway",
    "rating": "4",
    "category": "Novel",
    "url": "some url#2"
  }
]
```
<p>In my main.dart file I have a function that reads my JSON file, decodes and loads it in a list named "data":</p>
<pre class="lang-dart prettyprint-override"><code>readData(){
    DefaultAssetBundle.of(context).loadString("json/books.json").then((s){
      setState(() {
        data = json.decode(s);
      });

    });
  }

@override
  void initState() {
    super.initState();
    readData();

  }

</code>```

I can easily add new books to "data" and everything is fine except for one thing, - I don't know how to update/write information to JSON, so the app could show me the updated list with the new book after a restart. I've added. How do I do this? And what should I write into the JSON file, - the updated List with all books or just a Map with a new book?

Answer to NelsonThiago

This code is in "class AddingPageState extends  State":

```<code>Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }
  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/books.json');
  }
  Future<File> writeData(List list) async { // "list" is the updated book-list
    final file = await _localFile;
    String encodedData = jsonEncode(list);
    return file.writeAsString('$encodedData');
  }
</code>```

And I call "writeData" in onPressed function.

答:
See the following example. But it requires to create a class. The sample json file is like below (pretty much similar to your json file) -

```<code>[
  {"name":"Ash","age":"22","hobby":"golf"},
  {"name":"philip","age":"17","hobby":"fishing"},
  {"name":"charles","age":"32","hobby":"drawing"},
]
</code>```

And I am editing the above code answered by Ward Suleiman so that you can read from a local json file and write to it-

```<code>import 'dart:io';
import 'dart:convert';

List<Player> players = [];

void main() async{
    print("hello world");
    final File file = File('D:/Sadi/.../test.json'); //load the json file
    await readPlayerData(file); //read data from json file

    Player newPlayer = Player(  //add a new item to data list
      'Samy Brook',
      '31',
      'cooking'
      );

  players.add(newPlayer);

  print(players.length);

  players  //convert list data  to json
      .map(
        (player) => player.toJson(),
      )
      .toList();

    file.writeAsStringSync(json.encode(players));  //write (the whole list) to json file
}

Future<void> readPlayerData (File file) async {

    String contents = await file.readAsString();
    var jsonResponse = jsonDecode(contents);

    for(var p in jsonResponse){

        Player player = Player(p['name'],p['age'],p['hobby']);
        players.add(player);
    }

}
</code>```

And the Player class -

```<code>class Player {
  late String name;
  late String age;
  late String hobby;

  Player(
     this.name,
     this.age,
    this.hobby,

  );

  Player.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    age = json['age'];
    hobby = json['hobby'];

  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['age'] = this.age;
    data['hobby'] = this.hobby;

    return data;
  }

}
</code>```

Body:
I made a small application, sort of like a library app where you can add books you've read. So, I have a local JSON file, which looks like this:

[
  {
    "name": "Harry Potter and the Deathly Hallows",
    "author": "J.K. Rowling",
    "rating": "4.5",
    "category": "Fantasy",
    "url": "some url"
  },
  {
    "name": "For Whom The Bell Tolls",
    "author": "E. Hemingway",
    "rating": "4",
    "category": "Novel",
    "url": "some url#2"
  }
]

In my main.dart file I have a function that reads my JSON file, decodes and loads it in a list named "data":

readData(){
    DefaultAssetBundle.of(context).loadString("json/books.json").then((s){
      setState(() {
        data = json.decode(s);
      });

    });
  }

@override
  void initState() {
    super.initState();
    readData();

  }

I can easily add new books to "data" and everything is fine except for one thing, - I don't know how to update/write information to JSON, so the app could show me the updated list with the new book after a restart. I've added. How do I do this? And what should I write into the JSON file, - the updated List with all books or just a Map with a new book?

Answer to NelsonThiago

This code is in "class AddingPageState extends  State":

Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }
  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/books.json');
  }
  Future<File> writeData(List list) async { // "list" is the updated book-list
    final file = await _localFile;
    String encodedData = jsonEncode(list);
    return file.writeAsString('$encodedData');
  }

And I call "writeData" in onPressed function.

Body:
See the following example. But it requires to create a class. The sample json file is like below (pretty much similar to your json file) -

[
  {"name":"Ash","age":"22","hobby":"golf"},
  {"name":"philip","age":"17","hobby":"fishing"},
  {"name":"charles","age":"32","hobby":"drawing"},
]

And I am editing the above code answered by Ward Suleiman so that you can read from a local json file and write to it-

import 'dart:io';
import 'dart:convert';

List<Player> players = [];

void main() async{
    print("hello world");
    final File file = File('D:/Sadi/.../test.json'); //load the json file
    await readPlayerData(file); //read data from json file

    Player newPlayer = Player(  //add a new item to data list
      'Samy Brook',
      '31',
      'cooking'
      );

  players.add(newPlayer);

  print(players.length);

  players  //convert list data  to json
      .map(
        (player) => player.toJson(),
      )
      .toList();

    file.writeAsStringSync(json.encode(players));  //write (the whole list) to json file
}

Future<void> readPlayerData (File file) async {

    String contents = await file.readAsString();
    var jsonResponse = jsonDecode(contents);

    for(var p in jsonResponse){

        Player player = Player(p['name'],p['age'],p['hobby']);
        players.add(player);
    }

}

And the Player class -

class Player {
  late String name;
  late String age;
  late String hobby;

  Player(
     this.name,
     this.age,
    this.hobby,

  );

  Player.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    age = json['age'];
    hobby = json['hobby'];

  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['age'] = this.age;
    data['hobby'] = this.hobby;

    return data;
  }

}


问:
How to analyze generic lifetime when it is relevant to variance

 0 // code snippet 1
 1
 2 struct MutStr<'a >{
 3     s: &'a mut &'a str,
 4 }
 5
 6 fn main() {
 7     let mut s: &'static str = "hello";
 8     *MutStr{
 9         s: &mut s,
10     }.s = "world";
11     println!("{}", s);
12 }
```
<blockquote>
<p>Rust Playground link of <code>code snippet 1</code></p>
</blockquote>
<p>The <code>code snippnet 1</code> above varies from Rust for Rustacean Ch1 listing 1-11 where I use <code>'a</code> to replace two lifetimes <code>'a</code> and <code>'b</code> , and this code can not compile, whereas I can not tell the reason:(</p>
<p>I can analyze some simple code such as the following one (from Programming Rust Verson 2 page 120):</p>
<pre class="lang-rust prettyprint-override"><code> 0 // code snippet 2
 1
 2 struct S<'a> {
 3     x: &'a i32,
 4     y: &'a i32
 5 }
 6
 7 fn main() {
 8     let x = 10;
 9     let r;
10     {
11         let y = 20;
12         {
13             let s = S {x: &x, y: &y};
14             r = s.x;
15         }
16     }
17     println!("{}", r);
18 }
</code>```

Rust Playground link of code snippet 2

I denote lifetime of x, y and r with 'x ,  'y and 'r respectively:

'x
'y
'r

line: from 8 to 18
line: from 11 to 16
line: from 9 to 17

When  instantiating s in line 13,  we are requiring 'x:'a ('x outlives 'a) 'y:'a , and when assignment r = s.x happens in line 14 , we are requiring 'a:'r . Nevertheless, this is impossible for the reason that 'y:'a conflicts with 'a:'r (see table above, 'y is shorter than 'r ) so that rustc can not find a deterministic lifetime for generic lifetime 'a satisfying those conflicting conditions.

Update: I am expecting a analyze process for  code snippet 1 similar to the above one, or a general inference method when encountering lifetime problems:)

I have read this article , knowing some basic concepts about variance, such as covariance  invariance and contravariance . And I kind of think my question relate to that, but don't know how to use that to analyze code snippet 1.

答:
I have read this article, knowing some basic concepts about variance, such as covariance invariance and contravariance. And I kind of think my question relate to that, but don't know how to use that to analyze code snippet 1.

You are on the right track, the difference does lie with lifetime variance. There is a table in the Rust Reference 10.5 Subtyping and Variance that I think is helpful:

Type
Variance in 'a
Variance in T

&'a T
covariant
covariant

&'a mut T
covariant
invariant

In your second snippet, your references are immutable meaning the lifetime associated with them can be shortened as necessary. A reference to the variable y cannot lengthen its lifetime so the reference to x must be shortened. An thus the reference bound to r is tied to the lifetime of y and therefore you get an error when you try to use r after y has gone out of scope.

In the first snippet however, you have a mutable reference to a &'a str. If you look at the table above, you'll see that types referenced by a mutable reference are invariant and since the type is itself a &'a str, that means that 'a is invariant. This means, unlike in the second snippet, the compiler can not shorten the lifetime of 'a at all. So when you try to use s to make a MutStr, the compiler sees that you're passing a &'static str that it cannot shorten, so 'a must be 'static. But then it tries to reconcile that 'a is also linked to the variable s which is not 'static, so you get the error.

Body:
 0 // code snippet 1
 1
 2 struct MutStr<'a >{
 3     s: &'a mut &'a str,
 4 }
 5
 6 fn main() {
 7     let mut s: &'static str = "hello";
 8     *MutStr{
 9         s: &mut s,
10     }.s = "world";
11     println!("{}", s);
12 }

Rust Playground link of code snippet 1

The code snippnet 1 above varies from Rust for Rustacean Ch1 listing 1-11 where I use 'a to replace two lifetimes 'a and 'b , and this code can not compile, whereas I can not tell the reason:(

I can analyze some simple code such as the following one (from Programming Rust Verson 2 page 120):

 0 // code snippet 2
 1
 2 struct S<'a> {
 3     x: &'a i32,
 4     y: &'a i32
 5 }
 6
 7 fn main() {
 8     let x = 10;
 9     let r;
10     {
11         let y = 20;
12         {
13             let s = S {x: &x, y: &y};
14             r = s.x;
15         }
16     }
17     println!("{}", r);
18 }

Rust Playground link of code snippet 2

I denote lifetime of x, y and r with 'x ,  'y and 'r respectively:

'x
'y
'r

line: from 8 to 18
line: from 11 to 16
line: from 9 to 17

When  instantiating s in line 13,  we are requiring 'x:'a ('x outlives 'a) 'y:'a , and when assignment r = s.x happens in line 14 , we are requiring 'a:'r . Nevertheless, this is impossible for the reason that 'y:'a conflicts with 'a:'r (see table above, 'y is shorter than 'r ) so that rustc can not find a deterministic lifetime for generic lifetime 'a satisfying those conflicting conditions.

Update: I am expecting a analyze process for  code snippet 1 similar to the above one, or a general inference method when encountering lifetime problems:)

I have read this article , knowing some basic concepts about variance, such as covariance  invariance and contravariance . And I kind of think my question relate to that, but don't know how to use that to analyze code snippet 1.


问:
Breaking space (opposite of non-breaking space)
While solving a little bug on a website caused by a non-breaking space ( ) I was wondering if there's an opposite.

Is there an HTML code for a breaking space, and if so, what is it?

I saw mention in this question about a zero-width space (), but that won't give any width (obviously).

Does an HTML entity exist for a regular space?

答:
There may be other blank entities (which won't compact to a single) but there is another workaround for doing some padding but still having some wrapping occur as required:

Use the "ZeroWidthSpace" html entity and alternate with either "nbsp" for clarity or simply a space character.


问:
count number of value per id in array
I have this script in php i want to get the number of value in the table
in below my script

```<code>$count = 0;

foreach ($info as $key => $value)
{
    foreach ($value as $c => $val)
    {
        var_dump($val) . "<br>";

        if (strcmp($val,"Tankh ") == 0)
        {
            $count++;
            //echo $count;
        }
    }

    // die();

    echo $count;
    return $count;
</code>```

var_dump the $val:

```<code>string(9) "Nomclient"
string(13) "Villeclient "
string(7) "Mohamed"
string(8) "Tankh "
string(6) "Fatima"
string(9) "Tankh "
string(6) "Brahim"
string(6) "Tankh "
string(5) "Jamal"
string(8) "Tankh "
string(5) "Ikram"
string(6) "Tankh "
string(6) "Karima"
string(5) "Rain"
</code>```

thanks in advance

答:
I think you'd want something like this... if I understand correctly:

```<code>$val_counts = array();

foreach ($info as $key => $value)
{
   foreach ($value as $c => $val)
   {
      $val_counts[$val]++;
   }
}
</code>```

Then later, var_dump($val_counts) and you'll see how many time each value was in your 2-dimensional array.

Title: count number of value per id in array

Body:
I have this script in php i want to get the number of value in the table
in below my script

$count = 0;

foreach ($info as $key => $value)
{
    foreach ($value as $c => $val)
    {
        var_dump($val) . "
";

        if (strcmp($val,"Tankh ") == 0)
        {
            $count++;
            //echo $count;
        }
    }

    // die();

    echo $count;
    return $count;

var_dump the $val:

string(9) "Nomclient"
string(13) "Villeclient "
string(7) "Mohamed"
string(8) "Tankh "
string(6) "Fatima"
string(9) "Tankh "
string(6) "Brahim"
string(6) "Tankh "
string(5) "Jamal"
string(8) "Tankh "
string(5) "Ikram"
string(6) "Tankh "
string(6) "Karima"
string(5) "Rain"

thanks in advance

Body:
I think you'd want something like this... if I understand correctly:

$val_counts = array();

foreach ($info as $key => $value)
{
   foreach ($value as $c => $val)
   {
      $val_counts[$val]++;
   }
}

Then later, var_dump($val_counts) and you'll see how many time each value was in your 2-dimensional array.


问:
JS - jQuery Remove all bands that contains a class but keep the one with the ID that is in the URL
I need your help. I am new to Javascript and jQuery. I have something to do.
I have a list of divs with the same class but each div has a specific ID.
Let say I have this:

```<code><div class="list" id="apples"></div>
<div class="list" id="bananas"></div>
<div class="list" id="pineapples"></div>
</code>```

I have the URL https://johndoe.com/apples, https://johndoe.com/bananas and https://johndoe.com/pineapples.

All divs are displayed on the 3 pages but I want to have only the div with id apples displayed on the Apples page and the others to be entirely removed not hidden. I want the same for each page (bananas displayed on bananas' page...). So what I wrote is this. I thought that changing apples div's class to something else would avoid it to be deleted.

```<code>var fruitId = val['id'];
function displayDiv()
{
    var selectedSection = document.getElementById(fruitId);
    if (window.location.href.indexOf(fruitId) > 0)
    {
        selectedSection.setAttribute('class', 'selectedfruit');
        $("div.list").remove();
    }
}
</code>```

Do not pay attention to fruitId it's 'apples', 'bananas' and 'pineapples' in the JSON file and I have the correct list.

答:
I tried this and it works perfectly BUT I still have Uncaught TypeError: window.location.href.contains is not a function

```<code>$("div.list").filter(function(){
   if (window.location.href.indexOf(this.id) > -1)
    {
        return !window.location.href.contains(this.id)
    }
    $("div.list").remove();
});
</code>```

What can I do to remove the error? If I replace the "contains" with "indexOf" then I don't have any results.

Body:
I need your help. I am new to Javascript and jQuery. I have something to do.
I have a list of divs with the same class but each div has a specific ID.
Let say I have this:

I have the URL https://johndoe.com/apples, https://johndoe.com/bananas and https://johndoe.com/pineapples.

All divs are displayed on the 3 pages but I want to have only the div with id apples displayed on the Apples page and the others to be entirely removed not hidden. I want the same for each page (bananas displayed on bananas' page...). So what I wrote is this. I thought that changing apples div's class to something else would avoid it to be deleted.

var fruitId = val['id'];
function displayDiv()
{
    var selectedSection = document.getElementById(fruitId);
    if (window.location.href.indexOf(fruitId) > 0)
    {
        selectedSection.setAttribute('class', 'selectedfruit');
        $("div.list").remove();
    }
}

Do not pay attention to fruitId it's 'apples', 'bananas' and 'pineapples' in the JSON file and I have the correct list.

Body:
I tried this and it works perfectly BUT I still have Uncaught TypeError: window.location.href.contains is not a function

$("div.list").filter(function(){
   if (window.location.href.indexOf(this.id) > -1)
    {
        return !window.location.href.contains(this.id)
    }
    $("div.list").remove();
});

What can I do to remove the error? If I replace the "contains" with "indexOf" then I don't have any results.


问:
After installing scrubadub_spacy package, spacy.load("en_core_web_sm") not working OSError: [E053] Could not read config.cfg
I am getting the below error when I'm trying to run the following line of code to load en_core_web_sm in the Azure Machine Learning instance.

I debugged the issue and found out that once I install scrubadub_spacy, that seems is the issue causing the error.

```<code>spacy.load("en_core_web_sm")
</code>```
```<code>OSError                                   Traceback (most recent call last)
<ipython-input-2-c6e652d70518> in <module>
     1 # Load English tokenizer, tagger, parser and NER
----> 2 nlp = spacy.load("en_core_web_sm")

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/__init__.py in load(name, vocab, disable, exclude, config)
    50     """
    51     return util.load_model(
---> 52         name, vocab=vocab, disable=disable, exclude=exclude, config=config
    53     )
    54

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/util.py in load_model(name, vocab, disable, exclude, config)
   418             return get_lang_class(name.replace("blank:", ""))()
   419         if is_package(name):  # installed as package
--> 420             return load_model_from_package(name, **kwargs)  # type: ignore[arg-type]
   421         if Path(name).exists():  # path to model data directory
   422             return load_model_from_path(Path(name), **kwargs)  # type: ignore[arg-type]

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/util.py in load_model_from_package(name, vocab, disable, exclude, config)
   451     """
   452     cls = importlib.import_module(name)
--> 453     return cls.load(vocab=vocab, disable=disable, exclude=exclude, config=config)  # type: ignore[attr-defined]
   454
   455

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/en_core_web_sm/__init__.py in load(**overrides)
    10
    11 def load(**overrides):
---> 12     return load_model_from_init_py(__file__, **overrides)

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/util.py in load_model_from_init_py(init_file, vocab, disable, exclude, config)
   619         disable=disable,
   620         exclude=exclude,
--> 621         config=config,
   622     )
   623

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/util.py in load_model_from_path(model_path, meta, vocab, disable, exclude, config)
   485     config_path = model_path / "config.cfg"
   486     overrides = dict_to_dot(config)
--> 487     config = load_config(config_path, overrides=overrides)
   488     nlp = load_model_from_config(config, vocab=vocab, disable=disable, exclude=exclude)
   489     return nlp.from_disk(model_path, exclude=exclude, overrides=overrides)

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/util.py in load_config(path, overrides, interpolate)
   644     else:
   645         if not config_path or not config_path.exists() or not config_path.is_file():
--> 646             raise IOError(Errors.E053.format(path=config_path, name="config.cfg"))
   647         return config.from_disk(
   648             config_path, overrides=overrides, interpolate=interpolate

OSError: [E053] Could not read config.cfg from /anaconda/envs/azureml_py36/lib/python3.6/site-packages/en_core_web_sm/en_core_web_sm-2.3.1/config.cfg
</code>```

I installed the packages using the below three lines codes from Spacy

```<code>pip install -U pip setuptools wheel
pip install -U spacy
python -m spacy download en_core_web_sm
</code>```

How should I fix this issue? thanks in advance.

答:
Taking the path from your error message:

```<code>en_core_web_sm-2.3.1/config.cfg
</code>```

You have a model for v2.3, but it's looking for a config.cfg, which is only a thing in v3 of spaCy. It looks like you upgraded spaCy without realizing it.

There are two ways to fix this. One is to reinstall the model with spacy download, which will get a version that matches your current spaCy version. If you are just starting something that is probably the best idea. Based on the release date of scrubadub, it seems to be intended for use with spaCy v3.

However, note that v2 and v3 are pretty different - if you have a project with v2 of spaCy you might want to downgrade instead.

Body:
I am getting the below error when I'm trying to run the following line of code to load en_core_web_sm in the Azure Machine Learning instance.

I debugged the issue and found out that once I install scrubadub_spacy, that seems is the issue causing the error.

spacy.load("en_core_web_sm")

OSError                                   Traceback (most recent call last)
<ipython-input-2-c6e652d70518> in <module>
     1 # Load English tokenizer, tagger, parser and NER
----> 2 nlp = spacy.load("en_core_web_sm")

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/__init__.py in load(name, vocab, disable, exclude, config)
    50     """
    51     return util.load_model(
---> 52         name, vocab=vocab, disable=disable, exclude=exclude, config=config
    53     )
    54

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/util.py in load_model(name, vocab, disable, exclude, config)
   418             return get_lang_class(name.replace("blank:", ""))()
   419         if is_package(name):  # installed as package
--> 420             return load_model_from_package(name, **kwargs)  # type: ignore[arg-type]
   421         if Path(name).exists():  # path to model data directory
   422             return load_model_from_path(Path(name), **kwargs)  # type: ignore[arg-type]

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/util.py in load_model_from_package(name, vocab, disable, exclude, config)
   451     """
   452     cls = importlib.import_module(name)
--> 453     return cls.load(vocab=vocab, disable=disable, exclude=exclude, config=config)  # type: ignore[attr-defined]
   454
   455

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/en_core_web_sm/__init__.py in load(**overrides)
    10
    11 def load(**overrides):
---> 12     return load_model_from_init_py(__file__, **overrides)

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/util.py in load_model_from_init_py(init_file, vocab, disable, exclude, config)
   619         disable=disable,
   620         exclude=exclude,
--> 621         config=config,
   622     )
   623

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/util.py in load_model_from_path(model_path, meta, vocab, disable, exclude, config)
   485     config_path = model_path / "config.cfg"
   486     overrides = dict_to_dot(config)
--> 487     config = load_config(config_path, overrides=overrides)
   488     nlp = load_model_from_config(config, vocab=vocab, disable=disable, exclude=exclude)
   489     return nlp.from_disk(model_path, exclude=exclude, overrides=overrides)

/anaconda/envs/azureml_py36/lib/python3.6/site-packages/spacy/util.py in load_config(path, overrides, interpolate)
   644     else:
   645         if not config_path or not config_path.exists() or not config_path.is_file():
--> 646             raise IOError(Errors.E053.format(path=config_path, name="config.cfg"))
   647         return config.from_disk(
   648             config_path, overrides=overrides, interpolate=interpolate

OSError: [E053] Could not read config.cfg from /anaconda/envs/azureml_py36/lib/python3.6/site-packages/en_core_web_sm/en_core_web_sm-2.3.1/config.cfg

I installed the packages using the below three lines codes from Spacy

pip install -U pip setuptools wheel
pip install -U spacy
python -m spacy download en_core_web_sm

How should I fix this issue? thanks in advance.

Body:
Taking the path from your error message:

en_core_web_sm-2.3.1/config.cfg

You have a model for v2.3, but it's looking for a config.cfg, which is only a thing in v3 of spaCy. It looks like you upgraded spaCy without realizing it.

There are two ways to fix this. One is to reinstall the model with spacy download, which will get a version that matches your current spaCy version. If you are just starting something that is probably the best idea. Based on the release date of scrubadub, it seems to be intended for use with spaCy v3.

However, note that v2 and v3 are pretty different - if you have a project with v2 of spaCy you might want to downgrade instead.


问:
MySQL DATETIME - Change only the date
Starting with : 2011-01-17 09:30:00

Let's say I want to edit just the date with 2011-01-28

What is the most efficient way to end up with: 2011-01-28 09:30:00

Thanks!

For everyone saying Date_Add... that would require me to subtract the dates, then add the days.  Thats a possibility... but was looking to remove that first step, and just "replace" the date

答:
Just Use:</p>
```<code>UPDATE table_name set column_name= DATE_FORMAT(column_name,'%Y-%m-28 %H:%i-%s');
</code>```

ContentLicense: CC BY-SA 2.5

Title: MySQL DATETIME - Change only the date

Body:
Just Use:

UPDATE table_name set column_name= DATE_FORMAT(column_name,'%Y-%m-28 %H:%i-%s');


问:
How do I map state into a component as a prop?
Hey for some reason my questions aren't being rendered. I feel my issue may be with my QuizData.map but I can't tell what the issue is because I can console.log     console.log(quizData.map(item => item.question)) and get the results.

Any clue as to what may be causing this issue? Thank you!

Parent Component

```<code>export default function QuizData() {

const [quizData, setQuizData] = React.useState([{
    question: "",
    answers: "",
    correctAnswer: "",
    selectedAnswer: ""
}]);
React.useEffect(() => {
    fetch("https://opentdb.com/api.php?amount=5&category=12&difficulty=medium&type=multiple")
        .then(res => res.json())
        .then(data => setQuizData(data.results.map(item => ({
            question: item.question,
            answers: item.incorrect_answers.concat(item.correct_answer),
            correctAnswer: item.correct_answer
        }))))
},[])
return (
    <div>

        {quizData.map((item) => {
            <div>
                <Question
                    question={item.question}
                    answers={item.answer}
                    chosenAnswer={quizData.selectedAnswer}
                    updateAnswers={handleSelectedAnswer}
                />
            </div>
        })}
          <button
            onClick={() => {
                    checkSelectedAnswer();
                    scoreQuiz();
                    finishQuiz()
                    }
                }>
            Check answers
        </button>
  </div>
)}
</code>```

Child component

```<code>export default function Question(props) {

return (
    <div>

                    {props.question.map(item => <h3>item</h3>)}

                    {props.answers.map((item, index) => {
                        <div key={index}>
                            <input
                                type="radio"
                                name={`answer option-${item}`}
                                id={`answer-options-${index}`}
                                value={props.chosenAnswer}
                                onChange={props.updateAnswers}
                            />
                            <label htmlFor={`answer-options-${index}`}>{answerOption}</label>
                        </div>
                    })}

    </div>
)}
</code>```

答:
You should return the mapped element, as:

```<code>return (
    <div>
        {quizData.map((item) => {
           return <div>
                <Question
                    question={item.question}
                    answers={item.answer}
                    chosenAnswer={quizData.selectedAnswer}
                    updateAnswers={handleSelectedAnswer}
                />
            </div>
        })}
  </div>
)
</code>```

or

```<code>    return (
      <div>
          {quizData.map((item) => (<div>
                     <Question
                      question={item.question}
                      answers={item.answer}
                      chosenAnswer={quizData.selectedAnswer}
                      updateAnswers={handleSelectedAnswer}
                  />
              </div>
    ))}
    </div>
  )
</code>```

Update it in both the maps

Body:
Hey for some reason my questions aren't being rendered. I feel my issue may be with my QuizData.map but I can't tell what the issue is because I can console.log     console.log(quizData.map(item => item.question)) and get the results.

Any clue as to what may be causing this issue? Thank you!

Parent Component

export default function QuizData() {

const [quizData, setQuizData] = React.useState([{
    question: "",
    answers: "",
    correctAnswer: "",
    selectedAnswer: ""
}]);
React.useEffect(() => {
    fetch("https://opentdb.com/api.php?amount=5&category=12&difficulty=medium&type=multiple")
        .then(res => res.json())
        .then(data => setQuizData(data.results.map(item => ({
            question: item.question,
            answers: item.incorrect_answers.concat(item.correct_answer),
            correctAnswer: item.correct_answer
        }))))
},[])
return (

        {quizData.map((item) => {

                <Question
                    question={item.question}
                    answers={item.answer}
                    chosenAnswer={quizData.selectedAnswer}
                    updateAnswers={handleSelectedAnswer}
                />

        })}
          <button
            onClick={() => {
                    checkSelectedAnswer();
                    scoreQuiz();
                    finishQuiz()
                    }
                }>
            Check answers
        </button>

)}

Child component

export default function Question(props) {

return (

                    {props.question.map(item =>
item
)}

                    {props.answers.map((item, index) => {

                            <input
                                type="radio"
                                name={`answer option-${item}`}
                                id={`answer-options-${index}`}
                                value={props.chosenAnswer}
                                onChange={props.updateAnswers}
                            />
                            <label htmlFor={`answer-options-${index}`}>{answerOption}

                    })}

)}

Body:
You should return the mapped element, as:

return (
    <div>
        {quizData.map((item) => {
           return <div>
                <Question
                    question={item.question}
                    answers={item.answer}
                    chosenAnswer={quizData.selectedAnswer}
                    updateAnswers={handleSelectedAnswer}
                />
            </div>
        })}
  </div>
)

or

    return (
      <div>
          {quizData.map((item) => (<div>
                     <Question
                      question={item.question}
                      answers={item.answer}
                      chosenAnswer={quizData.selectedAnswer}
                      updateAnswers={handleSelectedAnswer}
                  />
              </div>
    ))}
    </div>
  )

Update it in both the maps


问:
Ionic react component is not getting imported
I am trying to import IonAccordion and IonAccordionGroup, but I'm facing error like
"Line 38:16:  'IonAccordionGroup' is not defined  react/jsx-no-undef".
And I'm using library type as react for ionic app development. And latest version of ionic and react.
Here I've attached the picture

Thank You

答:
This should be as simple as including the following lines at the top of your Menu.tsx file:

```<code>import React from 'react';
import { IonAccordionGroup } from '@ionic/react';
</code>```

Note that IonAccordion is a new component for Ionic React 6 and you will need to upgrade to version 6 if you are using an older version of Ionic React.

Body:
This should be as simple as including the following lines at the top of your Menu.tsx file:

import React from 'react';
import { IonAccordionGroup } from '@ionic/react';

Note that IonAccordion is a new component for Ionic React 6 and you will need to upgrade to version 6 if you are using an older version of Ionic React.


问:
Using glue_data() in a function works with some column names and not others
I'm working on a function that takes a dataframe and user-specified columns as inputs and uses glue_data() to output some nicely formatted text.

Whether or not a variable works seems to be the luck of the draw, but is consistent from attempt to attempt. e.g. with mtcars, mpg always works, and hp never does:

```<code>library(glue)
data <- head(mtcars)

print_messages <- function(x=NULL, att1=NULL, att2=NULL) {

  # This if-else seems to be the problem
  if(is.null(att1)) {
    att1_glue <- ""
  } else {
    att1_glue <- paste0("{", deparse(substitute(att1)),"}")
  }

  if(is.null(att2)) {
    att2_glue <- ""
  } else {
    att2_glue <- paste0("{", deparse(substitute(att2)),"}")
  }

  pattern <-   paste("", att1_glue,"", att2_glue)

  glue_data(x, pattern)

}

print_messages(data, att1=mpg, att2=NULL)

# 21
# 21
# 22.8
# 21.4
# 18.7
# 18.1

print_messages(data, att1=mpg, att2=hp)
#> Error in print_messages(data, att1 = mpg, att2 = hp): object 'hp' not found

</code>```

This is not a function of which variable goes in att1 vs att2

I have figured out that the if-else is the problem, but don't know how to fix it. It was inserted because I can't just have a null argument -- this makes glue_data() return a 0-character string:

```<code>print_messages <- function(x=NULL,att1=NULL, att2=NULL) {

  att1_glue <- paste0("{", deparse(substitute(att1)),"}")
  att2_glue <- paste0("{", deparse(substitute(att2)),"}")

  pattern <-   paste("",att1_glue,"", att2_glue)

  glue_data(x, pattern)

}

print_messages(data, att1=mpg, att2=hp )
# 21  110
# 21  110
# 22.8  93
# 21.4  110
# 18.7  175
# 18.1  105

print_messages(data, att1=hp, att2=NULL )

</code>```

I have tried other approaches to using the argument from the function in glue_data(), like from this answer. But the central issue seems to be with the if-else.

I'm wondering what's going on there? Even if there is a way to fix this on the glue side, I'd be interested in why the parsing works with some columns and not others!

Thank you for your help!

答:
Evaluation of non-existing objects will throw an error.

```<code>f <- function(x = NULL) if(is.null(x)) cat("hi") else cat("bye")
f(mpg) # error
f("mpg")
#> bye
f()
#> hi
</code>```

The first function should throw an error, do you perhaps have an object called mpg in your environment? In that case lexical scoping will find it, and yield is.null(mpg) as FALSE.

An alternative is to use dots ..., and using the vectorized nature of paste, avoiding the need for pre-filled arguments with NULL.

```<code>print_messages <- function(data, ...){
  expr = paste0("{",
                vapply(substitute(...()), deparse, "")
                , "}", collapse = " ")
  glue_data(data, expr)
}
</code>```

Body:
I'm working on a function that takes a dataframe and user-specified columns as inputs and uses glue_data() to output some nicely formatted text.

Whether or not a variable works seems to be the luck of the draw, but is consistent from attempt to attempt. e.g. with mtcars, mpg always works, and hp never does:

library(glue)
data <- head(mtcars)

print_messages <- function(x=NULL, att1=NULL, att2=NULL) {

  # This if-else seems to be the problem
  if(is.null(att1)) {
    att1_glue <- ""
  } else {
    att1_glue <- paste0("{", deparse(substitute(att1)),"}")
  }

  if(is.null(att2)) {
    att2_glue <- ""
  } else {
    att2_glue <- paste0("{", deparse(substitute(att2)),"}")
  }

  pattern <-   paste("", att1_glue,"", att2_glue)

  glue_data(x, pattern)

}

print_messages(data, att1=mpg, att2=NULL)

# 21
# 21
# 22.8
# 21.4
# 18.7
# 18.1

print_messages(data, att1=mpg, att2=hp)
#> Error in print_messages(data, att1 = mpg, att2 = hp): object 'hp' not found

This is not a function of which variable goes in att1 vs att2

I have figured out that the if-else is the problem, but don't know how to fix it. It was inserted because I can't just have a null argument -- this makes glue_data() return a 0-character string:

print_messages <- function(x=NULL,att1=NULL, att2=NULL) {

  att1_glue <- paste0("{", deparse(substitute(att1)),"}")
  att2_glue <- paste0("{", deparse(substitute(att2)),"}")

  pattern <-   paste("",att1_glue,"", att2_glue)

  glue_data(x, pattern)

}

print_messages(data, att1=mpg, att2=hp )
# 21  110
# 21  110
# 22.8  93
# 21.4  110
# 18.7  175
# 18.1  105

print_messages(data, att1=hp, att2=NULL )

I have tried other approaches to using the argument from the function in glue_data(), like from this answer. But the central issue seems to be with the if-else.

I'm wondering what's going on there? Even if there is a way to fix this on the glue side, I'd be interested in why the parsing works with some columns and not others!

Thank you for your help!

Body:
Evaluation of non-existing objects will throw an error.

f <- function(x = NULL) if(is.null(x)) cat("hi") else cat("bye")
f(mpg) # error
f("mpg")
#> bye
f()
#> hi

The first function should throw an error, do you perhaps have an object called mpg in your environment? In that case lexical scoping will find it, and yield is.null(mpg) as FALSE.

An alternative is to use dots ..., and using the vectorized nature of paste, avoiding the need for pre-filled arguments with NULL.

print_messages <- function(data, ...){
  expr = paste0("{",
                vapply(substitute(...()), deparse, "")
                , "}", collapse = " ")
  glue_data(data, expr)
}


问:
How Can I convert this raw sql query to laravel AR
I want to get the number of boys from the students table. This student table is connected to the users table with user_id and the users table is connected to the genders table with gender_id.

I have the raw query and it works. I only want a way to convert it to AR.

```<code>DB::select('SELECT COUNT(*) FROM users u, students s WHERE s.user_id = u.id AND u.gender_id = 2');
</code>```

Relations,

```<code>public function user()
{
    return $this->belongsTo(User::class, 'user_id');
}

public function gender(){
    return $this->belongsTo(Gender::class, 'gender_id');
}
</code>```

答:
If you have a relation between student and user models you can use this.</p>
```<code> Student::query()->whereHas('user', function ($q) {
        $q->where('gender_id', 2);
    })->count();
</code>```

Body:
I want to get the number of boys from the students table. This student table is connected to the users table with user_id and the users table is connected to the genders table with gender_id.

I have the raw query and it works. I only want a way to convert it to AR.

DB::select('SELECT COUNT(*) FROM users u, students s WHERE s.user_id = u.id AND u.gender_id = 2');

Relations,

public function user()
{
    return $this->belongsTo(User::class, 'user_id');
}

public function gender(){
    return $this->belongsTo(Gender::class, 'gender_id');
}

Body:
If you have a relation between student and user models you can use this.

 Student::query()->whereHas('user', function ($q) {
        $q->where('gender_id', 2);
    })->count();


问:
Static images are not rendering in production on pdf using wkhtmltopd in django application
I am using pdfkit to convert html into pdf. Everything seems to be working perfectly in development, but after building a docker image and running it locally, the pdf is generated but images are not loaded.

Here is my how I am rendering image, which seems to be working fine locally:

```<code><img src="{{ host_url }}/static/tcs.jpg" style="width:100px;display:block;" />
</code>```

Here's my code in django view function:

```<code>template = get_template("tcs_invoice.html")
data = {
  "host_url": settings.HOST
}
html = template.render(data)  # Renders the template with the context data.
pdf = pdfkit.from_string(html, False)
 return HttpResponse(pdf, content_type='application/pdf')
</code>```

I have installed wkhtmltopdf on my docker container. When I hit the url in the browser the image is shown. why does it not render in production mode.

答:
So after trying almost everything, even aws s3(privet bucket) none of them work !
The only way to pass the image with URL ; but we can't always do that in the case of confidential(in my case ) static images like signatures. solution?

```<code>If you are hosting it I mean env is Linux add this to settings.py:

STATIC_URL = '/static/'

STATIC_ROOT=(
os.path.join(BASE_DIR,'static')
)
STATICFILES_DIRS =[
     os.path.join(BASE_DIR, 'staticfiles'),
 ]
</code>```

1.Then your static files will be here ,0.0.0.0/static/img/....

2.You need to pass the image in html page through url only to be converted to PDF

3.From the backend get the domain and pass the url to page

```<code>from django.contrib.sites.shortcuts import get_current_site
current_domain = get_current_site(request).domain

template=get_template('template location like template/some.html')
                template_render=template.render({'value':yourquery,"current_domain":current_domain})

                options={
                'page-size': 'Letter',
                "enable-local-file-access": None,
                "disable-smart-shrinking": None,
                "zoom": "0.7",}
                pdf=pdfkit.from_string(template_render,False,options)
                response = HttpResponse(pdf,content_type='application/pdf')
                response['Content-Disposition'] = 'attachment;
                filename="ourcodeworld.pdf" '
                return HttpResponse(pdf, content_type='application/pdf')
</code>```

4.In this way you will be able to pass the domain cause it might change.
5.

```<code>change the static  :
<img src="{% static 'img/someimage.png' %}>
  to
<img src="http://{{current_domain}}/static/img/someimage.png">
</code>```

It works everywhere! even in EC2.
Upvotes are appreciated, Thank you!

Body:
I am using pdfkit to convert html into pdf. Everything seems to be working perfectly in development, but after building a docker image and running it locally, the pdf is generated but images are not loaded.

Here is my how I am rendering image, which seems to be working fine locally:

Here's my code in django view function:

template = get_template("tcs_invoice.html")
data = {
  "host_url": settings.HOST
}
html = template.render(data)  # Renders the template with the context data.
pdf = pdfkit.from_string(html, False)
 return HttpResponse(pdf, content_type='application/pdf')

I have installed wkhtmltopdf on my docker container. When I hit the url in the browser the image is shown. why does it not render in production mode.

Body:
So after trying almost everything, even aws s3(privet bucket) none of them work !
The only way to pass the image with URL ; but we can't always do that in the case of confidential(in my case ) static images like signatures. solution?

If you are hosting it I mean env is Linux add this to settings.py:

STATIC_URL = '/static/'

STATIC_ROOT=(
os.path.join(BASE_DIR,'static')
)
STATICFILES_DIRS =[
     os.path.join(BASE_DIR, 'staticfiles'),
 ]

1.Then your static files will be here ,0.0.0.0/static/img/....

2.You need to pass the image in html page through url only to be converted to PDF

3.From the backend get the domain and pass the url to page

from django.contrib.sites.shortcuts import get_current_site
current_domain = get_current_site(request).domain

template=get_template('template location like template/some.html')
                template_render=template.render({'value':yourquery,"current_domain":current_domain})

                options={
                'page-size': 'Letter',
                "enable-local-file-access": None,
                "disable-smart-shrinking": None,
                "zoom": "0.7",}
                pdf=pdfkit.from_string(template_render,False,options)
                response = HttpResponse(pdf,content_type='application/pdf')
                response['Content-Disposition'] = 'attachment;
                filename="ourcodeworld.pdf" '
                return HttpResponse(pdf, content_type='application/pdf')

4.In this way you will be able to pass the domain cause it might change.
5.

change the static  :
<img src="{% static 'img/someimage.png' %}>
  to
<img src="http://{{current_domain}}/static/img/someimage.png">

It works everywhere! even in EC2.
Upvotes are appreciated, Thank you!


问:
Function as template argument that has a different structure depending on method
I am writing a routine to find the numerical roots of a function in C++. Depending on the algorithm, I can supply either the function or both the function and derivative. For example, I have two separate routines

```<code>template <typename T, typename Func>
T Bisection(Func func, T x) {
  // algorithm details...

  auto f = func(x);

  // more details...
}

template <typename T, typename Func>
T Newton(Func func, T x) {
  // algorithm details...

  auto [f, df] = func(x);

  // more details...
}
</code>```

Note that one method assumes that the Func type will be a simple one-variable function, whereas the other assumes it is some structure that contains both the function 'f' and the derivative 'df'. Both of these routines seem to work for my tests so far.

I would like to write a master routine which accepts a parameter method, which selects either of these with a switch statement. What I have in mind is:

```<code>enum Method {
  Bisection, Newton
};

template <typename T, typename Func>
T find_root(Func func, T x, Method method) {
  switch(method) {
  case Bisection: return Bisection(func, x);
  case Newton: return Newton(func, x);
  default: // do other stuff...
  }
}
</code>```

This does not compile. If I write a routine with method = Bisection for example, I get error error: cannot decompose non-array non-class type 'const float' because the Newton method needs a different structure for the binding, even though I am not using it. Is there a generic way I can circumvent this to allow for a uniform master method? I have another method which the user supplies the function and first and second derivative, so that structure has three components.

答:
The problem is that in your case you are instantiating both functions for the types that doesn't fit the implementation. You may try if constexpr, but for this case you need to move the method parameter the template parameters:

enum class Method {
    Bisection, Newton
};

template <Method method, typename T, typename Func>
T find_root(Func func, T x) {
    if constexpr (method == Method::Bisection) {
        return Bisection(func, x);
    }
    else if constexpr (method == Method::Newton) {
        return Newton(func, x);
    }
    else {
    }
}
```

In this case the compiler will not instantiate the functions for the branches where expression is false (note that for the compiler to eliminate the false branches the expression needs to depend on the template parameters).

Body:
I am writing a routine to find the numerical roots of a function in C++. Depending on the algorithm, I can supply either the function or both the function and derivative. For example, I have two separate routines

template <typename T, typename Func>
T Bisection(Func func, T x) {
  // algorithm details...

  auto f = func(x);

  // more details...
}

template <typename T, typename Func>
T Newton(Func func, T x) {
  // algorithm details...

  auto [f, df] = func(x);

  // more details...
}

Note that one method assumes that the Func type will be a simple one-variable function, whereas the other assumes it is some structure that contains both the function 'f' and the derivative 'df'. Both of these routines seem to work for my tests so far.

I would like to write a master routine which accepts a parameter method, which selects either of these with a switch statement. What I have in mind is:

enum Method {
  Bisection, Newton
};

template <typename T, typename Func>
T find_root(Func func, T x, Method method) {
  switch(method) {
  case Bisection: return Bisection(func, x);
  case Newton: return Newton(func, x);
  default: // do other stuff...
  }
}

This does not compile. If I write a routine with method = Bisection for example, I get error error: cannot decompose non-array non-class type 'const float' because the Newton method needs a different structure for the binding, even though I am not using it. Is there a generic way I can circumvent this to allow for a uniform master method? I have another method which the user supplies the function and first and second derivative, so that structure has three components.

Body:
The problem is that in your case you are instantiating both functions for the types that doesn't fit the implementation. You may try if constexpr, but for this case you need to move the method parameter the template parameters:

enum class Method {
    Bisection, Newton
};

template <Method method, typename T, typename Func>
T find_root(Func func, T x) {
    if constexpr (method == Method::Bisection) {
        return Bisection(func, x);
    }
    else if constexpr (method == Method::Newton) {
        return Newton(func, x);
    }
    else {
    }
}

In this case the compiler will not instantiate the functions for the branches where expression is false (note that for the compiler to eliminate the false branches the expression needs to depend on the template parameters).


问:
iphone-How to change the tokenid in URL
In login session one Token id was generated, So i need to replace same token id in next screen URL. how we can do that.

Here is clear explanation:
login session token id generated

```<code><USER USER_NAME="newadmin01" **TOKEN_ID="0.14002050365183227"** FULL_NAME="newadmin01, newadmin01"/>
</code>```

for next url i need replace login session token id, (0.22341921751959004 replace to "0.14002050365183227)

http://localhost/questionnaire/QuestionnaireList?username=newadmin01&token=0.22341921751959004&levelid=4519
Thanks in advance

答:
If you want to change your URL from

http://localhost/questionnaire/QuestionnaireList?username=newadmin01&token=0.22341921751959004&levelid=4519

to

http://localhost/questionnaire/QuestionnaireList?username=newadmin01&token="0.14002050365183227&levelid=4519

you can use the method below to split the string and then rebuild it.

```<code>NSArray *string = [stringtoreplace componentsJoinedByString: @"="];
</code>```

That will return an array of strings.

You can then replace the one you want in the array and rebuild it using the stringappend method.

Or easier you can just use stringByReplacingOccurancesOfString to replace whatever you want replacing.

here's the document http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

ContentLicense: CC BY-SA 3.0

Title: iphone-How to change the tokenid in URL

Body:
In login session one Token id was generated, So i need to replace same token id in next screen URL. how we can do that.

Here is clear explanation:
login session token id generated

<USER USER_NAME="newadmin01" **TOKEN_ID="0.14002050365183227"** FULL_NAME="newadmin01, newadmin01"/>

for next url i need replace login session token id, (0.22341921751959004 replace to "0.14002050365183227)

http://localhost/questionnaire/QuestionnaireList?username=newadmin01&token=0.22341921751959004&levelid=4519
Thanks in advance

Body:
If you want to change your URL from

http://localhost/questionnaire/QuestionnaireList?username=newadmin01&token=0.22341921751959004&levelid=4519

to

http://localhost/questionnaire/QuestionnaireList?username=newadmin01&token="0.14002050365183227&levelid=4519

you can use the method below to split the string and then rebuild it.

NSArray *string = [stringtoreplace componentsJoinedByString: @"="];

That will return an array of strings.

You can then replace the one you want in the array and rebuild it using the stringappend method.

Or easier you can just use stringByReplacingOccurancesOfString to replace whatever you want replacing.

here's the document http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html


问:
Android Studio BumbleBee, Maven()
I updated the Android Studio and Created a new project.
I'm using some dependencies from GitHub, but after sync now, I'm getting this warning. If I ignore it, the application won't get installed.

Project Level build.gradle

```<code>buildscript {
    ext {
        compose_version = '1.6.10'
    }
    dependencies {
        classpath 'com.google.gms:google-services:4.3.10'
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10'
    }
}

plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.5.31' apply false
}

allprojects {
    repositories {
        google()
        maven { url 'https://jitpack.io' }
        maven {
            url "https://maven.google.com"
        }
//        mavenCentral()
        maven { url 'https://github.com/leonardocardoso/mvn-repo/raw/master/maven-deploy' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

App Level build.gradle

```<code>plugins {
    id 'com.android.application'
}

android {
    compileSdk 31

    buildFeatures {
        dataBinding true
    }

    defaultConfig {
        applicationId "com.eg.eg"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$compose_version"
    implementation 'com.github.scottyab:showhidepasswordedittext:0.8'

}
</code>```

settings.gradle

```<code>import org.gradle.api.initialization.resolve.RepositoriesMode

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()

    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
    repositories {
        google()
        mavenCentral()

    }
}
rootProject.name = "MyPro_v02"
include ':app'

</code>```

How To Resolve this issue in Android Studio latest version BumbleBee?

答:
For newer Android Studio projects created in Android Studio Bumblebee | 2021.1.1 or newer, the JitPack repository needs to be added into the root level file settings.gradle instead of build.gradle:

```<code>dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
      // ...
        maven { url 'https://jitpack.io' }
    }
}
</code>```

Title: Android Studio BumbleBee, Maven()

Body:
I updated the Android Studio and Created a new project.
I'm using some dependencies from GitHub, but after sync now, I'm getting this warning. If I ignore it, the application won't get installed.

Project Level build.gradle

buildscript {
    ext {
        compose_version = '1.6.10'
    }
    dependencies {
        classpath 'com.google.gms:google-services:4.3.10'
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10'
    }
}

plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.5.31' apply false
}

allprojects {
    repositories {
        google()
        maven { url 'https://jitpack.io' }
        maven {
            url "https://maven.google.com"
        }
//        mavenCentral()
        maven { url 'https://github.com/leonardocardoso/mvn-repo/raw/master/maven-deploy' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App Level build.gradle

plugins {
    id 'com.android.application'
}

android {
    compileSdk 31

    buildFeatures {
        dataBinding true
    }

    defaultConfig {
        applicationId "com.eg.eg"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$compose_version"
    implementation 'com.github.scottyab:showhidepasswordedittext:0.8'

}

settings.gradle

import org.gradle.api.initialization.resolve.RepositoriesMode

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()

    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
    repositories {
        google()
        mavenCentral()

    }
}
rootProject.name = "MyPro_v02"
include ':app'

How To Resolve this issue in Android Studio latest version BumbleBee?

Body:
For newer Android Studio projects created in Android Studio Bumblebee | 2021.1.1 or newer, the JitPack repository needs to be added into the root level file settings.gradle instead of build.gradle:

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
      // ...
        maven { url 'https://jitpack.io' }
    }
}


答:
Use filter with list. Also note that you should not use str as a variable or a function because it's already a symbol/function in Python, it may cause some weird bugs.

```<code>def str_to_list(string):
    new = list(string)
    for i in new:
        if i.isdigit() and int(i) > 5:
            new.remove(i)

    # This will remove all whitespaces from your list.
    return list(filter(str.strip, new))

print(str_to_list("6 dollars"))
# Output: ['d', 'o', 'l', 'l', 'a', 'r', 's']
</code>```

Hope it helped :)

Title: why am I not able to compare a space in string after splitting to a space?

Body:
def str_to_list(str):
    # Insert your code here
    new = list(str)
    for i in new:
        if i ==  or (i.isdigit() and int(i) > 5):
            new.remove(i)
    return new

I expect out to be ['d', 'o', 'l', 'l', 'a', 'r']

But I get [' ', 'd', 'o', 'l', 'l', 'a', 'r']

Body:
Use filter with list. Also note that you should not use str as a variable or a function because it's already a symbol/function in Python, it may cause some weird bugs.

def str_to_list(string):
    new = list(string)
    for i in new:
        if i.isdigit() and int(i) > 5:
            new.remove(i)

    # This will remove all whitespaces from your list.
    return list(filter(str.strip, new))

print(str_to_list("6 dollars"))
# Output: ['d', 'o', 'l', 'l', 'a', 'r', 's']

Hope it helped :)


问:
Getting AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1 with no other stack trace
When using Retrofit and Coroutines to fetch data from an API I sometimes get an app crash with no stacktrace in Logcat except this: AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1

答:
This is usually caused by Retrofit throwing a common exception like UnknownHostException (if there's no Internet) and coroutines swallowing the exception if you didn't specify a CoroutineExceptionHandler.

So add a coroutine exception handler in your launch code, something like this:

```<code>val coroutineExceptionHandler = CoroutineExceptionHandler{_, throwable ->
    throwable.printStackTrace()
}

fun getFromApi() {
    viewModelScope.launch(Dispatchers.IO + coroutineExceptionHandler) {
        retrofitService.getStuffFromInternet()
    }
}
</code>```

Note this just logs the error to Logcat so you can see the missing stacktrace. You still need to figure out what's causing it.

Body:
This is usually caused by Retrofit throwing a common exception like UnknownHostException (if there's no Internet) and coroutines swallowing the exception if you didn't specify a CoroutineExceptionHandler.

So add a coroutine exception handler in your launch code, something like this:

val coroutineExceptionHandler = CoroutineExceptionHandler{_, throwable ->
    throwable.printStackTrace()
}

fun getFromApi() {
    viewModelScope.launch(Dispatchers.IO + coroutineExceptionHandler) {
        retrofitService.getStuffFromInternet()
    }
}

Note this just logs the error to Logcat so you can see the missing stacktrace. You still need to figure out what's causing it.


问:
Json deserialization data modification on the fly
Let's say that I have a semi-complex json model like this:

```<code>      "Person": {
        "Name": "John",
        "LastName": "Doe",
        "Birth":{
          "Day": 3,
          "Month": 3,
          "Year": 1989
        },
        "Physical":{
          "General": {
            "Height": 176.0, // cm
            "Weigth": 70000.0 // gr
          },
          "Arm":{
            "Length": 82.0, // cm
            "HandLength": 18.0, // cm
            "HandWeight": 312.0 // gr
          },
          "Leg": {
            "Length": 89.0, // cm
            "FootLength": 25.0, // cm
            "FootWeight": 486.0 // gr
          }
        }
      },
     "Person": {........}
</code>```

And I'm using a model like:

```<code>public class PersonModel
{
    public class Birth
    {
        [JsonPropertyName("Day")]
        public int Day { get; set; }

        [JsonPropertyName("Month")]
        public int Month { get; set; }

        [JsonPropertyName("Year")]
        public int Year { get; set; }
    }

    public class General
    {
        [JsonPropertyName("Height")]
        public double Height { get; set; }

        [JsonPropertyName("Weigth")]
        public double Weigth { get; set; }
    }

    public class Arm
    {
        [JsonPropertyName("Length")]
        public double Length { get; set; }

        [JsonPropertyName("HandLength")]
        public double HandLength { get; set; }

        [JsonPropertyName("HandWeight")]
        public double HandWeight { get; set; }
    }

    public class Leg
    {
        [JsonPropertyName("Length")]
        public double Length { get; set; }

        [JsonPropertyName("FootLength")]
        public double FootLength { get; set; }

        [JsonPropertyName("FootWeight")]
        public double FootWeight { get; set; }
    }

    public class Physical
    {
        [JsonPropertyName("General")]
        public General General { get; set; }

        [JsonPropertyName("Arm")]
        public Arm Arm { get; set; }

        [JsonPropertyName("Leg")]
        public Leg Leg { get; set; }
    }

    public class Person
    {
        [JsonPropertyName("Name")]
        public string Name { get; set; }

        [JsonPropertyName("LastName")]
        public string LastName { get; set; }

        [JsonPropertyName("Birth")]
        public Birth Birth { get; set; }

        [JsonPropertyName("Physical")]
        public Physical Physical { get; set; }
    }

    public class Root
    {
        [JsonPropertyName("Person")]
        public Person Person { get; set; }
    }
}
</code>```

And let's say I have a controller method like:

```<code>[HttpGet]
public async Task<ActionResult<IEnumerable<PersonModel.Root>>> GetPeople(SomeRequestModel people, [FromQuery] LengthUnit length = LengthUnit.cm, [FromQuery] WeightUnit weight = WeightUnit.gr, CancellationToken token = default)
{
    // Generate the data in 'rawJson' variable
    var result = JsonSerializer.Deserialize<IEnumerable<PersonModel.Root>>(rawJson);
    // Here, based on 'length' and 'weight' parameters, I need to convert units
    return result;
}

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum LengthUnit
{
    cm,
    foot
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum WeightUnit
{
    gr,
    pound
}
</code>```

Based on controller parameters, I need to convert values. For example, if the request is like /GetPeople?length=foot

I need to return;

```<code>      "Person": {
        "Name": "John",
        "LastName": "Doe",
        "Birth":{
          "Day": 3,
          "Month": 3,
          "Year": 1989
        },
        "Physical":{
          "General": {
            "Height": 5.77428, // feet
            "Weigth": 70000.0 // gr
          },
          "Arm":{
            "Length": 2.69029, // feet
            "HandLength": 0.590551, // feet
            "HandWeight": 312.0 // gr
          },
          "Leg": {
            "Length": 2.91995, // feet
            "FootLength": 0.82021, // feet
            "FootWeight": 486.0 // gr
          }
        }
      },
     "Person": {........}
</code>```

I understand that I can easily accomplish this by writing if-else statements after deserialization and modifying properties directly. On the other hand, I don't like the idea of doing this inside of my controller nor having a bulky helper method that I call after deserialization, referencing my deserialize object.

Just curious is there a good and clean way to accomplish this? I don't mind using Newtonsoft.Json or System.Text.Json.

答:
I would just to put this to getters/setters

```<code>public static convert=true;

public class General
    {
       private double _height;

        [JsonPropertyName("Height")]
        public double Height {
         get { return  convert? SmToFeet(_height) : _height ; }
         set  { _height=value; }
       }

        [JsonPropertyName("Weigth")]
        public double Weigth { get; set; }
    }

private double SmToFeet( double num)
{
    return num/30.5;
}
</code>```

the same for another properties. Or you can make convert in set if you are sure that you don' t need metric.

Body:
Let's say that I have a semi-complex json model like this:

      "Person": {
        "Name": "John",
        "LastName": "Doe",
        "Birth":{
          "Day": 3,
          "Month": 3,
          "Year": 1989
        },
        "Physical":{
          "General": {
            "Height": 176.0, // cm
            "Weigth": 70000.0 // gr
          },
          "Arm":{
            "Length": 82.0, // cm
            "HandLength": 18.0, // cm
            "HandWeight": 312.0 // gr
          },
          "Leg": {
            "Length": 89.0, // cm
            "FootLength": 25.0, // cm
            "FootWeight": 486.0 // gr
          }
        }
      },
     "Person": {........}

And I'm using a model like:

public class PersonModel
{
    public class Birth
    {
        [JsonPropertyName("Day")]
        public int Day { get; set; }

        [JsonPropertyName("Month")]
        public int Month { get; set; }

        [JsonPropertyName("Year")]
        public int Year { get; set; }
    }

    public class General
    {
        [JsonPropertyName("Height")]
        public double Height { get; set; }

        [JsonPropertyName("Weigth")]
        public double Weigth { get; set; }
    }

    public class Arm
    {
        [JsonPropertyName("Length")]
        public double Length { get; set; }

        [JsonPropertyName("HandLength")]
        public double HandLength { get; set; }

        [JsonPropertyName("HandWeight")]
        public double HandWeight { get; set; }
    }

    public class Leg
    {
        [JsonPropertyName("Length")]
        public double Length { get; set; }

        [JsonPropertyName("FootLength")]
        public double FootLength { get; set; }

        [JsonPropertyName("FootWeight")]
        public double FootWeight { get; set; }
    }

    public class Physical
    {
        [JsonPropertyName("General")]
        public General General { get; set; }

        [JsonPropertyName("Arm")]
        public Arm Arm { get; set; }

        [JsonPropertyName("Leg")]
        public Leg Leg { get; set; }
    }

    public class Person
    {
        [JsonPropertyName("Name")]
        public string Name { get; set; }

        [JsonPropertyName("LastName")]
        public string LastName { get; set; }

        [JsonPropertyName("Birth")]
        public Birth Birth { get; set; }

        [JsonPropertyName("Physical")]
        public Physical Physical { get; set; }
    }

    public class Root
    {
        [JsonPropertyName("Person")]
        public Person Person { get; set; }
    }
}

And let's say I have a controller method like:

[HttpGet]
public async Task<ActionResult<IEnumerable<PersonModel.Root>>> GetPeople(SomeRequestModel people, [FromQuery] LengthUnit length = LengthUnit.cm, [FromQuery] WeightUnit weight = WeightUnit.gr, CancellationToken token = default)
{
    // Generate the data in 'rawJson' variable
    var result = JsonSerializer.Deserialize<IEnumerable<PersonModel.Root>>(rawJson);
    // Here, based on 'length' and 'weight' parameters, I need to convert units
    return result;
}

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum LengthUnit
{
    cm,
    foot
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum WeightUnit
{
    gr,
    pound
}

Based on controller parameters, I need to convert values. For example, if the request is like /GetPeople?length=foot

I need to return;

      "Person": {
        "Name": "John",
        "LastName": "Doe",
        "Birth":{
          "Day": 3,
          "Month": 3,
          "Year": 1989
        },
        "Physical":{
          "General": {
            "Height": 5.77428, // feet
            "Weigth": 70000.0 // gr
          },
          "Arm":{
            "Length": 2.69029, // feet
            "HandLength": 0.590551, // feet
            "HandWeight": 312.0 // gr
          },
          "Leg": {
            "Length": 2.91995, // feet
            "FootLength": 0.82021, // feet
            "FootWeight": 486.0 // gr
          }
        }
      },
     "Person": {........}

I understand that I can easily accomplish this by writing if-else statements after deserialization and modifying properties directly. On the other hand, I don't like the idea of doing this inside of my controller nor having a bulky helper method that I call after deserialization, referencing my deserialize object.

Just curious is there a good and clean way to accomplish this? I don't mind using Newtonsoft.Json or System.Text.Json.

Body:
I would just to put this to getters/setters

public static convert=true;

public class General
    {
       private double _height;

        [JsonPropertyName("Height")]
        public double Height {
         get { return  convert? SmToFeet(_height) : _height ; }
         set  { _height=value; }
       }

        [JsonPropertyName("Weigth")]
        public double Weigth { get; set; }
    }

private double SmToFeet( double num)
{
    return num/30.5;
}

the same for another properties. Or you can make convert in set if you are sure that you don' t need metric.


问:
How to find the most frequent letters and the number of occurrences, using Stream API?
I have List with single letters inside. I need to count all duplicates and find the most frequent duplicate. The list generates randomly, so it may contain several most frequent letters.

Is it possible to create only one map inside one Stream or put the second map inside Stream? I need only one Stream chain, using the method groupingBy().

```<code>public static void mostFrequentlyDuplicateLetters(List<String> letters) {
     Map<String, Long> collect = letterList
            .stream()
            .collect(Collectors.groupingBy(String::valueOf, Collectors.counting()))
            .entrySet()
            .stream()
            .filter(// How to find the most frequent letters and put them on a map?))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        }
</code>```

答:
it may contain several most frequent letters

The solution below allows to determine all the letters from the given list that have a maximum frequency.

```<code>    public static void main(String[] args) {
        Map<String, Long> frequencies = getFrequencyMap(List.of("A", "B", "B", "C", "C", "C", "B", "D"));
        long max = getMaxFrequency(frequencies);
        System.out.println("max = " + max);
        System.out.println(mostFrequentlyDuplicateLetters(frequencies, max));
    }
</code>```
```<code>    public static Map<String, Long> getFrequencyMap(List<String> letters) {
        return letters.stream()
                .collect(Collectors.groupingBy(UnaryOperator.identity(), Collectors.counting()));
    }
</code>```
```<code>    public static long getMaxFrequency(Map<String, Long> frequencies) {
        return frequencies.values().stream()
                .mapToLong(Long::longValue)
                .max()
                .orElse(0);
    }
</code>```
```<code>    public static List<String> mostFrequentlyDuplicateLetters(Map<String, Long> frequencies,
                                                              long frequency) {
        return frequencies.entrySet().stream()
                .filter(entry -> entry.getValue() == frequency)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }
</code>```

output (both letters B and C have frequency = 3)

```<code>max = 3
[B, C]
</code>```

Is it possible to create only one map inside one Stream

If you want your code to be both efficient and clean the answer is NO. By trying to fuse more than one concern in one method you'll violate the first of the SOLID principles - The single responsibility principle.

Body:
I have List with single letters inside. I need to count all duplicates and find the most frequent duplicate. The list generates randomly, so it may contain several most frequent letters.

Is it possible to create only one map inside one Stream or put the second map inside Stream? I need only one Stream chain, using the method groupingBy().

public static void mostFrequentlyDuplicateLetters(List<String> letters) {
     Map<String, Long> collect = letterList
            .stream()
            .collect(Collectors.groupingBy(String::valueOf, Collectors.counting()))
            .entrySet()
            .stream()
            .filter(// How to find the most frequent letters and put them on a map?))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        }

Body:
it may contain several most frequent letters

The solution below allows to determine all the letters from the given list that have a maximum frequency.

    public static void main(String[] args) {
        Map<String, Long> frequencies = getFrequencyMap(List.of("A", "B", "B", "C", "C", "C", "B", "D"));
        long max = getMaxFrequency(frequencies);
        System.out.println("max = " + max);
        System.out.println(mostFrequentlyDuplicateLetters(frequencies, max));
    }

    public static Map<String, Long> getFrequencyMap(List<String> letters) {
        return letters.stream()
                .collect(Collectors.groupingBy(UnaryOperator.identity(), Collectors.counting()));
    }

    public static long getMaxFrequency(Map<String, Long> frequencies) {
        return frequencies.values().stream()
                .mapToLong(Long::longValue)
                .max()
                .orElse(0);
    }

    public static List<String> mostFrequentlyDuplicateLetters(Map<String, Long> frequencies,
                                                              long frequency) {
        return frequencies.entrySet().stream()
                .filter(entry -> entry.getValue() == frequency)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }

output (both letters B and C have frequency = 3)

max = 3
[B, C]

Is it possible to create only one map inside one Stream

If you want your code to be both efficient and clean the answer is NO. By trying to fuse more than one concern in one method you'll violate the first of the SOLID principles - The single responsibility principle.


问:
How to find Hue value of an Image and use it to apply on other images of similar kind?
I'm trying to replace color of an object in an image. Suppose if I want to replace the color in the below image object  to the color in the below image object

I change this color using CAD tool, I want to achieve this using python code
I'm replacing HUE color of an Image as below code

```<code>import cv2
import numpy as np

# read image
img = cv2.imread(r"C:\Research\Replace_colors\Bright\Test\b2\img_1_2_pid_13_group_18_P50_A174.png")

# convert img to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h = hsv[:,:,0]
s = hsv[:,:,1]
v = hsv[:,:,2]

# shift the hue
# cv2 will clip automatically to avoid color wrap-around
huechange = 10   # 0 is no change; 0<=huechange<=180
hnew = cv2.add(h, huechange)

# combine new hue with s and v
hsvnew = cv2.merge([hnew,s,v])

# convert from HSV to BGR
result = cv2.cvtColor(hsvnew, cv2.COLOR_HSV2BGR)

# save result
cv2.imwrite('result.png', result)
</code>```

I was able to get color close to my required color but not exact color as I wanted

How can I change HUE value so I can replace color exactly ??

Any help or suggestion on this will be very helpful

答:
Are you sure you are using the right value for huechange and you don't need to change the value channel? When I use a color picker on the large flat part to the top right I get the following HSV values:

Original: (51, 100%, 56.1%)

Modified: (70, 100%, 56.1%)

Desired: (60, 100%, 28.2%)

Body:
I'm trying to replace color of an object in an image. Suppose if I want to replace the color in the below image object  to the color in the below image object

I change this color using CAD tool, I want to achieve this using python code
I'm replacing HUE color of an Image as below code

import cv2
import numpy as np

# read image
img = cv2.imread(r"C:\Research\Replace_colors\Bright\Test\b2\img_1_2_pid_13_group_18_P50_A174.png")

# convert img to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h = hsv[:,:,0]
s = hsv[:,:,1]
v = hsv[:,:,2]

# shift the hue
# cv2 will clip automatically to avoid color wrap-around
huechange = 10   # 0 is no change; 0<=huechange<=180
hnew = cv2.add(h, huechange)

# combine new hue with s and v
hsvnew = cv2.merge([hnew,s,v])

# convert from HSV to BGR
result = cv2.cvtColor(hsvnew, cv2.COLOR_HSV2BGR)

# save result
cv2.imwrite('result.png', result)

I was able to get color close to my required color but not exact color as I wanted

How can I change HUE value so I can replace color exactly ??

Any help or suggestion on this will be very helpful


问:
How to call a Swift function with a callback from C
I am trying to write an iOS plugin for Unity, which requires the use of a bridge with a C layer.

The plugin itself is written in Swift.

Currently my implementation works like so:

// Swift

```<code>@objc public class SomeClass  {

    @objc public func SomeFunction() -> String {
        return "Hello"
    }

}
</code>```

// C

```<code>extern "C" {

    void _someFunction() {
        // I can access the Swift file using "[SomeClass shared]"
        // This returns the "Hello" string correctly
        NSString *helloMessage = [[SomeClass shared] SomeFunction];
    }

}
</code>```

This works, but now I need to make an async call which requires a callback from the Swift implementation.

// Swift

```<code>@objc public class SomeClass  {

    @objc public func SomeFunction(completionHandler: (String) -> Void) {
        // Gets called after some async operations
        completionHandler(“hello”)
    }

}
</code>```

Is it possible to call this Swift function from the C layer and how would you do so?

// C

```<code>extern "C" {

    void _someFunction() {
        // ??????
    }

}
</code>```

答:
If you set up bridging well then the call should be like

```<code>void _someFunction() {
    [[SomeClass shared] SomeFunctionWithCompletionHandler:^(NSString * _Nonnull value) {
        NSLog(@"Result: %@", value);
    }];
}
</code>```

Btw, classes to be visible in Objective-C should be 'is-a' NSObject, like

```<code>@objcMembers public class SomeClass: NSObject  {

    public static var shared = SomeClass()

    public func SomeFunction() -> String {
        return "Hello"
    }

    public func SomeFunction(completionHandler: (String) -> Void) {
        // Gets called after some async operations
        completionHandler("hello")
    }

}
</code>```

Tested with Xcode 13.2 / iOS 15.2

Body:
I am trying to write an iOS plugin for Unity, which requires the use of a bridge with a C layer.

The plugin itself is written in Swift.

Currently my implementation works like so:

// Swift

@objc public class SomeClass  {

    @objc public func SomeFunction() -> String {
        return "Hello"
    }

}

// C

extern "C" {

    void _someFunction() {
        // I can access the Swift file using "[SomeClass shared]"
        // This returns the "Hello" string correctly
        NSString *helloMessage = [[SomeClass shared] SomeFunction];
    }

}

This works, but now I need to make an async call which requires a callback from the Swift implementation.

// Swift

@objc public class SomeClass  {

    @objc public func SomeFunction(completionHandler: (String) -> Void) {
        // Gets called after some async operations
        completionHandler(“hello”)
    }

}

Is it possible to call this Swift function from the C layer and how would you do so?

// C

extern "C" {

    void _someFunction() {
        // ??????
    }

}

Body:
If you set up bridging well then the call should be like

void _someFunction() {
    [[SomeClass shared] SomeFunctionWithCompletionHandler:^(NSString * _Nonnull value) {
        NSLog(@"Result: %@", value);
    }];
}

Btw, classes to be visible in Objective-C should be 'is-a' NSObject, like

@objcMembers public class SomeClass: NSObject  {

    public static var shared = SomeClass()

    public func SomeFunction() -> String {
        return "Hello"
    }

    public func SomeFunction(completionHandler: (String) -> Void) {
        // Gets called after some async operations
        completionHandler("hello")
    }

}

Tested with Xcode 13.2 / iOS 15.2


问:
How to find the square root of perfect square?
I'm working on this simple task implementing this function trying to find the square root of a perfect square in Scala, and then I'm testing it with this simple test method. What is it that I'm doing wrong?</p>

```<code>def squareRootOfPerfectSquare(a: Int): Option[Int] =
  if (scala.math.sqrt(a) % 1 == 0)
    scala.math.sqrt(a)
  else
    -1
</code>```

答:
```<code>def squareRootOfPerfectSquare(a: Int): Option[Int] = {
val sqrt = math.sqrt(a)
if (math.sqrt(a).ceil == math.sqrt(a))
   Some(sqrt.toInt)
else
   None
 }
</code>```

Body:
I'm working on this simple task implementing this function trying to find the square root of a perfect square in Scala, and then I'm testing it with this simple test method. What is it that I'm doing wrong?

def squareRootOfPerfectSquare(a: Int): Option[Int] =
  if (scala.math.sqrt(a) % 1 == 0)
    scala.math.sqrt(a)
  else
    -1


问:
ujson behaving weirdly during the installation of spacy_readability
I've had difficulty installing spacy_readability which seems to be caused by an old version of ujson. So I have installed the latest version of ujson:

```<code>!pip install --upgrade ujson --user
Requirement already satisfied: ujson in c:\users\desktop pc\appdata\roaming\python\python38\site-packages (1.35)
Collecting ujson
  Using cached ujson-5.1.0-cp38-cp38-win_amd64.whl (36 kB)
Installing collected packages: ujson
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
syllapy 0.7.1 requires ujson<2.0,>=1.35, but you have ujson 5.1.0 which is incompatible.
  Attempting uninstall: ujson
    Found existing installation: ujson 1.35
    Uninstalling ujson-1.35:
      Successfully uninstalled ujson-1.35
Successfully installed ujson-5.1.0
</code>```

I don't think the error is relevant because, I am not using syllapy, but perhaps i am mistaken. Then i have attempted spacey_readability

```<code>!pip install spacy_readability --user

Requirement already satisfied: spacy_readability in c:\users\desktop pc\appdata\roaming\python\python38\site-packages (1.4.1)
Requirement already satisfied: syllapy<1,>=0 in c:\users\desktop pc\appdata\roaming\python\python38\site-packages (from spacy_readability) (0.7.1)
Requirement already satisfied: spacy<3.0,>=2.0 in c:\programdata\anaconda3\lib\site-packages (from spacy_readability) (2.2.3)
Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (1.0.6)
Requirement already satisfied: preshed<3.1.0,>=3.0.2 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (3.0.6)
Requirement already satisfied: cymem<2.1.0,>=2.0.2 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (2.0.6)
Requirement already satisfied: blis<0.5.0,>=0.4.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (0.4.1)
Requirement already satisfied: srsly<1.1.0,>=0.1.0 in c:\users\desktop pc\appdata\roaming\python\python38\site-packages (from spacy<3.0,>=2.0->spacy_readability) (1.0.5)
Requirement already satisfied: setuptools in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (52.0.0.post20210125)
Requirement already satisfied: requests<3.0.0,>=2.13.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (2.25.1)
Requirement already satisfied: numpy>=1.15.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (1.20.1)
Requirement already satisfied: thinc<7.4.0,>=7.3.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (7.3.1)
Requirement already satisfied: catalogue<1.1.0,>=0.0.7 in c:\users\desktop pc\appdata\roaming\python\python38\site-packages (from spacy<3.0,>=2.0->spacy_readability) (1.0.0)
Requirement already satisfied: wasabi<1.1.0,>=0.4.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (0.9.0)
Requirement already satisfied: plac<1.2.0,>=0.9.6 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (1.1.3)
Requirement already satisfied: idna<3,>=2.5 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.0,>=2.0->spacy_readability) (2.10)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.0,>=2.0->spacy_readability) (1.26.4)
Requirement already satisfied: certifi>=2017.4.17 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.0,>=2.0->spacy_readability) (2020.12.5)
Requirement already satisfied: chardet<5,>=3.0.2 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.0,>=2.0->spacy_readability) (4.0.0)
Collecting ujson<2.0,>=1.35
  Using cached ujson-1.35-cp38-cp38-win_amd64.whl
Requirement already satisfied: tqdm<5.0.0,>=4.10.0 in c:\programdata\anaconda3\lib\site-packages (from thinc<7.4.0,>=7.3.0->spacy<3.0,>=2.0->spacy_readability) (4.59.0)
Installing collected packages: ujson
  Attempting uninstall: ujson
    Found existing installation: ujson 5.1.0
    Uninstalling ujson-5.1.0:
      Successfully uninstalled ujson-5.1.0
Successfully installed ujson-1.35
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
python-language-server 0.36.2 requires ujson>=3.0.0; python_version > "3", but you have ujson 1.35 which is incompatible.
python-jsonrpc-server 0.4.0 requires ujson>=3.0.0, but you have ujson 1.35 which is incompatible.
</code>```

I find this output very confusing. It seems to be detecting ujson 1.35 then replacing the more recent version of it with this, noticing that it is not recent enough and then causing an error. How do I avoid this?

答:
You can make pip not check dependencies using pip install --no-deps [whatever].

Note that spaCy readability has not been updated since 2019, so you might be better off reimplementing things yourself.

https://github.com/mholtzscher/spacy_readability

Body:
I've had difficulty installing spacy_readability which seems to be caused by an old version of ujson. So I have installed the latest version of ujson:

!pip install --upgrade ujson --user
Requirement already satisfied: ujson in c:\users\desktop pc\appdata\roaming\python\python38\site-packages (1.35)
Collecting ujson
  Using cached ujson-5.1.0-cp38-cp38-win_amd64.whl (36 kB)
Installing collected packages: ujson
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
syllapy 0.7.1 requires ujson<2.0,>=1.35, but you have ujson 5.1.0 which is incompatible.
  Attempting uninstall: ujson
    Found existing installation: ujson 1.35
    Uninstalling ujson-1.35:
      Successfully uninstalled ujson-1.35
Successfully installed ujson-5.1.0

I don't think the error is relevant because, I am not using syllapy, but perhaps i am mistaken. Then i have attempted spacey_readability

!pip install spacy_readability --user

Requirement already satisfied: spacy_readability in c:\users\desktop pc\appdata\roaming\python\python38\site-packages (1.4.1)
Requirement already satisfied: syllapy<1,>=0 in c:\users\desktop pc\appdata\roaming\python\python38\site-packages (from spacy_readability) (0.7.1)
Requirement already satisfied: spacy<3.0,>=2.0 in c:\programdata\anaconda3\lib\site-packages (from spacy_readability) (2.2.3)
Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (1.0.6)
Requirement already satisfied: preshed<3.1.0,>=3.0.2 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (3.0.6)
Requirement already satisfied: cymem<2.1.0,>=2.0.2 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (2.0.6)
Requirement already satisfied: blis<0.5.0,>=0.4.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (0.4.1)
Requirement already satisfied: srsly<1.1.0,>=0.1.0 in c:\users\desktop pc\appdata\roaming\python\python38\site-packages (from spacy<3.0,>=2.0->spacy_readability) (1.0.5)
Requirement already satisfied: setuptools in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (52.0.0.post20210125)
Requirement already satisfied: requests<3.0.0,>=2.13.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (2.25.1)
Requirement already satisfied: numpy>=1.15.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (1.20.1)
Requirement already satisfied: thinc<7.4.0,>=7.3.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (7.3.1)
Requirement already satisfied: catalogue<1.1.0,>=0.0.7 in c:\users\desktop pc\appdata\roaming\python\python38\site-packages (from spacy<3.0,>=2.0->spacy_readability) (1.0.0)
Requirement already satisfied: wasabi<1.1.0,>=0.4.0 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (0.9.0)
Requirement already satisfied: plac<1.2.0,>=0.9.6 in c:\programdata\anaconda3\lib\site-packages (from spacy<3.0,>=2.0->spacy_readability) (1.1.3)
Requirement already satisfied: idna<3,>=2.5 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.0,>=2.0->spacy_readability) (2.10)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.0,>=2.0->spacy_readability) (1.26.4)
Requirement already satisfied: certifi>=2017.4.17 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.0,>=2.0->spacy_readability) (2020.12.5)
Requirement already satisfied: chardet<5,>=3.0.2 in c:\programdata\anaconda3\lib\site-packages (from requests<3.0.0,>=2.13.0->spacy<3.0,>=2.0->spacy_readability) (4.0.0)
Collecting ujson<2.0,>=1.35
  Using cached ujson-1.35-cp38-cp38-win_amd64.whl
Requirement already satisfied: tqdm<5.0.0,>=4.10.0 in c:\programdata\anaconda3\lib\site-packages (from thinc<7.4.0,>=7.3.0->spacy<3.0,>=2.0->spacy_readability) (4.59.0)
Installing collected packages: ujson
  Attempting uninstall: ujson
    Found existing installation: ujson 5.1.0
    Uninstalling ujson-5.1.0:
      Successfully uninstalled ujson-5.1.0
Successfully installed ujson-1.35
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
python-language-server 0.36.2 requires ujson>=3.0.0; python_version > "3", but you have ujson 1.35 which is incompatible.
python-jsonrpc-server 0.4.0 requires ujson>=3.0.0, but you have ujson 1.35 which is incompatible.

I find this output very confusing. It seems to be detecting ujson 1.35 then replacing the more recent version of it with this, noticing that it is not recent enough and then causing an error. How do I avoid this?