问:
OkHttp 4.x giving error when trying to access url via Call request
I recently started update to okhttp3 to 4.x

In doing so I am getting following build time error:

Using 'url(): HttpUrl' is an error. moved to val

The issue is happening when I am trying to get url from request object obtained via call:

e.g

```<code>   call.enque(callback : Callback){
     override fun onFailure(call : Call, t:Throwable) {
       val url = call.request().url().toString
     }
   }
</code>```

I looked up further and the Url object within Request is val aka final now.

Also, no directions on their upgrade guide https://square.github.io/okhttp/upgrading_to_okhttp_4/

I would appreciate for any suggestions on another way to obtain Url.

答:
```<code>Using 'url(): HttpUrl' is an error. moved to val
</code>```

This means you should change the function call url() to a property access url.

okhttp 4 comes with replaceWith param in the deprecation annotation that makes e.g. Android Studio to offer that fix automatically with right-click/alt-enter on the error:

```<code>@Deprecated(
  message = "moved to val",
  replaceWith = ReplaceWith(expression = "url"),
  level = DeprecationLevel.ERROR)
</code>```

From comments:

Upon further investigation I found out that the request() or Request object is from Retrofit 2. And Retrofit 2 returns call object from okhttp3

That's an issue with Android Studio. You can work around it with explicit cast to okhttp 4 types, e.g. (call.request() as Request).url.

Body:
I recently started update to okhttp3 to 4.x

In doing so I am getting following build time error:

Using 'url(): HttpUrl' is an error. moved to val

The issue is happening when I am trying to get url from request object obtained via call:

e.g

   call.enque(callback : Callback){
     override fun onFailure(call : Call, t:Throwable) {
       val url = call.request().url().toString
     }
   }

I looked up further and the Url object within Request is val aka final now.

Also, no directions on their upgrade guide https://square.github.io/okhttp/upgrading_to_okhttp_4/

I would appreciate for any suggestions on another way to obtain Url.

Body:
Using 'url(): HttpUrl' is an error. moved to val

This means you should change the function call url() to a property access url.

okhttp 4 comes with replaceWith param in the deprecation annotation that makes e.g. Android Studio to offer that fix automatically with right-click/alt-enter on the error:

@Deprecated(
  message = "moved to val",
  replaceWith = ReplaceWith(expression = "url"),
  level = DeprecationLevel.ERROR)

From comments:

Upon further investigation I found out that the request() or Request object is from Retrofit 2. And Retrofit 2 returns call object from okhttp3

That's an issue with Android Studio. You can work around it with explicit cast to okhttp 4 types, e.g. (call.request() as Request).url.


来源: stackexchange

问:
Django migrations integrity error column contains null values
```<code>django.db.utils.IntegrityError: column "required_tem_grid" contains null values
</code>```

So I mistakenly gave wrong type of value when Django asked me to provide default value for existing rows. Problem is now that I am stuck with this error. I have been burned by this error before too and the only way I could recover was to create another db and running migrations again. Is there any other way? I have tried to revert to previous migration (initial) but this error pops up everywhere. There is no such column in the database that I can see. Is there some place this default value gets cached?

答: Well I managed to solve it this way: Delete migration files and cached files, remove offending entry from models, delete migration data from django_migrations table for the app, run makemigrations and migrate --fake-initial. I was then able to change models and run migrations.

ContentLicense: CC BY-SA 4.0

Body:
django.db.utils.IntegrityError: column "required_tem_grid" contains null values

So I mistakenly gave wrong type of value when Django asked me to provide default value for existing rows. Problem is now that I am stuck with this error. I have been burned by this error before too and the only way I could recover was to create another db and running migrations again. Is there any other way? I have tried to revert to previous migration (initial) but this error pops up everywhere. There is no such column in the database that I can see. Is there some place this default value gets cached?


问:
Populate React Table with firebase realtime database data
I want to populate my table which i build using react library (react-table-6) with firebase data (using realtime database). I am getting values in console but not being able to put in table, each value in its own field. Values are rendering but i know im doing some silly mistake here.
See this image to see screen

Can anybody explain what im doing wrong here,
Below dropping function through which im retrieving values..

State:

```<code>this.state = {
         data: [ {trainerName: '', CourseName: '', evidence: '', comment: ''}
        ]}
</code>```

function:

```<code>get_course_list(){
        return firebase.database().ref('Users/CourseApprovals/').on('value', (snapshot) => {
            var data = [];
            snapshot.forEach((childSnapshot) => {
                var childData= childSnapshot.val();
                var child1 = childData.comments;
                var child2 = childData.evidence;
                var child3 = childData.selectedTrainer.label;
                var child4 = childData.selectedTrainer.value;
                var CompleteData = {child1, child2, child3, child4};
                data.push({
                    data: CompleteData
                });
            })
            this.setState({
                data
            }, console.log(data))
        })
    }

    componentDidMount(){
        this.get_course_list();
    }

</code>```

And in render,

```<code> <ReactTable
                        data={data}
                        columns={[
                            { Header: "SL No", maxWidth: 100,filterable: false, Cell: props => {
                                return <div>{props.index + 1}</div>;
                              }},
                            { Header: "Trainer Name", accessor: "trainerName", className: "sticky", headerClassName: "sticky" },
                            { Header: 'Course Name', accessor: 'CourseName'},
                            { Header: "Evidence", accessor: "evidence" },
                            { Header: 'Comments', accessor: 'comment'},
                        ]}
                        defaultPageSize={10}
                        className="-striped -highlight"
                        />
</code>```

答:
The problem may be in pushing data twice into the data array. Try this:

```<code>get_course_list() {
  let data = [];
  firebase.database().ref('Users/CourseApprovals').on('value', snapshot => {
    if (snapshot.exists()) {
       // making sure data exists
       snapshot.forEach(child => {
         let a = child.val();
         // build the object
         let CompleteData = {
           child1: a.comments,
           child2: a.evidence,
           child3: a.selectedTrainer.label,
           child4: a.selectedTrainer.value
         }

         // you are currently doing: data.push({ data: CompleteData })
         // by doing so your data array looks like this:
         // data:[{ data: { child1: '', ... } }, ...]

         data.push(CompleteData)

         // now your array should look like this:
         // data:[{ child1: '', ... }, ...]

       });
       // setState
       this.setState({ data });
       console.log(data);
    }
  })
}

componentDidMount() {
  this.get_course_list();
}
</code>```

Body:
I want to populate my table which i build using react library (react-table-6) with firebase data (using realtime database). I am getting values in console but not being able to put in table, each value in its own field. Values are rendering but i know im doing some silly mistake here.
See this image to see screen

Can anybody explain what im doing wrong here,
Below dropping function through which im retrieving values..

State:

this.state = {
         data: [ {trainerName: '', CourseName: '', evidence: '', comment: ''}
        ]}

function:

get_course_list(){
        return firebase.database().ref('Users/CourseApprovals/').on('value', (snapshot) => {
            var data = [];
            snapshot.forEach((childSnapshot) => {
                var childData= childSnapshot.val();
                var child1 = childData.comments;
                var child2 = childData.evidence;
                var child3 = childData.selectedTrainer.label;
                var child4 = childData.selectedTrainer.value;
                var CompleteData = {child1, child2, child3, child4};
                data.push({
                    data: CompleteData
                });
            })
            this.setState({
                data
            }, console.log(data))
        })
    }

    componentDidMount(){
        this.get_course_list();
    }

And in render,

 <ReactTable
                        data={data}
                        columns={[
                            { Header: "SL No", maxWidth: 100,filterable: false, Cell: props => {
                                return
{props.index + 1}
;
                              }},
                            { Header: "Trainer Name", accessor: "trainerName", className: "sticky", headerClassName: "sticky" },
                            { Header: 'Course Name', accessor: 'CourseName'},
                            { Header: "Evidence", accessor: "evidence" },
                            { Header: 'Comments', accessor: 'comment'},
                        ]}
                        defaultPageSize={10}
                        className="-striped -highlight"
                        />

Body:
The problem may be in pushing data twice into the data array. Try this:

get_course_list() {
  let data = [];
  firebase.database().ref('Users/CourseApprovals').on('value', snapshot => {
    if (snapshot.exists()) {
       // making sure data exists
       snapshot.forEach(child => {
         let a = child.val();
         // build the object
         let CompleteData = {
           child1: a.comments,
           child2: a.evidence,
           child3: a.selectedTrainer.label,
           child4: a.selectedTrainer.value
         }

         // you are currently doing: data.push({ data: CompleteData })
         // by doing so your data array looks like this:
         // data:[{ data: { child1: '', ... } }, ...]

         data.push(CompleteData)

         // now your array should look like this:
         // data:[{ child1: '', ... }, ...]

       });
       // setState
       this.setState({ data });
       console.log(data);
    }
  })
}

componentDidMount() {
  this.get_course_list();
}


问:
Redux state is updated but UI is not updating
I have created simple app to add user using redux and antd library. When user is added I am trying to show success message. I am able to get that updated message in state but when I alert that message it shows blank. When I again click the button then it shows success message in alert.

I have created codesandbox link : https://codesandbox.io/s/admiring-waterfall-v04g9

Please help me out, I am quite new to react.

答:
here is what possibly happened
- since your callback function is synchronous, eventhough the addUser function is placed before alert function, it is not a guarenty that it will execute before it. </p>

<p>solution is to make your function asynchronous as follows to guaranty that the user is added and hence state updated (with the user and the message you are displaying) before the alert is fired. make sure to save changes and refresh the sandbox to test it. </p>

```<code>handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields(async (err, values) => {
  if (!err) {
    await this.props.addUser(values);
    alert(this.props.message);
  }
});
</code>```

Body:
here is what possibly happened
- since your callback function is synchronous, eventhough the addUser function is placed before alert function, it is not a guarenty that it will execute before it.

solution is to make your function asynchronous as follows to guaranty that the user is added and hence state updated (with the user and the message you are displaying) before the alert is fired. make sure to save changes and refresh the sandbox to test it.

handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields(async (err, values) => {
  if (!err) {
    await this.props.addUser(values);
    alert(this.props.message);
  }
});


