问:
React Cannot read property 'lastName' of undefined
I'm trying to merge data from two API in the new API but I'm getting error Uncaught TypeError: Cannot read property 'lastName' of undefined. This is happening because is not finding lastName when it missing in API2. In this case, I want to initialize it as empty string if not able to find that in the merged API.

API 1 look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
}
}
</code>```

API2 look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1'
 }
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3'
}
}
</code>```

Merged API look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second Test' //lastName from API 2 + name from API 1
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
lastName: '' //lastName from API 2 + name from API 1
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1 Test 2' //lastName from API 2 + name from API 1
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3 Test 3' //lastName from API 2 + name from API 1
}
</code>```

Fetched data:

```<code>const [api1, setApi1] = useState([]);
const [api2, setApi2] = useState([]);
const [mergeApi, setMergeAPi] = useState([]);

useEffect(() => {
  fetch('api1')
  .then((response) => {
    setApi1(response);
  });
});

useEffect(() => {
  fetch('api2')
  .then((response) => {
    setApi2(response);
  });
});

useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name;
    });
    return {
      ...api1,
      // name: `${d.name} - ${d.lastName}`
      name: d ? `${d.name} - ${d.lastName}` : ""; // solution there
    }
  });
});
</code>```

答:
I have found solution for that:</p>

```<code>useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name;
    });
    return {
      ...api1,
      // name: `${d.name} - ${d.lastName}`
      name: d ? `${d.name} - ${d.lastName}` : ""; // solution there
    }
  });
});
</code>```

Body:
I'm trying to merge data from two API in the new API but I'm getting error Uncaught TypeError: Cannot read property 'lastName' of undefined. This is happening because is not finding lastName when it missing in API2. In this case, I want to initialize it as empty string if not able to find that in the merged API.

API 1 look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
}
}

API2 look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1'
 }
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3'
}
}

Merged API look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second Test' //lastName from API 2 + name from API 1
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
lastName: '' //lastName from API 2 + name from API 1
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1 Test 2' //lastName from API 2 + name from API 1
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3 Test 3' //lastName from API 2 + name from API 1
}

Fetched data:

const [api1, setApi1] = useState([]);
const [api2, setApi2] = useState([]);
const [mergeApi, setMergeAPi] = useState([]);

useEffect(() => {
  fetch('api1')
  .then((response) => {
    setApi1(response);
  });
});

useEffect(() => {
  fetch('api2')
  .then((response) => {
    setApi2(response);
  });
});

useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name;
    });
    return {
      ...api1,
      // name: `${d.name} - ${d.lastName}`
      name: d ? `${d.name} - ${d.lastName}` : ""; // solution there
    }
  });
});

Body:
I have found solution for that:

useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name;
    });
    return {
      ...api1,
      // name: `${d.name} - ${d.lastName}`
      name: d ? `${d.name} - ${d.lastName}` : ""; // solution there
    }
  });
});


来源: stackexchange

问:
Mac pip install mysql-python unsuccessful
I installed MySQL and Workbench from website. I have a django project whose requirements.txt:

```<code>Django==1.11.12
djangorestframework==3.8.2
django-cors-headers==2.2.0
drfdocs==0.0.11
mysql-python==1.2.5
django-rest-auth==0.9.3
django-allauth==0.35.0
nltk==3.2.5
django-extensions==2.0.7
pyparsing==2.2.0
pydot==1.2.4
</code>```

When I run

```<code>pip install -r requirements.txt
</code>```

I got an error mysql_config not found. To solve this I ran

```<code>PATH=$PATH:/usr/local/mysql/bin
</code>```

It now throws

```<code>    _mysql.c:44:10: fatal error: 'my_config.h' file not found
    #include "my_config.h"
             ^~~~~~~~~~~~~
    1 error generated.
    error: command 'cc' failed with exit status 1

    ----------------------------------------
Command ""/Users/nitish/gitProjects/Vision Backlog/vb_env/bin/python" -u -c "import setuptools, tokenize;__file__='/private/var/folders/ql/_w2_rlvs2351pdcnzhn04sf40000gn/T/pip-install-M4ue9E/mysql-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/ql/_w2_rlvs2351pdcnzhn04sf40000gn/T/pip-record-7OCzf1/install-record.txt --single-version-externally-managed --compile --install-headers "/Users/nitish/gitProjects/Vision Backlog/vb_env/include/site/python2.7/mysql-python"" failed with error code 1 in /private/var/folders/ql/_w2_rlvs2351pdcnzhn04sf40000gn/T/pip-install-M4ue9E/mysql-python/
</code>```

Why is this happening?

UPDATE: following bellow solution threw:

```<code>Collecting MySQL-python
  Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/ql/_w2_rlvs2351pdcnzhn04sf40000gn/T/pip-install-X6b4rU/MySQL-python/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 53, in get_config
        libraries = [ dequote(i[2:]) for i in libs if i.startswith(compiler_flag("l")) ]
      File "setup_posix.py", line 8, in dequote
        if s[0] in "\"'" and s[0] == s[-1]:
    IndexError: string index out of range
</code>```

答:
```<code>brew install mysql@5.7
export PATH="/usr/local/Cellar/mysql@5.7/5.7.29/bin:$PATH"
export LDFLAGS="-L/usr/local/Cellar/mysql@5.7/5.7.29/lib -L/usr/local/Cellar/openssl@1.1/1.1.1d/lib"
export CPPFLAGS="-I/usr/local/Cellar/mysql@5.7/5.7.29/include -I/usr/local/Cellar/openssl@1.1/1.1.1d/include"
/Users/tivanli/source/bk_project/pizza/venv/bin/pip install MySQL-python==1.2.5
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I installed MySQL and Workbench from website. I have a django project whose requirements.txt:

Django==1.11.12
djangorestframework==3.8.2
django-cors-headers==2.2.0
drfdocs==0.0.11
mysql-python==1.2.5
django-rest-auth==0.9.3
django-allauth==0.35.0
nltk==3.2.5
django-extensions==2.0.7
pyparsing==2.2.0
pydot==1.2.4

When I run

pip install -r requirements.txt

I got an error mysql_config not found. To solve this I ran

PATH=$PATH:/usr/local/mysql/bin

It now throws

    _mysql.c:44:10: fatal error: 'my_config.h' file not found
    #include "my_config.h"
             ^~~~~~~~~~~~~
    1 error generated.
    error: command 'cc' failed with exit status 1

    ----------------------------------------
Command ""/Users/nitish/gitProjects/Vision Backlog/vb_env/bin/python" -u -c "import setuptools, tokenize;__file__='/private/var/folders/ql/_w2_rlvs2351pdcnzhn04sf40000gn/T/pip-install-M4ue9E/mysql-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/ql/_w2_rlvs2351pdcnzhn04sf40000gn/T/pip-record-7OCzf1/install-record.txt --single-version-externally-managed --compile --install-headers "/Users/nitish/gitProjects/Vision Backlog/vb_env/include/site/python2.7/mysql-python"" failed with error code 1 in /private/var/folders/ql/_w2_rlvs2351pdcnzhn04sf40000gn/T/pip-install-M4ue9E/mysql-python/

Why is this happening?

UPDATE: following bellow solution threw:

Collecting MySQL-python
  Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/ql/_w2_rlvs2351pdcnzhn04sf40000gn/T/pip-install-X6b4rU/MySQL-python/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "setup_posix.py", line 53, in get_config
        libraries = [ dequote(i[2:]) for i in libs if i.startswith(compiler_flag("l")) ]
      File "setup_posix.py", line 8, in dequote
        if s[0] in "\"'" and s[0] == s[-1]:
    IndexError: string index out of range


问:
Masking each word in sentence except first and last letter with a fixed amount of asterisks
I want to mask except first and last letter of word in sentence in oracle.

My query is:

```<code>select regexp_replace('Hello World', '(?<!^.?).(?!.?$)','*') as str2
   from dual;
</code>```

result: Hello World

Expect Result: H***o W***d

答:
You may use

```<code>SELECT REGEXP_REPLACE('Hello World', '(\w)\w*(\w)', '\1***\2') as str2 from dual
</code>```

See an online demo

The regex will only match at least two-letter words, so any one-letter word will remain unaffected.

Pattern details

(\w) - Group 1 (later, referred to via \1): any word (letter, digit or _) char

\w* - any 0+ word chars as many as possible

(\w) - Group 2 (later, referred to via \2): any word char.

The \1***\2 replacement pattern replaces the match with the contents of Group 1, then three asterisks (adjust as you see fit), and then the contents of Group 2.

Body:
I want to mask except first and last letter of word in sentence in oracle.

My query is:

select regexp_replace('Hello World', '(?<!^.?).(?!.?$)','*') as str2
   from dual;

result: Hello World

Expect Result: H***o W***d

Body:
You may use

SELECT REGEXP_REPLACE('Hello World', '(\w)\w*(\w)', '\1***\2') as str2 from dual

See an online demo

The regex will only match at least two-letter words, so any one-letter word will remain unaffected.

Pattern details

(\w) - Group 1 (later, referred to via \1): any word (letter, digit or _) char

\w* - any 0+ word chars as many as possible

(\w) - Group 2 (later, referred to via \2): any word char.

The \1***\2 replacement pattern replaces the match with the contents of Group 1, then three asterisks (adjust as you see fit), and then the contents of Group 2.


问:
How to get a calculated column based on 2 different column in Power Query
Appreciate for any helps and suggestions.
I have a table structure as following:-

```<code>  Date,   Product Code   ,Result ,Schedule
  Day1,   A              ,0      ,0
  Day2,   A              ,20     ,100
  Day3,   A              ,200    ,100
</code>```

How can i add a new column [Different] which reset by product code

```<code>  Date   ,Product Code   ,Result ,Schedule ,Different
  Day1   ,A              ,0      ,0        ,0
  Day2   ,A              ,20     ,100      ,-80
  Day3   ,A              ,200    ,100      ,20
</code>```

Where different = previous's different + result - schedule

thank you.

答:
Paste code below in Home ... Advanced Editor, save, and name it fnRunningSum

It will create a function to do a cumultive running total on column named Amount

```<code>(MyTable as table) =>
let Source = Table.Buffer(MyTable),
MyColumn="Amount",
TableType = Value.Type(Table.AddColumn(Source, "Cumul", each null, type number)),
Cumulative = List.Skip(List.Accumulate(Table.Column(Source,MyColumn),{0},(cumulative,MyColumn) => cumulative & {List.Last(cumulative) + MyColumn})),
Cumu = Table.FromColumns(Table.ToColumns(Source)&{Cumulative},TableType)
in Cumu
</code>```

