问:
Why isn't flatlist not able to map through and display the data?
I am using Zomato API to get the list of restaurants, data is in the form of the array which has object restaurants in which there are different restaurant objects and then their name and other details.

It's my first time using a flat List and I am not able to display this data.

Goal: Use the search bar to display the list of restaurants in the city using flatlist.

```<code>import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { SearchBar } from 'react-native-elements';
import { FlatList } from 'react-native-gesture-handler';

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = { search: '', data: [] };
    }

    componentDidMount() {
        fetch('https://developers.zomato.com/api/v2.1/search', {
            method: 'GET',
            headers: {
                'user-key': '999999999999999999999999999'
            },
            params: JSON.stringify({
                entity_type: 'city',
                q: {this.state.search}
            }),
        }).then((response) => response.json())
            .then((responseJson) => { return this.setState({ data: responseJson.restaurants }) })
            .catch((error) => { console.warn(error) }
            );
    }

    render() {
        let data = this.state.data;
        let name = data.map(p => p.restaurant.name)
        console.warn("Check Data", name)
        return (
            <View>
                <SearchBar
                    round
                    searchIcon={{ size: 24 }}
                    placeholder='Search'
                    onChangeText={search => { this.setState({ search }) }}
                    value={this.state.search}
                />
//Using this method to display the data if any

                {name.length != 0 ?
                    <FlatList
                        data={name}
                        keyExtractor={(x, i) => x + i}
                        renderItem={({ name }) => <Text>{name}-DATA</Text>}
                    />
                    : <View style={{height:"100%", width:"100%", alignItems:"center",
                                      justifyContent:"center"}}>
                        <Text>No data found</Text>
                    </View>
                }

            </View>
        );
    }
}

export default Main;
</code>```

Maybe the way I declared state is wrong, or maybe the way I'm storing the data in the state is wrong.
I got the names of the restaurant in the console.warn successfully.

答:
Without your users-key I can't surely understand what is your api results.
Here

```<code>import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { SearchBar } from 'react-native-elements';
import { FlatList } from 'react-native-gesture-handler';

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = { search: '', data: [] };
    }

    componentDidMount() {
        fetch('http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop/', {
            method: 'GET',
        }).then((response) => response.json())
            .then((responseJson) => { return this.setState({ data: responseJson }) })
            .catch((error) => { alert(error) }
            );
    }

    render() {
        let data = this.state.data;
        return (
            <View>
                <SearchBar
                    round
                    searchIcon={{ size: 24 }}
                    placeholder='Search'
                    onChangeText={search => { this.setState({ search }) }}
                    value={this.state.search}
                />

                {data.length != 0 ?
                    <FlatList
                        data={data}
                        keyExtractor={(x, i) => x + i}
                        renderItem={({ item }) => <Text>{item.name}-DATA</Text>}
                    />
                    : <View style={{height:"100%", width:"100%", alignItems:"center",
                                      justifyContent:"center"}}>
                        <Text>No data found</Text>
                    </View>
                }

            </View>
        );
    }
}

export default Main;
</code>```

This is a working code with another api call just add your api call instead on mine.. This is working properly. I guess you are just messing with your data.

Body:
I am using Zomato API to get the list of restaurants, data is in the form of the array which has object restaurants in which there are different restaurant objects and then their name and other details.

It's my first time using a flat List and I am not able to display this data.

Goal: Use the search bar to display the list of restaurants in the city using flatlist.

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { SearchBar } from 'react-native-elements';
import { FlatList } from 'react-native-gesture-handler';

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = { search: '', data: [] };
    }

    componentDidMount() {
        fetch('https://developers.zomato.com/api/v2.1/search', {
            method: 'GET',
            headers: {
                'user-key': '999999999999999999999999999'
            },
            params: JSON.stringify({
                entity_type: 'city',
                q: {this.state.search}
            }),
        }).then((response) => response.json())
            .then((responseJson) => { return this.setState({ data: responseJson.restaurants }) })
            .catch((error) => { console.warn(error) }
            );
    }

    render() {
        let data = this.state.data;
        let name = data.map(p => p.restaurant.name)
        console.warn("Check Data", name)
        return (
            <View>
                <SearchBar
                    round
                    searchIcon={{ size: 24 }}
                    placeholder='Search'
                    onChangeText={search => { this.setState({ search }) }}
                    value={this.state.search}
                />
//Using this method to display the data if any

                {name.length != 0 ?
                    <FlatList
                        data={name}
                        keyExtractor={(x, i) => x + i}
                        renderItem={({ name }) => <Text>{name}-DATA</Text>}
                    />
                    : <View style={{height:"100%", width:"100%", alignItems:"center",
                                      justifyContent:"center"}}>
                        <Text>No data found</Text>
                    </View>
                }

            </View>
        );
    }
}

export default Main;

Maybe the way I declared state is wrong, or maybe the way I'm storing the data in the state is wrong.
I got the names of the restaurant in the console.warn successfully.

Body:
Without your users-key I can't surely understand what is your api results.
Here

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { SearchBar } from 'react-native-elements';
import { FlatList } from 'react-native-gesture-handler';

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = { search: '', data: [] };
    }

    componentDidMount() {
        fetch('http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop/', {
            method: 'GET',
        }).then((response) => response.json())
            .then((responseJson) => { return this.setState({ data: responseJson }) })
            .catch((error) => { alert(error) }
            );
    }

    render() {
        let data = this.state.data;
        return (
            <View>
                <SearchBar
                    round
                    searchIcon={{ size: 24 }}
                    placeholder='Search'
                    onChangeText={search => { this.setState({ search }) }}
                    value={this.state.search}
                />

                {data.length != 0 ?
                    <FlatList
                        data={data}
                        keyExtractor={(x, i) => x + i}
                        renderItem={({ item }) => <Text>{item.name}-DATA</Text>}
                    />
                    : <View style={{height:"100%", width:"100%", alignItems:"center",
                                      justifyContent:"center"}}>
                        <Text>No data found</Text>
                    </View>
                }

            </View>
        );
    }
}

export default Main;

This is a working code with another api call just add your api call instead on mine.. This is working properly. I guess you are just messing with your data.


来源: stackexchange

问:
Procedure for logging into Discord OAuth using PKCE
I'm attempting to add Discord OAuth to a mobile app using PKCE. I'm able to successfully authenticate with DiscordAPI, and I receive a code back from the server.

However, when I try to call the https://discordapp.com/api/oauth2/token endpoint I continually get a Bad Request result.

I've tried a few approaches to attaining my token, but all have failed.

Attempt (1) using HttpClient:

```<code>var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("client_id", Constants.ClientId));
nvc.Add(new KeyValuePair<string, string>("client_secret", Constants.Secret));
nvc.Add(new KeyValuePair<string, string>("code_verifier", codeVerifier)); // method param
nvc.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
nvc.Add(new KeyValuePair<string, string>("code", authCode)); // method param
nvc.Add(new KeyValuePair<string, string>("redirect_uri", Constants.Redirect));
nvc.Add(new KeyValuePair<string, string>("scope", "identify email connections"));

var req = new HttpRequestMessage(HttpMethod.Post, "https://discordapp.com/api/oauth2/token")
{
    Content = new FormUrlEncodedContent(nvc)
};
var authTokenResponse = await this.Client.SendAsync(req).ConfigureAwait(false);
// results in BadRequest
</code>```

I've also tried using a StringContent object like this:

```<code>var stringContent = new StringContent($"grant_type=authorization_code&client_id={Constants.ClientId}&client_secret={Constants.Secret}&code_verifier={codeVerifier}&code={authCode}&redirect_uri={Constants.Redirect}&scopes=identify%20email%20connections", Encoding.UTF8, "application/x-www-form-urlencoded");
</code>```

Both of these result in Bad Request

Attempt (2) using RestSharp

```<code>var client = new RestSharp.RestClient($"{this.Client.BaseAddress}/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"grant_type=authorization_code&client_id={Constants.ClientId}&client_secret={Constants.Secret}&code_verifier={code}&code={authCode}&redirect_uri={Constants.Redirect}&scopes=identify%20email%20connections", ParameterType.RequestBody);
var response = await client.ExecuteAsync(request);
</code>```

I've carefully double-checked all of my values and made sure my Client Id and Secret are correct. I've tried sending the request with and without the code_verifier. Without the code_verifier I get Unauthorized.

Question

How should I modify my HttpClient request to successfully attain my auth token?

More info:

To comply with PKCE, I need a code_verifier. This is how I'm generating the code. (Note, I am not trying to use this as an auth code.)

```<code>Random rng = new Random();
byte[] code = new byte[32];
rng.NextBytes(code);

CodeVerifier = Base64UrlEncoder.Encode(rng.ToString());
</code>```

Then I use a hashing algorithm borrowed from c-sharpcorner.com, which looks like this:

```<code>using (SHA256 sha256Hash = SHA256.Create())
{
    // ComputeHash - returns byte array
    var bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));

    // Convert byte array to a string
    var builder = new StringBuilder();
    for (int i = 0; i < bytes.Length; i++)
    {
        builder.Append(bytes[i].ToString("x2"));
    }
    return builder.ToString();
}
</code>```

I pass the result as my code_challenge while attaining my auth code.

Here's is where I learned that PKCE was required.

https://github.com/discordapp/discord-api-docs/issues/450

PKCE discussion continues here:

https://github.com/discordapp/discord-api-docs/issues/1296

Update:

Alright, so based iwokal's answer, I re-read the posts linked above, so PKCE is only "required" if you are using a Custom Scheme Redirect, if you are just using an http redirect just leave the code_verifier out and you are good to go.

That said, this PKCE workflow is undocumented. Since I spent 500 points, I'll award the points to whoever is able to resolve the PKCE OAuth workflow.