问:
How can I construct a unique_ptr pointing to a vector with single element conveniently?
I would like to construct a unique_ptr holding a vector<string>, which contains single element only. Is it possible to do this in single line of code?
I try this approach:

```<code>auto values = make_unique<vector<string>>({value});
</code>```

But compiler (clang++) complains:

```<code>No matching function for call to 'make_unique' candidate template ignored:
substitution failure [with _Tp = std::__1::vector<std::__1::basic_string<char>, std::__1::allocator<std::__1::basic_string<char> > >]: no type named '__unique_array_unknown_bound' in 'std::__1::__unique_if<st... candidate template ignored: substitution failure [with _Tp = std::__1::vector<std::__1::basic_string<char>, std::__1::allocator<std::__1::basic_string<char> > >]: no type named '__unique_array_known_bound' in 'std::__1::__unique_if<std:... candidate function [with _Tp = std::__1::vector<std::__1::basic_string<char>, std::__1::allocator<std::__1::basic_string<char> > >, _Args = <>] not viable: requires 0 arguments, but 1 was provided

</code>```

I don't understand why it doesn't work since vector apparently accepts using initializer_list for construction.

```<code>string value = ...;
auto values = vector<string>({value}); // this works
</code>```

Is creating a unique_ptr<vector<string>> and calling its push_back the only viable approach for constructing such a unique_ptr?

```<code>auto values = make_unique<vector<string>>();
values->push_back(value);
</code>```

More broadly, if I have a fixed number of elements (for example, 3 elements), and would like to build a unique_ptr holding a vector with these elements, what is the idiomatic way to do it?

答:
If value is a local variable, you can use the iterator constructor. Otherwise, you can directly use new to use the initialiser list constructor.

using string_vec = std::vector<std::string>;

auto values = std::make_unique<string_vec>(&value, &value + 1);
auto values = std::unique_ptr<string_vec>(new string_vec{ value });
```

And of course the second way easily generalises to small fixed-size initializers, like new string_vec{ value_1, value_2, value_3 }. With the first way, you would have to store them in a std::string[3] and just pass the begin/end of that.

Body:
I would like to construct a unique_ptr holding a vector<string>, which contains single element only. Is it possible to do this in single line of code?
I try this approach:

auto values = make_unique<vector<string>>({value});

But compiler (clang++) complains:

No matching function for call to 'make_unique' candidate template ignored:
substitution failure [with _Tp = std::__1::vector<std::__1::basic_string<char>, std::__1::allocator<std::__1::basic_string<char> > >]: no type named '__unique_array_unknown_bound' in 'std::__1::__unique_if<st... candidate template ignored: substitution failure [with _Tp = std::__1::vector<std::__1::basic_string<char>, std::__1::allocator<std::__1::basic_string<char> > >]: no type named '__unique_array_known_bound' in 'std::__1::__unique_if<std:... candidate function [with _Tp = std::__1::vector<std::__1::basic_string<char>, std::__1::allocator<std::__1::basic_string<char> > >, _Args = <>] not viable: requires 0 arguments, but 1 was provided

I don't understand why it doesn't work since vector apparently accepts using initializer_list for construction.

string value = ...;
auto values = vector<string>({value}); // this works

Is creating a unique_ptr<vector<string>> and calling its push_back the only viable approach for constructing such a unique_ptr?

auto values = make_unique<vector<string>>();
values->push_back(value);

More broadly, if I have a fixed number of elements (for example, 3 elements), and would like to build a unique_ptr holding a vector with these elements, what is the idiomatic way to do it?

Body:
If value is a local variable, you can use the iterator constructor. Otherwise, you can directly use new to use the initialiser list constructor.

using string_vec = std::vector<std::string>;

auto values = std::make_unique<string_vec>(&value, &value + 1);
auto values = std::unique_ptr<string_vec>(new string_vec{ value });

And of course the second way easily generalises to small fixed-size initializers, like new string_vec{ value_1, value_2, value_3 }. With the first way, you would have to store them in a std::string[3] and just pass the begin/end of that.


问:
How to make 3D carousel rotate automatically, no clicks required and stop at mouse hover
I found this 3D carousel online and wondering how to make it rotate infinitely without clicking buttons and stops at mouse hover, then continues to rotate again when there is no hover.

```<code>var carousel = $(".carousel"),
    currdeg  = 0;

$(".next").on("click", { d: "n" }, rotate);
$(".prev").on("click", { d: "p" }, rotate);

function rotate(e){
  if(e.data.d=="n"){
    currdeg = currdeg - 60;
  }
  if(e.data.d=="p"){
    currdeg = currdeg + 60;
  }
  carousel.css({
    "-webkit-transform": "rotateY("+currdeg+"deg)",
    "-moz-transform": "rotateY("+currdeg+"deg)",
    "-o-transform": "rotateY("+currdeg+"deg)",
    "transform": "rotateY("+currdeg+"deg)"
  });
}
</code>```

Here is a codepen

答:
@mamoun othman did a great job here! I added the hover pause/restart functionality below:

var carousel = $(".carousel"), currdeg  = 0;

function rotate(e){
  currdeg = currdeg - 60
  carousel.css({
    "-webkit-transform": "rotateY("+currdeg+"deg)",
    "-moz-transform": "rotateY("+currdeg+"deg)",
    "-o-transform": "rotateY("+currdeg+"deg)",
    "transform": "rotateY("+currdeg+"deg)"
  });
}

// storing state in window.carouselPause
const startCarousel = (e) => window.carouselPause = setInterval(rotate, 1000);
const stopCarousel = (e) => clearInterval(window.carouselPause);

carousel.on({
  // pause carousel when mouse is over
  'mouseenter': stopCarousel,
  // resume when mouse is off
  'mouseleave': startCarousel
});

// start the carousel when the page is loaded
startCarousel();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #333;
  padding: 70px 0;
  font: 15px/20px Arial, sans-serif;
}

.container {
  margin: 0 auto;
  width: 250px;
  height: 200px;
  position: relative;
  perspective: 1000px;
}

.carousel {
  height: 100%;
  width: 100%;
  position: absolute;
  transform-style: preserve-3d;
  transition: transform 1s;
}

.item {
  display: block;
  position: absolute;
  background: #000;
  width: 250px;
  height: 200px;
  line-height: 200px;
  font-size: 5em;
  text-align: center;
  color: #FFF;
  opacity: 0.95;
  border-radius: 10px;
}

.a {
  transform: rotateY(0deg) translateZ(250px);
  background: #ed1c24;
}
.b {
  transform: rotateY(60deg) translateZ(250px);
  background: #0072bc;
}
.c {
  transform: rotateY(120deg) translateZ(250px);
  background: #39b54a;
}
.d {
  transform: rotateY(180deg) translateZ(250px);
  background: #f26522;
}
.e {
  transform: rotateY(240deg) translateZ(250px);
  background: #630460;
}
.f {
  transform: rotateY(300deg) translateZ(250px);
  background: #8c6239;
}

.next, .prev {
  color: #444;
  position: absolute;
  top: 100px;
  padding: 1em 2em;
  cursor: pointer;
  background: #CCC;
  border-radius: 5px;
  border-top: 1px solid #FFF;
  box-shadow: 0 5px 0 #999;
  transition: box-shadow 0.1s, top 0.1s;
}
.next:hover, .prev:hover { color: #000; }
.next:active, .prev:active {
  top: 104px;
  box-shadow: 0 1px 0 #999;
}
.next { right: 5em; }
.prev { left: 5em; }</code>```

A

B

C

D

E

F

```

Body:
I found this 3D carousel online and wondering how to make it rotate infinitely without clicking buttons and stops at mouse hover, then continues to rotate again when there is no hover.

var carousel = $(".carousel"),
    currdeg  = 0;

$(".next").on("click", { d: "n" }, rotate);
$(".prev").on("click", { d: "p" }, rotate);

function rotate(e){
  if(e.data.d=="n"){
    currdeg = currdeg - 60;
  }
  if(e.data.d=="p"){
    currdeg = currdeg + 60;
  }
  carousel.css({
    "-webkit-transform": "rotateY("+currdeg+"deg)",
    "-moz-transform": "rotateY("+currdeg+"deg)",
    "-o-transform": "rotateY("+currdeg+"deg)",
    "transform": "rotateY("+currdeg+"deg)"
  });
}

Here is a codepen

Body:
@mamoun othman did a great job here! I added the hover pause/restart functionality below:

var carousel = $(".carousel"), currdeg  = 0;

function rotate(e){
  currdeg = currdeg - 60
  carousel.css({
    "-webkit-transform": "rotateY("+currdeg+"deg)",
    "-moz-transform": "rotateY("+currdeg+"deg)",
    "-o-transform": "rotateY("+currdeg+"deg)",
    "transform": "rotateY("+currdeg+"deg)"
  });
}

// storing state in window.carouselPause
const startCarousel = (e) => window.carouselPause = setInterval(rotate, 1000);
const stopCarousel = (e) => clearInterval(window.carouselPause);

carousel.on({
  // pause carousel when mouse is over
  'mouseenter': stopCarousel,
  // resume when mouse is off
  'mouseleave': startCarousel
});

// start the carousel when the page is loaded
startCarousel();

body {
  background: #333;
  padding: 70px 0;
  font: 15px/20px Arial, sans-serif;
}

.container {
  margin: 0 auto;
  width: 250px;
  height: 200px;
  position: relative;
  perspective: 1000px;
}

.carousel {
  height: 100%;
  width: 100%;
  position: absolute;
  transform-style: preserve-3d;
  transition: transform 1s;
}

.item {
  display: block;
  position: absolute;
  background: #000;
  width: 250px;
  height: 200px;
  line-height: 200px;
  font-size: 5em;
  text-align: center;
  color: #FFF;
  opacity: 0.95;
  border-radius: 10px;
}

.a {
  transform: rotateY(0deg) translateZ(250px);
  background: #ed1c24;
}
.b {
  transform: rotateY(60deg) translateZ(250px);
  background: #0072bc;
}
.c {
  transform: rotateY(120deg) translateZ(250px);
  background: #39b54a;
}
.d {
  transform: rotateY(180deg) translateZ(250px);
  background: #f26522;
}
.e {
  transform: rotateY(240deg) translateZ(250px);
  background: #630460;
}
.f {
  transform: rotateY(300deg) translateZ(250px);
  background: #8c6239;
}

.next, .prev {
  color: #444;
  position: absolute;
  top: 100px;
  padding: 1em 2em;
  cursor: pointer;
  background: #CCC;
  border-radius: 5px;
  border-top: 1px solid #FFF;
  box-shadow: 0 5px 0 #999;
  transition: box-shadow 0.1s, top 0.1s;
}
.next:hover, .prev:hover { color: #000; }
.next:active, .prev:active {
  top: 104px;
  box-shadow: 0 1px 0 #999;
}
.next { right: 5em; }
.prev { left: 5em; }

<div class="container">
  <div class="carousel">
    <div class="item a">A</div>
    <div class="item b">B</div>
    <div class="item c">C</div>
    <div class="item d">D</div>
    <div class="item e">E</div>
    <div class="item f">F</div>
  </div>
</div>
<!--<div class="next">Next</div>
<div class="prev">Prev</div>-->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>


问:
Letter Change using Python
Problem statement:

Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.

My Python program is:

```<code>def LetterChanges(str):
    for i in range(0,len(str)):
        a=ord(str[i])
        if a==122:
            str=str.replace(str[i],'a',1)
        elif a==90:
            str=str.replace(str[i],'a',1)
        elif (a>=65 and a<=90) or (a>=97 and a<=122):
            a=a+1
            char=chr(a)
            str=str.replace(str[i],char,1)
    for i in range(0,len(str)):
        if str[i]=='a':
            str=str.replace(str[i],'A',1)
        elif str[i]=='e':
            str=str.replace(str[i],'E',1)
        elif str[i]=='i':
            str=str.replace(str[i],'I',1)
        elif str[i]=='o':
            str=str.replace(str[i],'O',1)
        elif str[i]=='u':
            str=str.replace(str[i],'U',1)
    return(str)