Load your data into powerquery, here assumed to be in range Table1. Paste code below in Home ... Advanced Editor...

What it does is (1) add a new column that is Result-Schedule (2) Group on Product Code and cumulative sum the new column (3) Expand to get the columns back

```<code>letSource = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Added Custom" = Table.AddColumn(Source, "Amount", each [Result]-[Schedule]),
#"Grouped Rows" = Table.Group(#"Added Custom" , {"Product Code"}, {{"AllData", fnRunningSum}}),
#"Expanded AllData" = Table.ExpandTableColumn(#"Grouped Rows", "AllData", {"Date", "Result", "Schedule", "Cumul"}, {"Date", "Result", "Schedule", "Different"})
in #"Expanded AllData"
</code>```

Body:
Appreciate for any helps and suggestions.
I have a table structure as following:-

  Date,   Product Code   ,Result ,Schedule
  Day1,   A              ,0      ,0
  Day2,   A              ,20     ,100
  Day3,   A              ,200    ,100

How can i add a new column [Different] which reset by product code

  Date   ,Product Code   ,Result ,Schedule ,Different
  Day1   ,A              ,0      ,0        ,0
  Day2   ,A              ,20     ,100      ,-80
  Day3   ,A              ,200    ,100      ,20

Where different = previous's different + result - schedule

thank you.

Body:
Paste code below in Home ... Advanced Editor, save, and name it fnRunningSum

It will create a function to do a cumultive running total on column named Amount

(MyTable as table) =>
let Source = Table.Buffer(MyTable),
MyColumn="Amount",
TableType = Value.Type(Table.AddColumn(Source, "Cumul", each null, type number)),
Cumulative = List.Skip(List.Accumulate(Table.Column(Source,MyColumn),{0},(cumulative,MyColumn) => cumulative & {List.Last(cumulative) + MyColumn})),
Cumu = Table.FromColumns(Table.ToColumns(Source)&{Cumulative},TableType)
in Cumu

Load your data into powerquery, here assumed to be in range Table1. Paste code below in Home ... Advanced Editor...

What it does is (1) add a new column that is Result-Schedule (2) Group on Product Code and cumulative sum the new column (3) Expand to get the columns back

letSource = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Added Custom" = Table.AddColumn(Source, "Amount", each [Result]-[Schedule]),
#"Grouped Rows" = Table.Group(#"Added Custom" , {"Product Code"}, {{"AllData", fnRunningSum}}),
#"Expanded AllData" = Table.ExpandTableColumn(#"Grouped Rows", "AllData", {"Date", "Result", "Schedule", "Cumul"}, {"Date", "Result", "Schedule", "Different"})
in #"Expanded AllData"


问:
Use dotPeek from within Visual Studio without ReSharper
dotPeek is a free .NET decompiler. While being a standalone tool, it is also part of ReSharper: If you tell ReSharper to navigate to the definition of a class which is located in a .dll file, it will automatically decompile the file and present you the source code.

I don't want to use ReSharper. Can I get the same or a similar functionality without ReSharper or is this a ReSharper-only feature?

答:
From dotPeek 2019.3.2 at least, an option exists to integrate dotPeek to Visual Studio.

EDIT: I've looked into this option and, what it seems it only do, is that within dotPeek, it allows you to export a dll into a visual studio project. So this does not answer your question, sorry.

ContentLicense: CC BY-SA 3.0


问:
Why am I getting TypeError: _this.props."functionName" is not a function ReactJS
So I have the following scripts, it has been a while since I edited them but as far as I can remember they were working flawlessly last time I checked. But now, for some reason the editProfile function has stopped working. I was thinking it was a binding issue but I can't seem to figure out the answer. I tried adding the function to the script itself instead of importing it from authActions but still, that did not work. So in short the issue is in the following piece of code (the following excerpt is from the second script posted below)

```<code>handleSubmit = (e) => {
            e.preventDefault();
            this.props.editProfile(this.state);
            this.props.onClose()

        }
</code>```

both edit profile and onClose are not working. The error is listed below. Both functions throw the same error. In other words if I remove 'this.props.editProfile(this.state);' I'll get the same error for 'this.props.onClose()'

```<code>import {storage} from 'config/fbConfig';
import {toastr} from 'react-redux-toastr'

export const signIn = (credentials) => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().signInWithEmailAndPassword(
      credentials.email,
      credentials.password
    ).then(() => {
      dispatch({ type: 'LOGIN_SUCCESS' });
      toastr.success('ברוכים הבאים לאתר שותפים')
      }).catch((err) => {
      dispatch({ type: 'LOGIN_ERROR', err });
      toastr.error('אירעה שגיאת אימות.')
    });

  }
}

export const signInwithPhoneNumber = () => {
  return (dispatch, getState, {
    getFirebase
  }) => {
   // const firebase = getFirebase();

  }
}

export const signOut = () => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().signOut().then(() => {
      dispatch({ type: 'SIGNOUT_SUCCESS' })
    });
  }
}

export const signUp = (newUser) => {
  return (dispatch, getState, {getFirebase, getFirestore}) => {
    const firebase = getFirebase();
    const firestore = getFirestore();

    firebase.auth().createUserWithEmailAndPassword(
      newUser.email,
      newUser.password
    ).then(resp => {
      return firestore.collection('Partners').doc(resp.user.uid).set({
        displayName: newUser.displayName,
        phoneNumber: newUser.phoneNumber,
        email: newUser.email,
        location: null,
        displayImage: "https://wattleparkkgn.sa.edu.au/wp-content/uploads/2017/06/placeholder-profile-sq.jpg",

      });
    }).then(() => {
      dispatch({ type: 'SIGNUP_SUCCESS' });
      //dispatch(send_EmailVerification())
    }).catch((err) => {
      dispatch({ type: 'SIGNUP_ERROR', err});
    });
  }
}

export const editProfile = (profile) => {
  return (dispatch, getState, {
    getFirebase, getFirestore
  }) => {
    const firestore = getFirestore();
      const Puid = getState().firebase.auth.uid;
      if (profile.uploadedImages !== ''){
       const uploadedImages = profile.uploadedImages
            const uploadTask = storage.ref(`images/${uploadedImages.name}`).put(uploadedImages);
            uploadTask.on('state_changed',
                (snapshot) => {
                    // progrss function ....
                    const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
                    console.log(progress);
                },
                (error) => {
                    // error function ....
                    console.log(error);
                },
                () => {
                    // complete function ....
                    storage.ref('images').child(uploadedImages.name).getDownloadURL().then(url => {
                      // displayImage = url;

                      firestore.collection('Partners').doc(Puid).set({
                        displayName: profile.displayName,
                        phoneNumber: profile.phoneNumber,
                        location: profile.location,
                        displayImage: url

                      }).then(() => {
                        toastr.success('הודעה', 'הפרופיל עודכן בהצלחה')
                        dispatch({
                          type: 'EDIT_PROFILE_SUCCESS'
                        })

                      }).catch(function (error) {
                        // An error happened.
                        dispatch({
                          type: 'EDIT_PROFILE_ERROR'
                        })
                        toastr.error('אופס! אירעה תקלה :|')
                      });
                    })
                });
              }
              else{

                 firestore.collection('Accounts').doc(Puid).set({
                   ...profile,
                   displayName: profile.displayName,
                   phoneNumber: profile.phoneNumber,
                   location: profile.location,
                   displayImage: profile.displayImage

                 }).then(() => {
                   dispatch({
                     type: 'EDIT_PROFILE_SUCCESS'
                   })
                   toastr.success('הודעה', 'הפרופיל עודכן בהצלחה')
                 }).catch(function (error) {
                   // An error happened.
                   dispatch({
                     type: 'EDIT_PROFILE_ERROR'
                   })
                   toastr.error('אופס! לא יכולנו לעדכן את הפרופיל')
                 });
              }

  }
}

export const send_EmailVerification = () => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().currentUser.sendEmailVerification().then(() => {
      //email send
      dispatch({ type: 'EMAIL_VERIFICATION_SUCCESS' })
      toastr.info('הודעה', 'הודעת אימות נשלחה למייל')
    }).catch(function (error) {
      // An error happened.
      toastr.error('The message')
    });;
  }
}
</code>```

This is the buildProfile script that needs to use "editProfile" function from above script.