You can cook up a solution from scratch and I'll test it.

答:
Well, after some research i might have idea what is going on. Are you trying to get token based by authorisation code created by you?

I believe that the correct way is to sent https://discordapp.com/api/oauth2/authorize request which will redirect to provided url with querystring containing proper auth code.

You should use this code in the step of getting token.

I don't know if this changes anything but I believe that there is no such parameter as "scopes" according to documentation it should be "scope".

ContentLicense: CC BY-SA 4.0

Body:
I'm attempting to add Discord OAuth to a mobile app using PKCE. I'm able to successfully authenticate with DiscordAPI, and I receive a code back from the server.

However, when I try to call the https://discordapp.com/api/oauth2/token endpoint I continually get a Bad Request result.

I've tried a few approaches to attaining my token, but all have failed.

Attempt (1) using HttpClient:

var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("client_id", Constants.ClientId));
nvc.Add(new KeyValuePair<string, string>("client_secret", Constants.Secret));
nvc.Add(new KeyValuePair<string, string>("code_verifier", codeVerifier)); // method param
nvc.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
nvc.Add(new KeyValuePair<string, string>("code", authCode)); // method param
nvc.Add(new KeyValuePair<string, string>("redirect_uri", Constants.Redirect));
nvc.Add(new KeyValuePair<string, string>("scope", "identify email connections"));

var req = new HttpRequestMessage(HttpMethod.Post, "https://discordapp.com/api/oauth2/token")
{
    Content = new FormUrlEncodedContent(nvc)
};
var authTokenResponse = await this.Client.SendAsync(req).ConfigureAwait(false);
// results in BadRequest

I've also tried using a StringContent object like this:

var stringContent = new StringContent($"grant_type=authorization_code&client_id={Constants.ClientId}&client_secret={Constants.Secret}&code_verifier={codeVerifier}&code={authCode}&redirect_uri={Constants.Redirect}&scopes=identify%20email%20connections", Encoding.UTF8, "application/x-www-form-urlencoded");

Both of these result in Bad Request

Attempt (2) using RestSharp

var client = new RestSharp.RestClient($"{this.Client.BaseAddress}/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"grant_type=authorization_code&client_id={Constants.ClientId}&client_secret={Constants.Secret}&code_verifier={code}&code={authCode}&redirect_uri={Constants.Redirect}&scopes=identify%20email%20connections", ParameterType.RequestBody);
var response = await client.ExecuteAsync(request);

I've carefully double-checked all of my values and made sure my Client Id and Secret are correct. I've tried sending the request with and without the code_verifier. Without the code_verifier I get Unauthorized.

Question

How should I modify my HttpClient request to successfully attain my auth token?

More info:

To comply with PKCE, I need a code_verifier. This is how I'm generating the code. (Note, I am not trying to use this as an auth code.)

Random rng = new Random();
byte[] code = new byte[32];
rng.NextBytes(code);

CodeVerifier = Base64UrlEncoder.Encode(rng.ToString());

Then I use a hashing algorithm borrowed from c-sharpcorner.com, which looks like this:

using (SHA256 sha256Hash = SHA256.Create())
{
    // ComputeHash - returns byte array
    var bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));

    // Convert byte array to a string
    var builder = new StringBuilder();
    for (int i = 0; i < bytes.Length; i++)
    {
        builder.Append(bytes[i].ToString("x2"));
    }
    return builder.ToString();
}

I pass the result as my code_challenge while attaining my auth code.

Here's is where I learned that PKCE was required.

https://github.com/discordapp/discord-api-docs/issues/450

PKCE discussion continues here:

https://github.com/discordapp/discord-api-docs/issues/1296

Update:

Alright, so based iwokal's answer, I re-read the posts linked above, so PKCE is only "required" if you are using a Custom Scheme Redirect, if you are just using an http redirect just leave the code_verifier out and you are good to go.

That said, this PKCE workflow is undocumented. Since I spent 500 points, I'll award the points to whoever is able to resolve the PKCE OAuth workflow.

You can cook up a solution from scratch and I'll test it.


问:
EJS shows red mark when trying to embed data
i have this node server with express which directs data to different files like .ejs files and it worked before but I dont know what I did and so that it doesnt work, it marks every ejs's "<" in red.
im using VS CODE.

```<code>    var app = express();
app.set('view engine', 'ejs');

app.get('/', function(req, res){
    res.send("Hello wassup");
});

app.get('/homepage/:name', function(req,res){
    res.render('home', {fullname : req.params.name});
});

app.get('/profile/:name', function(req, res){
    var data = {Dummytext: "hey yo wassup and all that yea imma be right here tho",
        hobbies : ['baskeall','computing','drawing', 'Learning', 'Driving'] };
    res.render('profile', {fullname: req.params.name, data:data});
});

app.listen(4000);
</code>```

and i have for example this ejs file that doesnt work

```<code>    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>bla</title>
    <link rel="stylesheet" type="text/css" href="partials/nav.css">
</head>
<body>

<% include partials/nav.ejs %>

<div class="user-info">
    <div class="user-about">
        <div class="user-name"><span><%= fullname %></span></div>
        <div class="user-info_">
            <div class="userimg">
            <img src="/YDSign.png" alt="User profile" draggable="false" />
            </div>
            <div class="user-speech"><p><%= data.Dummytext%></p></div>
        </div>
    </div>
    <div class="user-button">
        <button type="button" class="friendAdd">Add Friend</button>
        <button type="button" class="friendBell">Bell</button>
    </div>
    <div class="user-hobbies">
        <div class="hobbies-list">
            <h1>Hobbies</h1>
            <div class="Upscroll"><img src="/iconList/ArrowUp.png" draggable="false"/></div>
            <ul>
                <% data.hobbies.forEach(function(item){ %>
                    <li><a><%= item %></a><img src="iconList/Hobbies.png" class="ident" /></li>
                <% }); %>
            </ul>
            <div class="Downscroll"><img src="/iconList/ArrowDown.png" draggable="false" /></div>
        </div>
    </div>
</div>
</code>```

答:
Everything is fine.

You just should install plugin EJS language support in VSCode.
Just click CTRL+SHIFT+X and then write ejs in the search bar after that install the first one.

That works for me.

Body:
i have this node server with express which directs data to different files like .ejs files and it worked before but I dont know what I did and so that it doesnt work, it marks every ejs's "<" in red.
im using VS CODE.

    var app = express();
app.set('view engine', 'ejs');

app.get('/', function(req, res){
    res.send("Hello wassup");
});

app.get('/homepage/:name', function(req,res){
    res.render('home', {fullname : req.params.name});
});

app.get('/profile/:name', function(req, res){
    var data = {Dummytext: "hey yo wassup and all that yea imma be right here tho",
        hobbies : ['baskeall','computing','drawing', 'Learning', 'Driving'] };
    res.render('profile', {fullname: req.params.name, data:data});
});

app.listen(4000);

and i have for example this ejs file that doesnt work

    <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>bla</title>
    <link rel="stylesheet" type="text/css" href="partials/nav.css">

<% include partials/nav.ejs %>

<%= fullname %>

<%= data.Dummytext%>

        <button type="button" class="friendAdd">Add Friend</button>
        <button type="button" class="friendBell">Bell</button>

Hobbies

                <% data.hobbies.forEach(function(item){ %>

<%= item %>

                <% }); %>


问:
Multiple Images Upload Field in Django
I am new to Django and i am using this tutorial to add a multiple image upload field to a model in my web application. So far i am stuck (I am unable to link the uploaded photos to Hotel model. The Photos get uploaded but are not associated with the hotel model) at how to associate my Photo Model to the Hotels Model on the HotelCreateView. My question is how do i associate this multiple image filed with my Hotel model so that on creating the hotel the images uploaded are linked to the created hotel. Kindly assist.

Thanks alot

Hotel Model

```<code>class Hotels(models.Model):
    """Stores all the information about the hotel and also used to query hotels"""

    name = models.CharField(max_length=255) #The name of the hotel
    address = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    country = models.CharField(max_length=255)
    mobile_number = models.CharField(max_length=12)
    created_at = models.DateTimeField(default=timezone.now)
    last_modified = models.DateTimeField(auto_now=True)
    description = models.TextField()
    slug = models.SlugField(unique=True)
    property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos')
    star_rating = models.PositiveIntegerField()
    contact_person = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True, blank=True,) #Owner of the hotel or person who created the hotel

    class Meta:
        unique_together = ('name', 'slug')
        verbose_name_plural = 'Hotels'
</code>```

Photo Model

```<code>class Photo(models.Model):
    title = models.CharField(max_length=255, blank=True)
    file = models.ImageField(upload_to='hotel_photos')
    hotel = models.ForeignKey(Hotels,on_delete=models.SET_NULL, null=True, blank=True,)

    class Meta:
        verbose_name_plural = 'Photos'

    def __str__(self):
        """Prints the name of the Photo"""
        return f'{self.hotel} photos'
</code>```

Forms.py

```<code>class PhotoForm(forms.ModelForm):
    class Meta:
        model = Photo
        fields = ('hotel','file', )
</code>```

Views.py

```<code>class PhotoUploadView(LoginRequiredMixin,View):
    def get(self, request):
        photos_list = Photo.objects.all()
        return render(self.request, 'hotels/uploads.html', {'photos': photos_list})

    def post(self, request):
        form = PhotoForm(self.request.POST, self.request.FILES, self.request.user)
        if form.is_valid():
            photo = form.save(commit=False)
            photo.hotel = self.request.hotel.contact_person
            photo.save()
            data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
        else:
            data = {'is_valid': False}
        return JsonResponse(data)
</code>```