print LetterChanges(raw_input())
</code>```

The problem with my code is that, when I input sen, the output was tfo which was correct.

But when I gave sent as my input, I got the wrong output.

答:
Here is my version of the algorithm.</p>

```<code>def LetterChanges(str):
    result = ''
    vowels = ['a','e','i','o','u']

    for s in str:
        if s.isalpha():
            if ord(s) == 122: #ASCII code of 'z'
                next_letter = chr(97)
            else:
                next_letter = chr(ord(s)+1)

            if next_letter in vowels:
                result += next_letter.upper()
            else:
                result += next_letter

        else:
            result += s

    return result
</code>```

Title: Letter Change using Python

Body:
Problem statement:

Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.

My Python program is:

def LetterChanges(str):
    for i in range(0,len(str)):
        a=ord(str[i])
        if a==122:
            str=str.replace(str[i],'a',1)
        elif a==90:
            str=str.replace(str[i],'a',1)
        elif (a>=65 and a<=90) or (a>=97 and a<=122):
            a=a+1
            char=chr(a)
            str=str.replace(str[i],char,1)
    for i in range(0,len(str)):
        if str[i]=='a':
            str=str.replace(str[i],'A',1)
        elif str[i]=='e':
            str=str.replace(str[i],'E',1)
        elif str[i]=='i':
            str=str.replace(str[i],'I',1)
        elif str[i]=='o':
            str=str.replace(str[i],'O',1)
        elif str[i]=='u':
            str=str.replace(str[i],'U',1)
    return(str)

print LetterChanges(raw_input())

The problem with my code is that, when I input sen, the output was tfo which was correct.

But when I gave sent as my input, I got the wrong output.

Body:
Here is my version of the algorithm.

def LetterChanges(str):
    result = ''
    vowels = ['a','e','i','o','u']

    for s in str:
        if s.isalpha():
            if ord(s) == 122: #ASCII code of 'z'
                next_letter = chr(97)
            else:
                next_letter = chr(ord(s)+1)

            if next_letter in vowels:
                result += next_letter.upper()
            else:
                result += next_letter

        else:
            result += s

    return result


问:
Django python View and Form - MultiValueDictKeyError at /result 'num1' - Why will my form not submit data
I've created a form to add two numbers and receive MultiValueDictKeyError at /result
'num1'.  I've tried many things but can't figure it out.  I figured I'd give this a try.

@project -> url.py:

```<code>from django.contrib import admin
    from django.urls import path, include
    from django.conf import settings
    from django.conf.urls.static import static
    from datetime import datetime

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('app1.urls')),
        path('result', include('app1.urls')),
    ]

    urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

@App-> url.py:

```<code>    from django.urls import path, include
    from django.conf.urls import include, url
    from django.conf import settings
    from django.conf.urls.static import static
    from . import views
    from . import urls
    from app1.models import Footprint
    import app1.views

    urlpatterns = [

        path("", views.index, name="index"),
        path('result', views.calc, name='result'),
    ]
</code>```

@App -> views.py:

```<code>    from django.shortcuts import render
    from django.http import HttpResponse
    from django.http import HttpRequest,HttpResponseRedirect
    from .models import Footprint

    # Create your views here.
    def index(request):
        foots = Footprint.objects.all()
        return render(request, "index.html", {'foots': foots})

    def calc(request):
        val1 = int(request.POST['num1'])
        val2 = int(request.POST['num2'])
        res = val1 + val2
        return render(request,'result.html',{'result': res})
</code>```

@templates -> index.html file where i write my form:

```<code>    {% block content %}
    <form action="calc" method="post">
        {% csrf_token %}
        <p style="color:white;">Installation Cost:</p> <input type="text" name="num1">
        <p style="color:white;">Installation Year:</p> <input type="text" name="num2"><br><br>
        <p><a href="result" class="btn btn-primary btn-lg btn-custom">SUBMIT</a></p>

    </form>
    {% endblock %}

</code>```

@result.html:

```<code>    {% block content %}
    Result: {{result}}
    {% endblock %}

</code>```

@here i got error

```<code>    MultiValueDictKeyError at /result
    'num1'
    Request Method: GET
    Request URL:    http://127.0.0.1:8000/result
    Django Version: 3.0.3
    Exception Type: MultiValueDictKeyError
    Exception Value:
    'num1'
    Exception Location: C:\Users\scott\Envs\venv\lib\site-
    packages\django\utils\datastructures.py in __getitem__, line 78
    Python Executable:  C:\Users\scott\Envs\venv\Scripts\python.exe
    Python Version: 3.8.0
    Python Path:
    ['C:\\Users\\scott\\projects\\marciano',
     'C:\\Users\\scott\\Envs\\venv\\Scripts\\python38.zip',
     'C:\\Users\\scott\\Envs\\venv\\DLLs',
     'C:\\Users\\scott\\Envs\\venv\\lib',
     'C:\\Users\\scott\\Envs\\venv\\Scripts',
     'c:\\users\\scott\\appdata\\local\\programs\\python\\python38\\Lib',
     'c:\\users\\scott\\appdata\\local\\programs\\python\\python38\\DLLs',
     'C:\\Users\\scott\\Envs\\venv',
     'C:\\Users\\scott\\Envs\\venv\\lib\\site-packages']
     Server time:   Fri, 14 Feb 2020 21:33:42 -0500

    Environment:

    Request Method: GET
    Request URL: http://127.0.0.1:8000/result

    Django Version: 3.0.3
    Python Version: 3.8.0
    Installed Applications:
    ['app1',
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles']
    Installed Middleware:
    ['django.middleware.security.SecurityMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware']

    Traceback (most recent call last):File "C:\Users\scott\Envs\venv\lib\site-    packages\django\utils\datastructures.py", line 76, in __getitem__
    list_ = super().__getitem__(key)

    During handling of the above exception ('num1'), another exception occurred:
      File "C:\Users\scott\Envs\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
      File "C:\Users\scott\Envs\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
      File "C:\Users\scott\Envs\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "C:\Users\scott\projects\marciano\app1\views.py", line 14, in calc
    val1 = int(request.POST['num1'])
      File "C:\Users\scott\Envs\venv\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__
    raise MultiValueDictKeyError(key)

    Exception Type: MultiValueDictKeyError at /result
    Exception Value: 'num1'
</code>```

答:
In your code templates -> index.html file where you write a form specify action change calc to result  and also remove a and href and add the <button type='submit'>submit</button>

@index.html

```<code>{% block content %}
    <form action="result" method="post"> #here change the action
        {% csrf_token %}
        <p style="color:white;">Installation Cost:</p> <input type="text" name="num1">
        <p style="color:white;">Installation Year:</p> <input type="text" name="num2"><br><br>
        <p><button type='submit' class="btn btn-primary btn-lg btn-custom">SUBMIT</button></p>
 # here  above you change the remove a and href='result' it reference and add submit button for submit the data
    </form>
{% endblock %}
</code>```

@apps -> url.py

```<code>path('result', views.calc, name='result'),  #here you name your url is result
</code>```

because you name your url result also best practice to remove hard code remove url use that {% url %} template tag

and use the get function in your view where you get the num1 and num2

@views -> views.py

```<code>def calc(request):
        val1 = int(request.POST.get('num1 ',1)) # here use the get method of dictionary see in python docs
        val2 = int(request.POST.get('num2',1)) # also same change use get method num2 is key and 1 is default value
        res = val1 + val2
        return render(request,'result.html',{'result': res})
</code>```

get()method is give a value of key if method not found any key it will return default value here we pass 1 if we not pass default value it take None

Here you make change in your code and if it work make a right answer for this question eventually let me know this work or not

Body:
I've created a form to add two numbers and receive MultiValueDictKeyError at /result
'num1'.  I've tried many things but can't figure it out.  I figured I'd give this a try.

@project -> url.py:

from django.contrib import admin
    from django.urls import path, include
    from django.conf import settings
    from django.conf.urls.static import static
    from datetime import datetime

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('app1.urls')),
        path('result', include('app1.urls')),
    ]

    urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

@App-> url.py:

    from django.urls import path, include
    from django.conf.urls import include, url
    from django.conf import settings
    from django.conf.urls.static import static
    from . import views
    from . import urls
    from app1.models import Footprint
    import app1.views

    urlpatterns = [

        path("", views.index, name="index"),
        path('result', views.calc, name='result'),
    ]