```<code>import React, { Component } from 'react'
import 'assets/css/Css.css'
import {editProfile} from 'store/actions/authActions'

import { Button,Icon} from 'react-materialize';

import GridContainer from "components/Grid/GridContainer.jsx";
import GridItem from "components/Grid/GridItem.jsx";
import Card from "components/Card/Card.jsx";
import withStyles from "@material-ui/core/styles/withStyles";

import { connect } from 'react-redux'
import { firestoreConnect } from 'react-redux-firebase'
import { compose } from 'redux'
import { Hidden } from '@material-ui/core';

import $ from 'jquery';
import 'react-redux-toastr/lib/css/react-redux-toastr.min.css'
import Properties from 'components/Profile/properties'

import { clearSelectedProperty } from "../../store/actions/propertyActions";

// @material-ui/icons

class BuildProfile extends Component {
    state = {
        displayName: (this.props.profile !== null) ? this.props.profile.displayName : '',
        location: (this.props.profile !== null) ? this.props.profile.location : '',
        displayImage: (this.props.profile !== null) ? this.props.profile.displayImage : '',
        phoneNumber: (this.props.profile !== null) ? this.props.profile.phoneNumber : '',
        uploadedImages: '',
        file:''
     }

    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
    }

    handleImagesUpload = (e) => {
        if (e.target.files) {
            const uploadedImages = e.target.files[0]
            const file =  URL.createObjectURL(e.target.files[0])
            this.setState(() => ({
                uploadedImages,
                file
            }));
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.editProfile(this.state);
        this.props.onClose()

    }
    handleSelectChange = (e) => {
        this.setState({
            location: e.target.value
        })
    }

    render() {

        const {profile, onClose} = this.props;
        const {
            displayName,
            location, displayImage, phoneNumber
        } = this.state
        const locationOptions = [
            {label: "תל אביב", value: 'תל אביב', type: "location"},
            {label: " ירושליים ", value: 'ירושליים', type: "location"},
            {label: "חיפה", value: 'חיפה', type: "location"}
        ];
        //if (auth.uid) return <Redirect to='/' />

        return (

            <GridContainer  justify="center">
                <GridItem xs={13} sm={12} md={4}>
                <Card >

<form onSubmit={this.handleSubmit}>
                        <div className="modal-header"><h3 style={{marginRight:-17}} className='center-align'>יצרירת פרופיל</h3></div>
                        <div className="modal-content" style={{padding:"6rem",marginTop:-40}}>
                        <div className="col s5 m4 l3 center">

                                    <img className="profile-pic circle" height="150" style={{maxWidth:200,marginTop:-25}}
                                         src={this.state.uploadedImages? this.state.file :  "https://wattleparkkgn.sa.edu.au/wp-content/uploads/2017/06/placeholder-profile-sq.jpg"}
                                         alt="profile pic"

                                         />

                                         {console.log(this.state.file)}
                                         <div className="row">

                                                                                <input type="file" id="uploadedImages" onChange={this.handleImagesUpload}  style={{marginRight:38,maxWidth:150,overflowX:"auto"}}/>
                                                                                </div>
                                </div>
                            <div className="row">

                                    <div className="input-field" style={{width:300}}>
                                        <input id="displayName" type="text" className="validate"

                                        placeholder={null}

                                               value={this.props.displayName}
                                               onChange={this.handleChange}/>
                                        <label className="active" htmlFor="displayName">שם מלא</label>
                                    </div>

                            </div>
                            <div className="row" style={{marginTop:-10}}>
                                    <div className="input-field" style={{width:300}}>
                                        <input id="phoneNumber" type="text" className="validate"
                                               value={profile.phoneNumber}
                                               onChange={this.handleChange}/>
                                        <label className="active" htmlFor="phoneNumber">מס׳ טלפון</label>
                                    </div>
                                </div>

                                <div className="col s12 m6 input-field">

                                    <select id="location" style={{display:"block", marginRight:-10}}
                                            onChange={this.handleSelectChange}
                                            value={null}
                                            required>
                                        <option value="" disabled defaultValue>Location
                                        </option>
                                        {locationOptions.map(function (option) {
                                            return <option key={option.value}
                                                           value={option.value}>{option.label}</option>
                                        })}
                                    </select>
                                    <label style={{marginTop:-37,marginRight:-10, fontSize:"12px"}}>איזור</label>

                                </div>
                                <div className="col s12 m6 input-field" style={{marginTop:30,marginRight:60}}>
                        <Button type="submit" waves="light" style={{backgroundColor:"#ff6969"}}>
המשך
</Button>

             </div>

         </div>

                    </form>
                    </Card>

                    </GridItem>
                            </GridContainer>

        )
    }
}

const mapStateToProps = (state, props) => {
    console.log(state,props)
     return {
       authError: state.auth.authError,
       auth: state.firebase.auth,
       properties: state.firestore.ordered.Properties,
       partner: state.firestore.ordered.Partners,
       profile: state.firebase.profile,
       selectedProperty: state.property,
       invitation: state.firestore.ordered.Invitations

     }

   }

   const mapDispatchToProps = (dispatch) => {
     return {

     }
   }

   export default compose(

     connect(mapStateToProps, mapDispatchToProps),
     firestoreConnect((props) => {
         if (!props.auth.uid) {
           props.history.push('/signin')
           return []
         }
         let propid = null
            if(props.invitation !== undefined){
                propid = props.invitation[0].propid
            }
            return [
             {
               collection: 'Invitations',
              doc: props.match.params.inviteid

             },
             {
               collection: 'Partners',
               doc: props.auth.uid
             },
             {
                 collection: 'Properties',
                 doc: propid
             },

           ]
        }

    )
    )(BuildProfile)
</code>```

I keep getting the following error

答:
BuildProfile component does not have a prop editProfile in props or it is not a function.
I see you are importing the editProfile function:

```<code>import {editProfile} from 'store/actions/authActions'
</code>```

Probably you want to call editProfile like this:

```<code>handleSubmit = (e) => {
            e.preventDefault();
            editProfile(this.state);
            onClose();
}
</code>```

Body:
So I have the following scripts, it has been a while since I edited them but as far as I can remember they were working flawlessly last time I checked. But now, for some reason the editProfile function has stopped working. I was thinking it was a binding issue but I can't seem to figure out the answer. I tried adding the function to the script itself instead of importing it from authActions but still, that did not work. So in short the issue is in the following piece of code (the following excerpt is from the second script posted below)

handleSubmit = (e) => {
            e.preventDefault();
            this.props.editProfile(this.state);
            this.props.onClose()

        }

both edit profile and onClose are not working. The error is listed below. Both functions throw the same error. In other words if I remove 'this.props.editProfile(this.state);' I'll get the same error for 'this.props.onClose()'

import {storage} from 'config/fbConfig';
import {toastr} from 'react-redux-toastr'

export const signIn = (credentials) => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().signInWithEmailAndPassword(
      credentials.email,
      credentials.password
    ).then(() => {
      dispatch({ type: 'LOGIN_SUCCESS' });
      toastr.success('ברוכים הבאים לאתר שותפים')
      }).catch((err) => {
      dispatch({ type: 'LOGIN_ERROR', err });
      toastr.error('אירעה שגיאת אימות.')
    });

  }
}

export const signInwithPhoneNumber = () => {
  return (dispatch, getState, {
    getFirebase
  }) => {
   // const firebase = getFirebase();

  }
}

export const signOut = () => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().signOut().then(() => {
      dispatch({ type: 'SIGNOUT_SUCCESS' })
    });
  }
}

export const signUp = (newUser) => {
  return (dispatch, getState, {getFirebase, getFirestore}) => {
    const firebase = getFirebase();
    const firestore = getFirestore();

    firebase.auth().createUserWithEmailAndPassword(
      newUser.email,
      newUser.password
    ).then(resp => {
      return firestore.collection('Partners').doc(resp.user.uid).set({
        displayName: newUser.displayName,
        phoneNumber: newUser.phoneNumber,
        email: newUser.email,
        location: null,
        displayImage: "https://wattleparkkgn.sa.edu.au/wp-content/uploads/2017/06/placeholder-profile-sq.jpg",

      });
    }).then(() => {
      dispatch({ type: 'SIGNUP_SUCCESS' });
      //dispatch(send_EmailVerification())
    }).catch((err) => {
      dispatch({ type: 'SIGNUP_ERROR', err});
    });
  }
}

export const editProfile = (profile) => {
  return (dispatch, getState, {
    getFirebase, getFirestore
  }) => {
    const firestore = getFirestore();
      const Puid = getState().firebase.auth.uid;
      if (profile.uploadedImages !== ''){
       const uploadedImages = profile.uploadedImages
            const uploadTask = storage.ref(`images/${uploadedImages.name}`).put(uploadedImages);
            uploadTask.on('state_changed',
                (snapshot) => {
                    // progrss function ....
                    const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
                    console.log(progress);
                },
                (error) => {
                    // error function ....
                    console.log(error);
                },
                () => {
                    // complete function ....
                    storage.ref('images').child(uploadedImages.name).getDownloadURL().then(url => {
                      // displayImage = url;

                      firestore.collection('Partners').doc(Puid).set({
                        displayName: profile.displayName,
                        phoneNumber: profile.phoneNumber,
                        location: profile.location,
                        displayImage: url

                      }).then(() => {
                        toastr.success('הודעה', 'הפרופיל עודכן בהצלחה')
                        dispatch({
                          type: 'EDIT_PROFILE_SUCCESS'
                        })

                      }).catch(function (error) {
                        // An error happened.
                        dispatch({
                          type: 'EDIT_PROFILE_ERROR'
                        })
                        toastr.error('אופס! אירעה תקלה :|')
                      });
                    })
                });
              }
              else{

                 firestore.collection('Accounts').doc(Puid).set({
                   ...profile,
                   displayName: profile.displayName,
                   phoneNumber: profile.phoneNumber,
                   location: profile.location,
                   displayImage: profile.displayImage

                 }).then(() => {
                   dispatch({
                     type: 'EDIT_PROFILE_SUCCESS'
                   })
                   toastr.success('הודעה', 'הפרופיל עודכן בהצלחה')
                 }).catch(function (error) {
                   // An error happened.
                   dispatch({
                     type: 'EDIT_PROFILE_ERROR'
                   })
                   toastr.error('אופס! לא יכולנו לעדכן את הפרופיל')
                 });
              }

  }
}

export const send_EmailVerification = () => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();

    firebase.auth().currentUser.sendEmailVerification().then(() => {
      //email send
      dispatch({ type: 'EMAIL_VERIFICATION_SUCCESS' })
      toastr.info('הודעה', 'הודעת אימות נשלחה למייל')
    }).catch(function (error) {
      // An error happened.
      toastr.error('The message')
    });;
  }
}

This is the buildProfile script that needs to use "editProfile" function from above script.

import React, { Component } from 'react'
import 'assets/css/Css.css'
import {editProfile} from 'store/actions/authActions'

import { Button,Icon} from 'react-materialize';

import GridContainer from "components/Grid/GridContainer.jsx";
import GridItem from "components/Grid/GridItem.jsx";
import Card from "components/Card/Card.jsx";
import withStyles from "@material-ui/core/styles/withStyles";

import { connect } from 'react-redux'
import { firestoreConnect } from 'react-redux-firebase'
import { compose } from 'redux'
import { Hidden } from '@material-ui/core';

import $ from 'jquery';
import 'react-redux-toastr/lib/css/react-redux-toastr.min.css'
import Properties from 'components/Profile/properties'

import { clearSelectedProperty } from "../../store/actions/propertyActions";

// @material-ui/icons