答:
You say that the widget allowing photos to be uploaded is on the hotel creation page. That is a problem, because this means the hotel is not created yet when photos are being uploaded. So the uploaded photos won't have a hotel they can get associated with.

There are two options:

Move the step to upload the photos to a second step, after the hotel has been created. Add the id of hotel that was just created to the url that you call for the PhotoUploadView so it's passed as a kwarg to the view.

```<code># in PhotoUploadView, post()
if form.is_valid():
    photo = form.save(commit=False)
    try:
        hotel = Hotel.objects.get(
            contact_person=self.request.user.userprofile,  # make sure hotel belongs to user
            id=self.kwargs.get('hotel_id'))
    except Hotel.DoesNotExist:
        raise Http404
    photo.hotel = hotel
    photo.save()
</code>```

Keep track of the uploaded images in the session of the user and associate the uploaded images to the hotel once the HotelCreationForm is submitted:

```<code># in PhotoUploadView, post()
if form.is_valid():
    photo = form.save()
    session = self.request.session
    if not session.get('uploaded_photos'):
        session['uploaded_photos'] = []
    session['uploaded_photos'].append(photo.id)
    data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}

# in HotelCreationView, form_valid() or post():
hotel = form.save()
session = self.request.session
if 'uploaded_photos' in session:
    Photo.objects.filter(id__in=session['uploaded_photos']).update(hotel=hotel)
    del session['uploaded_photos']
</code>```

Note that in this case you need to keep null=True, blank=True on the hotel field in your Photo model since you first save the photo without a hotel.

Also note that if a user never finishes saving the hotel, the photos will still be kept in the db and storage, without hotel associated, so you'll probably want to clean up every now and then (remove all photos that don't have a hotel).

Title: Multiple Images Upload Field in Django

Body:
I am new to Django and i am using this tutorial to add a multiple image upload field to a model in my web application. So far i am stuck (I am unable to link the uploaded photos to Hotel model. The Photos get uploaded but are not associated with the hotel model) at how to associate my Photo Model to the Hotels Model on the HotelCreateView. My question is how do i associate this multiple image filed with my Hotel model so that on creating the hotel the images uploaded are linked to the created hotel. Kindly assist.

Thanks alot

Hotel Model

class Hotels(models.Model):
    """Stores all the information about the hotel and also used to query hotels"""

    name = models.CharField(max_length=255) #The name of the hotel
    address = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    country = models.CharField(max_length=255)
    mobile_number = models.CharField(max_length=12)
    created_at = models.DateTimeField(default=timezone.now)
    last_modified = models.DateTimeField(auto_now=True)
    description = models.TextField()
    slug = models.SlugField(unique=True)
    property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos')
    star_rating = models.PositiveIntegerField()
    contact_person = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True, blank=True,) #Owner of the hotel or person who created the hotel

    class Meta:
        unique_together = ('name', 'slug')
        verbose_name_plural = 'Hotels'

Photo Model

class Photo(models.Model):
    title = models.CharField(max_length=255, blank=True)
    file = models.ImageField(upload_to='hotel_photos')
    hotel = models.ForeignKey(Hotels,on_delete=models.SET_NULL, null=True, blank=True,)

    class Meta:
        verbose_name_plural = 'Photos'

    def __str__(self):
        """Prints the name of the Photo"""
        return f'{self.hotel} photos'

Forms.py

class PhotoForm(forms.ModelForm):
    class Meta:
        model = Photo
        fields = ('hotel','file', )

Views.py

class PhotoUploadView(LoginRequiredMixin,View):
    def get(self, request):
        photos_list = Photo.objects.all()
        return render(self.request, 'hotels/uploads.html', {'photos': photos_list})

    def post(self, request):
        form = PhotoForm(self.request.POST, self.request.FILES, self.request.user)
        if form.is_valid():
            photo = form.save(commit=False)
            photo.hotel = self.request.hotel.contact_person
            photo.save()
            data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
        else:
            data = {'is_valid': False}
        return JsonResponse(data)

Body:
You say that the widget allowing photos to be uploaded is on the hotel creation page. That is a problem, because this means the hotel is not created yet when photos are being uploaded. So the uploaded photos won't have a hotel they can get associated with.

There are two options:

Move the step to upload the photos to a second step, after the hotel has been created. Add the id of hotel that was just created to the url that you call for the PhotoUploadView so it's passed as a kwarg to the view.

# in PhotoUploadView, post()
if form.is_valid():
    photo = form.save(commit=False)
    try:
        hotel = Hotel.objects.get(
            contact_person=self.request.user.userprofile,  # make sure hotel belongs to user
            id=self.kwargs.get('hotel_id'))
    except Hotel.DoesNotExist:
        raise Http404
    photo.hotel = hotel
    photo.save()

Keep track of the uploaded images in the session of the user and associate the uploaded images to the hotel once the HotelCreationForm is submitted:

# in PhotoUploadView, post()
if form.is_valid():
    photo = form.save()
    session = self.request.session
    if not session.get('uploaded_photos'):
        session['uploaded_photos'] = []
    session['uploaded_photos'].append(photo.id)
    data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}

# in HotelCreationView, form_valid() or post():
hotel = form.save()
session = self.request.session
if 'uploaded_photos' in session:
    Photo.objects.filter(id__in=session['uploaded_photos']).update(hotel=hotel)
    del session['uploaded_photos']

Note that in this case you need to keep null=True, blank=True on the hotel field in your Photo model since you first save the photo without a hotel.

Also note that if a user never finishes saving the hotel, the photos will still be kept in the db and storage, without hotel associated, so you'll probably want to clean up every now and then (remove all photos that don't have a hotel).


问:
Reading csv files with glob to pass data to a database very slow
I have many csv files and I am trying to pass all the data that they contain into a database. For this reason, I found that I could use the glob library to iterate over all csv files in my folder. Following is the code I used:

```<code>import requests as req
import pandas as pd
import glob
import json

endpoint = "testEndpoint"
path = "test/*.csv"

for fname in glob.glob(path):
    print(fname)

    df = pd.read_csv(fname)

    for index, row in df.iterrows():
        #print(row['ID'], row['timestamp'], row['date'], row['time'],
        #     row['vltA'], row['curA'], row['pwrA'], row['rpwrA'], row['frq'])

        print(row['timestamp'])

        testjson = {"data":
                        {"installationid": row['ID'],
                         "active": row['pwrA'],
                         "reactive": row['rpwrA'],
                         "current": row['curA'],
                         "voltage": row['vltA'],
                         "frq": row['frq'],
                         }, "timestamp": row['timestamp']}

        payload = {"payload": [testjson]}
        json_data = json.dumps(payload)
        response = req.post(
            endpoint, data=json_data, headers=headers)
</code>```

This code seems to work fine in the beginning. However, after some time it starts to become really slow (I noticed this because I print the timestamp as I upload the data) and eventually stops completely. What is the reason for this? Is something I am doing here really inefficient?

答:
I can see 3 possible problems here:

memory. read_csv is fast, but it loads the content of a full file in memory. If the files are really large, you could exhaust the real memory and start using swap which has terrible performances

iterrows: you seem to build a dataframe - meaning a data structure optimized for column wise access - to then access it by rows. This already is a bad idea and iterrows is know to have terrible performances because it builds a Series per each row

one post request per row. An http request has its own overhead, but furthemore, this means that you add rows to the database one at a time. If this is the only interface for your database, you may have no other choice, but you should search whether it is possible to prepare a bunch of rows and load it as a whole. It often provides a gain of more than one magnitude order.

Without more info I can hardly say more, but IHMO the higher gain is to be found on database feeding so here in point 3. If nothing can be done on that point, of if further performance gain is required, I would try to replace pandas with the csv module which is row oriented and has a limited footprint because it only processes one line at a time whatever the file size.

Finally, and if it makes sense for your use case, I would try to use one thread for the reading of the csv file that would feed a queue and a pool of threads to send requests to the database. That should allow to gain the HTTP overhead. But beware, depending on the endpoint implementation it could not improve much if really the database access if the limiting factor.

Body:
I have many csv files and I am trying to pass all the data that they contain into a database. For this reason, I found that I could use the glob library to iterate over all csv files in my folder. Following is the code I used:

import requests as req
import pandas as pd
import glob
import json

endpoint = "testEndpoint"
path = "test/*.csv"

for fname in glob.glob(path):
    print(fname)

    df = pd.read_csv(fname)

    for index, row in df.iterrows():
        #print(row['ID'], row['timestamp'], row['date'], row['time'],
        #     row['vltA'], row['curA'], row['pwrA'], row['rpwrA'], row['frq'])

        print(row['timestamp'])

        testjson = {"data":
                        {"installationid": row['ID'],
                         "active": row['pwrA'],
                         "reactive": row['rpwrA'],
                         "current": row['curA'],
                         "voltage": row['vltA'],
                         "frq": row['frq'],
                         }, "timestamp": row['timestamp']}

        payload = {"payload": [testjson]}
        json_data = json.dumps(payload)
        response = req.post(
            endpoint, data=json_data, headers=headers)

This code seems to work fine in the beginning. However, after some time it starts to become really slow (I noticed this because I print the timestamp as I upload the data) and eventually stops completely. What is the reason for this? Is something I am doing here really inefficient?


问:
Parse data to mappable nested list | React
I'm building a database where you can add comments to meetings and replies to those meetings. I took inspiration from this article since I've never done anything like this before.

I'm fetching my comments from my database and the structure looks like this:

```<code>"comments": [
        {
          "id": 5,
          "content": "First comment",
          "path": [
            5
          ],
          "depth": 1
        },
        {
          "id": 6,
          "content": "First reply on first comment",
          "path": [
            5,
            6
          ],
          "depth": 2
        },
        {
          "id": 7,
          "content": "Second comment",
          "path": [
            7
          ],
          "depth": 1
        },
        {
          "id": 8,
          "content": "First reply on second comment",
          "path": [
            7,
            8
          ],
          "depth": 2
        },
        {
          "id": 9,
          "content": "Second reply on second comment",
          "path": [
            7,
            9
          ],
          "depth": 2
        },
        {
          "id": 10,
          "content": "First reply on second comment second reply",
          "path": [
            7,
            9,
            10
          ],
          "depth": 3
        }
      ]
</code>```

Currently, I'm trying to create a nested list with my React application and display the comments in a similar way as StackOverflow does. I have an idea of how the structure will look like, but I'm not too sure how to implement it.

```<code>comments: [
    {
        id: 5,
        content: "First comment",
        replies: [
            {
                id: 6,
                content: "First reply on first comment",
                depth: 2
            }
        ]
    },
    {
        id: 100,
        content: "Comment with no replies",
        replies: []
    }

]
</code>```

Any help on how to get started on this is greatly appreciated and I hope I've described my problem clearly.

Thanks for reading and have a nice day.

答:
The first thing I would do is to add parentId, children, and order to each item. This will let you traverse the tree up or down regardless of which node you start with and to ensure the correct ordering. The parentId is self-explanatory, while the children should probably be named childrenIds as it just holds the IDs of the children in the appropriate order.

Then, I usually like to convert the array to a map that is keyed by some unique value like an ID. This give you an O(1) operation to get to any node that may be edited or removed. I like to use Ramda for things like this, but you could use any other utility or write your own.

utils.js

```<code>/**
 * Convert an array to an object, using the `id` as the key.
 */
 const keyById = R.indexBy(R.prop("id"));
</code>```

Now, you need to find the comments that are on the top of the list or just under what would be "root" if you had one. Since I've chosen to use parentId: null for to indicate this, we can find those top-level items with this.

```<code>const getTopLevelParents = R.filter(x => !x.parentId);
</code>```

With this, we can easily get our top-level items to begin iteration. This is where it might get a little more complicated. I'm also using Ramda here, so I hope it's not too unusual for understanding. The gist is, starting with the first item in the topLevel items, we recursively find the children items, sort by "order", set the depth, and concatenate that array of items to a single array. So the result is something more linear and ordered correctly. Because when we go to map this data to components, we don't want to have to skip around in order to find the parents and children. We want to be able to go from top to bottom, having already figured out all of this.

```<code>/**
 * Converts the mapping to an array and reorders the children so they are directly adjacent with the depth set.
 * @param treeMap Key value pair where the key is the ID and the value is the chapter
 */
function getTreeMapAsList(treeMap) {
  const topLevel = R.compose(
    getTopLevelParents,
    R.values
  )(treeMap);

  /**
   * Nest this function so it can have access to treeMap.
   */
  function getTree(data, depth = 0) {
    return R.reduce(
      (result, curr) => {
        result.push(curr);
        // hasLength is a utility that just checks if the length of an
        // item is greater than 0 in a way that won't blow up if something
        // doesn't exist.
        if (hasLength(R.prop("children", curr))) {
          const children = R.compose(
            R.sortBy(R.prop("order")),
            R.reduce((result, id) => {
              const child = R.prop(id, treeMap);
              if (child) {
                return R.compose(
                  R.append(R.__, result),
                  R.assoc("depth", depth + 1)
                )(child);
              }
              return result;
            }, [])
          )(curr.children);

          return result.concat(getTree(children, depth + 1));
        }
        return result;
      },
      [],
      data
    );
  }
</code>```

The tree is now properly ordered, with appropriate depths, and has been flattened into an array. Lastly, you can map over this array with your comment component.

Comment.js

```<code>function Comment({ data }) {
  return (
    <div
      style={{
        //It's important to default to zero here. You could also
        // just do this in the data or the mapper originally.
        marginLeft: `${R.propOr(0, "depth", data)}rem`
      }}
    >
      {data.content}
    </div>
  );
}
</code>```

App.js

```<code>function App() {
  // This is the map and should be stored in state somewhere.
  // If it's changing a lot, you should memoize it.
  const treeMap = keyById(data.comments);

  // This is the array, that is now ordered with appropriate depths
  // This should also be memoized.
  const treeList = getTreeMapAsList(treeMap);

  return (
    <div>
      <div>
        {/* Now we just have an array to iterate over. */}
        {treeList.map(item => {
          return <Comment data={item} key={item.id} />;
        })}
      </div>
    </div>
  );
}
</code>```

Here's a working example. Good luck!

Body:
I'm building a database where you can add comments to meetings and replies to those meetings. I took inspiration from this article since I've never done anything like this before.

I'm fetching my comments from my database and the structure looks like this:

"comments": [
        {
          "id": 5,
          "content": "First comment",
          "path": [
            5
          ],
          "depth": 1
        },
        {
          "id": 6,
          "content": "First reply on first comment",
          "path": [
            5,
            6
          ],
          "depth": 2
        },
        {
          "id": 7,
          "content": "Second comment",
          "path": [
            7
          ],
          "depth": 1
        },
        {
          "id": 8,
          "content": "First reply on second comment",
          "path": [
            7,
            8
          ],
          "depth": 2
        },
        {
          "id": 9,
          "content": "Second reply on second comment",
          "path": [
            7,
            9
          ],
          "depth": 2
        },
        {
          "id": 10,
          "content": "First reply on second comment second reply",
          "path": [
            7,
            9,
            10
          ],
          "depth": 3
        }
      ]

Currently, I'm trying to create a nested list with my React application and display the comments in a similar way as StackOverflow does. I have an idea of how the structure will look like, but I'm not too sure how to implement it.

comments: [
    {
        id: 5,
        content: "First comment",
        replies: [
            {
                id: 6,
                content: "First reply on first comment",
                depth: 2
            }
        ]
    },
    {
        id: 100,
        content: "Comment with no replies",
        replies: []
    }

]

Any help on how to get started on this is greatly appreciated and I hope I've described my problem clearly.

Thanks for reading and have a nice day.

Body:
The first thing I would do is to add parentId, children, and order to each item. This will let you traverse the tree up or down regardless of which node you start with and to ensure the correct ordering. The parentId is self-explanatory, while the children should probably be named childrenIds as it just holds the IDs of the children in the appropriate order.

Then, I usually like to convert the array to a map that is keyed by some unique value like an ID. This give you an O(1) operation to get to any node that may be edited or removed. I like to use Ramda for things like this, but you could use any other utility or write your own.

utils.js

/**
 * Convert an array to an object, using the `id` as the key.
 */
 const keyById = R.indexBy(R.prop("id"));

Now, you need to find the comments that are on the top of the list or just under what would be "root" if you had one. Since I've chosen to use parentId: null for to indicate this, we can find those top-level items with this.

const getTopLevelParents = R.filter(x => !x.parentId);

With this, we can easily get our top-level items to begin iteration. This is where it might get a little more complicated. I'm also using Ramda here, so I hope it's not too unusual for understanding. The gist is, starting with the first item in the topLevel items, we recursively find the children items, sort by "order", set the depth, and concatenate that array of items to a single array. So the result is something more linear and ordered correctly. Because when we go to map this data to components, we don't want to have to skip around in order to find the parents and children. We want to be able to go from top to bottom, having already figured out all of this.

/**
 * Converts the mapping to an array and reorders the children so they are directly adjacent with the depth set.
 * @param treeMap Key value pair where the key is the ID and the value is the chapter
 */
function getTreeMapAsList(treeMap) {
  const topLevel = R.compose(
    getTopLevelParents,
    R.values
  )(treeMap);

  /**
   * Nest this function so it can have access to treeMap.
   */
  function getTree(data, depth = 0) {
    return R.reduce(
      (result, curr) => {
        result.push(curr);
        // hasLength is a utility that just checks if the length of an
        // item is greater than 0 in a way that won't blow up if something
        // doesn't exist.
        if (hasLength(R.prop("children", curr))) {
          const children = R.compose(
            R.sortBy(R.prop("order")),
            R.reduce((result, id) => {
              const child = R.prop(id, treeMap);
              if (child) {
                return R.compose(
                  R.append(R.__, result),
                  R.assoc("depth", depth + 1)
                )(child);
              }
              return result;
            }, [])
          )(curr.children);

          return result.concat(getTree(children, depth + 1));
        }
        return result;
      },
      [],
      data
    );
  }

The tree is now properly ordered, with appropriate depths, and has been flattened into an array. Lastly, you can map over this array with your comment component.

Comment.js

function Comment({ data }) {
  return (
    <div
      style={{
        //It's important to default to zero here. You could also
        // just do this in the data or the mapper originally.
        marginLeft: `${R.propOr(0, "depth", data)}rem`
      }}
    >
      {data.content}
    </div>
  );
}

App.js

function App() {
  // This is the map and should be stored in state somewhere.
  // If it's changing a lot, you should memoize it.
  const treeMap = keyById(data.comments);

  // This is the array, that is now ordered with appropriate depths
  // This should also be memoized.
  const treeList = getTreeMapAsList(treeMap);

  return (
    <div>
      <div>
        {/* Now we just have an array to iterate over. */}
        {treeList.map(item => {
          return <Comment data={item} key={item.id} />;
        })}
      </div>
    </div>
  );
}

Here's a working example. Good luck!


问:
Adding Custom attribute in forms
I am using magento V1.5. I am working on Customer EAV & have tried to create another EAV module.

I have added few attributes in customer entity. Now MY requirement is those attributes must be editable from frontend as well as backend.

Please tell me how to add those attributes in forntend form (customer edit form). & Tell me what to do in backend to have those options to be editable.
I am thinking if there is a way in admin like in our Form.php we prepare form with adding elements to it. then we not need to write a code to create actual html. Magento automatically does it. SO idea is it must also load the new attributes in that was just added. (like they appear in product edit.)

Second Issue is, Can u guys tell me what should I write in my Grid.php >> prepareCollection (for other EAV module ). so that it must get all the attributes with their values ( or may be few )

here is something that I have in my Grid.php but its not working

```<code>protected function _prepareCollection()
{
    $collection = Mage::getModel('pincodes/eavpincodes')->getCollection();

    $this->setCollection($collection);
    return parent::_prepareCollection();
}
</code>```

& this is my collection file

```<code>class Namespace_Pincodes_Model_Resource_Eav_Mysql4_Eavpincodes_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
    protected function _construct()
    {
        $this->_init('pincodes/eavpincodes');
    }
}
</code>```

But its not returning anything in my grid

& here is my Attribute collection file

```<code>class Inkfruit_Pincodes_Model_Resource_Eav_Mysql4_Attribute_Collection extends Mage_Eav_Model_Mysql4_Entity_Attribute_Collection
{
public function _construct()
{
    $this->_init('pincodes/resource_eav_attribute', 'eav/entity_attribute');
}

protected function _initSelect()
{

    $this->getSelect()->from(array('main_table' => $this->getResource()->getMainTable()))
        ->where('main_table.entity_type_id=?', Mage::getModel('eav/entity')->setType('pincodes_eavpincodes')->getTypeId())
        ->join(
        array('additional_table' => $this->getTable('pincodes/eavpincodes')),
        'additional_table.attribute_set_id=main_table.attribute_id'  // I think this sql need to be changed but I have no idea what it'll be
        );
    return $this;
}
</code>```

}

