问:
snsdev-dev already exists in stack
Issue:
New amplify project created throws this error:

Error:
Resource Name: SNSRole (AWS::IAM::Role)
Event Type: create
Reason: snsdev-dev already exists in stack arn:aws:cloudformation:eu-west-1:

✖ An error occurred when pushing the resources to the cloud

Resource is not in the state stackUpdateComplete
An error occured during the push operation: Resource is not in the state stackUpdateComplete

Amplify project created as follows:

```<code># mkdir react-rds
# cd react-rds

# amplify init
? Enter a name for the project react-rds
? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using react

⠙ Initializing project in the cloud...
Your project has been successfully initialized and connected to the cloud!

# amplify add auth
 Do you want to use the default authentication and security configuration? Default configuration
 Warning: you will not be able to edit these selections.
 How do you want users to be able to sign in? Username
 Do you want to configure advanced settings? No, I am done.

Successfully added resource reactrds0xxxbxde locally

# amplify push
? Are you sure you want to continue? Yes
⠼ Updating resources in the cloud. This may take a few minutes...

CREATE_FAILED      SNSRole                                                         AWS::IAM::Role             Sun May 31 2020 16:35:24 GMT+1000 (Australian Eastern Standard Time) snsdev-dev already exists in stack arn:aws:cloudformation:eu-west-1:4711111:stack/amplify-react-amplified-dev-12110-authreactamplifiedc7111f-1TOaaaaBPI1/e9xxxxx0-9fxx-11ex-97xx6-0acxxxxxee0
CREATE_FAILED      amplify-react-rds-dev-163108-authreactrds011de-1PHaaaaaWIJ AWS::CloudFormation::Stack Sun May 31 2020 16:35:24 GMT+1000 (Australian Eastern Standard Time) The following resource(s) failed to create: [SNSRole].

✖ An error occurred when pushing the resources to the cloud

Resource is not in the state stackUpdateComplete
An error occured during the push operation: Resource is not in the state stackUpdateComplete
</code>```

Then the above error comes on the first push.

答:
Resource already exists error will be popped up if you are trying to create a AWS resource with same name that is already created through another stack and existing.
Check for any duplicate stacks and delete them if not required. Else try to rename the resource</p>

Title: snsdev-dev already exists in stack

Body:
Issue:
New amplify project created throws this error:

Error:
Resource Name: SNSRole (AWS::IAM::Role)
Event Type: create
Reason: snsdev-dev already exists in stack arn:aws:cloudformation:eu-west-1:

✖ An error occurred when pushing the resources to the cloud

Resource is not in the state stackUpdateComplete
An error occured during the push operation: Resource is not in the state stackUpdateComplete

Amplify project created as follows:

# mkdir react-rds
# cd react-rds

# amplify init
? Enter a name for the project react-rds
? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using react

⠙ Initializing project in the cloud...
Your project has been successfully initialized and connected to the cloud!

# amplify add auth
 Do you want to use the default authentication and security configuration? Default configuration
 Warning: you will not be able to edit these selections.
 How do you want users to be able to sign in? Username
 Do you want to configure advanced settings? No, I am done.

Successfully added resource reactrds0xxxbxde locally

# amplify push
? Are you sure you want to continue? Yes
⠼ Updating resources in the cloud. This may take a few minutes...

CREATE_FAILED      SNSRole                                                         AWS::IAM::Role             Sun May 31 2020 16:35:24 GMT+1000 (Australian Eastern Standard Time) snsdev-dev already exists in stack arn:aws:cloudformation:eu-west-1:4711111:stack/amplify-react-amplified-dev-12110-authreactamplifiedc7111f-1TOaaaaBPI1/e9xxxxx0-9fxx-11ex-97xx6-0acxxxxxee0
CREATE_FAILED      amplify-react-rds-dev-163108-authreactrds011de-1PHaaaaaWIJ AWS::CloudFormation::Stack Sun May 31 2020 16:35:24 GMT+1000 (Australian Eastern Standard Time) The following resource(s) failed to create: [SNSRole].

✖ An error occurred when pushing the resources to the cloud

Resource is not in the state stackUpdateComplete
An error occured during the push operation: Resource is not in the state stackUpdateComplete

Then the above error comes on the first push.


来源: stackexchange

问:
How do I prevent Element.focus() change cursor position in contenteditable div?
I do not wish to move the cursor, anywhere but when I call the function focus, it moves the cursor to the beginning. I wish to keep the cursor where it is. I am doing this in ReactJS using Typescript.

```<code>const element = document.getElementById('editable-div');
element.focus();   // sets cursor to beginning here
// rest of my code is here
</code>```

I want to call focus because I need to append stuff in the contenteditable div and in some cases insert stuff. But as soon as I do focus(), it moves the cursor at the wrong place. How do I fix this?

答:
With the help of document.createRange and Window.getSelection it is possible

const { useState, useEffect, useRef } = React;

const random = (from, to) => Math.floor(Math.random() * (to - from) + from);
const randomText = () => Array(random(5, 10)).fill(0).map((pr, index) => String.fromCharCode(index + 50)).join('')

const setCaretToTheEnd = (element) => {
  const position = element.textContent.length;
  const [childNode] = element.childNodes;
  const range = document.createRange();
  const selection = window.getSelection();
  range.setStart(childNode, position);
  range.setEnd(childNode, position);
  range.collapse(true);
  selection.removeAllRanges();
  selection.addRange(range);
}

const App = () => {
  const [text, setText] = useState('');
  const inputRef = useRef(null);

  useEffect(() => {
    if(inputRef && inputRef.current && text) {
      const element = inputRef.current;

      setCaretToTheEnd(element);
      element.focus();
    }
  }, [text]);

  useEffect(() => {
    let isUnmounted = false;
    let handle = null;

    const changeText = () => {
      setText(randomText());

      handle = setTimeout(changeText, 4000);
    }

    handle = setTimeout(changeText, 500);

    return () => {
      isUnmounted = true;
      clearTimeout(handle);
    }
  }, [])

  const onChange = ({target: {value}}) => setText(value);

  return

{text}

}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.contentEditable {
  padding: 1rem;
  border: 1px solid black;
}</code>```

```

ContentLicense: CC BY-SA 4.0

Body:
I do not wish to move the cursor, anywhere but when I call the function focus, it moves the cursor to the beginning. I wish to keep the cursor where it is. I am doing this in ReactJS using Typescript.

const element = document.getElementById('editable-div');
element.focus();   // sets cursor to beginning here
// rest of my code is here

I want to call focus because I need to append stuff in the contenteditable div and in some cases insert stuff. But as soon as I do focus(), it moves the cursor at the wrong place. How do I fix this?

Body:
With the help of document.createRange and Window.getSelection it is possible

const { useState, useEffect, useRef } = React;

const random = (from, to) => Math.floor(Math.random() * (to - from) + from);
const randomText = () => Array(random(5, 10)).fill(0).map((pr, index) => String.fromCharCode(index + 50)).join('')

const setCaretToTheEnd = (element) => {
  const position = element.textContent.length;
  const [childNode] = element.childNodes;
  const range = document.createRange();
  const selection = window.getSelection();
  range.setStart(childNode, position);
  range.setEnd(childNode, position);
  range.collapse(true);
  selection.removeAllRanges();
  selection.addRange(range);
}

const App = () => {
  const [text, setText] = useState('');
  const inputRef = useRef(null);

  useEffect(() => {
    if(inputRef && inputRef.current && text) {
      const element = inputRef.current;

      setCaretToTheEnd(element);
      element.focus();
    }
  }, [text]);

  useEffect(() => {
    let isUnmounted = false;
    let handle = null;

    const changeText = () => {
      setText(randomText());

      handle = setTimeout(changeText, 4000);
    }

    handle = setTimeout(changeText, 500);

    return () => {
      isUnmounted = true;
      clearTimeout(handle);
    }
  }, [])

  const onChange = ({target: {value}}) => setText(value);

  return <div>
    <div ref={inputRef} suppressContentEditableWarning={true} className="contentEditable" onChange={onChange} contentEditable>{text}</div>
  </div>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );

.contentEditable {
  padding: 1rem;
  border: 1px solid black;
}

<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
<div id="root"></div>
<script src="https://unpkg.com/material-ui-lab-umd@4.0.0-alpha.32/material-ui-lab.development.js"></script>
<div id="root"></div>


问:
How to Proxy Fontawesome Pro npm packages
I work for a Company where our Frontend Build are on a Server with a very strict firewall policy

Therefore we use a Proxy (Nexus3) for https://registry.npmjs.org which works great.

Now i want to do the same for Fontawesome Pro 5

Fontawesome tells me to add those two lines in my .npmrc file see:
https://fontawesome.com/how-to-use/on-the-web/setup/using-package-managers

```<code>@fortawesome:registry=https://npm.fontawesome.com/
//npm.fontawesome.com/:_authToken=${FONTAWESOME_NPM_AUTH_TOKEN}
</code>```

my old npmrc file had this line

```<code>registry=https://nexus.mycompany.com/repository/npm-proxy/
</code>```

i tried the following:

```<code>registry=https://nexus.mycompany.com/repository/npm-proxy/
@fortawesome:registry=https://nexus.mycompany.com/repository/fontawesome/ <!-- which i created on the nexus side-->
//nexus.mycompany.com/repository/fontawesome/:_authToken=${FONTAWESOME_NPM_AUTH_TOKEN}
</code>```

but it doesn't work and i dont know if i need a diffrent setting on the nexus side or a diffrent setting on the npmrc side...

答: We do have the same issue and we're asking the corresponding teams to add the Font Awesome Pro URL to the allowed list in the Firewall.</p>

Body:
I work for a Company where our Frontend Build are on a Server with a very strict firewall policy