class BuildProfile extends Component {
    state = {
        displayName: (this.props.profile !== null) ? this.props.profile.displayName : '',
        location: (this.props.profile !== null) ? this.props.profile.location : '',
        displayImage: (this.props.profile !== null) ? this.props.profile.displayImage : '',
        phoneNumber: (this.props.profile !== null) ? this.props.profile.phoneNumber : '',
        uploadedImages: '',
        file:''
     }

    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
    }

    handleImagesUpload = (e) => {
        if (e.target.files) {
            const uploadedImages = e.target.files[0]
            const file =  URL.createObjectURL(e.target.files[0])
            this.setState(() => ({
                uploadedImages,
                file
            }));
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.editProfile(this.state);
        this.props.onClose()

    }
    handleSelectChange = (e) => {
        this.setState({
            location: e.target.value
        })
    }

    render() {

        const {profile, onClose} = this.props;
        const {
            displayName,
            location, displayImage, phoneNumber
        } = this.state
        const locationOptions = [
            {label: "תל אביב", value: 'תל אביב', type: "location"},
            {label: " ירושליים ", value: 'ירושליים', type: "location"},
            {label: "חיפה", value: 'חיפה', type: "location"}
        ];
        //if (auth.uid) return <Redirect to='/' />

        return (

            <GridContainer  justify="center">
                <GridItem xs={13} sm={12} md={4}>
                <Card >

<form onSubmit={this.handleSubmit}>

יצרירת פרופיל

                                         {console.log(this.state.file)}

                                                                                <input type="file" id="uploadedImages" onChange={this.handleImagesUpload}  style={{marginRight:38,maxWidth:150,overflowX:"auto"}}/>

                                        <input id="displayName" type="text" className="validate"

                                        placeholder={null}

                                               value={this.props.displayName}
                                               onChange={this.handleChange}/>
                                        שם מלא

                                        <input id="phoneNumber" type="text" className="validate"
                                               value={profile.phoneNumber}
                                               onChange={this.handleChange}/>
                                        מס׳ טלפון

                                    <select id="location" style={{display:"block", marginRight:-10}}
                                            onChange={this.handleSelectChange}
                                            value={null}
                                            required>
                                        <option value="" disabled defaultValue>Location
                                        </option>
                                        {locationOptions.map(function (option) {
                                            return <option key={option.value}
                                                           value={option.value}>{option.label}</option>
                                        })}
                                    </select>
                                    איזור

                        <Button type="submit" waves="light" style={{backgroundColor:"#ff6969"}}>
המשך
</Button>

                    </form>
                    </Card>

                    </GridItem>
                            </GridContainer>

        )
    }
}

const mapStateToProps = (state, props) => {
    console.log(state,props)
     return {
       authError: state.auth.authError,
       auth: state.firebase.auth,
       properties: state.firestore.ordered.Properties,
       partner: state.firestore.ordered.Partners,
       profile: state.firebase.profile,
       selectedProperty: state.property,
       invitation: state.firestore.ordered.Invitations

     }

   }

   const mapDispatchToProps = (dispatch) => {
     return {

     }
   }

   export default compose(

     connect(mapStateToProps, mapDispatchToProps),
     firestoreConnect((props) => {
         if (!props.auth.uid) {
           props.history.push('/signin')
           return []
         }
         let propid = null
            if(props.invitation !== undefined){
                propid = props.invitation[0].propid
            }
            return [
             {
               collection: 'Invitations',
              doc: props.match.params.inviteid

             },
             {
               collection: 'Partners',
               doc: props.auth.uid
             },
             {
                 collection: 'Properties',
                 doc: propid
             },

           ]
        }

    )
    )(BuildProfile)

I keep getting the following error

Body:
BuildProfile component does not have a prop editProfile in props or it is not a function.
I see you are importing the editProfile function:

import {editProfile} from 'store/actions/authActions'

Probably you want to call editProfile like this:

handleSubmit = (e) => {
            e.preventDefault();
            editProfile(this.state);
            onClose();
}


问:
Create decimal values of character hex
With the following code I'm reading a text file and displaying one column on the screen.

```<code>externalData <- read.delim("testdata.txt", header = FALSE, sep = "@")

i = 1;
while(i < 11) {
  appel <- as.character(externalData[i,3,1])
  i = i + 1;
  print(appel)
}
</code>```

The output looks like this:

I'm trying to convert these values from hexadecimal to decimal.

I've tried the following:

```<code>strtoi(c(appel))
</code>```

but this doesn't seem to work, this only removes the quotation marks from the first one and the last one, and sets everything in-between to N/A (probably because there are letters in them).

答:
From ?strtoi

Convert strings to integers according to the given base using the C function strtol, or choose a suitable base following the C rules.

Arguments

x    a character vector, or something coercible to this by as.character.

base   an integer which is between 2 and 36 inclusive, or zero (default).

1.Create a reproducible minimal example

```<code>appel <- c("158308", "d8db89")
</code>```

2.Solution using strtoi base argument:

```<code>strtoi(appel, base=16)
</code>```

Returns:

```<code>[1]  1409800 14211977
</code>```

Title: Create decimal values of character hex

Body:
With the following code I'm reading a text file and displaying one column on the screen.

externalData <- read.delim("testdata.txt", header = FALSE, sep = "@")

i = 1;
while(i < 11) {
  appel <- as.character(externalData[i,3,1])
  i = i + 1;
  print(appel)
}

The output looks like this:

I'm trying to convert these values from hexadecimal to decimal.

I've tried the following:

strtoi(c(appel))

but this doesn't seem to work, this only removes the quotation marks from the first one and the last one, and sets everything in-between to N/A (probably because there are letters in them).

Body:
From ?strtoi

Convert strings to integers according to the given base using the C function strtol, or choose a suitable base following the C rules.

Arguments

x    a character vector, or something coercible to this by as.character.

base   an integer which is between 2 and 36 inclusive, or zero (default).

1.Create a reproducible minimal example

appel <- c("158308", "d8db89")

2.Solution using strtoi base argument:

strtoi(appel, base=16)

Returns:

[1]  1409800 14211977


问:
Recursive SQL Query with Postgres Ranges To Find Availability
I followed this blogpost: https://info.crunchydata.com/blog/range-types-recursion-how-to-search-availability-with-postgresql

CREATE TABLE travels (
    id serial PRIMARY KEY,
    travel_dates daterange NOT NULL,
    EXCLUDE USING spgist (travel_dates WITH &&)
);

```

<p>and found this function to be buggy when I've inserted rows with duration back to back</p>

<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION travels_get_available_dates(daterange)
RETURNS TABLE(available_dates daterange)
AS $$
    WITH RECURSIVE calendar AS (
        SELECT
            $1 AS left,
             $1 AS center,
             $1 AS right
        UNION
        SELECT
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN daterange(lower(calendar.left), lower(travels.travel_dates * calendar.left))
                ELSE daterange(lower(calendar.right), lower(travels.travel_dates * calendar.right))
            END AS left,
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN travels.travel_dates * calendar.left
                ELSE travels.travel_dates * calendar.right
            END AS center,
            CASE travels.travel_dates && calendar.right
                WHEN TRUE THEN daterange(upper(travels.travel_dates * calendar.right), upper(calendar.right))
                ELSE daterange(upper(travels.travel_dates * calendar.left), upper(calendar.left))
            END AS right
        FROM calendar
        JOIN travels ON
            travels.travel_dates && $1 AND
            travels.travel_dates <> calendar.center AND (
                travels.travel_dates && calendar.left OR
                travels.travel_dates && calendar.right
            )
)
SELECT *
FROM (
    SELECT
        a.left AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.left <> b.left AND
        a.left @> b.left
    GROUP BY a.left
    HAVING NOT bool_or(COALESCE(a.left @> b.left, FALSE))
    UNION
    SELECT
        a.right AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.right <> b.right AND
        a.right @> b.right
    GROUP BY a.right
    HAVING NOT bool_or(COALESCE(a.right @> b.right, FALSE))
) a
$$ LANGUAGE SQL STABLE;

</code>```

```<code>INSERT INTO travels (travel_dates)
VALUES
    (daterange('2018-03-02', '2018-03-02', '[]')),
    (daterange('2018-03-06', '2018-03-09', '[]')),
    (daterange('2018-03-11', '2018-03-12', '[]')),
    (daterange('2018-03-16', '2018-03-17', '[]')),
    (daterange('2018-03-25', '2018-03-27', '[]'));
</code>```

This works as expected at this point.

```<code>SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;
</code>```

```<code>available_dates
-------------------------
[2018-03-01,2018-03-02)
[2018-03-03,2018-03-06)
[2018-03-10,2018-03-11)
[2018-03-13,2018-03-16)
[2018-03-18,2018-03-25)
[2018-03-28,2018-04-01)
</code>```

But when this row is added:

INSERT INTO travels (travel_dates)
VALUES
(daterange('2018-03-03', '2018-03-05', '[]'));
```

<p>And re-run</p>

```SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;
```

<p>I get</p>

```available_dates
-------------------------
empty
```

答:
I think that you should take another approach:

CREATE OR REPLACE FUNCTION travels_get_available_dates(daterange)
RETURNS TABLE(
  available_dates daterange
)
AS $$
  WITH RECURSIVE calendar(available_dates) AS
  (
    SELECT
      CASE
        WHEN $1 @> travel_dates THEN unnest(array[
          daterange(lower($1),lower(travel_dates)),
          daterange(upper(travel_dates),upper($1))
        ])
        WHEN lower($1) < lower(travel_dates) THEN daterange(lower($1),lower(travel_dates))
        WHEN upper($1) > upper(travel_dates) THEN daterange(upper(travel_dates),upper($1))
      END
    FROM travels
      WHERE $1 && travel_dates AND NOT travel_dates @> $1
    UNION
    SELECT
      CASE
        WHEN available_dates @> travel_dates THEN unnest(array[
          daterange(lower(available_dates),lower(travel_dates)),
          daterange(upper(travel_dates),upper(available_dates))
        ])
        WHEN lower(available_dates) < lower(travel_dates) THEN daterange(lower(available_dates),lower(travel_dates))
        WHEN upper(available_dates) > upper(travel_dates) THEN daterange(upper(travel_dates),upper(available_dates))
      END
    FROM travels
      JOIN calendar ON available_dates && travel_dates AND NOT travel_dates @> available_dates
  )

  SELECT $1 AS available_dates
    WHERE NOT EXISTS(SELECT 1 FROM travels WHERE travel_dates <@ $1)
  UNION
  SELECT * FROM calendar
    WHERE $1 <> available_dates AND 'empty' <> available_dates
      AND NOT EXISTS(SELECT 1 FROM travels WHERE available_dates && travel_dates)
$$ LANGUAGE SQL STABLE;
```

We have to recursively split the given range on left and right segments and then get only those which are not occupied.

Body:
I followed this blogpost: https://info.crunchydata.com/blog/range-types-recursion-how-to-search-availability-with-postgresql

CREATE TABLE travels (
    id serial PRIMARY KEY,
    travel_dates daterange NOT NULL,
    EXCLUDE USING spgist (travel_dates WITH &&)
);

and found this function to be buggy when I've inserted rows with duration back to back