@App -> views.py:

    from django.shortcuts import render
    from django.http import HttpResponse
    from django.http import HttpRequest,HttpResponseRedirect
    from .models import Footprint

    # Create your views here.
    def index(request):
        foots = Footprint.objects.all()
        return render(request, "index.html", {'foots': foots})

    def calc(request):
        val1 = int(request.POST['num1'])
        val2 = int(request.POST['num2'])
        res = val1 + val2
        return render(request,'result.html',{'result': res})

@templates -> index.html file where i write my form:

    {% block content %}
    <form action="calc" method="post">
        {% csrf_token %}

Installation Cost:
 <input type="text" name="num1">

Installation Year:
 <input type="text" name="num2">

SUBMIT

    </form>
    {% endblock %}

@result.html:

    {% block content %}
    Result: {{result}}
    {% endblock %}

@here i got error

    MultiValueDictKeyError at /result
    'num1'
    Request Method: GET
    Request URL:    http://127.0.0.1:8000/result
    Django Version: 3.0.3
    Exception Type: MultiValueDictKeyError
    Exception Value:
    'num1'
    Exception Location: C:\Users\scott\Envs\venv\lib\site-
    packages\django\utils\datastructures.py in __getitem__, line 78
    Python Executable:  C:\Users\scott\Envs\venv\Scripts\python.exe
    Python Version: 3.8.0
    Python Path:
    ['C:\\Users\\scott\\projects\\marciano',
     'C:\\Users\\scott\\Envs\\venv\\Scripts\\python38.zip',
     'C:\\Users\\scott\\Envs\\venv\\DLLs',
     'C:\\Users\\scott\\Envs\\venv\\lib',
     'C:\\Users\\scott\\Envs\\venv\\Scripts',
     'c:\\users\\scott\\appdata\\local\\programs\\python\\python38\\Lib',
     'c:\\users\\scott\\appdata\\local\\programs\\python\\python38\\DLLs',
     'C:\\Users\\scott\\Envs\\venv',
     'C:\\Users\\scott\\Envs\\venv\\lib\\site-packages']
     Server time:   Fri, 14 Feb 2020 21:33:42 -0500

    Environment:

    Request Method: GET
    Request URL: http://127.0.0.1:8000/result

    Django Version: 3.0.3
    Python Version: 3.8.0
    Installed Applications:
    ['app1',
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles']
    Installed Middleware:
    ['django.middleware.security.SecurityMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware']

    Traceback (most recent call last):File "C:\Users\scott\Envs\venv\lib\site-    packages\django\utils\datastructures.py", line 76, in __getitem__
    list_ = super().__getitem__(key)

    During handling of the above exception ('num1'), another exception occurred:
      File "C:\Users\scott\Envs\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
      File "C:\Users\scott\Envs\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
      File "C:\Users\scott\Envs\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "C:\Users\scott\projects\marciano\app1\views.py", line 14, in calc
    val1 = int(request.POST['num1'])
      File "C:\Users\scott\Envs\venv\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__
    raise MultiValueDictKeyError(key)

    Exception Type: MultiValueDictKeyError at /result
    Exception Value: 'num1'

Body:
In your code templates -> index.html file where you write a form specify action change calc to result  and also remove a and href and add the <button type='submit'>submit</button>

@index.html

{% block content %}
    <form action="result" method="post"> #here change the action
        {% csrf_token %}
        <p style="color:white;">Installation Cost:</p> <input type="text" name="num1">
        <p style="color:white;">Installation Year:</p> <input type="text" name="num2"><br><br>
        <p><button type='submit' class="btn btn-primary btn-lg btn-custom">SUBMIT</button></p>
 # here  above you change the remove a and href='result' it reference and add submit button for submit the data
    </form>
{% endblock %}

@apps -> url.py

path('result', views.calc, name='result'),  #here you name your url is result

because you name your url result also best practice to remove hard code remove url use that {% url %} template tag

and use the get function in your view where you get the num1 and num2

@views -> views.py

def calc(request):
        val1 = int(request.POST.get('num1 ',1)) # here use the get method of dictionary see in python docs
        val2 = int(request.POST.get('num2',1)) # also same change use get method num2 is key and 1 is default value
        res = val1 + val2
        return render(request,'result.html',{'result': res})

get()method is give a value of key if method not found any key it will return default value here we pass 1 if we not pass default value it take None

Here you make change in your code and if it work make a right answer for this question eventually let me know this work or not


问:
Counting lack of a condition when joining tables
I'm sure this isn't that hard but I can't figure out the words to search for the answer online.  Here is the situation:

I have two tables, Transaction and Transaction Detail.  I need to modify records on Transaction that DON'T have a particular value when joining tables.

```<code>Transaction           Transaction Detail

Tran ID tran_type     Tran ID   Tranhead_id
1       45              1           145
2       3               1           148
3       45              2           230
                        2           467
                        3           220
                        3           310
</code>```

I need to join these tables by tran_id and then select the Transaction records with tran_type 45 that don't have a matching record on Transaction detail with tranhead_id = 145.  In this case tran_id 3 would be the only record selected.

答:
I would use an exists clause here:</p>

```<code>SELECT t.*
FROM [Transaction] t
WHERE
    tran_type = 45 AND
    NOT EXISTS (SELECT 1 FROM [Transaction Detail] td
                WHERE td.[Tran ID] = t.[Tran ID] AND td.Tranhead_id = 145);
</code>```

Body:
I'm sure this isn't that hard but I can't figure out the words to search for the answer online.  Here is the situation:

I have two tables, Transaction and Transaction Detail.  I need to modify records on Transaction that DON'T have a particular value when joining tables.

Transaction           Transaction Detail

Tran ID tran_type     Tran ID   Tranhead_id
1       45              1           145
2       3               1           148
3       45              2           230
                        2           467
                        3           220
                        3           310

I need to join these tables by tran_id and then select the Transaction records with tran_type 45 that don't have a matching record on Transaction detail with tranhead_id = 145.  In this case tran_id 3 would be the only record selected.

Body:
I would use an exists clause here:

SELECT t.*
FROM [Transaction] t
WHERE
    tran_type = 45 AND
    NOT EXISTS (SELECT 1 FROM [Transaction Detail] td
                WHERE td.[Tran ID] = t.[Tran ID] AND td.Tranhead_id = 145);


问:
Typescript generic type constraint from array of types
I have an array of types declared as

```<code>const APIS = [NewsApi, CommentsApi, FileApi];
</code>```

I want to have a method that accepts one of these types from that APIS array, like the following:

```<code>myMethod<T extends anyof APIS>(apiType: T): T {
    const api = new apiType(); //pseudo code, does not work off course
    // some common configuration code
    return api;
}
</code>```

. I cannot do myMethod<T extends NewsApi|CommentsApi>(): T, as the APIS array is auto generated. Is this possible with typescript?

Update:

Aleksey's solution works great for passing in the input. However, the return type cannot be inferred from the usage.

```<code>const myApi = myMethod(NewsApi);
</code>```

In above case, myApi is not of type NewsApi, but NewsApi|CommentsApi|FileApi.
Is it possible to set the return type explicitly to instance of input api type?

答:
If you can change definition of the array to readonly tuple:

```<code>const APIS = [NewsApi, CommentsApi, FileApi] as const;
</code>```

then you can get union of possible array values using lookup type:

```<code>type ApiConstructors = typeof APIS[number];

function myMethod<T extends InstanceType<ApiConstructors>>(apiType: new () => T): T {
  return new apiType();
}

const api = myMethod(NewsApi); // api is of type NewsApi
</code>```

InstanceType utility used to get instance type of a constructor function.

Playground

Body:
I have an array of types declared as

const APIS = [NewsApi, CommentsApi, FileApi];

I want to have a method that accepts one of these types from that APIS array, like the following:

myMethod<T extends anyof APIS>(apiType: T): T {
    const api = new apiType(); //pseudo code, does not work off course
    // some common configuration code
    return api;
}

. I cannot do myMethod<T extends NewsApi|CommentsApi>(): T, as the APIS array is auto generated. Is this possible with typescript?

Update:

Aleksey's solution works great for passing in the input. However, the return type cannot be inferred from the usage.

const myApi = myMethod(NewsApi);

In above case, myApi is not of type NewsApi, but NewsApi|CommentsApi|FileApi.
Is it possible to set the return type explicitly to instance of input api type?

Body:
If you can change definition of the array to readonly tuple:

const APIS = [NewsApi, CommentsApi, FileApi] as const;

then you can get union of possible array values using lookup type:

type ApiConstructors = typeof APIS[number];

function myMethod<T extends InstanceType<ApiConstructors>>(apiType: new () => T): T {
  return new apiType();
}

const api = myMethod(NewsApi); // api is of type NewsApi

InstanceType utility used to get instance type of a constructor function.

<a href="https://www.typescriptlang.org/play/index.html#code/MYGwhgzhAEByCmB3CBBADgS2gbwLAChpoBbARgC5owA7ATwG4CBfAg0SGAYQHtjj5qAF1SYcBIsQBMlGg2at87KNABiGEPHRY8hEgGYZdRvhb423ahEHQUABQCSAZWgBeaAG0EyLQBpoPPgFhX1V1TUwAXSoYYAsrYwJBWjR4G0weS0EAJwBXYEFuLJg3JJTuADMbB0d3ahziACN4LIiE-HKc6nyMCxJaAFl4QQALbgATAB4AFWh4AA9BATGYe0yaYHgp5PgJrQyrXPzCiAA+E4AKMEwtlMpqJGhzgEpXE+gpp8oZnSIsoZystRoPdEFRrttnsZTOZMmCsG5iAMhqMxucvCIME96NAAPQ4uHQDAwCrQUqpdFaBRKGAqbjcHDQUyIwYjcbnWncLG4-EAUTmKXy8DGsyyWUKQA" rel="nofollow noreferrer">Playground


问:
c# read in two bytes from string
HI,

I'm reading a file in as hex and storing it in a string, what I need to do is then read in two chars at a time so say i have a string that contains

313233343536373839

I would need to read in 31 followed by 32 followed by 33

I'm new to c# and programming in general, my book has nothing on it and I can't find an example that explains it well for me, if you could advise me I would be greatful!

答:
If you want to convert this hex string representation into a byte array you could use the following:</p>

```<code>string str = "313233343536373839";
byte[] buffer = Enumerable
    .Range(0, str.Length)
    .Where(x => x % 2 == 0)
    .Select(x => Convert.ToByte(str.Substring(x, 2), 16))
    .ToArray();
</code>```

ContentLicense: CC BY-SA 3.0

Title: c# read in two bytes from string

Body:
If you want to convert this hex string representation into a byte array you could use the following:

string str = "313233343536373839";
byte[] buffer = Enumerable
    .Range(0, str.Length)
    .Where(x => x % 2 == 0)
    .Select(x => Convert.ToByte(str.Substring(x, 2), 16))
    .ToArray();


问:
How do you get the information for one person
How do you use people.get to get the information for someone with a particular first and surname? I am confused as to how it works as there doesn't seem to be a people.search that you can call first. Thanks</p>

答: Unfortunately you cannot filter by fields (or at all). You can, however, get a list of contacts with people.conections.list and find you contact in the response.</p>


问:
Simulate Pairs (X, Y) from a Common Distribution?
I wanted to use R to simulate pairs from a common distribution, and just wanted to check if my approach is correct:

X, Y ~ N(15, 4) (independently and identically distributed)

So, if I wanted to simulate 10 (x, y) pairs from this normal distribution, would I just do:

```<code>x <- rnorm(10, 15, 4)
y <- rnorm(10, 15, 4)
</code>```

And then the these two vectors would contain 10 samples each and we could consider corresponding elements pairs? Or is there a different way to simulate the two variables at the same time/step?

答:
As long as you're not supposed to be drawing actual pairs from a 2D multivariate normal, then yes, you're drawing IID samples and making couplings from x and y gives you "pairs".  It's kind of a strange way to think about pairs though.

You could just as easily do matrix(rnorm(20, 15, 4), nrow = 2).  Given that the draws in rnorm are independent, you don't actually need two separate calls to rnorm.

Body:
I wanted to use R to simulate pairs from a common distribution, and just wanted to check if my approach is correct:

X, Y ~ N(15, 4) (independently and identically distributed)

So, if I wanted to simulate 10 (x, y) pairs from this normal distribution, would I just do:

x <- rnorm(10, 15, 4)
y <- rnorm(10, 15, 4)

And then the these two vectors would contain 10 samples each and we could consider corresponding elements pairs? Or is there a different way to simulate the two variables at the same time/step?


问:
How can I quit the for loop if value doesn't exist?
I've made a function that calculates distance using 4 values: lat1, lon1, lat2, and lat2

```<code>def greatcirclem(lat1,lon1,lat2,lon2):
    lat1,lon1,lat2,lon2=map(np.deg2rad,[lat1,lon1,lat2,lon2])
    dlon=lon2-lon1
    sint1=np.sin(lat1)
    sint2=np.sin(lat2)
    cost1=np.cos(lat1)
    cost2=np.cos(lat2)
    codln=np.cos(dlon)
    aaa=np.arccos(sint1*sint2+cost1*cost2*codln)
    ccc=np.rad2deg(aaa)
    km_greatcircle=ccc*1.852*60
    m_greatcircle=km_greatcircle*100
    return m_greatcircle
</code>```

When I apply this function in a for loop an error occurs when lat2,lon2 doesn't exist.

I mean cause I just select values from n rows and n+1 rows in my function, n+1 rows will be out of range at the end of part.

When the values don't exist how can I quit the for loop?

I'll attach my for loop code also.

```<code>for row in range(min(data3.index),max(data3.index)):
    data3.loc[row+1,'diff_m'] = greatcirclem(data3.loc[row,'lat'], data3.loc[row,'lon'], data3.loc[row+1,'lat'], data3.loc[row+1,'lon'])
</code>```

答:
Perhaps there are two solutions:

1) Write your function with default values?