Therefore we use a Proxy (Nexus3) for https://registry.npmjs.org which works great.

Now i want to do the same for Fontawesome Pro 5

Fontawesome tells me to add those two lines in my .npmrc file see:
https://fontawesome.com/how-to-use/on-the-web/setup/using-package-managers

@fortawesome:registry=https://npm.fontawesome.com/
//npm.fontawesome.com/:_authToken=${FONTAWESOME_NPM_AUTH_TOKEN}

my old npmrc file had this line

registry=https://nexus.mycompany.com/repository/npm-proxy/

i tried the following:

registry=https://nexus.mycompany.com/repository/npm-proxy/
@fortawesome:registry=https://nexus.mycompany.com/repository/fontawesome/
//nexus.mycompany.com/repository/fontawesome/:_authToken=${FONTAWESOME_NPM_AUTH_TOKEN}

but it doesn't work and i dont know if i need a diffrent setting on the nexus side or a diffrent setting on the npmrc side...


问:
Borrow a hashmap without Borrowing his content
I'm new to rust, I've read the doc on ownership and borrowing. And obviously, I'm beginning to struggle with the concept ...

Here is my code :

```<code>
#[derive(Serialize, Deserialize, Debug)]
pub struct City {
    name: String,
    dep: String,
    dynamic: String,
    population: u64,
    cp: String,
    price_max: u8,
    price_mid: u8,
    price_min: u8,
    lng: f64,
    lat: f64,
    dist_near_city: Vec<(String, u64)>
}

fn load_cities<P: AsRef<Path>>(path: P) -> HashMap<String, City> {
    // Open the file in read-only mode with buffer.
    let file = File::open(path).expect("Unable to open file");
    let reader = BufReader::new(file);
    let retval: HashMap<String, City> = serde_json::from_reader(reader).expect("Unable to parse json");

    return retval;
}

fn update_nearby_cities(pin_city: &mut City, cities : &HashMap<String, City>, min_pop: u64, distKm: f64){
    pin_city.dist_near_city = Vec::new();
    for (id, city) in cities {
        if city.population > min_pop && is_nearby(&pin_city, &city, distKm){
            pin_city.dist_near_city.push((id.to_string(), city.population));
        }
    }
}

fn main(){
    let path  = "/home/marcel/Documents/immobilier/cities_export2.json";
    let mut cities = load_cities(path);

    for (cp, mut current_city) in &cities {
        update_nearby_cities(&mut current_city, &cities, 2000, 10.);
    }
}
</code>```

I get the error for the arg &mut current_city inside the loop of the main() :

cannot borrow data in a&reference as mutable

First of all, I don't understand why I can't borrow a mutable reference because it's possible in other part of my code and in the doc (https://doc.rust-lang.org/rust-by-example/scope/borrow/mut.html)

I think it's because the loop on &cities gives me a current_city: &City and by giving &mut current_city I pass a &mut &City which is a problem (I don't know what to do with this type, I don't even think I understand what this thing is ...).

So If I try to pass only mut current_city I get Exepted expression.

The other problem I foresee, is that I'm trying to borrow the hashmap cites in the loop and reborrow it inside the loop.

How to do this kind of things properly, and is my thinking on the error are correct ?

答:
for entry in &cities gives a iterator over (&K, &V). If you need an iterator over (&K, &mut V) use `&mut cities'

Even with this change code will not work. You are trying to iterate & modify cities at the same time.

One easy way without doing lot of refactoring is to compute all the results at once and then add them later into the hashmap.

```<code>fn get_nearby_cities(pin_city: &City, cities : &HashMap<String, City>, min_pop: u64, distKm: f64) -> Vec<(String, u64)> {
    let mut dist_near_city = Vec::new();
    for (id, city) in cities {
        if city.population > min_pop && is_nearby(&pin_city, &city, distKm){
            dist_near_city.push((id.to_string(), city.population));
        }
    }

    dist_near_city
}

   # Compute all the required results. Unfortunately, I ended up clone the string. May be this could be avoided.
   let mut result = HashMap::new();
    for (cp, current_city) in &cities {
        result.insert(cp.clone(), get_nearby_cities(current_city, &cities, 2000, 10.));
    }

    for (city, nearby_cities) in result {
        cities.get_mut(&city).unwrap().dist_near_city.extend(nearby_cities);
    }
</code>```

Body:
I'm new to rust, I've read the doc on ownership and borrowing. And obviously, I'm beginning to struggle with the concept ...

Here is my code :

#[derive(Serialize, Deserialize, Debug)]
pub struct City {
    name: String,
    dep: String,
    dynamic: String,
    population: u64,
    cp: String,
    price_max: u8,
    price_mid: u8,
    price_min: u8,
    lng: f64,
    lat: f64,
    dist_near_city: Vec<(String, u64)>
}

fn load_cities<P: AsRef<Path>>(path: P) -> HashMap<String, City> {
    // Open the file in read-only mode with buffer.
    let file = File::open(path).expect("Unable to open file");
    let reader = BufReader::new(file);
    let retval: HashMap<String, City> = serde_json::from_reader(reader).expect("Unable to parse json");

    return retval;
}

fn update_nearby_cities(pin_city: &mut City, cities : &HashMap<String, City>, min_pop: u64, distKm: f64){
    pin_city.dist_near_city = Vec::new();
    for (id, city) in cities {
        if city.population > min_pop && is_nearby(&pin_city, &city, distKm){
            pin_city.dist_near_city.push((id.to_string(), city.population));
        }
    }
}

fn main(){
    let path  = "/home/marcel/Documents/immobilier/cities_export2.json";
    let mut cities = load_cities(path);

    for (cp, mut current_city) in &cities {
        update_nearby_cities(&mut current_city, &cities, 2000, 10.);
    }
}

I get the error for the arg &mut current_city inside the loop of the main() :

cannot borrow data in a&reference as mutable

First of all, I don't understand why I can't borrow a mutable reference because it's possible in other part of my code and in the doc (https://doc.rust-lang.org/rust-by-example/scope/borrow/mut.html)

I think it's because the loop on &cities gives me a current_city: &City and by giving &mut current_city I pass a &mut &City which is a problem (I don't know what to do with this type, I don't even think I understand what this thing is ...).

So If I try to pass only mut current_city I get Exepted expression.

The other problem I foresee, is that I'm trying to borrow the hashmap cites in the loop and reborrow it inside the loop.

How to do this kind of things properly, and is my thinking on the error are correct ?

Body:
for entry in &cities gives a iterator over (&K, &V). If you need an iterator over (&K, &mut V) use `&mut cities'

Even with this change code will not work. You are trying to iterate & modify cities at the same time.

One easy way without doing lot of refactoring is to compute all the results at once and then add them later into the hashmap.

fn get_nearby_cities(pin_city: &City, cities : &HashMap<String, City>, min_pop: u64, distKm: f64) -> Vec<(String, u64)> {
    let mut dist_near_city = Vec::new();
    for (id, city) in cities {
        if city.population > min_pop && is_nearby(&pin_city, &city, distKm){
            dist_near_city.push((id.to_string(), city.population));
        }
    }

    dist_near_city
}

   # Compute all the required results. Unfortunately, I ended up clone the string. May be this could be avoided.
   let mut result = HashMap::new();
    for (cp, current_city) in &cities {
        result.insert(cp.clone(), get_nearby_cities(current_city, &cities, 2000, 10.));
    }

    for (city, nearby_cities) in result {
        cities.get_mut(&city).unwrap().dist_near_city.extend(nearby_cities);
    }


问:
Android view binding between modules
Does view binding work between modules?

How to reproduce: Create 2 modules >>> create layout1 in module1 and create layout2 in module2 >>> Create Fragment1 in module1 with view which will be including layout1, layout2 >>> try to get binding >>> layout1 will work becouse it is in the same module as Fragment1, but layout2 will not work becouse of wrong binding generation

My example:

Authentication module has dependency to common module.

base_button.xml is in common module.

login_input_component.xml is in Authentication module so there is no problem.

But this error occures on loginButton binding.

It tries to find BaseButtonBinding in authentication module even if base_button.xml is in another module.

All modules has:

```<code>buildFeatures {
    dataBinding = true
    viewBinding = true
}
</code>```

答:
If I am correct you have this kind of structure

project

|   -- app

|   -- module1 [ contains layout_one.xml and layout_fragment.xml]

|   -- module2 [ contains layout_two.xml]

layout_fragment.xml will include both layout_one.xml and layout_two.xml

Now in order to make this work, all you need to do is go to module1 build.gradle file and add this dependency

```<code>implementation project(":module2")
</code>```

Note your app will be aware of module1 and module2 files but module1 and module2 files will not be aware of both of there existence. So by specifying this dependency we make module1 to depend on module2

and also make sure in each module viewBinding is enabled

Title: Android view binding between modules

Body:
Does view binding work between modules?

How to reproduce: Create 2 modules >>> create layout1 in module1 and create layout2 in module2 >>> Create Fragment1 in module1 with view which will be including layout1, layout2 >>> try to get binding >>> layout1 will work becouse it is in the same module as Fragment1, but layout2 will not work becouse of wrong binding generation

My example:

Authentication module has dependency to common module.

base_button.xml is in common module.

login_input_component.xml is in Authentication module so there is no problem.

But this error occures on loginButton binding.

It tries to find BaseButtonBinding in authentication module even if base_button.xml is in another module.

All modules has:

buildFeatures {
    dataBinding = true
    viewBinding = true
}

Body:
If I am correct you have this kind of structure

project

|   -- app

|   -- module1 [ contains layout_one.xml and layout_fragment.xml]

|   -- module2 [ contains layout_two.xml]

layout_fragment.xml will include both layout_one.xml and layout_two.xml

Now in order to make this work, all you need to do is go to module1 build.gradle file and add this dependency