CREATE OR REPLACE FUNCTION travels_get_available_dates(daterange)
RETURNS TABLE(available_dates daterange)
AS $$
    WITH RECURSIVE calendar AS (
        SELECT
            $1 AS left,
             $1 AS center,
             $1 AS right
        UNION
        SELECT
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN daterange(lower(calendar.left), lower(travels.travel_dates * calendar.left))
                ELSE daterange(lower(calendar.right), lower(travels.travel_dates * calendar.right))
            END AS left,
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN travels.travel_dates * calendar.left
                ELSE travels.travel_dates * calendar.right
            END AS center,
            CASE travels.travel_dates && calendar.right
                WHEN TRUE THEN daterange(upper(travels.travel_dates * calendar.right), upper(calendar.right))
                ELSE daterange(upper(travels.travel_dates * calendar.left), upper(calendar.left))
            END AS right
        FROM calendar
        JOIN travels ON
            travels.travel_dates && $1 AND
            travels.travel_dates <> calendar.center AND (
                travels.travel_dates && calendar.left OR
                travels.travel_dates && calendar.right
            )
)
SELECT *
FROM (
    SELECT
        a.left AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.left <> b.left AND
        a.left @> b.left
    GROUP BY a.left
    HAVING NOT bool_or(COALESCE(a.left @> b.left, FALSE))
    UNION
    SELECT
        a.right AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.right <> b.right AND
        a.right @> b.right
    GROUP BY a.right
    HAVING NOT bool_or(COALESCE(a.right @> b.right, FALSE))
) a
$$ LANGUAGE SQL STABLE;

INSERT INTO travels (travel_dates)
VALUES
    (daterange('2018-03-02', '2018-03-02', '[]')),
    (daterange('2018-03-06', '2018-03-09', '[]')),
    (daterange('2018-03-11', '2018-03-12', '[]')),
    (daterange('2018-03-16', '2018-03-17', '[]')),
    (daterange('2018-03-25', '2018-03-27', '[]'));

This works as expected at this point.

SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;

available_dates
-------------------------
[2018-03-01,2018-03-02)
[2018-03-03,2018-03-06)
[2018-03-10,2018-03-11)
[2018-03-13,2018-03-16)
[2018-03-18,2018-03-25)
[2018-03-28,2018-04-01)

But when this row is added:

INSERT INTO travels (travel_dates)
VALUES
(daterange('2018-03-03', '2018-03-05', '[]'));

And re-run

SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;

I get

available_dates
-------------------------
empty

Body:
I think that you should take another approach:

CREATE OR REPLACE FUNCTION travels_get_available_dates(daterange)
RETURNS TABLE(
  available_dates daterange
)
AS $$
  WITH RECURSIVE calendar(available_dates) AS
  (
    SELECT
      CASE
        WHEN $1 @> travel_dates THEN unnest(array[
          daterange(lower($1),lower(travel_dates)),
          daterange(upper(travel_dates),upper($1))
        ])
        WHEN lower($1) < lower(travel_dates) THEN daterange(lower($1),lower(travel_dates))
        WHEN upper($1) > upper(travel_dates) THEN daterange(upper(travel_dates),upper($1))
      END
    FROM travels
      WHERE $1 && travel_dates AND NOT travel_dates @> $1
    UNION
    SELECT
      CASE
        WHEN available_dates @> travel_dates THEN unnest(array[
          daterange(lower(available_dates),lower(travel_dates)),
          daterange(upper(travel_dates),upper(available_dates))
        ])
        WHEN lower(available_dates) < lower(travel_dates) THEN daterange(lower(available_dates),lower(travel_dates))
        WHEN upper(available_dates) > upper(travel_dates) THEN daterange(upper(travel_dates),upper(available_dates))
      END
    FROM travels
      JOIN calendar ON available_dates && travel_dates AND NOT travel_dates @> available_dates
  )

  SELECT $1 AS available_dates
    WHERE NOT EXISTS(SELECT 1 FROM travels WHERE travel_dates <@ $1)
  UNION
  SELECT * FROM calendar
    WHERE $1 <> available_dates AND 'empty' <> available_dates
      AND NOT EXISTS(SELECT 1 FROM travels WHERE available_dates && travel_dates)
$$ LANGUAGE SQL STABLE;

We have to recursively split the given range on left and right segments and then get only those which are not occupied.


问:
Handling paper documentation
After every new program written a lot of paper documentation remains.

Apart from the usual scribble notes from the programmers there usually is a nice heap of papers containing physical model explanations, calculations and so on (equations, tables, graphs, little pictures describing variables ...)

We usually do numerically intensive calculations in console applications, which are not released to the public (remain in the house, only results go out). Before each project is finished all those papers have to be packed somehow with the application, so that one day, when someone will be reusing parts of it, has some idea what is what in there.
So far, we've been using the 'dirty' solution of just scanning all of it, and packing it up on the disc with the application.

So I was wondering ... for all science guys here in a similar situation ... how do you handle project documentation which is needed, but not released to the public ?
(the one that does, goes to the dtp laddies, and they make it nice and shiny - not our problem anymore :)

答: I create UI paper prototypes when designing the UI of an application, which produces lots of A3-sized papers (in one project we had many desks covered with papers). When the design is ready or it needs to be mailed to somebody, I take pictures of it with a digital camera, so that I can produce a series of pictures showing how to perform some tasks on the UI, which serves as documentation of how the application is meant to work. This serves also as a backup, in case somebody steals/cleans away the original papers.</p>

ContentLicense: CC BY-SA 2.5

Title: Handling paper documentation

OwnerDisplayName: Esko Luontola


问:
Are there any alternatives to XmlUnit?
I need to diff large directory structures containing generated .xml and .wsdl files.  The generated .xml files differ in the order that child elements appear.  The XmlUnit Diff.similar() method is supposed to handle this case:

'Two documents are considered to be "similar" if they contain the same elements and attributes regardless of order.'

This is not the case, however.  I took a .xml file, reversed the order of two child elements and XmlUnit says that they are not similar.

XmlUnit is broken, providing no more functionality than the built-in diff utility.

Is there an alternative to XmlUnit that recognizes simple differences in .xml files like ordering of child elements?

答:
I found out that setting the following option resolved the problem of inaccurate (un)similarity:</p>

```<code>XMLUnit.setIgnoreWhitespace(true);
</code>```

Title: Are there any alternatives to XmlUnit?

Body:
I found out that setting the following option resolved the problem of inaccurate (un)similarity:

XMLUnit.setIgnoreWhitespace(true);


问:
DialogFlow: Regexp not accept occurrence of case
Regexp entity

```<code>Hall ?([0-9]{1,2})?
</code>```

Case wants to accept :

Hall  //Not Accept

Hall1 //Accept

Hall 1 //Accept

but case 1 not satisfy by Regexp

And I Want to satisfy all 3 cases.

答:
I don't understand why your original regex doesn't match the first case.

Try this:

Hall\s?\d{0,2}

Body:
Regexp entity

Hall ?([0-9]{1,2})?

Case wants to accept :

Hall  //Not Accept

Hall1 //Accept

Hall 1 //Accept

but case 1 not satisfy by Regexp

And I Want to satisfy all 3 cases.


问:
Update git repository with case-changed files
Due to the per-developer naming convention I had to rename a bunch of files of a laravel app, eg. supplyController.php to SupplyContoller.php. The files are created on windows, so the filesys is case-insensitive, but the production VPS has debian/case-sensitive, so it's important to have the right naming to deploy.

The changes are already committed and pushed, and afaik it's the normal behavior, the git repo contains the lower-case version of files. Beside git mv for each file, is there any better solution recommended to correct the repo?

答:
git mv is indeed your best option.

What you may be interested too is probably a way to modify, in a bulk way, lot of different files?

If that is the case, then your real question is maybe: how to generate a loop that will perform the various git mv in an consistent way?

E.g.:

```<code>$ git mv controllers/abccontroller.php controllers/AbcController.php
$ git mv controllers/defcontroller.php controllers/DefController.php
$ git mv controllers/ghicontroller.php controllers/GhiController.php
$ git mv controllers/jklcontroller.php controllers/JklController.php
...
</code>```

I guess this would be easier on a non-Windows OS for two reasons: shells and file system really being case-insensitive (which they tend to be outside of Windows).

Body:
git mv is indeed your best option.

What you may be interested too is probably a way to modify, in a bulk way, lot of different files?

If that is the case, then your real question is maybe: how to generate a loop that will perform the various git mv in an consistent way?

E.g.:

$ git mv controllers/abccontroller.php controllers/AbcController.php
$ git mv controllers/defcontroller.php controllers/DefController.php
$ git mv controllers/ghicontroller.php controllers/GhiController.php
$ git mv controllers/jklcontroller.php controllers/JklController.php
...

I guess this would be easier on a non-Windows OS for two reasons: shells and file system really being case-insensitive (which they tend to be outside of Windows).


问:
Get and display the selected variation SKU in WooCommerce
I have this code that works for simple product type but not for variable products in WooCommerce:

```<code>add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
    global $product;

    return sprintf( '<div class="widget" sp-sku="%s"></div>', $product->get_sku() );
}
</code>```

How can I make it work for both simple and variable products?

答:
To make it work also for variable products and their variations, it requires Javascript (jQuery) to get the selected variation SKU for variable products.

Try the following that works for simple an variable product types, displaying the selected variation SKU for variable products:

```<code>add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
    global $product;

    if( ! is_a('WC_Product', $product) ) {
        $product = wc_get_product( get_the_id() );
    }

    ## 1 - For variable products (and their variations)
    if( $product->is_type('variable') ) {
        ob_start(); // Starting buffering

        ?>
        <div class="widget" sp-sku=""></div>
        <script type="text/javascript">
        jQuery( function($){
            $('form.variations_form').on('show_variation', function( event, data ){
                $( 'div.widget' ).attr( 'sp-sku', data.sku );
                // For testing
                console.log( 'Variation Id: ' + data.variation_id + ' | Sku: ' + data.sku );
            });
            $('form.variations_form').on('hide_variation', function(){
                $( 'div.widget' ).attr( 'sp-sku', '' );
            });
        });
        </script><?php

        return ob_get_clean(); // return the buffered content
    }
    ## 2 - For other products types
    else {
        return sprintf( '<div class="widget" sp-sku="%s"></div>', $product->get_sku() );
    }
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Body:
I have this code that works for simple product type but not for variable products in WooCommerce:

add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
    global $product;

    return sprintf( '

', $product->get_sku() );
}

How can I make it work for both simple and variable products?

Body:
To make it work also for variable products and their variations, it requires Javascript (jQuery) to get the selected variation SKU for variable products.

Try the following that works for simple an variable product types, displaying the selected variation SKU for variable products:

add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
    global $product;

    if( ! is_a('WC_Product', $product) ) {
        $product = wc_get_product( get_the_id() );
    }

    ## 1 - For variable products (and their variations)
    if( $product->is_type('variable') ) {
        ob_start(); // Starting buffering

        ?>
        <div class="widget" sp-sku=""></div>
        <script type="text/javascript">
        jQuery( function($){
            $('form.variations_form').on('show_variation', function( event, data ){
                $( 'div.widget' ).attr( 'sp-sku', data.sku );
                // For testing
                console.log( 'Variation Id: ' + data.variation_id + ' | Sku: ' + data.sku );
            });
            $('form.variations_form').on('hide_variation', function(){
                $( 'div.widget' ).attr( 'sp-sku', '' );
            });
        });
        </script><?php

        return ob_get_clean(); // return the buffered content
    }
    ## 2 - For other products types
    else {
        return sprintf( '<div class="widget" sp-sku="%s"></div>', $product->get_sku() );
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.


问:
How to use svg image as background image in react-native?
I use svg in my react-native app next way:

```<code>import TestLogo from "../../assets/TestLogo.svg";
<TestLogo />
</code>```

I use background image in next way:

```<code>import background from '../../assets/modules/auth/signUpPattern.png'
<ImageBackground source={background} style={{width: '100%', height: '100%',  alignItems: 'center'}}>
</code>```

If I use the next syntax:

```<code>    import Background from '../../assets/modules/auth/signUpPattern.svg'
    <ImageBackground source={<Background />} style={{width: '100%', height: '100%',  alignItems: 'center'}}>