def greatcirclem(lat1=0,lon1=0,lat2=0,lon2=0):

2) Put a conditional inside your for loop (more expensive, though):

```<code>      if lat2 and lon2:
          data3.loc[row+1,'diff_m'] = etc.
      else:
          continue #i.e. move on to the next data set OR insert arbitarty value
</code>```

It sounds like you're processing a data file where some entries might be missing? So you can either fudge in some values, or stick in a value that is so far out of bounds that it behaves as an error signal, or you could throw an exception... i.e. halt program execution because bad data. All depends on the case at hand.

Body:
I've made a function that calculates distance using 4 values: lat1, lon1, lat2, and lat2

def greatcirclem(lat1,lon1,lat2,lon2):
    lat1,lon1,lat2,lon2=map(np.deg2rad,[lat1,lon1,lat2,lon2])
    dlon=lon2-lon1
    sint1=np.sin(lat1)
    sint2=np.sin(lat2)
    cost1=np.cos(lat1)
    cost2=np.cos(lat2)
    codln=np.cos(dlon)
    aaa=np.arccos(sint1*sint2+cost1*cost2*codln)
    ccc=np.rad2deg(aaa)
    km_greatcircle=ccc*1.852*60
    m_greatcircle=km_greatcircle*100
    return m_greatcircle

When I apply this function in a for loop an error occurs when lat2,lon2 doesn't exist.

I mean cause I just select values from n rows and n+1 rows in my function, n+1 rows will be out of range at the end of part.

When the values don't exist how can I quit the for loop?

I'll attach my for loop code also.

for row in range(min(data3.index),max(data3.index)):
    data3.loc[row+1,'diff_m'] = greatcirclem(data3.loc[row,'lat'], data3.loc[row,'lon'], data3.loc[row+1,'lat'], data3.loc[row+1,'lon'])

Body:
Perhaps there are two solutions:

1) Write your function with default values?

def greatcirclem(lat1=0,lon1=0,lat2=0,lon2=0):

2) Put a conditional inside your for loop (more expensive, though):

      if lat2 and lon2:
          data3.loc[row+1,'diff_m'] = etc.
      else:
          continue #i.e. move on to the next data set OR insert arbitarty value

It sounds like you're processing a data file where some entries might be missing? So you can either fudge in some values, or stick in a value that is so far out of bounds that it behaves as an error signal, or you could throw an exception... i.e. halt program execution because bad data. All depends on the case at hand.


问:
How to programmatically control cogonito user access S3 object
Background

I use S3 to store paid content. My app also uses Cognito to authenticate users and also tracks who purchased what content. But how can I make an S3 object only accessible to the paid users?

For example: the object at "mybucket/private-content/obj1.pdf" needs to be accessible to user A but not to user B depending on the purchase record.

I can think of two solutions for now but none of them are ideal.

Solution 1

Make the bucket private. Then generate a signed URL for an object after the user purchased the content.
Problem: User A can purchase the content and share the signed URL to user B. User B can access the object without paying.

Solution 2
Every time when a user purchased some content, copy the object to a user folder in S3. And use a bucket policy to limit the user only accessing his own folder.
Problem: Need to duplicate content over and over. This increases my storage cost.

答:
Found a good enough solution using CloudFront signed URL together with a custom policy. In the custom policy, you can specify an IP range/address that can access the protected content.
This means that if a user share the link to another user, most likely the link will not work for the other user.

See here


问:
C#: Get field/property/method value (which is either string or uint) by name using reflection
I'm trying to parse some data out of many old assemblies from a 5-year old open source project and have mostly got it working, but the code is extremely verbose.

Edit: Also, I'm, trapped on .Net Framework 3.5

There are two members I'm interested in are named "Version" and "TargetVersion".

Until recently the "Version" member was a string defined in various ways. It's now replaced with a "ModVersion" member that grabs from assembly version. Some examples:

public string Version => "1.4";

public static readonly string Version = "1.8.14";

public const string Version = "2.8";

public static Version ModVersion => typeof(MainClass).Assembly.GetName().Version;
```

<p>The <code>TargetVersion</code> member only has two forms: <code>public static readonly uint</code> or <code>public const uint</code>.</p>

<p>So currently I get the member type, and then have nested <code>if .. else if ...</code> for various member types like so:</p>

<pre class="lang-cs prettyprint-override"><code>                    string dirty = string.Empty;

                    MemberTypes memberType = GetMemberType(mod, "Version");

                    if (memberType == MemberTypes.Property) {
                        Log.Info("It's a property");
                        dirty = mod
                            .GetProperty("Version", PUBLIC_STATIC)
                            .GetValue(mod, null)
                            .ToString();
                    } else if (memberType == MemberTypes.Field) {
                        Log.Info("It's a field");
                        dirty = mod
                            .GetField("Version", PUBLIC_STATIC)
                            .GetValue(mod)
                            .ToString();
                    } else if (memberType == MemberTypes.Method) {
                        Log.Info("It's a method");
                        dirty = mod
                            .GetMethod("Version", PUBLIC_STATIC)
                            .Invoke(null, null)
                            .ToString();
                    } else {
                        Log.Info("Version: Unsupported member type or not found");
                    }
</code>```

And then I've got a similar pile of code for getting the "TargetVersion" which is a uint. And now I'll need to add something else to get the new "ModVersion" in cases where "Version" is not found...