implementation project(":module2")

Note your app will be aware of module1 and module2 files but module1 and module2 files will not be aware of both of there existence. So by specifying this dependency we make module1 to depend on module2

and also make sure in each module viewBinding is enabled


问:
Application doing weird? C#
Soo, i was working on my application, i close it, do something else, and when i come back and debug it everything is diffrent, the application lookt kinda fat (text is bigger) and the worst thing, my custom contextmenustrip its hover over doesn't work anymore. Here are some pictures because you probably don't understand me:
Before:
Img1
After:
Img3

You probably still don't understand me but i have no idea what's going on myself so i can't explain

I didn't change anything in the code (not that i can remember)

答: Alright, i found the problem. In the Program.cs file u have a line that gives the form a style, i removed that line and now i added it back and now i have the normal style again!</p>

Title: Application doing weird? C#


问:
Get Address Details after i select address in search box in leaflet js
I am using leaflet for the first time as I am using open street map in place for Google.

In google autocomplete we use to get address's Suburb via

```<code>var place = autocomplete.getPlace();
</code>```

Can anyone help me in leafletJs to get address details.

Thanks Much in advance.

答:
Using the geocoding control to search for addresses and center the map.

  var map = L.map('map').setView([-28.4792625, 24.6727135], 4);

  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
  }).addTo(map);

  var searchControl = L.esri.Geocoding.geosearch().addTo(map);

  var results = L.layerGroup().addTo(map);

  searchControl.on('results', function (data) {
    results.clearLayers();
    for (var i = data.results.length - 1; i >= 0; i--) {
      results.addLayer(L.marker(data.results[i].latlng));
    }
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    body { margin:0; padding:0; }
    #map { position: absolute; top:0; bottom:0; right:0; left:0; }</code>```

  <meta charset="utf-8" />
  <title>Geocoding Control</title>
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
  integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
  crossorigin=""/>

  <link rel="stylesheet" href="https://unpkg.com/esri-leaflet-geocoder@2.3.3/dist/esri-leaflet-geocoder.css"
    integrity="sha512-IM3Hs+feyi40yZhDH6kV8vQMg4Fh20s9OzInIIAc4nx7aMYMfo+IenRUekoYsHZqGkREUgx0VvlEsgm7nCDW9g=="
    crossorigin="">

```

Source: http://esri.github.io/esri-leaflet/examples/geocoding-control.html

Body:
I am using leaflet for the first time as I am using open street map in place for Google.

In google autocomplete we use to get address's Suburb via

var place = autocomplete.getPlace();

Can anyone help me in leafletJs to get address details.

Thanks Much in advance.

Body:
Using the geocoding control to search for addresses and center the map.

  var map = L.map('map').setView([-28.4792625, 24.6727135], 4);

  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

  var searchControl = L.esri.Geocoding.geosearch().addTo(map);

  var results = L.layerGroup().addTo(map);

  searchControl.on('results', function (data) {
    results.clearLayers();
    for (var i = data.results.length - 1; i >= 0; i--) {
      results.addLayer(L.marker(data.results[i].latlng));
    }
  });

    body { margin:0; padding:0; }
    #map { position: absolute; top:0; bottom:0; right:0; left:0; }

<html>
<head>
  <meta charset="utf-8" />
  <title>Geocoding Control</title>
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />

  <!-- Load Leaflet from CDN -->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
  integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
  crossorigin=""/>
  <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"
  integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
  crossorigin=""></script>

  <!-- Load Esri Leaflet from CDN -->
  <script src="https://unpkg.com/esri-leaflet@2.4.1/dist/esri-leaflet.js"
  integrity="sha512-xY2smLIHKirD03vHKDJ2u4pqeHA7OQZZ27EjtqmuhDguxiUvdsOuXMwkg16PQrm9cgTmXtoxA6kwr8KBy3cdcw=="
  crossorigin=""></script>

  <!-- Load Esri Leaflet Geocoder from CDN -->
  <link rel="stylesheet" href="https://unpkg.com/esri-leaflet-geocoder@2.3.3/dist/esri-leaflet-geocoder.css"
    integrity="sha512-IM3Hs+feyi40yZhDH6kV8vQMg4Fh20s9OzInIIAc4nx7aMYMfo+IenRUekoYsHZqGkREUgx0VvlEsgm7nCDW9g=="
    crossorigin="">
  <script src="https://unpkg.com/esri-leaflet-geocoder@2.3.3/dist/esri-leaflet-geocoder.js"
    integrity="sha512-HrFUyCEtIpxZloTgEKKMq4RFYhxjJkCiF5sDxuAokklOeZ68U2NPfh4MFtyIVWlsKtVbK5GD2/JzFyAfvT5ejA=="
    crossorigin=""></script>

</head>
<body>

  <div id="map"></div>

</body>
</html>

Source: http://esri.github.io/esri-leaflet/examples/geocoding-control.html


问:
rspec how to reuse code in example groups
What I am trying to do is this:

```<code>describe Specs::Specs do
  shared_context 'common' do
    def get_property(type)
      subject.send(type)
    end
  end

  describe 'attributes not needing conversion' do
    include_context 'common'
    # USE THE CODE HERE
    get_property(:weight)
  end
end
</code>```

I want to dry up setting examples but I keep getting errors like:

get_property is not available on an example group (e.g. a describe or context block). It is only available from within individual examples (e.g. it blocks) or from constructs that run in the scope of an example (e.g. before, let, etc).

How do I make methods available in nested example group?
How do I make variables available in nested example group?

答: I think you can pass 'include_shared => true' as the examples show: https://relishapp.com/rspec/rspec-core/docs/example-groups/shared-context#declare-a-shared-context-and-include-it-with-metadata

ContentLicense: CC BY-SA 3.0

Body:
What I am trying to do is this:

describe Specs::Specs do
  shared_context 'common' do
    def get_property(type)
      subject.send(type)
    end
  end

  describe 'attributes not needing conversion' do
    include_context 'common'
    # USE THE CODE HERE
    get_property(:weight)
  end
end

I want to dry up setting examples but I keep getting errors like:

get_property is not available on an example group (e.g. a describe or context block). It is only available from within individual examples (e.g. it blocks) or from constructs that run in the scope of an example (e.g. before, let, etc).

How do I make methods available in nested example group?
How do I make variables available in nested example group?


问:
IOError: [Errno 28] No space left on device while installing TensorFlow
I am trying to install TensorFlow in my local directory using the following command.

```<code>export TF_BINARY_URL=http://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0-cp27-none-linux_x86_64.whl
pip install --install-option="--prefix=$PYTHONUSERBASE" --upgrade $TF_BINARY_URL
</code>```

I am getting the following error:

```<code>IOError: [Errno 28] No space left on device
</code>```

Then I did df to see the following:

```<code>Filesystem             1K-blocks       Used   Available Use% Mounted on
tmpfs                      10240      10240           0 100% /tmp
tmpfs                      10240      10240           0 100% /var/tmp
</code>```

Is there a way I can install TF without the temp files being downloaded in /tmp or /var/tmp? Thanks.

答:
```<code>export TMPDIR=/bigspace/space
</code>```

Why?:
It is likely that  /tmp directory do not have enough space for some reason.

During the pip installation, pip will use /tmp directory to perform what is necessary to perform installation (e.g. download source etc).

Thus if you do not have enough space in /tmp that package installation requires then you will get disk space error.

You can configure your  /tmp directory location using below command

Body:
I am trying to install TensorFlow in my local directory using the following command.

export TF_BINARY_URL=http://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0-cp27-none-linux_x86_64.whl
pip install --install-option="--prefix=$PYTHONUSERBASE" --upgrade $TF_BINARY_URL

I am getting the following error:

IOError: [Errno 28] No space left on device

Then I did df to see the following:

Filesystem             1K-blocks       Used   Available Use% Mounted on
tmpfs                      10240      10240           0 100% /tmp
tmpfs                      10240      10240           0 100% /var/tmp

Is there a way I can install TF without the temp files being downloaded in /tmp or /var/tmp? Thanks.

Body:
export TMPDIR=/bigspace/space

Why?:
It is likely that  /tmp directory do not have enough space for some reason.

During the pip installation, pip will use /tmp directory to perform what is necessary to perform installation (e.g. download source etc).

Thus if you do not have enough space in /tmp that package installation requires then you will get disk space error.

You can configure your  /tmp directory location using below command


问:
Rendering joinTables as a list in Grails
I've got two domain classes: Car and Driver.  I'd like to make a gsp view that displays the Car and Driver info in a list that looks more or less a default scaffolded list.  For example:

```<code>Make  Model  Driver  Age
------------------------
Chevy Nova   Joe     20
Chevy Nova   Mike    30
Chevy Nova   Sally   40
</code>```

Here's the domain classes:

```<code>class Car {
  String make
  String model

  static constraints = { }
  static hasMany = [ drivers : Driver ]

  static mapping = {
    drivers joinTable: [name: 'Car_Driver', column: 'DRIVER_ID', key: 'CAR_ID']
  }
}

class Driver {
  String name
  int    age

  static constraints = { }
}
</code>```

Make a car and give it a few drivers:

```<code>def car = new Car(make: 'Chevy', model: 'Nova')
def driver1 = new Driver(name: 'Joe', age: 20)
def driver2 = new Driver(name: 'Mike', age: 30)
def driver3 = new Driver(name: 'Sally', age: 40)

car.addToDrivers(driver1)
car.addToDrivers(driver2)
car.addToDrivers(driver3)
car.save()
</code>```

What do I need to do in my CarController and/or gsp view to make a joined list happen (and still work with pagination)?

答:
If a Driver can have only one Car, you need a Driver to reference Car and just to render scaffolding list for a Driver.

To tweak list columns, you'll have to grails generate-views.

If a Driver can have many Cars, and you don't want to pull Car_Driver table into visible domain model (it has no own domain meaning),  make a scaffolding-like list action using SQL query result as a cardriverInstancesList. Like here: SQL/Database Views in Grails.

Just check that result is a PagedResultList. If not, you can create a PagedResultList by hand, it is easily constructed from a List and totalCount, which you can find with SQL.

Body:
I've got two domain classes: Car and Driver.  I'd like to make a gsp view that displays the Car and Driver info in a list that looks more or less a default scaffolded list.  For example:

Make  Model  Driver  Age
------------------------
Chevy Nova   Joe     20
Chevy Nova   Mike    30
Chevy Nova   Sally   40

Here's the domain classes:

class Car {
  String make
  String model

  static constraints = { }
  static hasMany = [ drivers : Driver ]

  static mapping = {
    drivers joinTable: [name: 'Car_Driver', column: 'DRIVER_ID', key: 'CAR_ID']
  }
}

class Driver {
  String name
  int    age

  static constraints = { }
}

Make a car and give it a few drivers:

def car = new Car(make: 'Chevy', model: 'Nova')
def driver1 = new Driver(name: 'Joe', age: 20)
def driver2 = new Driver(name: 'Mike', age: 30)
def driver3 = new Driver(name: 'Sally', age: 40)

car.addToDrivers(driver1)
car.addToDrivers(driver2)
car.addToDrivers(driver3)
car.save()

What do I need to do in my CarController and/or gsp view to make a joined list happen (and still work with pagination)?


问:
Understanding UIViewRepresentable
Swift 5.0 iOS 13

Trying to understand how UIViewRepresentable works, and put together this simple example, almost there, but maybe its complete nonsense. Yes, I know there is already a tapGesture in SwiftUI, this is just a test.

Won't compile cause it says 'super.init' isn't called on all paths before returning from initialiser, which I try and set but obviously not correctly.

```<code>import SwiftUI

struct newView: UIViewRepresentable {

typealias UIViewType = UIView
var v = UIView()

func updateUIView(_ uiView: UIView, context: Context) {
  v.backgroundColor = UIColor.yellow
}

func makeUIView(context: Context) -> UIView {
  let tapGesture = UITapGestureRecognizer(target: self, action: #selector(Coordinator.handleTap(sender:)))
  v.addGestureRecognizer(tapGesture)
  return v
}

func makeCoordinator() -> newView.Coordinator {
  Coordinator(v)
}

final class Coordinator: UIView {
  private let view: UIView

init(_ view: UIView) {
    self.view = view
}

required init?(coder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
}

@objc func handleTap(sender: UITapGestureRecognizer) {
    print("tap")
  }
 }

}
</code>```

答:
Just make your Coordinator is a NSObject, it usually plays bridge/controller/delegate/actor role, but not presentation, so should not be is-a-UIView

```<code>final class Coordinator: NSObject {
  private let view: UIView

init(_ view: UIView) {
    self.view = view
}
</code>```

and one more...

```<code>func makeUIView(context: Context) -> UIView {
  // make target a coordinator, which is already present in context !!
  let tapGesture = UITapGestureRecognizer(target: context.coordinator,
        action: #selector(Coordinator.handleTap(sender:)))
  v.addGestureRecognizer(tapGesture)
  return v
}
</code>```

Title: Understanding UIViewRepresentable

Body:
Swift 5.0 iOS 13

Trying to understand how UIViewRepresentable works, and put together this simple example, almost there, but maybe its complete nonsense. Yes, I know there is already a tapGesture in SwiftUI, this is just a test.

Won't compile cause it says 'super.init' isn't called on all paths before returning from initialiser, which I try and set but obviously not correctly.

import SwiftUI

struct newView: UIViewRepresentable {

typealias UIViewType = UIView
var v = UIView()

func updateUIView(_ uiView: UIView, context: Context) {
  v.backgroundColor = UIColor.yellow
}

func makeUIView(context: Context) -> UIView {
  let tapGesture = UITapGestureRecognizer(target: self, action: #selector(Coordinator.handleTap(sender:)))
  v.addGestureRecognizer(tapGesture)
  return v
}

func makeCoordinator() -> newView.Coordinator {
  Coordinator(v)
}

final class Coordinator: UIView {
  private let view: UIView

init(_ view: UIView) {
    self.view = view
}

required init?(coder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
}

@objc func handleTap(sender: UITapGestureRecognizer) {
    print("tap")
  }
 }

}

Body:
Just make your Coordinator is a NSObject, it usually plays bridge/controller/delegate/actor role, but not presentation, so should not be is-a-UIView

final class Coordinator: NSObject {
  private let view: UIView

init(_ view: UIView) {
    self.view = view
}

and one more...

func makeUIView(context: Context) -> UIView {
  // make target a coordinator, which is already present in context !!
  let tapGesture = UITapGestureRecognizer(target: context.coordinator,
        action: #selector(Coordinator.handleTap(sender:)))
  v.addGestureRecognizer(tapGesture)
  return v
}


问:
Querying data from multiple odbc connections simultaneously?
I am creating a report with Crystal 2011. With all the reports I create with Crystal, I code the SQL first, then drop it into Crystal and use its formatting tools.

We have Intersystem's Cache database. In the report I am currently creating, I need to pull data from our production, testing, and sandbox environments into this single report. Each environment has a unique jdbc url.

In the report I will be comparing data between the environments looking for discrepancies.

Does anyone have any ideas how to pull data via multiple jdbc/odbc connections into a single report?

Any suggestions would be greatly appreciated!

答: Sub Reports can can point to different database connection.</p>


问:
How use TextToColumns in Win32com
I would like a exemple how to use TextToColumns in Win32com

Sub VBA_Code()
  Columns("A").TextToColumns DataType:=xlDelimited, FieldInfo:=Array(1, xlDMYFormat)
End Sub```

答:
I solved my own question using code below

xw.Range('A:A').api.TextToColumns()```

Thanks

Title: How use TextToColumns in Win32com

Body:
I solved my own question using code below

xw.Range('A:A').api.TextToColumns()

Thanks


问:
MongoDB CRUD operations in Ansible playbook
Can anyone share a simple example of how to create database, a collection and perform CRUD operations in Ansible playbook using mongodb module.</p>

答:
Looks like ansible provides only common admin task like adding Shards to cluster or create users.

In this case you have to use the shell module, e.g.

```<code>- copy:
    # create or copy .js file with required commands
    dest: ~/script-file.js

- shell:
    cmd: mongo -u <user> -p <password> ~/script-file.js
</code>```

For single command you can also use

```<code>- shell:
    cmd: mongo -u <user> -p <password>
    stdin: db.createCollection("col")
</code>```

Body:
Looks like ansible provides only common admin task like adding Shards to cluster or create users.

In this case you have to use the shell module, e.g.

- copy:
    # create or copy .js file with required commands
    dest: ~/script-file.js

- shell:
    cmd: mongo -u <user> -p <password> ~/script-file.js

For single command you can also use

- shell:
    cmd: mongo -u <user> -p <password>
    stdin: db.createCollection("col")


问:
SQL: get the latest record in each day of each user
I have a table that looks like

```<code>user_id behavior time
A B1 2020-05-30 09:07:21
A B1 2020-05-31 12:38:21
A B2 2020-05-31 14:39:23
B B1 2020-05-31 12:32:09
</code>```

I would like to get the latest records in each day of each user, so the above table will become

```<code>    user_id behavior time
    A B1 2020-05-30 09:07:21
    A B2 2020-05-31 14:39:23
    B B1 2020-05-31 12:32:09
</code>```

I look to some other questions in stackoverflow but did not find exactly what I am looking for.

Thanks for your help.

答:
Your question is unclear, but you can use qualify either way.  If you want the last time per user_id/behavior, then:

```<code>select t.*
from t
qualify row_number() over (partition by user_id, behavior order by time desc) = 1;
</code>```

If you want the last rows on the most recent day for each user, then:

```<code>select t.*
from t
qualify dense_rank() over (partition by user_id order by date(time) desc) = 1;
</code>```

qualify does filtering like where and having.  However, it allows the use of window functions.

Body:
I have a table that looks like

user_id behavior time
A B1 2020-05-30 09:07:21
A B1 2020-05-31 12:38:21
A B2 2020-05-31 14:39:23
B B1 2020-05-31 12:32:09

I would like to get the latest records in each day of each user, so the above table will become

    user_id behavior time
    A B1 2020-05-30 09:07:21
    A B2 2020-05-31 14:39:23
    B B1 2020-05-31 12:32:09

I look to some other questions in stackoverflow but did not find exactly what I am looking for.

Thanks for your help.

Body:
Your question is unclear, but you can use qualify either way.  If you want the last time per user_id/behavior, then:

select t.*
from t
qualify row_number() over (partition by user_id, behavior order by time desc) = 1;

If you want the last rows on the most recent day for each user, then:

select t.*
from t
qualify dense_rank() over (partition by user_id order by date(time) desc) = 1;

qualify does filtering like where and having.  However, it allows the use of window functions.


问:
Jpa repository special words like "and' , "or" not working
I have a simple UserRepository which extends JpaRepository.

I am trying to find a user for a given username and password.

Here is my repository class

```<code>    public interface UserRepository extends JpaRepository<User, Integer> {

        public Optional<User> findByusUnameAndusPassword(String username, String password);
    }
</code>```

Here is my entity class

```<code>    public class User implements java.io.Serializable {

    @Id
    @Column(name = "us_id", unique = true, nullable = false)
    private int usId;

    @Column(name = "us_uname", unique = true, nullable = false)
    private String usUname;

    @Column(name = "us_password", nullable = false, length = 100)
    private String usPassword;
 }
</code>```

This is the error that I am getting

```<code>    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.example.repository.UserRepository.findByusUnameAndusPaasword(java.lang.String,boolean)! No property andusPassword found for type String! Traversed path: User.usUname.
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:178) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:101) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1821) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getObjectForBeanInstance(AbstractAutowireCapableBeanFactory.java:1266) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:260) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:623) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:611) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:51) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:36) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:897) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) [spring-boot-test-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassBasedTestDescriptor.java:341) [junit-jupiter-engine-5.6.2.jar:5.6.2]
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:346) [junit-jupiter-engine-5.6.2.jar:5.6.2]
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:341) [junit-jupiter-engine-5.6.2.jar:5.6.2]
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_251]
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[na:1.8.0_251]
</code>```

答:
Use findByUsUnameAndUsPassword instead of findByusUnameAndusPassword.

```<code>Optional<User> findByUsUnameAndUsPassword(String username, String password);
</code>```

Body:
I have a simple UserRepository which extends JpaRepository.

I am trying to find a user for a given username and password.

Here is my repository class

    public interface UserRepository extends JpaRepository<User, Integer> {

        public Optional<User> findByusUnameAndusPassword(String username, String password);
    }

Here is my entity class

    public class User implements java.io.Serializable {

    @Id
    @Column(name = "us_id", unique = true, nullable = false)
    private int usId;

    @Column(name = "us_uname", unique = true, nullable = false)
    private String usUname;

    @Column(name = "us_password", nullable = false, length = 100)
    private String usPassword;
 }

This is the error that I am getting

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.example.repository.UserRepository.findByusUnameAndusPaasword(java.lang.String,boolean)! No property andusPassword found for type String! Traversed path: User.usUname.
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:178) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:101) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1821) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getObjectForBeanInstance(AbstractAutowireCapableBeanFactory.java:1266) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:260) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:623) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:611) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:51) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:36) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:897) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) [spring-boot-test-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98) [spring-test-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassBasedTestDescriptor.java:341) [junit-jupiter-engine-5.6.2.jar:5.6.2]
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:346) [junit-jupiter-engine-5.6.2.jar:5.6.2]
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:341) [junit-jupiter-engine-5.6.2.jar:5.6.2]
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_251]
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[na:1.8.0_251]

Body:
Use findByUsUnameAndUsPassword instead of findByusUnameAndusPassword.

Optional<User> findByUsUnameAndUsPassword(String username, String password);


问:
Conda dependency from custom channel is not getting installed
I'm struggling with building my own conda package. The build runs OK and the meta.yaml file looks like this:

package:
  name: simple_nodes_embedding
  version: "0.1.0"

source:
  path: ..

build:
  number: 0

requirements:
  build:
    - pip
    - python=3.7
    - setuptools
  run:
    - python=3.7
    - pypardiso
    - networkx >=2.4
    - scipy
    - numpy>=1.18.1
    - markdown
    - statsmodels

about:
  home: https://github.com/monomonedula/simple-graph-embedding
  license: Apache License 2.0
  license_file: LICENSE.txt
  summary: Simple deterministic algorithm for generating graph nodes topological embeddings.
```