</code>```

I got empty space, not svg image background, how to fix it?

答:
react-native doesn't support .svg formats. u can use library like react-native-svg
or any other.</p>

Body:
I use svg in my react-native app next way:

import TestLogo from "../../assets/TestLogo.svg";
<TestLogo />

I use background image in next way:

import background from '../../assets/modules/auth/signUpPattern.png'
<ImageBackground source={background} style={{width: '100%', height: '100%',  alignItems: 'center'}}>

If I use the next syntax:

    import Background from '../../assets/modules/auth/signUpPattern.svg'
    <ImageBackground source={<Background />} style={{width: '100%', height: '100%',  alignItems: 'center'}}>

I got empty space, not svg image background, how to fix it?


问:
How to merge two collections into one without any conditions
I have two Different collections named X and Y i have to just send these two collections data into a new collection Z.

Is it possible to just send the two collections data into one.

I can see many similar questions but with many conditions in the data so here i don't need any conditions just clubbing the two collections of data into new collection.

答:
You can use copyTo command.

```<code>db.myt1.copyTo('myt3');
db.myt.copyTo('myt3');
</code>```

Now we have myt3 as a copy of myt1 and myt collections.

Body:
You can use copyTo command.

db.myt1.copyTo('myt3');
db.myt.copyTo('myt3');

Now we have myt3 as a copy of myt1 and myt collections.


问:
There are possible way of dividing two float numbers which was casted from unsigned int make negative float result?
```<code>unsigned int deltaTime = now() - last();
unsigned int freq = getFreq();
float timeOfGap = float(deltaTime) / float(freq);

ASSERT(0.0f <= timeOfGap, "WHAT?");
</code>```

I got a really weired result from my program. I didn't catch a scene which is happened. But I have a log which said that really raised at least multiple times.

There are possible way of dividing between two float numbers which was casted from unsigned int make negative float result?

OK, thank you guys. I'm glad to see your attentions.
Let me try to add some descriptions about it. It'll be helpful for you.

I'm working for an online game, and this situation was raised rarely but frequently while hundreds of million times game was serving. I can't debug or catch the exact shot, but it is logged on the db error messages.

The timeOfGap should be NaN as you noticed, but the log didn't alert the value exactly. The timeOfGap is accumulated like below;

```<code>mTotalFrameRateTimeAsASecond += timeOfGap;
</code>```

And this program logs mTotalFrameRateTimeAsASecond, that was a negative value. But except this sign of value was a negative, it is correct value. Meaning, it point time as look as good if I divide the final value with a framerate. A hypothetical play time was 500 sec, it is -30000(with 60 framerate per sec).

答:
The value nan will not compare to anything successfully. So if you have:

```<code>float f = 0.0 / 0.0;

assert(f > 0 || f <= 0);
</code>```

The assertion will fail!

Body:
unsigned int deltaTime = now() - last();
unsigned int freq = getFreq();
float timeOfGap = float(deltaTime) / float(freq);

ASSERT(0.0f <= timeOfGap, "WHAT?");

I got a really weired result from my program. I didn't catch a scene which is happened. But I have a log which said that really raised at least multiple times.

There are possible way of dividing between two float numbers which was casted from unsigned int make negative float result?

OK, thank you guys. I'm glad to see your attentions.
Let me try to add some descriptions about it. It'll be helpful for you.

I'm working for an online game, and this situation was raised rarely but frequently while hundreds of million times game was serving. I can't debug or catch the exact shot, but it is logged on the db error messages.

The timeOfGap should be NaN as you noticed, but the log didn't alert the value exactly. The timeOfGap is accumulated like below;

mTotalFrameRateTimeAsASecond += timeOfGap;

And this program logs mTotalFrameRateTimeAsASecond, that was a negative value. But except this sign of value was a negative, it is correct value. Meaning, it point time as look as good if I divide the final value with a framerate. A hypothetical play time was 500 sec, it is -30000(with 60 framerate per sec).

Body:
The value nan will not compare to anything successfully. So if you have:

float f = 0.0 / 0.0;

assert(f > 0 || f <= 0);

The assertion will fail!


问:
Mysql trigger update time
I trying to after update table, update new update_time. Whats my wrong?

```<code>DELIMITER $$
CREATE TRIGGER after_update AFTER UPDATE ON urunler
    FOR EACH ROW
        BEGIN
            IF NEW.adi != OLD.adi THEN
                UPDATE urunler SET update_time=now();
            END IF;
        END$$
DELIMITER ;
</code>```

getting error

```<code>#1442 - Can't update table 'urunler' in stored function/trigger because it is already used by statement which invoked this stored function/trigger
</code>```

SOLVED WITH "BEFORE" not AFTER...

答:
To apply a DML operation on the same table may raise mutating table error.

Rather, replace UPDATE urunler SET update_time=now(); with SET new.update_time = now();

where [old/new].update_time expression represents a column within that table.

Title: Mysql trigger update time

Body:
I trying to after update table, update new update_time. Whats my wrong?

DELIMITER $$
CREATE TRIGGER after_update AFTER UPDATE ON urunler
    FOR EACH ROW
        BEGIN
            IF NEW.adi != OLD.adi THEN
                UPDATE urunler SET update_time=now();
            END IF;
        END$$
DELIMITER ;

getting error

#1442 - Can't update table 'urunler' in stored function/trigger because it is already used by statement which invoked this stored function/trigger

SOLVED WITH "BEFORE" not AFTER...


问:
How can I pass predefined variable to playbook's "- hosts: "POD_'+VARIABLE+'_master_sn""
I have a file named "all" under group_vars with predefined variable, the value of which can be changed, let say, from "C" to "D' depends on what I need:

```<code>VARIABLE: C
</code>```

Also, I have a task under my playbook:

```<code>- hosts: "POD_'+VARIABLE+'_master_sn"
  tasks:
    - include_role:
        name: sn_static_hosts
        tasks_from: remove
</code>```

As you can see, I want to perform concatenation, but getting this:

```<code>[WARNING]: Could not match supplied host pattern, ignoring: POD_'+source_pod_name_capital_letter+'_master_sn
</code>```

I have tried to play with brackets, removed/added "+" etc, but got only warnings or errors.

Is that possible to have this kind of concatenation?

UPDATE:

I need to read VARIABLE from some pre-defined file, not from the console.

答:
You can try as below:

```<code>- hosts: "POD_{{VARIABLE}}_master_sn"
  tasks:
  - include_role:
     name: sn_static_hosts
     tasks_from: remove
</code>```

Below is how I tested with localhost:

Playbook

```<code>- hosts: "loc{{var}}host"
</code>```

Command:

```<code>ansible-playbook test.yml -e "var=al"
</code>```

Output:

PLAY [localhost]

Body:
I have a file named "all" under group_vars with predefined variable, the value of which can be changed, let say, from "C" to "D' depends on what I need:

VARIABLE: C

Also, I have a task under my playbook:

- hosts: "POD_'+VARIABLE+'_master_sn"
  tasks:
    - include_role:
        name: sn_static_hosts
        tasks_from: remove

As you can see, I want to perform concatenation, but getting this:

[WARNING]: Could not match supplied host pattern, ignoring: POD_'+source_pod_name_capital_letter+'_master_sn

I have tried to play with brackets, removed/added "+" etc, but got only warnings or errors.

Is that possible to have this kind of concatenation?

UPDATE:

I need to read VARIABLE from some pre-defined file, not from the console.

Body:
You can try as below:

- hosts: "POD_{{VARIABLE}}_master_sn"
  tasks:
  - include_role:
     name: sn_static_hosts
     tasks_from: remove

Below is how I tested with localhost:

Playbook

- hosts: "loc{{var}}host"

Command:

ansible-playbook test.yml -e "var=al"

Output:

PLAY [localhost]


问:
How to make CSS height 100% scrollable?
I want to make the two-tone background. 50% of left side is in the main background color and 50% right side in another color (say pink). I could accomplish that but now facing another problem. When the mouse cursor is on the pink background color, the page becomes unscrollable. How to fix this and make it scrollable?

html code

html,
body {
  margin: 0;
  overflow: scroll;
  height: 100%;
  background-color: #f5f5f5;
}

#background {
  position: fixed;
  top: 0px;
  left: 50%;
  width: 50%;
  height: 100%;
  background-color: pink;
  z-index: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="background"></div>
</body></code>```

答:
I've fixed this by changing height: 100% in html, body to </p>

```<code>min-height: 100%;
</code>```

Title: How to make CSS height 100% scrollable?

Body:
I've fixed this by changing height: 100% in html, body to

min-height: 100%;


问:
cmder passing wrong characters to console
When I try to edit any file in vim Cmder is pasing wrong characters.

arrow up/down are writing "←OB" or "←OA"

ctrl + a is typing "☺"

I'm using CMDER + cygwin. Any idea how to make it work ?

答:
I cannot comment due to a low reputation but can you post some more details e.g. what version of Cmder and Cygwin are you using? Also if you run the Cygwin outside Cmder, does it work? What kind of keyboard do you have and which keyboard layout do you use?