Is there any way I can reduce duplication? For example, is it possible to use generics? (I'm still newbie at C#) to avoid duplicating the code for the string vs uint vs. Version? And is there a way to chop down the amount of code that deals with the different member types?

I've seen something like this elsewhere on SO but no idea how to adapt it to my use case:

```<code>MemberInfo info = type.GetField(memberName) as MemberInfo ??
    type.GetProperty(memberName) as MemberInfo;
</code>```

What I'm ultimately hoping to achieve is something where I can specify a type and member name and just get the value back. Sort of a bool TryGetMemberValue<T>(Type thing, string memberName, out <T>value) method.

Hope this question isn't too dumb, I'm still learning the basics :o

答:
You were nearly there, maybe something like this

Note : I have just returned a string. You could pass another generic parameter in if you like and cast the results, however i assume all the types you want to work with will override ToString

```<code>public static bool TryGetValue<T>(T instance, string name, out string value)
{
   value = default;

   var member = typeof(T).GetMember(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
                         .FirstOrDefault();

   if (member == null)return false;

   switch (member.MemberType)
   {
      case MemberTypes.Field:
         value = (member as FieldInfo)?.GetValue(instance).ToString();
         break;
      case MemberTypes.Method:
         value = (member as MethodInfo)?.Invoke(instance, null).ToString();
         break;
      case MemberTypes.Property:
         value = (member as PropertyInfo)?.GetValue(instance).ToString();
         break;
      default:
         return false;
   }

   return true;

}
</code>```

or if you really want the type explicitly

```<code>public static bool TryGetValue<T,T2>(T instance, string name, out string value)
{
   ...

   switch (member.MemberType)
   {
      case MemberTypes.Field:
         value = (T2)(member as FieldInfo)?.GetValue(instance);
      ...
}
</code>```

Full Demo Here

Update

Here is a version where you give the type, and it spins up an instance to get the instance members, then disposes if it needs to

```<code>public static T GetValue<T>(object instance , MemberInfo member)
{
   switch (member.MemberType)
   {
      case MemberTypes.Field: return (T)(member as FieldInfo)?.GetValue(instance);
      case MemberTypes.Method: return (T)(member as MethodInfo)?.Invoke(instance, null);
      case MemberTypes.Property: return (T)(member as PropertyInfo)?.GetValue(instance);
      default:return default;
   }
}

public static bool TryGetValue<T>(Assembly asm, string className, string name, out T value)
{
   value = default;
   var type = asm.GetType(className);
   var instance = Activator.CreateInstance(type);

   try
   {
      var member = type.GetMember(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
                       .FirstOrDefault();

      if (instance == null || member == null) return false;

      value = GetValue<T>(instance, member);
   }
   finally
   {
      (instance as IDisposable)?.Dispose();
   }

   return true;
}
</code>```

Usage

```<code>Assembly asm = <some assembly>;

if(TryGetValue<uint>(asm, "MyNameSpace.Test1", "TargetVersion", out var out1))
     Console.WriteLine(out1);
</code>```

Body:
I'm trying to parse some data out of many old assemblies from a 5-year old open source project and have mostly got it working, but the code is extremely verbose.

Edit: Also, I'm, trapped on .Net Framework 3.5

There are two members I'm interested in are named "Version" and "TargetVersion".

Until recently the "Version" member was a string defined in various ways. It's now replaced with a "ModVersion" member that grabs from assembly version. Some examples:

public string Version => "1.4";

public static readonly string Version = "1.8.14";

public const string Version = "2.8";

public static Version ModVersion => typeof(MainClass).Assembly.GetName().Version;

The TargetVersion member only has two forms: public static readonly uint or public const uint.

So currently I get the member type, and then have nested if .. else if ... for various member types like so:

                    string dirty = string.Empty;

                    MemberTypes memberType = GetMemberType(mod, "Version");

                    if (memberType == MemberTypes.Property) {
                        Log.Info("It's a property");
                        dirty = mod
                            .GetProperty("Version", PUBLIC_STATIC)
                            .GetValue(mod, null)
                            .ToString();
                    } else if (memberType == MemberTypes.Field) {
                        Log.Info("It's a field");
                        dirty = mod
                            .GetField("Version", PUBLIC_STATIC)
                            .GetValue(mod)
                            .ToString();
                    } else if (memberType == MemberTypes.Method) {
                        Log.Info("It's a method");
                        dirty = mod
                            .GetMethod("Version", PUBLIC_STATIC)
                            .Invoke(null, null)
                            .ToString();
                    } else {
                        Log.Info("Version: Unsupported member type or not found");
                    }

And then I've got a similar pile of code for getting the "TargetVersion" which is a uint. And now I'll need to add something else to get the new "ModVersion" in cases where "Version" is not found...

Is there any way I can reduce duplication? For example, is it possible to use generics? (I'm still newbie at C#) to avoid duplicating the code for the string vs uint vs. Version? And is there a way to chop down the amount of code that deals with the different member types?

I've seen something like this elsewhere on SO but no idea how to adapt it to my use case:

MemberInfo info = type.GetField(memberName) as MemberInfo ??
    type.GetProperty(memberName) as MemberInfo;

What I'm ultimately hoping to achieve is something where I can specify a type and member name and just get the value back. Sort of a bool TryGetMemberValue<T>(Type thing, string memberName, out <T>value) method.

Hope this question isn't too dumb, I'm still learning the basics :o

Body:
You were nearly there, maybe something like this

Note : I have just returned a string. You could pass another generic parameter in if you like and cast the results, however i assume all the types you want to work with will override ToString

public static bool TryGetValue<T>(T instance, string name, out string value)
{
   value = default;

   var member = typeof(T).GetMember(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
                         .FirstOrDefault();

   if (member == null)return false;

   switch (member.MemberType)
   {
      case MemberTypes.Field:
         value = (member as FieldInfo)?.GetValue(instance).ToString();
         break;
      case MemberTypes.Method:
         value = (member as MethodInfo)?.Invoke(instance, null).ToString();
         break;
      case MemberTypes.Property:
         value = (member as PropertyInfo)?.GetValue(instance).ToString();
         break;
      default:
         return false;
   }

   return true;

}

or if you really want the type explicitly

public static bool TryGetValue<T,T2>(T instance, string name, out string value)
{
   ...

   switch (member.MemberType)
   {
      case MemberTypes.Field:
         value = (T2)(member as FieldInfo)?.GetValue(instance);
      ...
}

Full Demo Here

Update

Here is a version where you give the type, and it spins up an instance to get the instance members, then disposes if it needs to

public static T GetValue<T>(object instance , MemberInfo member)
{
   switch (member.MemberType)
   {
      case MemberTypes.Field: return (T)(member as FieldInfo)?.GetValue(instance);
      case MemberTypes.Method: return (T)(member as MethodInfo)?.Invoke(instance, null);
      case MemberTypes.Property: return (T)(member as PropertyInfo)?.GetValue(instance);
      default:return default;
   }
}

public static bool TryGetValue<T>(Assembly asm, string className, string name, out T value)
{
   value = default;
   var type = asm.GetType(className);
   var instance = Activator.CreateInstance(type);

   try
   {
      var member = type.GetMember(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
                       .FirstOrDefault();

      if (instance == null || member == null) return false;

      value = GetValue<T>(instance, member);
   }
   finally
   {
      (instance as IDisposable)?.Dispose();
   }

   return true;
}

Usage

Assembly asm = <some assembly>;

if(TryGetValue<uint>(asm, "MyNameSpace.Test1", "TargetVersion", out var out1))
     Console.WriteLine(out1);


问:
Finding PID and Base Address in C++
I'm trying to write a code in C++ which would display a process ID and base address of some application, PID seems to look correct but base address is 0, which is incorrect. My question is - what's wrong here?

IDE: Code::Blocks

Also to make it even run i had to set up "-lpsapi" in
Settings -> Compiler -> Linker settings -> Other linker options

I was thinking about building this as admin but could't find such option in Code::Block (maybe build-in?)

Console output

Build messages

```<code>#define WINVER 0x0501
#include <iostream>
#include <cstdio>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <Psapi.h>
#include <tlhelp32.h>

using namespace std;

HANDLE GetHandle()
{
    string name = "PathOfExile_x64.exe";
    DWORD pid = 0;

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32 process;
    ZeroMemory(&process, sizeof(process));
    process.dwSize = sizeof(process);

    if (Process32First(snapshot, &process))
    {
        do
        {
            if (string(process.szExeFile) == name)
            {
               pid = process.th32ProcessID;
               break;
            }
        } while (Process32Next(snapshot, &process));
    }

    CloseHandle(snapshot);

    if (pid != 0)
    {
        cout << "pid = " << pid << endl;
        return OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    }

    return NULL;
}

HMODULE GetModule()
{
    HMODULE hMods[1024];
    HANDLE pHandle = GetHandle();
    DWORD cbNeeded;
    unsigned int i;

    if (EnumProcessModules(pHandle, hMods, sizeof(hMods), &cbNeeded))
        {
        for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
        {
            TCHAR szModName[MAX_PATH];
            if (GetModuleFileNameEx(pHandle, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR)))
            {
                string wstrModName = szModName;

                string wstrModContain = "PathOfExile_x64.exe";
                if (wstrModName.find(wstrModContain) != string::npos)
                {
                    CloseHandle(pHandle);
                    return hMods[i];
                }
            }
        }
    }
    return nullptr;
}

int main()
{
    HWND WindowHandle = FindWindow(nullptr, "Path of Exile");
    DWORD PID;
    GetWindowThreadProcessId(WindowHandle, &PID);
    PVOID hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, 0, PID);

    HMODULE Module = GetModule();
    DWORD BaseAddress = (DWORD)Module;

    cout << BaseAddress << endl;

}
</code>```

答:
I would do it like this, tested working.  I'm not familiar with the Enum functions, I prefer to use the ToolHelp32Snapshot function

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <tlhelp32.h>

DWORD GetProcId(const char* procName)
{
    DWORD procId = 0;
    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnap != INVALID_HANDLE_VALUE)
    {
        PROCESSENTRY32 procEntry;
        procEntry.dwSize = sizeof(procEntry);

        if (Process32First(hSnap, &procEntry))
        {
            do
            {
                if (!_stricmp(procEntry.szExeFile, procName))
                {
                    procId = procEntry.th32ProcessID;
                    break;
                }
            } while (Process32Next(hSnap, &procEntry));

        }
    }
    CloseHandle(hSnap);
    return procId;
}

uintptr_t GetModuleBaseAddress(DWORD procId, const char* modName)
{
    uintptr_t modBaseAddr = 0;
    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, procId);
    if (hSnap != INVALID_HANDLE_VALUE)
    {
        MODULEENTRY32 modEntry;
        modEntry.dwSize = sizeof(modEntry);
        if (Module32First(hSnap, &modEntry))
        {
            do
            {
                if (!_stricmp(modEntry.szModule, modName))
                {
                    modBaseAddr = (uintptr_t)modEntry.modBaseAddr;
                    break;
                }
            } while (Module32Next(hSnap, &modEntry));
        }
    }
    CloseHandle(hSnap);
    return modBaseAddr;
}

int main()
{
    DWORD procId = GetProcId("PathOfExile_x64.exe");

    uintptr_t modBase = GetModuleBaseAddress(procId, "PathOfExile_x64.exe");

    std::cout << "0x" << std::hex << modBase << std::endl;
    std::getchar();
    return 0;
}
```

Title: Finding PID and Base Address in C++

Body:
I'm trying to write a code in C++ which would display a process ID and base address of some application, PID seems to look correct but base address is 0, which is incorrect. My question is - what's wrong here?

IDE: Code::Blocks

Also to make it even run i had to set up "-lpsapi" in
Settings -> Compiler -> Linker settings -> Other linker options

I was thinking about building this as admin but could't find such option in Code::Block (maybe build-in?)

Console output

Build messages

#define WINVER 0x0501
#include <iostream>
#include <cstdio>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <Psapi.h>
#include <tlhelp32.h>

using namespace std;

HANDLE GetHandle()
{
    string name = "PathOfExile_x64.exe";
    DWORD pid = 0;

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32 process;
    ZeroMemory(&process, sizeof(process));
    process.dwSize = sizeof(process);

    if (Process32First(snapshot, &process))
    {
        do
        {
            if (string(process.szExeFile) == name)
            {
               pid = process.th32ProcessID;
               break;
            }
        } while (Process32Next(snapshot, &process));
    }

    CloseHandle(snapshot);

    if (pid != 0)
    {
        cout << "pid = " << pid << endl;
        return OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    }

    return NULL;
}

HMODULE GetModule()
{
    HMODULE hMods[1024];
    HANDLE pHandle = GetHandle();
    DWORD cbNeeded;
    unsigned int i;

    if (EnumProcessModules(pHandle, hMods, sizeof(hMods), &cbNeeded))
        {
        for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
        {
            TCHAR szModName[MAX_PATH];
            if (GetModuleFileNameEx(pHandle, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR)))
            {
                string wstrModName = szModName;

                string wstrModContain = "PathOfExile_x64.exe";
                if (wstrModName.find(wstrModContain) != string::npos)
                {
                    CloseHandle(pHandle);
                    return hMods[i];
                }
            }
        }
    }
    return nullptr;
}

int main()
{
    HWND WindowHandle = FindWindow(nullptr, "Path of Exile");
    DWORD PID;
    GetWindowThreadProcessId(WindowHandle, &PID);
    PVOID hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, 0, PID);

    HMODULE Module = GetModule();
    DWORD BaseAddress = (DWORD)Module;

    cout << BaseAddress << endl;

}


问:
Scraping class name on a website using php
So, I want to scrape a class name from a website. Here's the source of html code:

```<code><td title="Complexity" class="cvss6" itemscope itemtype="http://schema.org/Rating">
</code>```

I want to scrape the "cvss6" only, tried with this:

```<code>$nilai1 = explode('<td title="Complexity" class="', $kodeHTML);
$nilai_show2 = explode('" itemscope="', $nilai1[1]);echo "

<tr><td width='85%' align='left' bgcolor='#F5F5F5'>".$judul_show[0]."</td>";

if($nilai_show2[0] == 'cvss6') {
echo "<td width='15%' align='center' bgcolor='#FF0000'>High</td></tr>";

                    }
</code>```

but it didn't work, it just won't show anything on my site. I managed to scrape it's html plain text. But how do you scrape a text that is inside the class name?
Thanks

答:
To answer your question you could use regular expression to find what you need,
with code below we try to find term that expect class="something" with multiline flag (https://www.php.net/manual/fr/function.preg-match-all.php) :

```<code>preg_match_all(
    '/class="(.+?)"/m',
    '<b>exemple : </b><div class="test test1 test2 test3" align=left>This is a test</div class="t1 t2">',
    $out
);

var_dump($out[1]);

/* output
  array(2) {
    [0]=>
    string(22) "test test1 test2 test3"
    [1]=>
    string(5) "t1 t2"
  }
*/
</code>```

Also i advice you to use an library to crawl web page with php.

https://symfony.com/doc/current/components/dom_crawler.html

Body:
So, I want to scrape a class name from a website. Here's the source of html code:

I want to scrape the "cvss6" only, tried with this:

$nilai1 = explode('<td title="Complexity" class="', $kodeHTML);
$nilai_show2 = explode('" itemscope="', $nilai1[1]);echo "

".$judul_show[0]."	";

if($nilai_show2[0] == 'cvss6') {
echo "High
";

                    }

but it didn't work, it just won't show anything on my site. I managed to scrape it's html plain text. But how do you scrape a text that is inside the class name?
Thanks

Body:
To answer your question you could use regular expression to find what you need,
with code below we try to find term that expect class="something" with multiline flag (https://www.php.net/manual/fr/function.preg-match-all.php) :

preg_match_all(
    '/class="(.+?)"/m',
    '<b>exemple : </b><div class="test test1 test2 test3" align=left>This is a test</div class="t1 t2">',
    $out
);

var_dump($out[1]);

/* output
  array(2) {
    [0]=>
    string(22) "test test1 test2 test3"
    [1]=>
    string(5) "t1 t2"
  }
*/

Also i advice you to use an library to crawl web page with php.

https://symfony.com/doc/current/components/dom_crawler.html


问:
How to generate mousedown or keypress event programmatically?
I am developing a chrome extension that runs some javascript on a particular web page.

I want to simulate a click action on the google docs presentation view page's 'prev', 'next' toolbar.
Unfortunately, both are  tags with onmousedown events corresponding to obfuscated javascript.

If they were anchors,
document.getElementById("ToolbarNext").onclick(); works. However, the same for onmousedown does not seem to work, probably because it requires mouse co-ordinates, etc.
How do I generate this event?

An other option is to simulate a keypress 'j' or 'k' on the DOM. I tried a few options but could not figure that out either.

答: try dispatchEvent/fireEvent methods

Body: try dispatchEvent/fireEvent methods


问:
Is there a way to accept full payment from customers later on when their order is ready to deliver in woocommerce?
I am trying to develop a website using woocommerce wherein my customers would place an order to get some graphics designed by me as per their requirmens.

Now what I am trying to achieve is to fetch their requirement and if possible get a fraction of total amount from the customer as advance payment. I should then be able to design the graphic as per their requirement which will take some time suppose 2 to 3 days after which I should give them a link to the designed graphic but they should only be able to download it when they pay the rest of the amount i.e. the full amount.

Is there a plugin to achieve this functionality?

答:
there is a good paid solution for this which is the official "Woocommerce Deposits" plugin by the Woocommerce company itself:
https://woocommerce.com/products/woocommerce-deposits/

Meanwhile I'm searching for an alternative solution for you.


问:
how to solve java.net.SocketException: socket failed: EPERM (Operation not permitted)
When I was using my Android Studio to create a simple registration to my local database I met the problem that shows on the title, and here is my code:

```<code>public class registerInterface extends AppCompatActivity {
    private EditText editTextUsername, editTextPassword, editTextEmail;
    private Button buttonRegister, backToLogin;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registration_interface);
        editTextUsername = findViewById(R.id.username);
        editTextPassword = findViewById(R.id.password);
        editTextEmail = findViewById(R.id.email);

        buttonRegister = findViewById(R.id.register);
        backToLogin = findViewById(R.id.go_back_login);

        progressDialog = new ProgressDialog(this);

        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerUser();
            }
        });

    }

    public void registerUser(){
        final String email = editTextEmail.getText().toString().trim();
        final String password = editTextPassword.getText().toString().trim();
        final String username = editTextUsername.getText().toString().trim();

        progressDialog.setMessage("Registering...");
        progressDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, DataBaseConstants.URL_REGISTER, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                progressDialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                } catch (JSONException e){
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.hide();
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("username", username);
                params.put("email", email);
                params.put("password", password);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
}
</code>```

I have already add these in my AndroidManifest.xml, but still does not work:

```<code><uses-permission android:name="android.promission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
</code>```

I don't if it is the problem about the IP address, but I just cannot figure it out.

答: Hi and I have found the solution. It's the matter of the virtual device, in my version API 29 the connection of network is forbidden. I recommend using the third party virtual device and now I'm using 'NetEase MUMU' and if you meet similar question you can check it out.</p>

Body:
When I was using my Android Studio to create a simple registration to my local database I met the problem that shows on the title, and here is my code:

public class registerInterface extends AppCompatActivity {
    private EditText editTextUsername, editTextPassword, editTextEmail;
    private Button buttonRegister, backToLogin;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registration_interface);
        editTextUsername = findViewById(R.id.username);
        editTextPassword = findViewById(R.id.password);
        editTextEmail = findViewById(R.id.email);

        buttonRegister = findViewById(R.id.register);
        backToLogin = findViewById(R.id.go_back_login);

        progressDialog = new ProgressDialog(this);

        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerUser();
            }
        });

    }

    public void registerUser(){
        final String email = editTextEmail.getText().toString().trim();
        final String password = editTextPassword.getText().toString().trim();
        final String username = editTextUsername.getText().toString().trim();

        progressDialog.setMessage("Registering...");
        progressDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, DataBaseConstants.URL_REGISTER, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                progressDialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                } catch (JSONException e){
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.hide();
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("username", username);
                params.put("email", email);
                params.put("password", password);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
}

I have already add these in my AndroidManifest.xml, but still does not work:

<uses-permission android:name="android.promission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

I don't if it is the problem about the IP address, but I just cannot figure it out.


问:
Scope of a variable in functions
```<code>def swap(list1):
    print(i, j)
    temp = list1[i]
    list1[i] = list1[j]
    list1[j] = temp