<p>However, when I run</p>

```conda install simple_nodes_embedding -c local -c defaults -c conda-forge -c haasad
```

<p>and the built package is installed, pypardiso package from haasad channel is not getting installed.</p>

<pre class="lang-py prettyprint-override"><code>>>> from simple_nodes_embedding import embedding
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/vhhl/dev/simple-graph-embedding/simple_nodes_embedding/embedding.py", line 4, in <module>
    from pypardiso import spsolve
ModuleNotFoundError: No module named 'pypardiso'
</code>```

How do I fix this? And what is the correct way to specify depenedencies from custom channels when creating conda packages?

答: Well, the reason it wasn't working was that i specified the wrong name (I copied a part of it from the pypardiso package and forgot to replace the name) for the package in my setup.py file. I changed it and now it works fine

Body:
I'm struggling with building my own conda package. The build runs OK and the meta.yaml file looks like this:

package:
  name: simple_nodes_embedding
  version: "0.1.0"

source:
  path: ..

build:
  number: 0

requirements:
  build:
    - pip
    - python=3.7
    - setuptools
  run:
    - python=3.7
    - pypardiso
    - networkx >=2.4
    - scipy
    - numpy>=1.18.1
    - markdown
    - statsmodels

about:
  home: https://github.com/monomonedula/simple-graph-embedding
  license: Apache License 2.0
  license_file: LICENSE.txt
  summary: Simple deterministic algorithm for generating graph nodes topological embeddings.

However, when I run

conda install simple_nodes_embedding -c local -c defaults -c conda-forge -c haasad

and the built package is installed, pypardiso package from haasad channel is not getting installed.

>>> from simple_nodes_embedding import embedding
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/vhhl/dev/simple-graph-embedding/simple_nodes_embedding/embedding.py", line 4, in <module>
    from pypardiso import spsolve
ModuleNotFoundError: No module named 'pypardiso'

How do I fix this? And what is the correct way to specify depenedencies from custom channels when creating conda packages?


问:
Add IP restrictions on QnA maker app service
I am trying to add IP restrictions to my app service associated to my QnA Maker to make it available only through an application gateway.
Now, the service works through the gateway but the qna maker portal doesn't work anymore. I get the following error message when loading my knowledge base:

QnA Maker runtime error

Runtime unavailable. Please check that the App Service resource in
  your QnA Maker service is up and running.

According to Can qnamaker.ai load a url not open for the public?, the following IP ranges must be added to the app service whitelist:

West US: 13.91.0.0/16

East US: 52.191.0.0/18

Unfortunately, adding these IPs doesn't solve the issue and the QnA resource is still unavailable.

After multiple refresh of the page, the KB is sometime displayed. I think there are some others IP ranges that need to be added to work all the time.

Does anybody knows what is the complete list of IPs to add to fix the QnA maker portal ?

答:
If this host name is Valid and reachable via following IPs everything should work.

52.191.14.164

13.91.243.134

or

Hosting QnA Maker App on Isolated App Service Environment is bit hard, but feasible.
You need to integrate ILB with WAF so that the site is accessible externally:
https://learn.microsoft.com/en-us/azure/app-service/environment/integrate-with-application-gateway

You also need to manage certs:
https://learn.microsoft.com/en-us/azure/app-service/environment/create-ilb-ase#create-an-app-in-an-ilb-ase

Create the App Service with QNA Maker extension enabled(Part of existing template) in ASE

Manual: Add certs +WAF for the App Service in 1 (1hr work atleast)

Make sure the App Service is reachable in the browser(https://) and there are no cert issues

Create cognitive services instances (part of existing template) and pass it the app service host name from 1.

Deploy QnA Maker to their existing App Service Environment you can select “ Deploy to Azure,” modify the template as desired, and deploy to the subscription.  For example, this Web App template:
https://github.com/Azure/azure-quickstart-templates/tree/master/201-web-app-github-deploy


问:
Use Laravel Eloquent joining
Hello I want to retrieve only rows of quizzes that the student didn't take yet
When he completes a quiz the variable done in QuizStudent table is going to become 1

Quiz table

My relationships:
Quiz Modal:

```<code> public function quizstudents(){
        return $this->hasMany('App\Quizstudent');

    }