I had no issues with Cygwin, I created a task like this and it worked. I just put this into "Commands" (my cygwin is installed in the C:\Users\mflop\Apps:

```<code>C:\Users\mflop\Apps\cygwin\bin\mintty.exe -i /Cygwin-Terminal.ico -
</code>```

If that does not work, go to Cmder settings -> Keys & Macro -> Keyboard and try to play a bit with the settings there, especially the part Seize keys/Send to console. Some settings there might conflict with your Cygwin version. Also if you run it in the restricted environment (typically corporate setup with no admin rights, firewalls etc.) the Cmder and Cygwin might be affected by that.

Body:
I cannot comment due to a low reputation but can you post some more details e.g. what version of Cmder and Cygwin are you using? Also if you run the Cygwin outside Cmder, does it work? What kind of keyboard do you have and which keyboard layout do you use?

I had no issues with Cygwin, I created a task like this and it worked. I just put this into "Commands" (my cygwin is installed in the C:\Users\mflop\Apps:

C:\Users\mflop\Apps\cygwin\bin\mintty.exe -i /Cygwin-Terminal.ico -

If that does not work, go to Cmder settings -> Keys & Macro -> Keyboard and try to play a bit with the settings there, especially the part Seize keys/Send to console. Some settings there might conflict with your Cygwin version. Also if you run it in the restricted environment (typically corporate setup with no admin rights, firewalls etc.) the Cmder and Cygwin might be affected by that.


问:
C++ move semantics and code duplication as a result of method overloading
Before I begin, I didn't find anything that completely explains my question in an other stackoverflow post so I decided to create my own. Apologies if it is already answered somewhere else(kindly point me to the existing post if it does exist).

Lets say we have the following two methods inside of a class:

```<code>int do_stuff(Thing& thing){ /* Do stuff... */} // L-value version
int do_stuff(Thing&& thing){ /* Do stuff... */} // R-value version
</code>```

From what I have read, modern C++ has pretty much abandoned this kind of logic and it is recommending to just pass the Thing by value and let the compiler do it's magic. My question is, If I want to have two separate methods that explicitly handles L-values/R-values and avoid code duplication, which of the following is best(performance wise and as in best practice)?

```<code>int do_stuff(Thing& thing){ return do_stuff(std::move(thing)); } // The L-value version uses the R-value one
</code>```

Or

```<code>int do_stuff(Thing&& thing){ return do_stuff(thing); } // The R-value version uses the L-value one since text is an L-value inside the scope of do_stuff(Thing&&)
</code>```

Edit: The purpose of the question is for me to understand this simple case of move semantics and not to create a valid C++ API.

Edit #2: The print and std::string parts of the question are used as an example. They can be anything.

Edit #3: Renamed the example code. The methods do modify the Thing object.

答:
There is no difference in performance. std::move does nothing but casts the type  of its argument, so a smart compiler will omit the call to std::move, and even omit the redundant call to do_stuff. You can see under -O2, in either case, GCC compiles the do_stuff that calls the other do_stuff to a simple jmp command to the other do_stuff.

So it is opinion-based which way is better. I personally like the second way because it is shorter.

Body:
Before I begin, I didn't find anything that completely explains my question in an other stackoverflow post so I decided to create my own. Apologies if it is already answered somewhere else(kindly point me to the existing post if it does exist).

Lets say we have the following two methods inside of a class:

int do_stuff(Thing& thing){ /* Do stuff... */} // L-value version
int do_stuff(Thing&& thing){ /* Do stuff... */} // R-value version

From what I have read, modern C++ has pretty much abandoned this kind of logic and it is recommending to just pass the Thing by value and let the compiler do it's magic. My question is, If I want to have two separate methods that explicitly handles L-values/R-values and avoid code duplication, which of the following is best(performance wise and as in best practice)?

int do_stuff(Thing& thing){ return do_stuff(std::move(thing)); } // The L-value version uses the R-value one

Or

int do_stuff(Thing&& thing){ return do_stuff(thing); } // The R-value version uses the L-value one since text is an L-value inside the scope of do_stuff(Thing&&)

Edit: The purpose of the question is for me to understand this simple case of move semantics and not to create a valid C++ API.

Edit #2: The print and std::string parts of the question are used as an example. They can be anything.

Edit #3: Renamed the example code. The methods do modify the Thing object.


问:
Unicode std::string class replacement
I'm looking for suggestions regarding unicode aware std::string library replacements. I have a bunch of code that uses std::string, its iterators etc, and would like to now support unicode strings (free or open source implementations preferred, regex capabilities would be great!).

I'm not sure at this point if I require a complete rewrite or if I can get away with dropping in a new string library that supports all of the std::string interfaces. The unicode world seems very complex and I'm just wanting to enable it in my applications not have to learn every single aspect of it.

btw how does the index operator work when it has to pass back a reference to either a 1, 2,3 or 4 structure which could in theory change to either a 1,2,3 or 4 byte structure.  if a larger or smaller sized value is passed, does the shifting back and forth of the internal data representation occur insitu?

答:
You don't need a complete rewrite if you make sure about what your std::string contains. For example, you could assume (and convert inputs to be sure) that your std::string contain UTF8 encoded strings (for those that need localization). Don't forget that std::string is only a container of raw data, it's not associated with an encoding (even in C++0x, it's only a possibility, not a requirement).

Then when you pass text to other libraries that require different encodings, you can use libraries like UTF8CPP to convert to the required encoding (but most of the time such libraries will do it themselves).

That way makes it simple. UTF8 with standard std::string in your code, enabling passing unicode string to everything else (with conversion if necessary).

There have been a lot of discussions about this in the boost community mailing list. Maybe reading it (if you have enough time...) can help you understand other possible solutions.

Title: Unicode std::string class replacement


问:
How to post image to instagram story in Swift?
is there any way to share image to instagram story directly. I can Only Share image using default share functionality i am using swift 5 and xcode 11.</p>

答:
iOS Swift

Import Below Module.

```<code>import AVKit
import Photos
</code>```

Add Below function for share image on Instagram.

```<code> func shareOnInstagram() {

        let instagramURL = URL(string: "instagram://app")

        PHPhotoLibrary.shared().performChanges({
            let request = PHAssetChangeRequest.creationRequestForAsset(from: yourImage)

            let assetID = request.placeholderForCreatedAsset?.localIdentifier ?? ""
            let shareURL = "instagram://library?LocalIdentifier=" + assetID

            DispatchQueue.main.async {
                if UIApplication.shared.canOpenURL(instagramURL!) {
                    if let urlForRedirect = URL(string: shareURL) {
                        UIApplication.shared.open(urlForRedirect, options: [:], completionHandler: nil)
                    }
                } else {
                    //show alert for Instagram is not installed in your device.
                }
            }
        }, completionHandler: { (bSuccess, error) in

        })
    }
</code>```

Body:
iOS Swift

Import Below Module.

import AVKit
import Photos

Add Below function for share image on Instagram.

 func shareOnInstagram() {

        let instagramURL = URL(string: "instagram://app")

        PHPhotoLibrary.shared().performChanges({
            let request = PHAssetChangeRequest.creationRequestForAsset(from: yourImage)

            let assetID = request.placeholderForCreatedAsset?.localIdentifier ?? ""
            let shareURL = "instagram://library?LocalIdentifier=" + assetID

            DispatchQueue.main.async {
                if UIApplication.shared.canOpenURL(instagramURL!) {
                    if let urlForRedirect = URL(string: shareURL) {
                        UIApplication.shared.open(urlForRedirect, options: [:], completionHandler: nil)
                    }
                } else {
                    //show alert for Instagram is not installed in your device.
                }
            }
        }, completionHandler: { (bSuccess, error) in

        })
    }


问:
How to stop HREF from adding to the url path. linking to local files in PHP
My code is really straight forward but the problem is whenever I click on an anchor tag
 it will automatically append to the url path resulting in a page that does not exist.
 For example

```<code> <li> <a href="blog/tag?cat=<?= $singleTag['id'];?>"
       class="d-flex text-capitalize">
                           <p><?= $singleTag['name']; ?></p>
       </a>  </li>
</code>```

It will assume that I'm trying to navigate to

blog/blog/tag?cat=something

I really don't know where the first /blog
                      came from I looked into other answers and they were suggesting
 to add // dobule back slashes infront of the link but that will not work since I'm trying to refer to a local file.

My routes file

```<code><?php

$router->get('','controllers/index.php');
$router->get('about','controllers/about.php');
$router->get('contact','controllers/contact.php');
$router->get('events','controllers/events.php');
$router->get('event/detail','controllers/event-detail.php');
$router->get('news','controllers/news.php');
$router->get('news/detail','controllers/news-detail.php');
$router->get('members','controllers/members.php');
$router->get('blog','controllers/blog.php');
$router->get('blog/detail','controllers/single-blog.php');
 $router->get('blog/tag','controllers/all-blog-tags.php');
$router->get('oops','controllers/error-page.php');    ?>
</code>```

My request class

```<code><?php

class Request
{
    public static function uri()
    {
      //  dd(parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY));
      $urlQuery = parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY);
       if (strpos($urlQuery, 'slug=') !== false) {
       $GLOBALS['slug'] = $urlQuery;

       }
       if (strpos($urlQuery, 'cat=') !== false) {
        $GLOBALS['cat'] = $urlQuery;

        }

          return ( trim(parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH),'/'));
     }

    public static function method()
    {
        return ($_SERVER['REQUEST_METHOD']);
    }
}                ?>
</code>```

My router class

```<code><?php

class Request
{
    public static function uri()
    {
      //  dd(parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY));
      $urlQuery = parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY);
       if (strpos($urlQuery, 'slug=') !== false) {
       $GLOBALS['slug'] = $urlQuery;

       }

          return ( trim(parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH),'/'));
     }

    public static function method()
    {
        return ($_SERVER['REQUEST_METHOD']);
    }
}
</code>```

答:
href="/blog/tag will start at the root of the public_html space on a server/local machine. For remote files this is the correct way to do it.

```<code>href="/blog/tag
      ^
      |
</code>```

Note the leading / to tell the browser to start at the local filepath root, so the browser will begin at

site.com/ <== this / is the leading one, above.

Therefore:

```<code>/blog/tag
</code>```

Will ALWAYS be:

```<code>your-website.com/blog/tag
</code>```

Without the leading slash, the path is relative to the current file, not to the website root.

Also browse this Q&A

Body:
My code is really straight forward but the problem is whenever I click on an anchor tag
 it will automatically append to the url path resulting in a page that does not exist.
 For example

 <a href="blog/tag?cat=<?= $singleTag['id'];?>"
       class="d-flex text-capitalize">

<?= $singleTag['name']; ?>

It will assume that I'm trying to navigate to

blog/blog/tag?cat=something

I really don't know where the first /blog
                      came from I looked into other answers and they were suggesting
 to add // dobule back slashes infront of the link but that will not work since I'm trying to refer to a local file.

My routes file

<?php

$router->get('','controllers/index.php');
$router->get('about','controllers/about.php');
$router->get('contact','controllers/contact.php');
$router->get('events','controllers/events.php');
$router->get('event/detail','controllers/event-detail.php');
$router->get('news','controllers/news.php');
$router->get('news/detail','controllers/news-detail.php');
$router->get('members','controllers/members.php');
$router->get('blog','controllers/blog.php');
$router->get('blog/detail','controllers/single-blog.php');
 $router->get('blog/tag','controllers/all-blog-tags.php');
$router->get('oops','controllers/error-page.php');    ?>

My request class

<?php

class Request
{
    public static function uri()
    {
      //  dd(parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY));
      $urlQuery = parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY);
       if (strpos($urlQuery, 'slug=') !== false) {
       $GLOBALS['slug'] = $urlQuery;

       }
       if (strpos($urlQuery, 'cat=') !== false) {
        $GLOBALS['cat'] = $urlQuery;

        }

          return ( trim(parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH),'/'));
     }

    public static function method()
    {
        return ($_SERVER['REQUEST_METHOD']);
    }
}                ?>