Guys thank you so much. This forum has been specially very helpful to me

Regards
SAM

Ok guys I have created a separate module for customers that has one mysql4_install file & it goes as follows

```<code>$installer = $this;
$installer->startSetup();
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

$setup->addAttribute('customer', 'profile_image', array(
                    'label'     => 'Profile Image',
                    'type'      => 'varchar',
                    'input'     => 'file',
                    'visible'   => true,
                    'required'  => false,
                    'user_defined' => true,
            ));

 $setup->addAttribute('customer', 'mobile', array(
                    'label'     => 'Mobile Number',
                    'type'      => 'int',
                    'input'     => 'text',
                    'visible'   => true,
                    'required'  => false,
                    'user_defined' => true,
            ));

$installer->endSetup();
$installer->installEntities();
</code>```

But when I hit the url for this module I see no error but these attributes are not in my database.

I also have created Entity_Setup file & it goes as follows I think its incorrect but I gave it a try

```<code><?php

class Namespace_Customer_Entity_Setup extends Mage_Eav_Model_Entity_Setup
{
public function getDefaultEntities()
    {
    return array (
        'customer' => array(
            'entity_model'      => 'customer/customer',
            'attribute_model'   => 'customer/attribute',
            'table'             => 'customer/entity',
            'attributes'        => array(
                'profile_image' => array(
                    //the EAV attribute type, NOT a mysql varchar
                    'type'              => 'varchar',
                    'backend'           => '',
                    'frontend'          => '',
                    'label'             => 'Profile Image',
                    'input'             => 'file',
                    'class'             => '',
                    'source'            => '',
                    // store scope == 0
                    // global scope == 1
                    // website scope == 2
                    'global'            => 0,
                    'visible'           => true,
                    'required'          => false,
                    'user_defined'      => true,
                    'default'           => '',
                    'searchable'        => true,
                    'filterable'        => true,
                    'comparable'        => false,
                    'visible_on_front'  => false,
                    'unique'            => false
                ),

                'mobile' => array(

                    'type'              => 'varchar',
                    'backend'           => '',
                    'frontend'          => '',
                    'label'             => 'Mobile Number',
                    'input'             => 'text',
                    'class'             => '',
                    'source'            => '',

                    'global'            => 0,
                    'visible'           => true,
                    'required'          => true,
                    'user_defined'      => true,
                    'default'           => '',
                    'searchable'        => true,
                    'filterable'        => true,
                    'comparable'        => false,
                    'visible_on_front'  => false,
                    'unique'            => false
                ),

            ),
        )
    );
   }
}
</code>```

But I see nothing, not any new attribute in database.

Can u guys help here whats wrong??
Thanks

答:
Having same issue here. Using addAttribute in 1.5.0.1 seems to add it into database but customer admin won't render it.

This method works fine with product and category attributes. And in 1.4.0.0 it works for customers too.

In Magento chagelog there is bullet point under improvements about customer attribute rendering. I'll start checking it next.

ContentLicense: CC BY-SA 3.0

Title: Adding Custom attribute in forms

Body:
I am using magento V1.5. I am working on Customer EAV & have tried to create another EAV module.

I have added few attributes in customer entity. Now MY requirement is those attributes must be editable from frontend as well as backend.

Please tell me how to add those attributes in forntend form (customer edit form). & Tell me what to do in backend to have those options to be editable.
I am thinking if there is a way in admin like in our Form.php we prepare form with adding elements to it. then we not need to write a code to create actual html. Magento automatically does it. SO idea is it must also load the new attributes in that was just added. (like they appear in product edit.)

Second Issue is, Can u guys tell me what should I write in my Grid.php >> prepareCollection (for other EAV module ). so that it must get all the attributes with their values ( or may be few )

here is something that I have in my Grid.php but its not working

protected function _prepareCollection()
{
    $collection = Mage::getModel('pincodes/eavpincodes')->getCollection();

    $this->setCollection($collection);
    return parent::_prepareCollection();
}

& this is my collection file

class Namespace_Pincodes_Model_Resource_Eav_Mysql4_Eavpincodes_Collection extends Mage_Eav_Model_Entity_Collection_Abstract
{
    protected function _construct()
    {
        $this->_init('pincodes/eavpincodes');
    }
}

But its not returning anything in my grid

& here is my Attribute collection file

class Inkfruit_Pincodes_Model_Resource_Eav_Mysql4_Attribute_Collection extends Mage_Eav_Model_Mysql4_Entity_Attribute_Collection
{
public function _construct()
{
    $this->_init('pincodes/resource_eav_attribute', 'eav/entity_attribute');
}

protected function _initSelect()
{

    $this->getSelect()->from(array('main_table' => $this->getResource()->getMainTable()))
        ->where('main_table.entity_type_id=?', Mage::getModel('eav/entity')->setType('pincodes_eavpincodes')->getTypeId())
        ->join(
        array('additional_table' => $this->getTable('pincodes/eavpincodes')),
        'additional_table.attribute_set_id=main_table.attribute_id'  // I think this sql need to be changed but I have no idea what it'll be
        );
    return $this;
}

}

Guys thank you so much. This forum has been specially very helpful to me

Regards
SAM

Ok guys I have created a separate module for customers that has one mysql4_install file & it goes as follows

$installer = $this;
$installer->startSetup();
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

$setup->addAttribute('customer', 'profile_image', array(
                    'label'     => 'Profile Image',
                    'type'      => 'varchar',
                    'input'     => 'file',
                    'visible'   => true,
                    'required'  => false,
                    'user_defined' => true,
            ));

 $setup->addAttribute('customer', 'mobile', array(
                    'label'     => 'Mobile Number',
                    'type'      => 'int',
                    'input'     => 'text',
                    'visible'   => true,
                    'required'  => false,
                    'user_defined' => true,
            ));

$installer->endSetup();
$installer->installEntities();

But when I hit the url for this module I see no error but these attributes are not in my database.

I also have created Entity_Setup file & it goes as follows I think its incorrect but I gave it a try

<?php

class Namespace_Customer_Entity_Setup extends Mage_Eav_Model_Entity_Setup
{
public function getDefaultEntities()
    {
    return array (
        'customer' => array(
            'entity_model'      => 'customer/customer',
            'attribute_model'   => 'customer/attribute',
            'table'             => 'customer/entity',
            'attributes'        => array(
                'profile_image' => array(
                    //the EAV attribute type, NOT a mysql varchar
                    'type'              => 'varchar',
                    'backend'           => '',
                    'frontend'          => '',
                    'label'             => 'Profile Image',
                    'input'             => 'file',
                    'class'             => '',
                    'source'            => '',
                    // store scope == 0
                    // global scope == 1
                    // website scope == 2
                    'global'            => 0,
                    'visible'           => true,
                    'required'          => false,
                    'user_defined'      => true,
                    'default'           => '',
                    'searchable'        => true,
                    'filterable'        => true,
                    'comparable'        => false,
                    'visible_on_front'  => false,
                    'unique'            => false
                ),

                'mobile' => array(

                    'type'              => 'varchar',
                    'backend'           => '',
                    'frontend'          => '',
                    'label'             => 'Mobile Number',
                    'input'             => 'text',
                    'class'             => '',
                    'source'            => '',

                    'global'            => 0,
                    'visible'           => true,
                    'required'          => true,
                    'user_defined'      => true,
                    'default'           => '',
                    'searchable'        => true,
                    'filterable'        => true,
                    'comparable'        => false,
                    'visible_on_front'  => false,
                    'unique'            => false
                ),

            ),
        )
    );
   }
}

But I see nothing, not any new attribute in database.

Can u guys help here whats wrong??
Thanks


问:
Pass form inputs to JavaScript function

TL;DR: Is there a way to pass what a HTML form submits as an object to a JavaScript function?

In a form like this one:

```<code><form action="javascript:myFunction(this);" name="myForm">
<label>First: <input type="text" name="first"></label>
<label>Second: <input type="text" name="second"></label>
<input type="submit" value="Submit this to Javascript!">
</form>
</code>```

I want to pass the values of the form's inputs to a JavaScript function myFunction, instead of sending them to some other page with action (as in this line here: action="sendToPHPPage.php").