</code>```

QuizStudent Modal:

```<code>  public function quiz(){
        return $this->belongsTo('App\Quiz','quiz_id');

    }
</code>```

I tried to do it using Query Builder It's working

```<code> $idUser = Auth::User()->id;
        $quizs= DB::table('quizzes')
       ->join('quizstudents', 'quizzes.id', '=', 'quizstudents.quizze_id')
       ->select('quizzes.id')
       ->where([['quizstudents.student_id','=',$idUser],['quizstudents.done','=','0']])

       ->distinct()
        ->get();
</code>```

but the problem is that I get the error on my view

Undefined property: stdClass::$classe

Because in view I use Eloquent style example: $quiz->answer and because I want to use paginate etc ..

So i tried to convert the QueryBuilder code above to eloquent I tried this:

```<code>   $quizs= Quiz::with('quizstudents')->whereIn('classe_id', $classes)->where([['quizstudents.student_id','=',$idUser],['quizstudents.done','=','0']])->orderBy('created_at','desc')->paginate(10);
</code>```

But I get the error

```<code>Column not found: 1054 Unknown column 'quizstudents.student_id' in 'where clause' (SQL: select count(*) as aggregate from `quizzes` where `classe_id` in (1) and (`quizstudents`.`student_id` = 79 and `quizstudents`.`done` = 0))
</code>```

Thank you for your time and sorry in advance

Edit: The two answers in bottom are amazing they are both working
  thanks for the  people who helped, please don't miss the part to set
  up your foreign key in the relationship if it's different than what's
  normal  A little explanation I created the modal Quiz and the
  migration and controller in the same time using modal:make Quiz -mc
  And didn't realise that the plural of quiz is quizzes so when I've set
  the foreign key I thoughet about quizze_id will be the default but
  Laravel is too smart and know that it should be quiz_id as default,
  the luck on english can hurt you beware of this  And sorry for my bad
  english

答:
What about this:

```<code>$doneQuizes = Quizstudents::where('student_id', $idUser) - >get() ;
$quizzes = Quiz::whereNotIn('id', $doneQuizes->pluck('quiz_id')) - >paginate(20);
</code>```

Not sure about your models.... But you get the idea.
I know the other answer is good... But why so much bloatware for a simple task.

Title: Use Laravel Eloquent joining

Body:
Hello I want to retrieve only rows of quizzes that the student didn't take yet
When he completes a quiz the variable done in QuizStudent table is going to become 1

Quiz table

My relationships:
Quiz Modal:

 public function quizstudents(){
        return $this->hasMany('App\Quizstudent');

    }

QuizStudent Modal:

  public function quiz(){
        return $this->belongsTo('App\Quiz','quiz_id');

    }

I tried to do it using Query Builder It's working

 $idUser = Auth::User()->id;
        $quizs= DB::table('quizzes')
       ->join('quizstudents', 'quizzes.id', '=', 'quizstudents.quizze_id')
       ->select('quizzes.id')
       ->where([['quizstudents.student_id','=',$idUser],['quizstudents.done','=','0']])

       ->distinct()
        ->get();

but the problem is that I get the error on my view

Undefined property: stdClass::$classe

Because in view I use Eloquent style example: $quiz->answer and because I want to use paginate etc ..

So i tried to convert the QueryBuilder code above to eloquent I tried this:

   $quizs= Quiz::with('quizstudents')->whereIn('classe_id', $classes)->where([['quizstudents.student_id','=',$idUser],['quizstudents.done','=','0']])->orderBy('created_at','desc')->paginate(10);

But I get the error

Column not found: 1054 Unknown column 'quizstudents.student_id' in 'where clause' (SQL: select count(*) as aggregate from `quizzes` where `classe_id` in (1) and (`quizstudents`.`student_id` = 79 and `quizstudents`.`done` = 0))

Thank you for your time and sorry in advance

Edit: The two answers in bottom are amazing they are both working
  thanks for the  people who helped, please don't miss the part to set
  up your foreign key in the relationship if it's different than what's
  normal  A little explanation I created the modal Quiz and the
  migration and controller in the same time using modal:make Quiz -mc
  And didn't realise that the plural of quiz is quizzes so when I've set
  the foreign key I thoughet about quizze_id will be the default but
  Laravel is too smart and know that it should be quiz_id as default,
  the luck on english can hurt you beware of this  And sorry for my bad
  english

Body:
What about this:

$doneQuizes = Quizstudents::where('student_id', $idUser) - >get() ;
$quizzes = Quiz::whereNotIn('id', $doneQuizes->pluck('quiz_id')) - >paginate(20);

Not sure about your models.... But you get the idea.
I know the other answer is good... But why so much bloatware for a simple task.


问:
How to get documents that contain sub-string in FaunaDB
I'm trying to retrieve all the tasks documents that have the string first in their name.

I currently have the following code, but it only works if I pass the exact name:

```<code>res, err := db.client.Query(
    f.Map(
        f.Paginate(f.MatchTerm(f.Index("tasks_by_name"), "My first task")),
        f.Lambda("ref", f.Get(f.Var("ref"))),
    ),
)
</code>```

I think I can use ContainsStr() somewhere, but I don't know how to use it in my query.

Also, is there a way to do it without using Filter()?  I ask because it seems like it filters after the pagination, and it messes up with the pages

答:
FaunaDB provides a lot of constructs, this makes it powerful but you have a lot to choose from. With great power comes a small learning curve :).

How to read the code samples

To be clear, I use the JavaScript flavor of FQL here and typically expose the FQL functions from the JavaScript driver as follows:

const faunadb = require('faunadb')
const q = faunadb.query
const {
  Not,
  Abort,
  ...
} = q
```