My router class

<?php

class Request
{
    public static function uri()
    {
      //  dd(parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY));
      $urlQuery = parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY);
       if (strpos($urlQuery, 'slug=') !== false) {
       $GLOBALS['slug'] = $urlQuery;

       }

          return ( trim(parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH),'/'));
     }

    public static function method()
    {
        return ($_SERVER['REQUEST_METHOD']);
    }
}

Body:
href="/blog/tag will start at the root of the public_html space on a server/local machine. For remote files this is the correct way to do it.

href="/blog/tag
      ^
      |

Note the leading / to tell the browser to start at the local filepath root, so the browser will begin at

site.com/ <== this / is the leading one, above.

Therefore:

/blog/tag

Will ALWAYS be:

your-website.com/blog/tag

Without the leading slash, the path is relative to the current file, not to the website root.

Also browse this Q&A


问:
How to display the list response which inside the object - react js
How to display the data in the below from the below json.

```<code>{
"a":
{
"b":[
  {"id":"ef718cce-1269-4fbd-827c-832f7824c025","name":"Veera6"},
  {"id":"0cda5ae9-e287-4666-804a-03f25e642d1f","name":"Veera9"},
  {"id":"31f8f042-dbc0-4dbf-ada8-b94c7e2d2a39","name":"Veera8"},
  {"id":"6292054c-8bfc-4d2d-b2f8-92e2bac5a578","name":"Veera7"},
  {"id":"c6756e5c-8fa5-40a9-ab92-5242bda97de3","name":"Veera10"}]
}
}
</code>```

code snipped below.

```<code>render() {

        return (
            <table>
                <thead>
                    <tr>
                    {
                        this.headers.map(function(h) {
                            return (
                                <th key = {h.key}>{h.label}</th>
                            )
                        })
                    }
                    </tr>
                </thead>
                <tbody>
                    {
                        this.state.tags.b.map(function(item, key) {
                        return (
                                <tr key = {key}>
                                  <td>{item.id}</td>
                                  <td>{item.name}</td>
                                </tr>
                            )
                        })
                    }
                </tbody>
            </table>
        )

    }
}
</code>```

How to display the data in table. Here i need to get the array/list b. Tried different approaches to get the data from the object array but no luck.

答:
Try this</p>

```<code>this.state.tags.a.b.map
</code>```

Body:
How to display the data in the below from the below json.

{
"a":
{
"b":[
  {"id":"ef718cce-1269-4fbd-827c-832f7824c025","name":"Veera6"},
  {"id":"0cda5ae9-e287-4666-804a-03f25e642d1f","name":"Veera9"},
  {"id":"31f8f042-dbc0-4dbf-ada8-b94c7e2d2a39","name":"Veera8"},
  {"id":"6292054c-8bfc-4d2d-b2f8-92e2bac5a578","name":"Veera7"},
  {"id":"c6756e5c-8fa5-40a9-ab92-5242bda97de3","name":"Veera10"}]
}
}

code snipped below.

render() {

        return (

                    {
                        this.headers.map(function(h) {
                            return (
                                {h.label}
                            )
                        })
                    }

                    {
                        this.state.tags.b.map(function(item, key) {
                        return (

                                  {item.id}
                                  {item.name}

                            )
                        })
                    }

        )

    }
}

How to display the data in table. Here i need to get the array/list b. Tried different approaches to get the data from the object array but no luck.

Body:
Try this

this.state.tags.a.b.map


答:
Try this once :

```<code>{
                        this.state.tags.a.b.map(function(item, key) {
                        return (
                                <tr key = {key}>
                                  <td>{item.id}</td>
                                  <td>{item.name}</td>
                                </tr>
                            )
                        })
                    }
</code>```

Hope it helps. feel free for doubts

Title: How to display the list response which inside the object - react js

Body:
Try this once :

{
                        this.state.tags.a.b.map(function(item, key) {
                        return (
                                <tr key = {key}>
                                  <td>{item.id}</td>
                                  <td>{item.name}</td>
                                </tr>
                            )
                        })
                    }

Hope it helps. feel free for doubts


问:
create index on creation of table in Oracle
In MySql, one can create an index on a (non-unique) column along with a table, e.g.

```<code>create table orders(
   orderid varchar(20) not null unique,
   customerid varchar(20),
   index(customerid)
   );
</code>```

Having not found a corresponding option in Oracle, i.e. creating the index on table creation rather than as a separate command afterwards, I suspect it is not possible. Is this correct? If so, what is the reason behind this - efficiency, as for example discussed here
Insertion of data after creating index on empty table or creating unique index after inserting data on oracle? ?
Thanks in advance!

答:
Other than indexes defined as part of a primary or unique constraint there does not appear to be a way to define an index as part of a CREATE TABLE statement in Oracle. Although the USING INDEX clause is part of the constraint-state element of the CREATE TABLE statement, a missing right parenthesis error is issued if you try to include a USING INDEX clause in any constraint definition except a PRIMARY or UNIQUE constraint - see this db<>fiddle for examples.

As to "why" - that's a question only someone on the architecture team at Oracle could answer. From my personal user-oriented point of view, I see no particular value to being able to create an index as part of the CREATE TABLE statement, but then I'm accustomed to how Oracle works and have my thought patterns oriented in that particular direction. YMMV.

Body:
In MySql, one can create an index on a (non-unique) column along with a table, e.g.

create table orders(
   orderid varchar(20) not null unique,
   customerid varchar(20),
   index(customerid)
   );

Having not found a corresponding option in Oracle, i.e. creating the index on table creation rather than as a separate command afterwards, I suspect it is not possible. Is this correct? If so, what is the reason behind this - efficiency, as for example discussed here
Insertion of data after creating index on empty table or creating unique index after inserting data on oracle? ?
Thanks in advance!


问:
Deleting a row in datagrid view
I want to Delete a row in the Gridview which is in the update panel . But instead of the command button ., i took a link button to get a confirmation message. Now if I press ok then the record should be deleted (both from db and frm girdview). I know how to delete from db but not when linkbutton is pressed, and deleting the record. And also the gridview is in update panel.so it should be reflected.

A sample code is appreciated.

Thanks

答:
Set PK_ID to link button's command args like that

```<code><asp:LinkButton runat="server" ID="btn_manage" Text="Delete" CommandArgument='<%#Eval("PK_ID") %>'
                                OnCommand="btn_manage_click">
</asp:LinkButton>
</code>```

and access this PK_ID on event

```<code>protected void btn_manage_click(object sender, CommandEventArgs e)
{
    string ID = e.CommandArgument.ToString();

    //you delete code and gridview bind code
}
</code>```

Title: Deleting a row in datagrid view

Body:
Set PK_ID to link button's command args like that

<asp:LinkButton runat="server" ID="btn_manage" Text="Delete" CommandArgument='<%#Eval("PK_ID") %>'
                                OnCommand="btn_manage_click">
</asp:LinkButton>

and access this PK_ID on event

protected void btn_manage_click(object sender, CommandEventArgs e)
{
    string ID = e.CommandArgument.ToString();

    //you delete code and gridview bind code
}


问:
How to insert a comma as a thousands separator in a pandas dataframe column?
I'm trying to format the Dollar Amount column to have a comma thousands separator for easier viewing, but I haven't been able to figure it out. Can someone please show me the way?</p>

```<code>import pandas as pd
df = pd.read_excel('filename.xlsx')
df['Dollar Amount'].head()

Index  Dollar Amount
0      5721.48
1      4000.00
2      4769.00
3       824.07
4       643.60
5       620.00

Name: Dollar Amount, dtype: float64
</code>```

答:
If you need to insert thousands comma separators in a specific column and remove the decimal place:

```<code>import pandas as pd
df = pd.DataFrame([(0.21, 1000.0), (0.01, 2000000.0), (0.66, 1000.0), (0.21, 330000.0)], columns=['A', 'B'])
</code>```

Before:

```<code>      A          B
0  0.21     1000.0
1  0.01  2000000.0
2  0.66     1000.0
3  0.21   330000.0
</code>```

For "Col B" insert comma separators and remove decimal place: A slight adjustment to YOBEN_S's code above gives:

```<code>lst = list(df.columns)
lst.remove('A')
for c in lst:
    df[c] = df[c].astype(int).apply(lambda x: f'{x:,}')
</code>```

After:

```<code>      A          B
0  0.21      1,000
1  0.01  2,000,000
2  0.66      1,000
3  0.21    330,000
</code>```

Body:
I'm trying to format the Dollar Amount column to have a comma thousands separator for easier viewing, but I haven't been able to figure it out. Can someone please show me the way?

import pandas as pd
df = pd.read_excel('filename.xlsx')
df['Dollar Amount'].head()

Index  Dollar Amount
0      5721.48
1      4000.00
2      4769.00
3       824.07
4       643.60
5       620.00

Name: Dollar Amount, dtype: float64

Body:
If you need to insert thousands comma separators in a specific column and remove the decimal place:

import pandas as pd
df = pd.DataFrame([(0.21, 1000.0), (0.01, 2000000.0), (0.66, 1000.0), (0.21, 330000.0)], columns=['A', 'B'])

Before:

      A          B
0  0.21     1000.0
1  0.01  2000000.0
2  0.66     1000.0
3  0.21   330000.0

For "Col B" insert comma separators and remove decimal place: A slight adjustment to YOBEN_S's code above gives:

lst = list(df.columns)
lst.remove('A')
for c in lst:
    df[c] = df[c].astype(int).apply(lambda x: f'{x:,}')

After:

      A          B
0  0.21      1,000
1  0.01  2,000,000
2  0.66      1,000
3  0.21    330,000