So far, my best attempt was to get all elements from the form, like this:

```<code>function myFunction(formThis) {
  let form = document.getElementsByName('myForm')[0];
  inputs = form.getElementsByTagName('input');
  for (let x of inputs) //do something with x.value

  console.log(formThis);
}
</code>```

What I wanted, though, was that the this in myFunction(this) would allow me directly work on the inputs of the form. So instead of using document.getElementsByName('myForm') I could simply work on the this argument. But console.log(thisForm) tells me that formThis === window. That is, this gets me the window object.

Question: How can I make the this be binded to the form -- that is, how can I make the this argument represent the form or become an object that has as keys each one of the inputs? Is this possible without using document.get... || document.querySelector...?

Related SO questions: How do I get the value of text input field using JavaScript? , Passing HTML input value as a JavaScript Function Parameter

答:
```<code><form class="contact_form" onsubmit="return sendForm()">
</code>```

<hr>

```<code>const sendForm = () => {
      event.preventDefault();
      console.log(event.target.elements[***])
    }
</code>```

Title: Pass form inputs to JavaScript function

Body:
TL;DR: Is there a way to pass what a HTML form submits as an object to a JavaScript function?

In a form like this one:

<form action="javascript:myFunction(this);" name="myForm">
First: <input type="text" name="first">
Second: <input type="text" name="second">
<input type="submit" value="Submit this to Javascript!">
</form>

I want to pass the values of the form's inputs to a JavaScript function myFunction, instead of sending them to some other page with action (as in this line here: action="sendToPHPPage.php").

So far, my best attempt was to get all elements from the form, like this:

function myFunction(formThis) {
  let form = document.getElementsByName('myForm')[0];
  inputs = form.getElementsByTagName('input');
  for (let x of inputs) //do something with x.value

  console.log(formThis);
}

What I wanted, though, was that the this in myFunction(this) would allow me directly work on the inputs of the form. So instead of using document.getElementsByName('myForm') I could simply work on the this argument. But console.log(thisForm) tells me that formThis === window. That is, this gets me the window object.

Question: How can I make the this be binded to the form -- that is, how can I make the this argument represent the form or become an object that has as keys each one of the inputs? Is this possible without using document.get... || document.querySelector...?

Related SO questions: How do I get the value of text input field using JavaScript? , Passing HTML input value as a JavaScript Function Parameter

Body:
<form class="contact_form" onsubmit="return sendForm()">

const sendForm = () => {
      event.preventDefault();
      console.log(event.target.elements[***])
    }


问:
Cannot delete document from local.system.replset when authentication enabled
I have MongoDB replica set with enabled authentication. I want to change replica set name. In order to do that I have to delete documents from local.system.replset collection. I have admin user with  root@admin role assigned, also I have regular user with readWrite@local role. When I try to execute remove from  the shell with any of the users above I get Unauthorized exception:

```<code>> db.system.replset.remove({})
WriteCommandError({
        "operationTime" : Timestamp(1582026365, 1),
        "ok" : 0,
        "errmsg" : "not authorized on local to execute command { delete: \"system.replset\", ordered: true, lsid: { id: UUID(\"43182bad-b13d-4ff4-a31b-3cdcb1dd49fa\") }, $clusterTime: { clusterTime: Timestamp(1582026355, 1), signature: { hash: BinData(0, E9FD8A23702CE215B193423CAF1C2AF3FEE83D6B), keyId: 6794747247067136002 } }, $db: \"local\" }",
        "code" : 13,
        "codeName" : "Unauthorized",
        "$clusterTime" : {
                "clusterTime" : Timestamp(1582026365, 1),
                "signature" : {
                        "hash" : BinData(0,"CyCvFtgLkpdhIrsJV67KBlVwL+U="),
                        "keyId" : NumberLong("6794747247067136002")
                }
        }
})
</code>```

If I try to execute same command on replica set with no authentication enabled I can successfully remove the record. What role am I missing on order to let user to delete record from local.system.replset? Or is it not supported when authentication is enabled?

答:
This answer https://stackoverflow.com/a/20120639/2138959 gave me a hint that root user may not have the privileges required and indeed it only has find privilege. I still don't know why readWrite@local didn't allow to write to system.replicaset, but when I added new role with find, insert, remove, update, bypassDocumentValidation, useUUID privileges for local.system.replset resource I was able to finally remove the replica set and update the name.

Another even simpler option is to assign dbOwner@local role to the user.

Body:
I have MongoDB replica set with enabled authentication. I want to change replica set name. In order to do that I have to delete documents from local.system.replset collection. I have admin user with  root@admin role assigned, also I have regular user with readWrite@local role. When I try to execute remove from  the shell with any of the users above I get Unauthorized exception:

> db.system.replset.remove({})
WriteCommandError({
        "operationTime" : Timestamp(1582026365, 1),
        "ok" : 0,
        "errmsg" : "not authorized on local to execute command { delete: \"system.replset\", ordered: true, lsid: { id: UUID(\"43182bad-b13d-4ff4-a31b-3cdcb1dd49fa\") }, $clusterTime: { clusterTime: Timestamp(1582026355, 1), signature: { hash: BinData(0, E9FD8A23702CE215B193423CAF1C2AF3FEE83D6B), keyId: 6794747247067136002 } }, $db: \"local\" }",
        "code" : 13,
        "codeName" : "Unauthorized",
        "$clusterTime" : {
                "clusterTime" : Timestamp(1582026365, 1),
                "signature" : {
                        "hash" : BinData(0,"CyCvFtgLkpdhIrsJV67KBlVwL+U="),
                        "keyId" : NumberLong("6794747247067136002")
                }
        }
})

If I try to execute same command on replica set with no authentication enabled I can successfully remove the record. What role am I missing on order to let user to delete record from local.system.replset? Or is it not supported when authentication is enabled?


问:
BadTokenException: Unable to add window -- window android.view.ViewRootImpl$W@cb70704 has already been added On Samsung devices
I'm using Xamarin for Android and I'm getting this error in an AlertDialog.Builder.Show() method, but it only happens on some Samsung (with Android 7.0) devices, we have tried some other devices and this problem doesn't happen. I'm getting it only after using the application some time. The stacktrace is the following

```<code>  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
  at Java.Interop.JniEnvironment+InstanceMethods.CallObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <7802aa64ad574c33adca332a3fa9706a>:0
  at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualObjectMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in <7802aa64ad574c33adca332a3fa9706a>:0
  at Android.App.AlertDialog+Builder.Show () [0x0000a] in <dc51acef1f304f0dab449a7fc6039799>:0
  at Prizma.Controls.Common.BindingComboBox.ShowDialog () [0x00062] in C:\TeamProjects\PrizmaProject\Main\MobileSales.iOS\Prizma.Controls.iOS\Common\BindingComboBox.cs:408
  --- End of managed Android.Views.WindowManagerBadTokenException stack trace ---
android.view.WindowManager$BadTokenException: Unable to add window -- window android.view.ViewRootImpl$W@cb70704 has already been added
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:902)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:377)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:97)
    at android.app.Dialog.show(Dialog.java:404)
    at android.app.AlertDialog$Builder.show(AlertDialog.java:1136)
    at mono.android.view.View_OnClickListenerImplementor.n_onClick(Native Method)
    at mono.android.view.View_OnClickListenerImplementor.onClick(View_OnClickListenerImplementor.java:30)
    at android.view.View.performClick(View.java:6261)
    at android.widget.TextView.performClick(TextView.java:11185)
    at android.view.View$PerformClick.run(View.java:23752)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
</code>```

My code is something like this

```<code>            try
            {
                AlertDialog.Builder a = new AlertDialog.Builder(MainActivity);
                a.SetTitle("Select");
                a.SetAdapter(_Adapter, new EventHandler<DialogClickEventArgs>(ClosedDialog));
                a.Create();
                a.Show();
            }
            catch (Exception ex)
            {
                //Exception code
            }
</code>```

I put the AlertDialog.Builder Show() method in a Try Catch, but after I get the exception for the first time, I keep getting it everytime.

Some remarks

I'm still getting this error even the application never goes to the background.

The app is compiled using the latest Android SDK (8.1)

I didin't have Xamarin Android to the latest version, but now I have it and the problem is still there.

Not just the AlertDialogs doesn't show after the error, the Popup menus too.

I got a Samsung Galaxy J7 Prime with Android 6.0.1 and this error didn't happen, but after upgrade it to 7.0 the problem started. In other devices like Motorola, Hawuei, LG, etc.. we don't have this issue even they have Android 7.0.

Please help me, I have weeks with this issue and my clients that have Samsung devices are killing me :)

Thanks in advance.

Regards

Allan

答:
```<code>try
{
    RunOnUiThread (() => {
          AlertDialog.Builder a = new AlertDialog.Builder(MainActivity);
            a.SetTitle("Select");
            a.SetAdapter(_Adapter, new EventHandler<DialogClickEventArgs>(ClosedDialog));
            a.Create();
            a.Show();
    });
}
catch (Exception ex)
{
    //Exception code
}
</code>```

with reference to : https://forums.xamarin.com/discussion/128420/badtokenexception-unable-to-add-window-window-android-view-viewrootimpl-has-already-been-added

Body:
I'm using Xamarin for Android and I'm getting this error in an AlertDialog.Builder.Show() method, but it only happens on some Samsung (with Android 7.0) devices, we have tried some other devices and this problem doesn't happen. I'm getting it only after using the application some time. The stacktrace is the following

  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <f32579baafc1404fa37ba3ec1abdc0bd>:0
  at Java.Interop.JniEnvironment+InstanceMethods.CallObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <7802aa64ad574c33adca332a3fa9706a>:0
  at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualObjectMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in <7802aa64ad574c33adca332a3fa9706a>:0
  at Android.App.AlertDialog+Builder.Show () [0x0000a] in <dc51acef1f304f0dab449a7fc6039799>:0
  at Prizma.Controls.Common.BindingComboBox.ShowDialog () [0x00062] in C:\TeamProjects\PrizmaProject\Main\MobileSales.iOS\Prizma.Controls.iOS\Common\BindingComboBox.cs:408
  --- End of managed Android.Views.WindowManagerBadTokenException stack trace ---