<p>You do have to be careful to export Map like that since it will conflict with JavaScripts map. In that case, you could just use q.Map.</p>

<h1>Option 1: using ContainsStr() & Filter</h1>

<p>Basic usage according to the docs </p>

<pre class="lang-js prettyprint-override"><code>ContainsStr('Fauna', 'a')
</code>```

Of course, this works on a specific value so in order to make it work you need Filter and Filter only works on paginated sets. That means that we first need to get a paginated set. One way to get a paginated set of documents is:

q.Map(
  Paginate(Documents(Collection('tasks'))),
  Lambda(['ref'], Get(Var('ref')))
)
```

<p>But we can do that more efficiently since one get === one read and we don't need the docs, we'll be filtering out a lot of them. It's interesting to know that one index page is also one read so we can define an index as follows:</p>

<pre class="lang-js prettyprint-override"><code>{
  name: "tasks_name_and_ref",
  unique: false,
  serialized: true,
  source: "tasks",
  terms: [],
  values: [
    {
      field: ["data", "name"]
    },
    {
      field: ["ref"]
    }
  ]
}
</code>```

And since we added name and ref to the values, the index will return pages of name and ref which we can then use to filter. We can, for example, do something similar with indexes, map over them and this will return us an array of booleans.

Map(
  Paginate(Match(Index('tasks_name_and_ref'))),
  Lambda(['name', 'ref'], ContainsStr(Var('name'), 'first'))
)
```

<p>Since Filter also works on arrays, we can actually simple replace <strong>Map</strong> with filter. We'll also add a to lowercase to ignore casing and we have what we need: </p>

<pre class="lang-js prettyprint-override"><code>Filter(
  Paginate(Match(Index('tasks_name_and_ref'))),
  Lambda(['name', 'ref'], ContainsStr(LowerCase(Var('name')), 'first'))
)
</code>```

In my case, the result is:

{
  "data": [
    [
      "Firstly, we'll have to go and refactor this!",
      Ref(Collection("tasks"), "267120709035098631")
    ],
    [
      "go to a big rock-concert abroad, but let's not dive in headfirst",
      Ref(Collection("tasks"), "267120846106001926")
    ],
    [
      "The first thing to do is dance!",
      Ref(Collection("tasks"), "267120677201379847")
    ]
  ]
}
```

<h2>Filter and reduced page sizes</h2>

<p>As you mentioned, this is not exactly what you want since it also means that if you request pages of 500 in size, they might be filtered out and you might end up with a page of size 3, then one of 7. You might think, why can't I just get my filtered elements in pages? Well, it's a good idea for performance reasons since it basically checks each value. Imagine you have a massive collection and filter out 99.99 percent. You might have to loop over many elements to get to 500 which all cost reads. We want pricing to be predictable :). </p>

<h1>Option 2: indexes!</h1>

<p>Each time you want to do something more efficient, the answer lies in indexes. FaunaDB provides you with the raw power to implement different search strategies but you'll have to be a bit creative and I'm here to help you with that :). </p>

<h2>Bindings</h2>

<p>In Index bindings, you can transform the attributes of your document and in our first attempt we will split the string into words (I'll implement multiple since I'm not entirely sure which kind of matching you want)</p>

<p>We do not have a string split function but since FQL is easily extended, we can write it ourselves bind to a variable in our host language (in this case javascript), or use one from this community-driven library: https://github.com/shiftx/faunadb-fql-lib</p>

<pre class="lang-js prettyprint-override"><code>function StringSplit(string: ExprArg, delimiter = " "){
    return If(
        Not(IsString(string)),
        Abort("SplitString only accept strings"),
        q.Map(
            FindStrRegex(string, Concat(["[^\\", delimiter, "]+"])),
            Lambda("res", LowerCase(Select(["data"], Var("res"))))
        )
    )
)
</code>```

And use it in our binding.

CreateIndex({
  name: 'tasks_by_words',
  source: [
    {
      collection: Collection('tasks'),
      fields: {
        words: Query(Lambda('task', StringSplit(Select(['data', 'name']))))
      }
    }
  ],
  terms: [
    {
      binding: 'words'
    }
  ]
})
```

<p>Hint, if you are not sure whether you have got it right, you can always throw the binding in <strong>values</strong> instead of terms and then you'll see in the fauna dashboard whether your index actually contains values: </p>

<p><img src="https://i.stack.imgur.com/LUrsZ.png" alt="enter image description here">
What did we do? We just wrote a binding that will transform the value into an <strong>array of values</strong> at the time a document is written. When you index the array of a document in FaunaDB, these values are indexes separately yet point all to the same document which will be very useful for our search implementation. </p>

<p>We can now find tasks that contain the string 'first' as one of their words by using the following query: </p>

```q.Map(
  Paginate(Match(Index('tasks_by_words'), 'first')),
  Lambda('ref', Get(Var('ref')))
)
```

<p>Which will give me the document with name:
"The first thing to do is dance!"</p>

<p>The other two documents didn't contain the exact words, so how do we do that? </p>

<h1>Option 3: indexes and Ngram (exact contains matching)</h1>