list1 = [5,3,8]
i, j = 0, len(list1)-1
while i < j:
    swap(list1)
    i += 1
    j -= 1
print(list1)
</code>```

Why am I able access the variables i, j in the function swap isn't it supposed to be out of scope?

答: Pretty simple - i and j are global, so accessible from every function you define - unless you shadow them with inner definitions (e.g. i = 'test123' in swap).

Title: Scope of a variable in functions

Body:
def swap(list1):
    print(i, j)
    temp = list1[i]
    list1[i] = list1[j]
    list1[j] = temp

list1 = [5,3,8]
i, j = 0, len(list1)-1
while i < j:
    swap(list1)
    i += 1
    j -= 1
print(list1)

Why am I able access the variables i, j in the function swap isn't it supposed to be out of scope?


问:
SELECT \ FROM AnyTableName
I tried to explore in SQL. Suddenly saw below query

```<code>SELECT \ FROM AnyTableName; --give you table name here
</code>```

works fine.
when i try to explore further, the below query, it gives value(s) as 0.00 and datatype as money .

```<code>IF OBJECT_ID('TEMPDB..#A') IS NOT NULL
    DROP TABLE #A;
SELECT \ AS A INTO #A;
SELECT A FROM #A;
EXEC TEMPDB..SP_HELP '#A';
</code>```

whats the logic behind SQL Server on this scenario?

答:
Someone else wondered the same thing and didn't really get a clear answer but from the research done there I'd say it's just a shortcut way to declare a money datatype, in the same way that adding a period after a number is a shortcut way to use decimals for calculations:

```<code>SELECT 1.    --returns 1.0 as a decimal number rather than an int
SELECT 1/2  --returns 0 because all operands are ints
SELECT 1/2. --returns 0.5; the addition of a decimal point makes the 2 a decimal instead - whole calc now done with decimals
</code>```

You don't need to write a .0, just a period will do, though arguably it's clearer to write 2.0.

Think of it like a other regular currency sign:

```<code>SELECT $   --0 money
SELECT ¥1  --1 money
SELECT €.  --0 money
SELECT £.5 --0.5 money
</code>```

etc all get changed to money datatype. Why is it this way for backslash? Well, we can't vouch for what the sql server dev team are thinking but I would propose that some people don't have these signs on their keyboards, so an alternative symbol was also provided that can be used for money if the sqlserver dev team weren't aware of all world currency symbols, or they wanted a standard way to refer to money datatype that specifically wasn't a currency symbol that varies from country to country

Title: SELECT \ FROM AnyTableName

Body:
I tried to explore in SQL. Suddenly saw below query

SELECT \ FROM AnyTableName; --give you table name here

works fine.
when i try to explore further, the below query, it gives value(s) as 0.00 and datatype as money .

IF OBJECT_ID('TEMPDB..#A') IS NOT NULL
    DROP TABLE #A;
SELECT \ AS A INTO #A;
SELECT A FROM #A;
EXEC TEMPDB..SP_HELP '#A';

whats the logic behind SQL Server on this scenario?

Body:
Someone else wondered the same thing and didn't really get a clear answer but from the research done there I'd say it's just a shortcut way to declare a money datatype, in the same way that adding a period after a number is a shortcut way to use decimals for calculations:

SELECT 1.    --returns 1.0 as a decimal number rather than an int
SELECT 1/2  --returns 0 because all operands are ints
SELECT 1/2. --returns 0.5; the addition of a decimal point makes the 2 a decimal instead - whole calc now done with decimals

You don't need to write a .0, just a period will do, though arguably it's clearer to write 2.0.

Think of it like a other regular currency sign:

SELECT $   --0 money
SELECT ¥1  --1 money
SELECT €.  --0 money
SELECT £.5 --0.5 money

etc all get changed to money datatype. Why is it this way for backslash? Well, we can't vouch for what the sql server dev team are thinking but I would propose that some people don't have these signs on their keyboards, so an alternative symbol was also provided that can be used for money if the sqlserver dev team weren't aware of all world currency symbols, or they wanted a standard way to refer to money datatype that specifically wasn't a currency symbol that varies from country to country


问:
How is state passed to selectors in a react-redux app?
I came across an example, where the mapStateToProps function is using memoization. I was just wondering how the "state" parameter is passed onto memoized selectors. After looking at the docs for reselect as well as redux, it seems that the mapStateToProps can return a function which accepts state as its argument, and the connect decorator might be the one passing the state to it but am not sure. Can someone please shed some light?

views/tracklist/index.js

```<code>const mapStateToProps = createSelector(
  getBrowserMedia,
  getPlayerIsPlaying,
  getPlayerTrackId,
  getCurrentTracklist,
  getTracksForCurrentTracklist,
  (media, isPlaying, playerTrackId, tracklist, tracks) => ({
    displayLoadingIndicator: tracklist.isPending || tracklist.hasNextPage,
    isMediaLarge: !!media.large,
    isPlaying,
    pause: audio.pause,
    pauseInfiniteScroll: tracklist.isPending || !tracklist.hasNextPage,
    play: audio.play,
    selectedTrackId: playerTrackId,
    tracklistId: tracklist.id,
    tracks
  })
);

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Tracklist);
</code>```

core/tracklists/selectors.js

```<code>export function getCurrentTracklist(state) {
//  console.log(state);
  let tracklists = getTracklists(state);
  return tracklists.get(tracklists.get('currentTracklistId'));
}