android.view.WindowManager$BadTokenException: Unable to add window -- window android.view.ViewRootImpl$W@cb70704 has already been added
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:902)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:377)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:97)
    at android.app.Dialog.show(Dialog.java:404)
    at android.app.AlertDialog$Builder.show(AlertDialog.java:1136)
    at mono.android.view.View_OnClickListenerImplementor.n_onClick(Native Method)
    at mono.android.view.View_OnClickListenerImplementor.onClick(View_OnClickListenerImplementor.java:30)
    at android.view.View.performClick(View.java:6261)
    at android.widget.TextView.performClick(TextView.java:11185)
    at android.view.View$PerformClick.run(View.java:23752)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

My code is something like this

            try
            {
                AlertDialog.Builder a = new AlertDialog.Builder(MainActivity);
                a.SetTitle("Select");
                a.SetAdapter(_Adapter, new EventHandler<DialogClickEventArgs>(ClosedDialog));
                a.Create();
                a.Show();
            }
            catch (Exception ex)
            {
                //Exception code
            }

I put the AlertDialog.Builder Show() method in a Try Catch, but after I get the exception for the first time, I keep getting it everytime.

Some remarks

I'm still getting this error even the application never goes to the background.

The app is compiled using the latest Android SDK (8.1)

I didin't have Xamarin Android to the latest version, but now I have it and the problem is still there.

Not just the AlertDialogs doesn't show after the error, the Popup menus too.

I got a Samsung Galaxy J7 Prime with Android 6.0.1 and this error didn't happen, but after upgrade it to 7.0 the problem started. In other devices like Motorola, Hawuei, LG, etc.. we don't have this issue even they have Android 7.0.

Please help me, I have weeks with this issue and my clients that have Samsung devices are killing me :)

Thanks in advance.

Regards

Allan

Body:
try
{
    RunOnUiThread (() => {
          AlertDialog.Builder a = new AlertDialog.Builder(MainActivity);
            a.SetTitle("Select");
            a.SetAdapter(_Adapter, new EventHandler<DialogClickEventArgs>(ClosedDialog));
            a.Create();
            a.Show();
    });
}
catch (Exception ex)
{
    //Exception code
}

with reference to : https://forums.xamarin.com/discussion/128420/badtokenexception-unable-to-add-window-window-android-view-viewrootimpl-has-already-been-added


问:
How to using custom authenticate server with bot framework?
I 'm creating a bot that running on telegram chanel. when user chatting with bot, it need to know who is chatting. so they must authenticate on my server.