<p>To get exact contains matching efficient, you need to use a (still undocumented function since we'll make it easier in the future) function called 'NGram'. Dividing a string in ngrams is a search technique that is often used underneath the hood in other search engines. In FaunaDB we can easily apply it as due to the power of the indexes and bindings. The Fwitter example has an example in it's source code that does autocompletion. This example won't work for your use-case but I do reference it for other users since it's meant for autocompleting short strings, not to search a short string in a longer string like a task. </p>

<p>We'll adapt it though for your use-case. When it comes to searching it's all a tradeoff of performance and storage and in FaunaDB users can choose their tradeoff. Note that in the previous approach, we stored each word separately, with Ngrams we'll split words even further to provide some form of fuzzy matching. The downside is that the index size might become very big if you make the wrong choice (this is equally true for search engines, hence why they let you define different algorithms). </p>

<p>What NGram essentially does is get substrings of a string of a certain length.
For example: </p>

<pre class="lang-js prettyprint-override"><code>NGram('lalala', 3, 3)
</code>```

Will return:

If we know that we won't be searching for strings longer than a certain length, let's say length 10 (it's a tradeoff, increasing the size will increase the storage requirements but allow you to do query for longer strings), you can write the following Ngram generator.

function GenerateNgrams(Phrase) {
  return Distinct(
    Union(
      Let(
        {
          // Reduce this array if you want less ngrams per word.
          indexes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
          indexesFiltered: Filter(
            Var('indexes'),
            // filter out the ones below 0
            Lambda('l', GT(Var('l'), 0))
          ),
          ngramsArray: q.Map(Var('indexesFiltered'), Lambda('l', NGram(LowerCase(Var('Phrase')), Var('l'), Var('l'))))
        },
        Var('ngramsArray')
      )
    )
  )
}
```

<p>You can then write your index as followed: </p>

<pre class="lang-js prettyprint-override"><code>CreateIndex({
  name: 'tasks_by_ngrams_exact',
  // we actually want to sort to get the shortest word that matches first
  source: [
    {
      // If your collections have the same property tht you want to access you can pass a list to the collection
      collection: [Collection('tasks')],
      fields: {
        wordparts: Query(Lambda('task', GenerateNgrams(Select(['data', 'name'], Var('task')))))
      }
    }
  ],
  terms: [
    {
      binding: 'wordparts'
    }
  ]
})
</code>```

And you have an index backed search where your pages are the size you requested.

```<code>q.Map(
  Paginate(Match(Index('tasks_by_ngrams_exact'), 'first')),
  Lambda('ref', Get(Var('ref')))
)
</code>```

Option 4: indexes and Ngrams of size 3 or trigrams (Fuzzy matching)

If you want fuzzy searching, often trigrams are used, in this case our index will be easy so we're not going to use an external function.

CreateIndex({
  name: 'tasks_by_ngrams',
  source: {
    collection: Collection('tasks'),
    fields: {
      ngrams: Query(Lambda('task', Distinct(NGram(LowerCase(Select(['data', 'name'], Var('task'))), 3, 3))))
    }
  },
  terms: [
    {
      binding: 'ngrams'
    }
  ]
})

```

<p>If we would place the binding in values again to see what comes out we'll see something like this:
<img src="https://i.stack.imgur.com/SQtA9.png" alt="enter image description here">
In this approach, we use both trigrams on the indexing side as on the querying side. On the querying side, that means that the 'first' word which we search for will also be divided in Trigrams as follows:</p>

<p><img src="https://i.stack.imgur.com/9TFAv.png" alt="enter image description here"></p>

<p>For example, we can now do a fuzzy search as follows: </p>

<pre class="lang-js prettyprint-override"><code>q.Map(
  Paginate(Union(q.Map(NGram('first', 3, 3), Lambda('ngram', Match(Index('tasks_by_ngrams'), Var('ngram')))))),
  Lambda('ref', Get(Var('ref')))
)
</code>```

In this case, we do actually 3 searches, we are searching for all of the trigrams and union the results. Which will return us all sentences that contain first.

But if we would have miss-spelled it and would have written frst we would still match all three since there is a trigram (rst) that matches.

Body:
I'm trying to retrieve all the tasks documents that have the string first in their name.

I currently have the following code, but it only works if I pass the exact name:

res, err := db.client.Query(
    f.Map(
        f.Paginate(f.MatchTerm(f.Index("tasks_by_name"), "My first task")),
        f.Lambda("ref", f.Get(f.Var("ref"))),
    ),
)

I think I can use ContainsStr() somewhere, but I don't know how to use it in my query.

Also, is there a way to do it without using Filter()?  I ask because it seems like it filters after the pagination, and it messes up with the pages

Body:
FaunaDB provides a lot of constructs, this makes it powerful but you have a lot to choose from. With great power comes a small learning curve :).

How to read the code samples

To be clear, I use the JavaScript flavor of FQL here and typically expose the FQL functions from the JavaScript driver as follows:

const faunadb = require('faunadb')
const q = faunadb.query
const {
  Not,
  Abort,
  ...
} = q

You do have to be careful to export Map like that since it will conflict with JavaScripts map. In that case, you could just use q.Map.

Option 1: using ContainsStr() & Filter

Basic usage according to the docs

ContainsStr('Fauna', 'a')

Of course, this works on a specific value so in order to make it work you need Filter and Filter only works on paginated sets. That means that we first need to get a paginated set. One way to get a paginated set of documents is:

q.Map(
  Paginate(Documents(Collection('tasks'))),
  Lambda(['ref'], Get(Var('ref')))
)

But we can do that more efficiently since one get === one read and we don't need the docs, we'll be filtering out a lot of them. It's interesting to know that one index page is also one read so we can define an index as follows:

{
  name: "tasks_name_and_ref",
  unique: false,
  serialized: true,
  source: "tasks",
  terms: [],
  values: [
    {
      field: ["data", "name"]
    },
    {
      field: ["ref"]
    }
  ]
}

And since we added name and ref to the values, the index will return pages of name and ref which we can then use to filter. We can, for example, do something similar with indexes, map over them and this will return us an array of booleans.

Map(
  Paginate(Match(Index('tasks_name_and_ref'))),
  Lambda(['name', 'ref'], ContainsStr(Var('name'), 'first'))
)

Since Filter also works on arrays, we can actually simple replace Map with filter. We'll also add a to lowercase to ignore casing and we have what we need:

Filter(
  Paginate(Match(Index('tasks_name_and_ref'))),
  Lambda(['name', 'ref'], ContainsStr(LowerCase(Var('name')), 'first'))
)

In my case, the result is:

{
  "data": [
    [
      "Firstly, we'll have to go and refactor this!",
      Ref(Collection("tasks"), "267120709035098631")
    ],
    [
      "go to a big rock-concert abroad, but let's not dive in headfirst",
      Ref(Collection("tasks"), "267120846106001926")
    ],
    [
      "The first thing to do is dance!",
      Ref(Collection("tasks"), "267120677201379847")
    ]
  ]
}

Filter and reduced page sizes

As you mentioned, this is not exactly what you want since it also means that if you request pages of 500 in size, they might be filtered out and you might end up with a page of size 3, then one of 7. You might think, why can't I just get my filtered elements in pages? Well, it's a good idea for performance reasons since it basically checks each value. Imagine you have a massive collection and filter out 99.99 percent. You might have to loop over many elements to get to 500 which all cost reads. We want pricing to be predictable :).

Option 2: indexes!

Each time you want to do something more efficient, the answer lies in indexes. FaunaDB provides you with the raw power to implement different search strategies but you'll have to be a bit creative and I'm here to help you with that :).

Bindings

In Index bindings, you can transform the attributes of your document and in our first attempt we will split the string into words (I'll implement multiple since I'm not entirely sure which kind of matching you want)

We do not have a string split function but since FQL is easily extended, we can write it ourselves bind to a variable in our host language (in this case javascript), or use one from this community-driven library: https://github.com/shiftx/faunadb-fql-lib

function StringSplit(string: ExprArg, delimiter = " "){
    return If(
        Not(IsString(string)),
        Abort("SplitString only accept strings"),
        q.Map(
            FindStrRegex(string, Concat(["[^\\", delimiter, "]+"])),
            Lambda("res", LowerCase(Select(["data"], Var("res"))))
        )
    )
)

And use it in our binding.

CreateIndex({
  name: 'tasks_by_words',
  source: [
    {
      collection: Collection('tasks'),
      fields: {
        words: Query(Lambda('task', StringSplit(Select(['data', 'name']))))
      }
    }
  ],
  terms: [
    {
      binding: 'words'
    }
  ]
})

Hint, if you are not sure whether you have got it right, you can always throw the binding in values instead of terms and then you'll see in the fauna dashboard whether your index actually contains values:

What did we do? We just wrote a binding that will transform the value into an array of values at the time a document is written. When you index the array of a document in FaunaDB, these values are indexes separately yet point all to the same document which will be very useful for our search implementation.

We can now find tasks that contain the string 'first' as one of their words by using the following query:

q.Map(
  Paginate(Match(Index('tasks_by_words'), 'first')),
  Lambda('ref', Get(Var('ref')))
)

Which will give me the document with name:
"The first thing to do is dance!"

The other two documents didn't contain the exact words, so how do we do that?

Option 3: indexes and Ngram (exact contains matching)

To get exact contains matching efficient, you need to use a (still undocumented function since we'll make it easier in the future) function called 'NGram'. Dividing a string in ngrams is a search technique that is often used underneath the hood in other search engines. In FaunaDB we can easily apply it as due to the power of the indexes and bindings. The Fwitter example has an example in it's source code that does autocompletion. This example won't work for your use-case but I do reference it for other users since it's meant for autocompleting short strings, not to search a short string in a longer string like a task.

We'll adapt it though for your use-case. When it comes to searching it's all a tradeoff of performance and storage and in FaunaDB users can choose their tradeoff. Note that in the previous approach, we stored each word separately, with Ngrams we'll split words even further to provide some form of fuzzy matching. The downside is that the index size might become very big if you make the wrong choice (this is equally true for search engines, hence why they let you define different algorithms).

What NGram essentially does is get substrings of a string of a certain length.
For example:

NGram('lalala', 3, 3)

Will return:

If we know that we won't be searching for strings longer than a certain length, let's say length 10 (it's a tradeoff, increasing the size will increase the storage requirements but allow you to do query for longer strings), you can write the following Ngram generator.

function GenerateNgrams(Phrase) {
  return Distinct(
    Union(
      Let(
        {
          // Reduce this array if you want less ngrams per word.
          indexes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
          indexesFiltered: Filter(
            Var('indexes'),
            // filter out the ones below 0
            Lambda('l', GT(Var('l'), 0))
          ),
          ngramsArray: q.Map(Var('indexesFiltered'), Lambda('l', NGram(LowerCase(Var('Phrase')), Var('l'), Var('l'))))
        },
        Var('ngramsArray')
      )
    )
  )
}

You can then write your index as followed:

CreateIndex({
  name: 'tasks_by_ngrams_exact',
  // we actually want to sort to get the shortest word that matches first
  source: [
    {
      // If your collections have the same property tht you want to access you can pass a list to the collection
      collection: [Collection('tasks')],
      fields: {
        wordparts: Query(Lambda('task', GenerateNgrams(Select(['data', 'name'], Var('task')))))
      }
    }
  ],
  terms: [
    {
      binding: 'wordparts'
    }
  ]
})

And you have an index backed search where your pages are the size you requested.

q.Map(
  Paginate(Match(Index('tasks_by_ngrams_exact'), 'first')),
  Lambda('ref', Get(Var('ref')))
)

Option 4: indexes and Ngrams of size 3 or trigrams (Fuzzy matching)

If you want fuzzy searching, often trigrams are used, in this case our index will be easy so we're not going to use an external function.

CreateIndex({
  name: 'tasks_by_ngrams',
  source: {
    collection: Collection('tasks'),
    fields: {
      ngrams: Query(Lambda('task', Distinct(NGram(LowerCase(Select(['data', 'name'], Var('task'))), 3, 3))))
    }
  },
  terms: [
    {
      binding: 'ngrams'
    }
  ]
})

If we would place the binding in values again to see what comes out we'll see something like this:

In this approach, we use both trigrams on the indexing side as on the querying side. On the querying side, that means that the 'first' word which we search for will also be divided in Trigrams as follows:

For example, we can now do a fuzzy search as follows:

q.Map(
  Paginate(Union(q.Map(NGram('first', 3, 3), Lambda('ngram', Match(Index('tasks_by_ngrams'), Var('ngram')))))),
  Lambda('ref', Get(Var('ref')))
)

In this case, we do actually 3 searches, we are searching for all of the trigrams and union the results. Which will return us all sentences that contain first.

But if we would have miss-spelled it and would have written frst we would still match all three since there is a trigram (rst) that matches.


问:
Is there a way to connect to sqlite3 database via python socket?
I'm trying to write a socket client program in Python that can request the following information from a server: school fees for the term of a particular student, the balance(if part of the fees has been paid) and the client must request an option to pay the fees.
I need to create the students database and login system.</p>

答:
SQLite3 cannot be used remotely.

Reference: https://stackoverflow.com/a/8357696/13564014


问:
PayPal Webhook Verification Java SDK
I am currently integrating the "PayPal Smart Payment Buttons" into a WebApp.
Passing custom fields and receiving a Webhook / Purchase Confirmation with this data works quite fine.

I am having trouble with validating a received Webhook. The Documentation is poor and leads mit either to v1 (deprecated) or to v2 Java SDK where nothing is mentioned about Webhook verification.

I integrated the following SDK in Java.

```<code><dependency>
            <groupId>com.paypal.sdk</groupId>
            <artifactId>checkout-sdk</artifactId>
            <version>1.0.2</version>
        </dependency>
</code>```

But I am not able to find a way to verify a Webhook.
Did I read over something or how can I achieve the Webhook verification?

答:
There is no supported SDK for webhook integration

(The references to old SDKs on this page: https://developer.paypal.com/docs/integration/direct/webhooks/rest-webhooks/#verify-event-notifications are out of date)

So, you have some choices.

DIY verification, using the information in the event headers:
https://developer.paypal.com/docs/integration/direct/webhooks/notification-messages/#event-headers

Direct integration with the HTTPS APIs:
https://developer.paypal.com/docs/api/webhooks/v1/#verify-webhook-signature

Don't use webhooks, at all, for anything, and instead switch your integration to a server side implementation that does not need webhooks.

The last option is actually what I would recommend.

Here is the server-side SDK you need: https://github.com/paypal/Checkout-Java-SDK

With that you would implement two routes, one for "Set Up Transaction" (create order), and one for "Capture Transaction" (capture the order). There is a guide for these steps here: https://developer.paypal.com/docs/checkout/reference/server-integration/

The web front-end that will then connect to those two server-side routes is: https://developer.paypal.com/demo/checkout/#/pattern/server

There is no need for webhooks when using this server-side integration; you have an immediate response of success or failure when doing the capture on the server.

Title: PayPal Webhook Verification Java SDK

Body:
I am currently integrating the "PayPal Smart Payment Buttons" into a WebApp.
Passing custom fields and receiving a Webhook / Purchase Confirmation with this data works quite fine.

I am having trouble with validating a received Webhook. The Documentation is poor and leads mit either to v1 (deprecated) or to v2 Java SDK where nothing is mentioned about Webhook verification.

I integrated the following SDK in Java.

<dependency>
            <groupId>com.paypal.sdk</groupId>
            <artifactId>checkout-sdk</artifactId>
            <version>1.0.2</version>
        </dependency>

But I am not able to find a way to verify a Webhook.
Did I read over something or how can I achieve the Webhook verification?


问:
Android hiding keyboard for autocomplete
I am trying to hide keyboard when I select one of the autocomplete results.
This is my code for the autocomplete.

```<code>input_address.setFocusable(false);
input_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Place.Field> fieldList = Arrays.asList(Place.Field.ADDRESS, Place.Field.LAT_LNG, Place.Field.NAME);
                Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fieldList).build(MainActivity.this);
                startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
            }
        });

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AUTOCOMPLETE_REQUEST_CODE && resultCode == RESULT_OK) {

            Place place = Autocomplete.getPlaceFromIntent(data);
            input_address.setText(place.getName());
            latitude = place.getLatLng().latitude;
            longitude = place.getLatLng().longitude;
            departure = "\"" + latitude + "\"" + ":" + "\"" + longitude + "\"";
        }
        if (resultCode == AutocompleteActivity.RESULT_ERROR) {
            Status status = Autocomplete.getStatusFromIntent(data);
            Toast.makeText(getApplicationContext(), status.getStatusMessage(),
                    Toast.LENGTH_SHORT).show();
        }

}
</code>```

And this is my xml code for input_address

```<code><EditText
        android:id="@+id/input_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_weight="1"
        android:hint="departure"
        android:textSize="20sp"
        android:inputType="text"
        android:imeOptions="actionDone"
        android:onClick="startAutocompleteActivity"