export const getTracksForCurrentTracklist = createSelector(
  getCurrentPage,
  getCurrentTrackIds,
  getTracks,
  (currentPage, trackIds, tracks) => {
    return trackIds
      .slice(0, currentPage * TRACKS_PER_PAGE)
      .map(id => tracks.get(id));
  }
);
</code>```

答:
In the cases you mentioned, mapStateToProps is a function which takes in state and returning object. When you passed mapStateToProps to connect, you passed a function which accepts state provided by connect as its argument.

createSelector creates a function which can take in state and returning object as well. Therefore you can assign it to mapStateToProps and pass it into connect.

In documentation, you'll normally find the following:

```<code>const mapStateToProps = (state) => {
    whatever code
}
</code>```

and

```<code>export default connect(mapStateToProps, mapDispatchToProps)(Component)
</code>```

where mapStateToProps takes in state argument which is provided by connect.

However, one can let mapStateToProps to be a selector as followed:

```<code>const mapStateToProps = createSelector(
    whatever code
)
</code>```

This is because createSelector can take in a state as followed:

```<code>createSelector(whatever code)(state)
</code>```

and return an object, just like what you find a mapStateToProps does in documentation.

Body:
I came across an example, where the mapStateToProps function is using memoization. I was just wondering how the "state" parameter is passed onto memoized selectors. After looking at the docs for reselect as well as redux, it seems that the mapStateToProps can return a function which accepts state as its argument, and the connect decorator might be the one passing the state to it but am not sure. Can someone please shed some light?

views/tracklist/index.js

const mapStateToProps = createSelector(
  getBrowserMedia,
  getPlayerIsPlaying,
  getPlayerTrackId,
  getCurrentTracklist,
  getTracksForCurrentTracklist,
  (media, isPlaying, playerTrackId, tracklist, tracks) => ({
    displayLoadingIndicator: tracklist.isPending || tracklist.hasNextPage,
    isMediaLarge: !!media.large,
    isPlaying,
    pause: audio.pause,
    pauseInfiniteScroll: tracklist.isPending || !tracklist.hasNextPage,
    play: audio.play,
    selectedTrackId: playerTrackId,
    tracklistId: tracklist.id,
    tracks
  })
);

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Tracklist);

core/tracklists/selectors.js

export function getCurrentTracklist(state) {
//  console.log(state);
  let tracklists = getTracklists(state);
  return tracklists.get(tracklists.get('currentTracklistId'));
}

export const getTracksForCurrentTracklist = createSelector(
  getCurrentPage,
  getCurrentTrackIds,
  getTracks,
  (currentPage, trackIds, tracks) => {
    return trackIds
      .slice(0, currentPage * TRACKS_PER_PAGE)
      .map(id => tracks.get(id));
  }
);

Body:
In the cases you mentioned, mapStateToProps is a function which takes in state and returning object. When you passed mapStateToProps to connect, you passed a function which accepts state provided by connect as its argument.

createSelector creates a function which can take in state and returning object as well. Therefore you can assign it to mapStateToProps and pass it into connect.

In documentation, you'll normally find the following:

const mapStateToProps = (state) => {
    whatever code
}

and

export default connect(mapStateToProps, mapDispatchToProps)(Component)

where mapStateToProps takes in state argument which is provided by connect.

However, one can let mapStateToProps to be a selector as followed:

const mapStateToProps = createSelector(
    whatever code
)

This is because createSelector can take in a state as followed:

createSelector(whatever code)(state)

and return an object, just like what you find a mapStateToProps does in documentation.


问:
Particle-JS Responsive canvas height issue
I've been working with a Bootstrap portfolio where I am trying to use particle.js on the profile picture.

I set the particles inside a DIV and gave it a bg-image with profile photo. The fact is, when I reload the screen on XL screen and resize the screen to xl > lg > md, it stays fine. But when The screen size increased to md > lg > xl, the canvas height doesn't decrease according to its parent. Please HELP!

Here is the link:

https://sabbir030.github.io/portfolio/

Canvas Height Issue

```<code><header id="main-header">
    <!-- full row for image to the left and others to the right -->
    <div class="row no-gutters">
      <!-- images to the left with 4 col -->
      <div class=" col-md-5 col-lg-4">

       <!-- PARTICLE JS WITH PROFILE PICTURE -->

        <div id="particles-js"></div>

      </div>

      <!-- Name and Menu to the right with 8 col -->
      <div class=" col-md-7 col-lg-8">

      </div>
    </div>
  </header>
</code>```

```<code>#particles-js {
    width: 100%;
    height: 100%;
    background-color: #b61924;
    background-image: url('../img/profile.jpg');
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: no-repeat;
}
</code>```

答:
You can define max-width, max-height and margin: 0 auto on #particles-js id for centering particle div.

```<code>#particles-js {
  max-width: 380px;
  max-height: 401px;
  margin: 0 auto;
}
</code>```

Body:
I've been working with a Bootstrap portfolio where I am trying to use particle.js on the profile picture.

I set the particles inside a DIV and gave it a bg-image with profile photo. The fact is, when I reload the screen on XL screen and resize the screen to xl > lg > md, it stays fine. But when The screen size increased to md > lg > xl, the canvas height doesn't decrease according to its parent. Please HELP!

Here is the link:

https://sabbir030.github.io/portfolio/

Canvas Height Issue

#particles-js {
    width: 100%;
    height: 100%;
    background-color: #b61924;
    background-image: url('../img/profile.jpg');
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: no-repeat;
}

Body:
You can define max-width, max-height and margin: 0 auto on #particles-js id for centering particle div.

#particles-js {
  max-width: 380px;
  max-height: 401px;
  margin: 0 auto;
}