i imagine that bot will send a button have a link of my authenticate endpoint (eg: https://localhost:8080/auth?code=abcd123a). user click to button then open the link in a browser that user logged in. Bot will know user identify because Bot and Server is using same database. But how bot know when user clicked to the link and be authenticated?

and is this pattern is effective (about the delay or UI)?

答:
You could add authentication to your bot via Azure Bot Service via OAuth identity providers. Does your authenticate endpoint support OAuth? In that case, your flow will be:

Bot sends OAuth card, redirecting to your authenticate endpoint.

User logs in, OAuth server redirects to Bot Service token endpoint.

Bot Services retrieves token and handles token life-cycle.

Bot retrieves the activity with the token and can use it for authentication.

Read more about the Bot Framework Token Service.

The Azure Bot Service takes care of the OAuth controllers and login links, stores the target client IDs and secrets, and performs user token management. Otherwise, you would need to do all this overhead yourself in your own hosted OAuth controllers + manage the token life-cycle.


问:
Python - ValueError: could not convert string to float
I am a beginner in python and I'm trying to graph some data from a file. The code is the following:

```<code>import matplotlib.pyplot as plt
import pandas as pd
from scipy.signal import find_peaks

import os

dataFrame = pd.read_csv('soporte.txt', sep='\t',skiprows=1, encoding = 'utf-8-sig')

x = dataFrame['Wavelength nm.']
y = dataFrame['Abs.']

indices, _ = find_peaks(y, threshold=1)

plt.plot(x, y)

plt.show()
</code>```

And I get the following error:

```<code>ValueError: could not convert string to float: '-0,04008'
</code>```

I'll show you a piece of the file I am trying to work with:

```<code>"soporte.spc - RawData"
"Wavelength nm."    "Abs."
180,0   -0,04008
181,0   -0,00084
182,0   -0,00746
183,0   0,00854
184,0   -0,01525
185,0   -0,00354
</code>```

Thank you very much!!!

L

答:
Use the decimal=',' option in pandas, i.e.,

```<code>dataFrame = pd.read_csv('soporte.txt', sep='\t',skiprows=1, encoding = 'utf-8-sig', decimal=',')
</code>```

Body:
I am a beginner in python and I'm trying to graph some data from a file. The code is the following:

import matplotlib.pyplot as plt
import pandas as pd
from scipy.signal import find_peaks

import os

dataFrame = pd.read_csv('soporte.txt', sep='\t',skiprows=1, encoding = 'utf-8-sig')

x = dataFrame['Wavelength nm.']
y = dataFrame['Abs.']

indices, _ = find_peaks(y, threshold=1)

plt.plot(x, y)

plt.show()

And I get the following error:

ValueError: could not convert string to float: '-0,04008'

I'll show you a piece of the file I am trying to work with:

"soporte.spc - RawData"
"Wavelength nm."    "Abs."
180,0   -0,04008
181,0   -0,00084
182,0   -0,00746
183,0   0,00854
184,0   -0,01525
185,0   -0,00354

Thank you very much!!!

L

Body:
Use the decimal=',' option in pandas, i.e.,

dataFrame = pd.read_csv('soporte.txt', sep='\t',skiprows=1, encoding = 'utf-8-sig', decimal=',')


问:
What is a watermark in Flink with respect to Event time processing? Why is it needed.?
What is a watermark in Flink with respect to Event time processing? Why is it needed.?
Why is it needed in all cases of event time being used. By all cases I mean if i dont do a window opeation
then why do we still need a water mark.
I come from spark background. In spark we need watermarks only when we use windows on the incoming events.

I have read few articles and it seems to me that watermarks and windows seems same.If there are differences please explain and point it put

Post your reply I did some more reading. Below is a query that is more specific.

Main Question:- Why do we need outoforder when we have acceptedlateness.

Given below example:

Assume you have a BoundedOutOfOrdernessTimestampExtractor with a 2 minute bound and a 10 minute tumbling window that starts at 12:00 and ends at 12:10:

12:01, A

12:04, B

WM, 12:02 // 12:04 - 2 minutes

12:02, C

12:08, D

12:14, E

WM, 12:12

12:16, F

WM, 12:14 // 12:16 - 2 minutes

12:09, G

In the above example  [12:02, C] record is not dropped but included into the window 12:00 -12:10 and later evaluated.- Hence the watermark could as well be the event timestamp

The record [12:09, G] is included into the window 12:00 - 12:10 only when there is a acceptedlateness of 5mins configured. This takes care of late and out of order events

So now adding to my previous question above, what is the necessary of outoforder option to be BoundedOutOfOrdernessTimestampExtractor of some value(other than 0) instead of the event timestamp istelf ?

 What is that outoforder can achieve which allowedlateness cannot and in what scenario it does?

答:
Watermarks and windows are closely related but they are very different concepts.

Watermarks are needed for any kind of event-based aggregation to cut off late events. Windows can only close when they receive an appropriate watermark and that's when results of aggregations are published.

If you have no out of order events, you can set watermarks to be equivalent to the timestamps of input events. But that's usually a luxury.

edit to address questions in comment.

is it a rule of thumb to keep the watermarks duration equal to window duration because by only doing so the result is calculated and emitted.

No, the durations are independent, but add up the lag on a given event.

Your watermark duration depends on your data and how much lag you can take for your application. Let's say most events are in order, 10% are coming up to 1s late, an additional 5% up to 10s, and 1% up to 1h.

If you set watermark duration to 0, then 16% of your data points are discarded, but Flink will receive no additional lag. If your watermark trails 1s behind your events, you will lose 6% of your data, but the results will have 1s more lag. If you want to retain all data, Flink will need to wait for 1h on each aggregation until Flink can be sure that no data is missing.

But then what is the role of trigger? and how does sliding windows coordinate with water marks and triggers. Can you please explain as how they work with each other ?

Let's say, you have a window of 1 min and a watermark delay of 5 s. A window will only trigger when it is sure that all relevant data has been seen. In this case, it needs to wait 1 min 5 s to trigger, such that the last event of the window has surely arrived.

Btw events later as watermark are discarded by default. You can change that behavior.


问:
How to use Do While Loop / While End While Loop in this code instead of GoTo
I'm a bit new with Visual Basic and I'm trying to make a program that would generate random numbers from 1 to 9 without repetition using arrays. I've also read that instead of using GoTo statements (as they are generally frowned upon), Do While Loop or While End While Statements could be used. I've tried using these loops but have not made it work. Here is the code:</p>

```<code>Dim x As Integer = 0, y As Integer = 0, num As Integer = 0, arr(8) As Integer
        lstLoop.Items.Clear()
        For x = 0 To 8
Start:
            Randomize()
            num = Fix(Rnd() * 9) + 1
            For y = 0 To 8
                If num = arr(y) Then
                    GoTo Start
                End If
            Next
        arr(x) = num
        lstLoop.Items.Add(arr(x))
        Next
</code>```

答:
The idea is to loop while you have found the number in the array:</p>

```<code>Sub GenerateRandom()

Dim x As Integer
Dim num As Integer
Dim arr(8) As Integer

Randomize Timer

For x = 0 To 8
    Do
        num = Fix(Rnd() * 9) + 1
    Loop While FindInArray(arr, x - 1, num)

    arr(x) = num
Next x

End Sub

Function FindInArray(arr() As Integer, maxIndex As Integer, num As Integer) As Boolean

Dim i As Integer
FindInArray = False

For i = 0 To maxIndex
    If arr(i) = num Then
        FindInArray = True
        Exit Function
    End If
Next

End Function
</code>```

Body:
I'm a bit new with Visual Basic and I'm trying to make a program that would generate random numbers from 1 to 9 without repetition using arrays. I've also read that instead of using GoTo statements (as they are generally frowned upon), Do While Loop or While End While Statements could be used. I've tried using these loops but have not made it work. Here is the code:

Dim x As Integer = 0, y As Integer = 0, num As Integer = 0, arr(8) As Integer
        lstLoop.Items.Clear()
        For x = 0 To 8
Start:
            Randomize()
            num = Fix(Rnd() * 9) + 1
            For y = 0 To 8
                If num = arr(y) Then
                    GoTo Start
                End If
            Next
        arr(x) = num
        lstLoop.Items.Add(arr(x))
        Next

Body:
The idea is to loop while you have found the number in the array:

Sub GenerateRandom()

Dim x As Integer
Dim num As Integer
Dim arr(8) As Integer

Randomize Timer

For x = 0 To 8
    Do
        num = Fix(Rnd() * 9) + 1
    Loop While FindInArray(arr, x - 1, num)

    arr(x) = num
Next x

End Sub

Function FindInArray(arr() As Integer, maxIndex As Integer, num As Integer) As Boolean

Dim i As Integer
FindInArray = False

For i = 0 To maxIndex
    If arr(i) = num Then
        FindInArray = True
        Exit Function
    End If
Next

End Function


问:
Reverse geocoding with python to get googlemaps url
I have two columns df['latitude'] and df['longitude'] and I am trying to reverse geocode them into full address google maps in df['Address']. However, I am not very successful. Is there a better way of doing this? I am using Geocoder package.

This is a sample from dataframe

\\
lat, lon
48.7082,2.2797
48.7577,2.2188
47.8333,2.2500
48.9833,1.7333
47.9333,1.9181
46.2735,4.2586
\\

答:
First set your api key for google maps access:

```<code>export GOOGLE_API_KEY=<Secret API Key>
export GOOGLE_CLIENT=<Secret Client>
export GOOGLE_CLIENT_SECRET=<Secret Client Secret>
</code>```

Then execute the following code to use "reverse" geocoding to create a location from a set of lat lon coordinates:

```<code>import geocoder
import pandas as pd

df = pd.DataFrame([{'lat':48.7082, 'lon':2.2797}, {'lat':48.7577,'lon':2.2188})

for index, row in df.iterrows():
    g = geocoder.google([row['lat'], row['lon']], method='reverse')
    print(g.json)
</code>```

Body:
First set your api key for google maps access:

export GOOGLE_API_KEY=<Secret API Key>
export GOOGLE_CLIENT=<Secret Client>
export GOOGLE_CLIENT_SECRET=<Secret Client Secret>

Then execute the following code to use "reverse" geocoding to create a location from a set of lat lon coordinates:

import geocoder
import pandas as pd

df = pd.DataFrame([{'lat':48.7082, 'lon':2.2797}, {'lat':48.7577,'lon':2.2188})

for index, row in df.iterrows():
    g = geocoder.google([row['lat'], row['lon']], method='reverse')
    print(g.json)


问:
Why introduce a new array in a method? Why not reuse the parameter?
In the method normalize I input an array say, {1, 2, 3, 4}, and the return is a normalized array, {0.1, 0.2, 0.3, 0.4}.
I know I should introduce a new array in the method (b in the following), but why actually?

```<code>public static double[] normalize(double[] a) {
    double[] b = new double[a.length];
    double sum = 0;
        for (int i = 0; i < b.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < b.length; i++) {
            b[i] = a[i]/sum;
        }
    return b;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4
</code>```

Why is the following wrong:

```<code>public static double[] normalize(double[] a) {
    double sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < a.length; i++) {
            a[i] = a[i]/sum;
        }
    return a;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4
</code>```

答:
In my opinion, you are creating a new variable with new values. The method receives one var and returns another var.

It's more reader-friendly.

Body:
In the method normalize I input an array say, {1, 2, 3, 4}, and the return is a normalized array, {0.1, 0.2, 0.3, 0.4}.
I know I should introduce a new array in the method (b in the following), but why actually?

public static double[] normalize(double[] a) {
    double[] b = new double[a.length];
    double sum = 0;
        for (int i = 0; i < b.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < b.length; i++) {
            b[i] = a[i]/sum;
        }
    return b;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4

Why is the following wrong:

public static double[] normalize(double[] a) {
    double sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < a.length; i++) {
            a[i] = a[i]/sum;
        }
    return a;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4


问:
How to insert value into an HTML form using PHP?
I have a form in a file named signup.php like this,

```<code><form action="includes/signup.inc.php" method="post">
<input type="text" name="uid" placeholder="Username..."><br><br>
<input type="text" name="mail" placeholder="Email..."><br><br>
<input type="password" name="pwd" placeholder="Password..."><br><br>
<input type="password" name="repeatPwd" placeholder="Repeat Password..."><br><br>
<input type="submit" name="btnSignup" value="Signup">
</form>
</code>```

Then I have this if statement in the signup.inc.php file.

```<code>if (!preg_match("/^[a-zA-z0-9]*$/", $username)) {
    header("Location: ../signup.php?error=invaliduid&mail=".$email);
    exit();
}
</code>```

That is if the user enter invalid username, then the user will be route back to the signup page, and I get an error message in the address bar, now I want to get the email from the address bar which the user entered, I make an if statement back in the signup.php file like this,

```<code>if ($_GET['error'] == "invaliduid") {
    echo "Invalid username.";
    $email = $_GET['mail'];
}
</code>```

Now I want to fill the original form

```<code><input type="text" name="mail" placeholder="Email...">
</code>```

And put the email from $_GET['mail'] and put it in the value portion of the form, but I am stuck on how to do this.

The program should work like this, if the user entered proper mail and an invalid username then the user route back to the signup page with the message invalid username, and email field should be populated with the email which he already entered.

答:
From what I understand, what you're looking for is simply this:

```<code><input type="text" name="mail" placeholder="Email..." value="<?= htmlspecialchars($email) ?>">
</code>```

(which is a less ugly way to write the following:)

```<code><input type="text" name="mail" placeholder="Email..." value="<?php echo htmlspecialchars($email); ?>">
</code>```

Body:
I have a form in a file named signup.php like this,

<form action="includes/signup.inc.php" method="post">
<input type="text" name="uid" placeholder="Username...">

<input type="text" name="mail" placeholder="Email...">

<input type="password" name="pwd" placeholder="Password...">

<input type="password" name="repeatPwd" placeholder="Repeat Password...">

<input type="submit" name="btnSignup" value="Signup">
</form>

Then I have this if statement in the signup.inc.php file.

if (!preg_match("/^[a-zA-z0-9]*$/", $username)) {
    header("Location: ../signup.php?error=invaliduid&mail=".$email);
    exit();
}

That is if the user enter invalid username, then the user will be route back to the signup page, and I get an error message in the address bar, now I want to get the email from the address bar which the user entered, I make an if statement back in the signup.php file like this,

if ($_GET['error'] == "invaliduid") {
    echo "Invalid username.";
    $email = $_GET['mail'];
}

Now I want to fill the original form

<input type="text" name="mail" placeholder="Email...">

And put the email from $_GET['mail'] and put it in the value portion of the form, but I am stuck on how to do this.

The program should work like this, if the user entered proper mail and an invalid username then the user route back to the signup page with the message invalid username, and email field should be populated with the email which he already entered.

Body:
From what I understand, what you're looking for is simply this:

<input type="text" name="mail" placeholder="Email..." value="<?= htmlspecialchars($email) ?>">

(which is a less ugly way to write the following:)

<input type="text" name="mail" placeholder="Email..." value="<?php echo htmlspecialchars($email); ?>">


问:
Problem with storing german words into the MySql DB....?
I am facing an small issue in my project When I am trying to store some German words into the MYSQL Database. When this German words contains umlauts i.e. characters ä, ö, ß, ü etc., they are not stored as they are.....?

I want to store them as it is into the Database.To do so I tried to change the COLLATION to UTF8-general-ci, and others in the list using PHP myAdmin. But none of them is working for me.

Am I in the right way or I have to do something else.

Please suggest some help.

Thanks In Advance......

答:
years ago I've faced the same problem. I've solved it by implicit setting NAMES option for mysql. In my code it looks like this:

//inside AbstractMapper class

```<code>public function __construct($modelClass, $dbTable) {
$this->setDbTable($dbTable);
$stmt = new Zend_Db_Statement_Pdo($this->getDbTable()->getAdapter(), 'set names utf8');
$stmt->execute();
$this->_model_class = $modelClass;
}
</code>```

Body:
years ago I've faced the same problem. I've solved it by implicit setting NAMES option for mysql. In my code it looks like this:

//inside AbstractMapper class

public function __construct($modelClass, $dbTable) {
$this->setDbTable($dbTable);
$stmt = new Zend_Db_Statement_Pdo($this->getDbTable()->getAdapter(), 'set names utf8');
$stmt->execute();
$this->_model_class = $modelClass;
}