/>
</code>```

How should I change my code to have keyboard when I click autocomplete result?
I tried adding under OnActivityResult with IMM but it didn't work. Please Help Thank you.

答:
```<code>input_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Place.Field> fieldList = Arrays.asList(Place.Field.ADDRESS, Place.Field.LAT_LNG, Place.Field.NAME);

//Code for hiding keyboard
 final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);

                Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fieldList).build(MainActivity.this);
                startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
            }
        });
</code>```

Body:
I am trying to hide keyboard when I select one of the autocomplete results.
This is my code for the autocomplete.

input_address.setFocusable(false);
input_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Place.Field> fieldList = Arrays.asList(Place.Field.ADDRESS, Place.Field.LAT_LNG, Place.Field.NAME);
                Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fieldList).build(MainActivity.this);
                startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
            }
        });

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AUTOCOMPLETE_REQUEST_CODE && resultCode == RESULT_OK) {

            Place place = Autocomplete.getPlaceFromIntent(data);
            input_address.setText(place.getName());
            latitude = place.getLatLng().latitude;
            longitude = place.getLatLng().longitude;
            departure = "\"" + latitude + "\"" + ":" + "\"" + longitude + "\"";
        }
        if (resultCode == AutocompleteActivity.RESULT_ERROR) {
            Status status = Autocomplete.getStatusFromIntent(data);
            Toast.makeText(getApplicationContext(), status.getStatusMessage(),
                    Toast.LENGTH_SHORT).show();
        }

}

And this is my xml code for input_address

<EditText
        android:id="@+id/input_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_weight="1"
        android:hint="departure"
        android:textSize="20sp"
        android:inputType="text"
        android:imeOptions="actionDone"
        android:onClick="startAutocompleteActivity"
/>

How should I change my code to have keyboard when I click autocomplete result?
I tried adding under OnActivityResult with IMM but it didn't work. Please Help Thank you.


问:
How to compare "4A4B4C" (string shows hex value) actual string is "JKL"
I am getting a string "4A4B4C4D4E4F".. it is equal to a string ("JKLMNO")

How can I check this type of string in c++.. (one string shows the hexadecimal representation of another)

hexadecimal value of

```<code>J=4A, K=4B, L=4C
</code>```

答:
One way is to convert each two hex digits from your hex string and convert it into a decimal value and then compare this converted numeric with the ASCII value of the string you have to be compared.

A sample code is shown:

```<code>int main (void)
{
  char str1[]="4A4B4C4D4E4F";
  char str2[]="JKLMNO";
  char buffer[3];
  int n, i = 0, j = 0, value, flag = 1;

  n = strlen (str1);
  while (i<n)
  {
    buffer[0] = str1[i++];
    buffer[1] = str1[i++];
    buffer[2] = '\0';
    value = strtol (buffer, NULL, 16);
    if (str2[j] != value)
    {
      flag = 0;
      break;
    }
    j++;
  }

  if (flag)
    printf ("\nMatch");
  else
    printf ("\nNo Match");

  printf ("\n");
  reutrn 0;
}
</code>```

Body:
I am getting a string "4A4B4C4D4E4F".. it is equal to a string ("JKLMNO")

How can I check this type of string in c++.. (one string shows the hexadecimal representation of another)

hexadecimal value of

J=4A, K=4B, L=4C

Body:
One way is to convert each two hex digits from your hex string and convert it into a decimal value and then compare this converted numeric with the ASCII value of the string you have to be compared.

A sample code is shown:

int main (void)
{
  char str1[]="4A4B4C4D4E4F";
  char str2[]="JKLMNO";
  char buffer[3];
  int n, i = 0, j = 0, value, flag = 1;

  n = strlen (str1);
  while (i<n)
  {
    buffer[0] = str1[i++];
    buffer[1] = str1[i++];
    buffer[2] = '\0';
    value = strtol (buffer, NULL, 16);
    if (str2[j] != value)
    {
      flag = 0;
      break;
    }
    j++;
  }

  if (flag)
    printf ("\nMatch");
  else
    printf ("\nNo Match");

  printf ("\n");
  reutrn 0;
}