来源: stackexchange

问:
Best way to determine the number of servers needed
How much traffic can one web server handle? What's the best way to see if we're beyond that?

I have an ASP.Net application that has a couple hundred users. Aspects of it are fairly processor intensive, but thus far we have done fine with only one server to run both SqlServer and the site. It's running Windows Server 2003, 3.4 GHz with 3.5 GB of RAM.

But lately I've started to notice slows at various times, and I was wondering what's the best way to determine if the server is overloaded by the usage of the application or if I need to do something to fix the application (I don't really want to spend a lot of time hunting down little optimizations if I'm just expecting too much from the box).

答:
On that hardware, a .NET application should be able to serve about 200-400 requests per second. If you have only a few hundred users, I doubt you are seeing even 2 requests per second, so I think you have a lot of capacity on that box, even with SQL server running.

Without know all of the details, I would say no, you will not see any performance improvement by adding servers.

By the way, if you're not using the Output Cache, I would start there.

OwnerDisplayName: Jared

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Gulzar

OwnerDisplayName: Portman


问:
How to solve race condition for refresh api token during multiple async requests?
There are like 5 async requests running at the same time that hit 401 response, and the default compensation function for it is to attempt to refresh the token to see if we can get granted access.

The problem is that if there are 5 async calls to refresh token endpoint, then we end with desynced, invalid token in our session.

This is Redux-Saga app with ReactJS on top of it.

答:
You need to receive some kind of signal when those five requests are done. You can do it using Promise.all which takes an array of promises and fulfill when all promises are fulfilled and rejects when at least one does.

```<code>const asyncRequest1 = makeAsyncRequestPromise();
const asyncRequest2 = makeAsyncRequestPromise();
const asyncRequest3 = makeAsyncRequestPromise();
const asyncRequest4 = makeAsyncRequestPromise();
const asyncRequest5 = makeAsyncRequestPromise();

const allDone = Promise.all([
    asyncRequest1.then(() => true, () => false),
    asyncRequest2.then(() => true, () => false),
    asyncRequest3.then(() => true, () => false),
    asyncRequest4.then(() => true, () => false),
    asyncRequest5.then(() => true, () => false),
]);

allDone.then((results) => {
    const someHasFailed = results.some(result => result === false);
    if (someHasFailed) {
        // make the refresh token here
    }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You need to receive some kind of signal when those five requests are done. You can do it using Promise.all which takes an array of promises and fulfill when all promises are fulfilled and rejects when at least one does.

const asyncRequest1 = makeAsyncRequestPromise();
const asyncRequest2 = makeAsyncRequestPromise();
const asyncRequest3 = makeAsyncRequestPromise();
const asyncRequest4 = makeAsyncRequestPromise();
const asyncRequest5 = makeAsyncRequestPromise();

const allDone = Promise.all([
    asyncRequest1.then(() => true, () => false),
    asyncRequest2.then(() => true, () => false),
    asyncRequest3.then(() => true, () => false),
    asyncRequest4.then(() => true, () => false),
    asyncRequest5.then(() => true, () => false),
]);

allDone.then((results) => {
    const someHasFailed = results.some(result => result === false);
    if (someHasFailed) {
        // make the refresh token here
    }
});


问:
How convert from persian date to gregorian date in android
I use a PersianDatePicker to select a date. This works fine, but I want to convert selected Persian date to a Gregorian date.

I have found some code and example from internet but the calculation is not right. When I select current date in Persian 5.7.1396 and convert this date to Gregorian I get 4.8.2017.

```<code>public static int g_days_in_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
        31, 30, 31 };
public static int j_days_in_month[] = { 31, 31, 31, 31, 31, 31, 30, 30, 30,
        30, 30, 29 };
/**
 * Converts Persian date to gregorian date
 * */
public static Calendar getGregorianCalendar(int year, int month, int day) {
    int gy, gm, gd;
    int jy, jm, jd;
    long g_day_no, j_day_no;
    boolean leap;
    int i;
    jy = year - 979;
    jm = month - 1;
    jd = day - 1;
    j_day_no = 365 * jy + (jy / 33) * 8 + (jy % 33 + 3) / 4;
    for (i = 0; i < jm; ++i)
        j_day_no += j_days_in_month[i];
    j_day_no += jd;
    g_day_no = j_day_no + 79;
    gy = (int) (1600 + 400 * (g_day_no / 146097)); /*
                                                     * 146097 = 365*400 +
                                                     * 400/4 - 400/100 +
                                                     * 400/400
                                                     */
    g_day_no = g_day_no % 146097;
    leap = true;
    if (g_day_no >= 36525) /* 36525 = 365*100 + 100/4 */
    {
        g_day_no--;
        gy += 100 * (g_day_no / 36524); /* 36524 = 365*100 + 100/4 - 100/100 */
        g_day_no = g_day_no % 36524;
        if (g_day_no >= 365)
            g_day_no++;
        else
            leap = false;
    }
    gy += 4 * (g_day_no / 1461); /* 1461 = 365*4 + 4/4 */
    g_day_no %= 1461;
    if (g_day_no >= 366) {
        leap = false;
        g_day_no--;
        gy += g_day_no / 365;
        g_day_no = g_day_no % 365;
    }
    for (i = 0; g_day_no >= g_days_in_month[i]
            + parsBooleanToInt(i == 1 && leap); i++)
        g_day_no -= g_days_in_month[i] + parsBooleanToInt(i == 1 && leap);
    gm = i + 1;
    gd = (int) (g_day_no + 1);
    GregorianCalendar gregorian = new  GregorianCalendar(gy, gm - 1, gd);
    return gregorian;
}
private static int parsBooleanToInt(Boolean sample) {
    if (sample)
        return 1;
    else
        return 0;
}
</code>```

答:
I have used this library for convert Jalali date to Gregorian date and vice versa :

https://github.com/samanzamani/PersianDate

You can use the toGregorian(int year, int month, int day) method from it.

ContentLicense: CC BY-SA 3.0

Body:
I use a PersianDatePicker to select a date. This works fine, but I want to convert selected Persian date to a Gregorian date.

I have found some code and example from internet but the calculation is not right. When I select current date in Persian 5.7.1396 and convert this date to Gregorian I get 4.8.2017.

public static int g_days_in_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
        31, 30, 31 };
public static int j_days_in_month[] = { 31, 31, 31, 31, 31, 31, 30, 30, 30,
        30, 30, 29 };
/**
 * Converts Persian date to gregorian date
 * */
public static Calendar getGregorianCalendar(int year, int month, int day) {
    int gy, gm, gd;
    int jy, jm, jd;
    long g_day_no, j_day_no;
    boolean leap;
    int i;
    jy = year - 979;
    jm = month - 1;
    jd = day - 1;
    j_day_no = 365 * jy + (jy / 33) * 8 + (jy % 33 + 3) / 4;
    for (i = 0; i < jm; ++i)
        j_day_no += j_days_in_month[i];
    j_day_no += jd;
    g_day_no = j_day_no + 79;
    gy = (int) (1600 + 400 * (g_day_no / 146097)); /*
                                                     * 146097 = 365*400 +
                                                     * 400/4 - 400/100 +
                                                     * 400/400
                                                     */
    g_day_no = g_day_no % 146097;
    leap = true;
    if (g_day_no >= 36525) /* 36525 = 365*100 + 100/4 */
    {
        g_day_no--;
        gy += 100 * (g_day_no / 36524); /* 36524 = 365*100 + 100/4 - 100/100 */
        g_day_no = g_day_no % 36524;
        if (g_day_no >= 365)
            g_day_no++;
        else
            leap = false;
    }
    gy += 4 * (g_day_no / 1461); /* 1461 = 365*4 + 4/4 */
    g_day_no %= 1461;
    if (g_day_no >= 366) {
        leap = false;
        g_day_no--;
        gy += g_day_no / 365;
        g_day_no = g_day_no % 365;
    }
    for (i = 0; g_day_no >= g_days_in_month[i]
            + parsBooleanToInt(i == 1 && leap); i++)
        g_day_no -= g_days_in_month[i] + parsBooleanToInt(i == 1 && leap);
    gm = i + 1;
    gd = (int) (g_day_no + 1);
    GregorianCalendar gregorian = new  GregorianCalendar(gy, gm - 1, gd);
    return gregorian;
}
private static int parsBooleanToInt(Boolean sample) {
    if (sample)
        return 1;
    else
        return 0;
}


问:
Discord selfbot - answering on messages from everyone
I have Discord selfbot in node.js and I wanna make a bot answering to massages from other server members, for example, if someone type "hey" selfbot will send into DMs "I'm busy rn, sorry"

I have this code but it is not working, I did not get any error but it is not working :(

```<code>client.on('message', message => {
  if (message.content.startsWith('hey'))
    target.send('im afk')
})
</code>```

答:
```<code>client.on('message', message => {
  if (message.content.startsWith('idk'))
    message.channel.send("Im Afk");
})
</code>```

The message has to start with 'idk' so that this is triggered.

Body:
I have Discord selfbot in node.js and I wanna make a bot answering to massages from other server members, for example, if someone type "hey" selfbot will send into DMs "I'm busy rn, sorry"

I have this code but it is not working, I did not get any error but it is not working :(

client.on('message', message => {
  if (message.content.startsWith('hey'))
    target.send('im afk')
})

Body:
client.on('message', message => {
  if (message.content.startsWith('idk'))
    message.channel.send("Im Afk");
})

The message has to start with 'idk' so that this is triggered.


问:
How to build a few instance of @nuxtjs/axios
How to build a few instances of @nuxtjs/axios in the Nuxt project and apply throughout the project and store.

Can the built-in instance use this pointer?

答:
Your will needed configure a multiples axios instances, and use this instances to get/post your requests.

```<code>import axios from 'axios'

    const api1 = axios.create({
      baseURL: 'https://some-domain.com/api1/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'foobar'}
    })

    const api2 = axios.create({
      baseURL: 'https://some-domain.com/api2/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'bar'}
    })
</code>```

so, what you need to do, is use your instance to make your requests, somethink like this:

```<code>api1.post('auth/recovery', payload)
ap2.post('auth/signin', payload)
</code>```

Body:
Your will needed configure a multiples axios instances, and use this instances to get/post your requests.

import axios from 'axios'

    const api1 = axios.create({
      baseURL: 'https://some-domain.com/api1/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'foobar'}
    })

    const api2 = axios.create({
      baseURL: 'https://some-domain.com/api2/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'bar'}
    })

so, what you need to do, is use your instance to make your requests, somethink like this:

api1.post('auth/recovery', payload)
ap2.post('auth/signin', payload)


问:
Java scheduler that works with native image compilation by GraalVM
I have the app on top of Quarkus framework. The main functionality of the app - simple REST API for scheduling some tasks (now it just posts some message to the log).

Scheduling functionality I implemented with Quartz framework and in common it looks like when the app get POST request for scheduling a new event it does two things:

save entity from the request to the database;

schedule Quartz job on mentioned in JSON date and time.

Also for case when the application just starts I created method which take all entities from database and schedule Quartz jobs for them.

But when I tried to build native image for that application using GraalVM I faced with such exception:

com.oracle.graal.pointsto.constraints.UnsupportedFeatureException: No
  instances of sun.security.provider.NativePRNG are allowed in the image
  heap as this class should be initialized at image runtime.

Fast search in Google gave me closed issue in GraalVM Github repo which say, that Quartz use RMI's ObjID with run-time initialization. Due to that Quartz couldn't be used in applications where is required native image compilation by GraalVM.

So does Quarkus scheduler provides abilities to schedule jobs right in Java code (something like in my implementation with Quartz)?  In all examples and pieces of code I found I could see only pretty simple usage of @Scheduled annotation on methods (like in official guide). Or maybe there are any other alternative tools for scheduling tasks in Java that works with native image compilation?

答:
Maybe off topic, but just to let you know that you might encounter weird scheduling problems when running your app in a (Docker) container, since the timezone in the container might be different than your local timezone. So the scheduler might fight fire at a totally diff time than you had configured.

To fix this I had to add the following lines in my Dockerfile:

```<code># set the correct timezone
RUN apk add --no-cache tzdata
ENV TZ=Europe/Amsterdam  <---your timezone
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
</code>```

Just my 2 cents.

Body:
Maybe off topic, but just to let you know that you might encounter weird scheduling problems when running your app in a (Docker) container, since the timezone in the container might be different than your local timezone. So the scheduler might fight fire at a totally diff time than you had configured.

To fix this I had to add the following lines in my Dockerfile:

# set the correct timezone
RUN apk add --no-cache tzdata
ENV TZ=Europe/Amsterdam  <---your timezone
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

Just my 2 cents.


问:
Forcing android camera resolution
In my android app, I would like to be able to limit the maximal resolution (or size in mb) of a picture being taken.

here is how i call the camera activity :

```<code>Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File( mTmpFilePath ) ) );
intent.putExtra( "filename", mTmpFilePath );
startActivityForResult( intent, REQUEST_CAMERA );
</code>```

Is there anyway to force or limit the camera resolution ?

答:
If you start camera application with intent,  you are depending on this application good will.
(some implementation will support this, and some not). You can try to set up image resolution via camera class,  but I found that not all advertised sizes are supported, some are ignored and some produce errors - camera applications behave differently on different devices. </p>

Title: Forcing android camera resolution

Body:
In my android app, I would like to be able to limit the maximal resolution (or size in mb) of a picture being taken.

here is how i call the camera activity :

Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File( mTmpFilePath ) ) );
intent.putExtra( "filename", mTmpFilePath );
startActivityForResult( intent, REQUEST_CAMERA );

Is there anyway to force or limit the camera resolution ?


问:
Change the mat-autocomplete width?
It seems like the <mat-autocomplete> width is always the width of the input we're typing in. Is there no way to make it larger? I have a very small input and can't read the dropdown items. I'm also limited in form space so can't make the input larger.

```<code><mat-form-field style="width: 100px;">
  <input matInput [matAutocomplete]="auto">
  <mat-autocomplete style="width: 500px;" #auto="matAutocomplete">
    <mat-option *ngFor="let item of items" [value]="item">
    </mat-option>
  </mat-autocomplete>
</mat-form-field>
</code>```

答:
Just add the panelWidth property to the mat-autocomplete

```<code><mat-autocomplete [panelWidth]="300">
</code>```

Title: Change the mat-autocomplete width?

Body:
It seems like the <mat-autocomplete> width is always the width of the input we're typing in. Is there no way to make it larger? I have a very small input and can't read the dropdown items. I'm also limited in form space so can't make the input larger.

<mat-form-field style="width: 100px;">
  <input matInput [matAutocomplete]="auto">
  <mat-autocomplete style="width: 500px;" #auto="matAutocomplete">
    <mat-option *ngFor="let item of items" [value]="item">
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

Body:
Just add the panelWidth property to the mat-autocomplete

<mat-autocomplete [panelWidth]="300">


问:
How to set a zoom in when I select the marker in the map?
How do I set the zoom only for the marker selected on the map and not for the focused location?
here is my code:
I tried lot of codes but I have no success yet.

```<code>export default class Mapper extends Component {
  constructor(props) {
    super(props);
    this.state = {
      focusedLocation: {
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta:
          (Dimensions.get('window').width / Dimensions.get('window').height) *
         0.00522,
      },
      locations: locations,
    };
    this.switchMapType = this.switchMapType.bind(this);
  }

  onPressZoomIn() {
    this.region = {
      latitude: this.state.focusedLocation.latitude,
      longitude: this.state.focusedLocation.longitude,
      latitudeDelta: this.state.focusedLocation.latitudeDelta * 0.5,
      longitudeDelta: this.state.focusedLocation.longitudeDelta * 0.5,
    };

    this.setState({
      focusedLocation: {
        latitudeDelta: this.region.latitudeDelta,
        longitudeDelta: this.region.longitudeDelta,
        latitude: this.region.latitude,
        longitude: this.region.longitude,
      },
    });
    this.map.animateToRegion(this.region, 500);
  }

  onPressZoomOut() {
    this.region = {
      latitude: this.state.focusedLocation.latitude,
      longitude: this.state.focusedLocation.longitude,
      latitudeDelta: this.state.focusedLocation.latitudeDelta / 0.5,
      longitudeDelta: this.state.focusedLocation.longitudeDelta / 0.5,
    };
    this.setState({
      focusedLocation: {
        latitudeDelta: this.region.latitudeDelta,
        longitudeDelta: this.region.longitudeDelta,
        latitude: this.region.latitude,
        longitude: this.region.longitude,
      },
    });
    this.map.animateToRegion(this.region, 500);
  }
  render() {
    return (
      <View style={styles.container}>
       <StatusBar hidden />
        <MapView
          //initialRegion={initialRegion}
          style={styles.mapView}
          rotateEnabled={true}
          scrollEnabled={true}
          showsMyLocationButton={false}
          showsUserLocation={true}
          zoomEnabled={true}
          mapType={this.state.mapType}
          showsPointsOfInterest={false}
          showBuildings={false}
          onMapReady={this._mapReady}
          ref={ref => (this.map = ref)}>
          {locations.map(
            (locations, id, latitude, longitude, hora, linha, prestadora) => (
              console.log(locations.latitude, locations.latitude),
              (
                <MapView.Marker
                  onPress={this.pickLocationHandler}
                  ref={mark => (locations.mark = mark)}
                  key={id}
                  title={locations.linha + ' - ' + locations.prestadora}
                  pinColor={'tomato'}
                  description={
                    'Aguarde o seu transporte a partir de: ' + locations.hora
                  }
                  coordinate={{
                    latitude: JSON.parse(locations.latitude),
                    longitude: JSON.parse(locations.longitude),
                  }}
                />
              )
            )
          )}
        </MapView>
        ...
        <ScrollView
          style={styles.placesContainer}
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onMomentumScrollEnd={e => {
            const locations =
              e.nativeEvent.contentOffset.x > 0
                ? e.nativeEvent.contentOffset.x / Dimensions.get('window').width
                : 0;

            const { latitude, longitude, mark } = this.state.locations[
              locations
            ];

            this.map.animateToCoordinate(
              {
                latitude: JSON.parse(latitude),
                longitude: JSON.parse(longitude),
              },
              500
            );

            setTimeout(() => {
              mark.showCallout();
            }, 500);
          }}>
          {locations.map(locations => (
            <View key={locations.id} style={styles.place}>
              <Text style={styles.title}>Ponto {locations.id} </Text>
              <Text style={styles.text}>A partir de: {locations.hora}</Text>
              <Image
                source={require('./assets/expo.symbol.white.png')}
                style={{
                  marginLeft: Dimensions.get('window').width / 1.5,
                  width: 67,
                  height: 67,
                  tintColor: '#FF3D00',
                }}
              />
            </View>
          ))}
        </ScrollView>
      </View>
    );
  }
}
</code>```

How can I fix it? for when I press the button zoom in, for example, it takes a zoom in the specific marker selected?

Here is the full code for your view: https://snack.expo.io/@matheus_cbrl/zoomin-zoomout

here is the code to pick Location by Handler marker:

```<code>pickLocationHandler = event => {
    const coords = event.nativeEvent.coordinate;
    console.log('Location picker Marker', coords);
    this.map.animateToRegion({
      ...this.state.focusedlocation,
      latitude: coords.latitude,
      longitude: coords.longitude,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta:
          (Dimensions.get('window').width / Dimensions.get('window').height) *
          0.00522,
    });

    this.setState(prevState => {
      return {
        focusedlocation: {
          ...prevState.focusedlocation,
          latitude: coords.latitude,
          longitude: coords.longitude,
        },
        locationChosen: true,
      };
    });
  };
</code>```

答:
First move to your marker, then zoom in.

Move to marker,

```<code>this.refs.map.animateToRegion({
     latitude: markerLat,
     longitude: markerLong,
})
</code>```

Then zoom in with
focusedLocation.

Body:
How do I set the zoom only for the marker selected on the map and not for the focused location?
here is my code:
I tried lot of codes but I have no success yet.

export default class Mapper extends Component {
  constructor(props) {
    super(props);
    this.state = {
      focusedLocation: {
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta:
          (Dimensions.get('window').width / Dimensions.get('window').height) *
         0.00522,
      },
      locations: locations,
    };
    this.switchMapType = this.switchMapType.bind(this);
  }

  onPressZoomIn() {
    this.region = {
      latitude: this.state.focusedLocation.latitude,
      longitude: this.state.focusedLocation.longitude,
      latitudeDelta: this.state.focusedLocation.latitudeDelta * 0.5,
      longitudeDelta: this.state.focusedLocation.longitudeDelta * 0.5,
    };

    this.setState({
      focusedLocation: {
        latitudeDelta: this.region.latitudeDelta,
        longitudeDelta: this.region.longitudeDelta,
        latitude: this.region.latitude,
        longitude: this.region.longitude,
      },
    });
    this.map.animateToRegion(this.region, 500);
  }

  onPressZoomOut() {
    this.region = {
      latitude: this.state.focusedLocation.latitude,
      longitude: this.state.focusedLocation.longitude,
      latitudeDelta: this.state.focusedLocation.latitudeDelta / 0.5,
      longitudeDelta: this.state.focusedLocation.longitudeDelta / 0.5,
    };
    this.setState({
      focusedLocation: {
        latitudeDelta: this.region.latitudeDelta,
        longitudeDelta: this.region.longitudeDelta,
        latitude: this.region.latitude,
        longitude: this.region.longitude,
      },
    });
    this.map.animateToRegion(this.region, 500);
  }
  render() {
    return (
      <View style={styles.container}>
       <StatusBar hidden />
        <MapView
          //initialRegion={initialRegion}
          style={styles.mapView}
          rotateEnabled={true}
          scrollEnabled={true}
          showsMyLocationButton={false}
          showsUserLocation={true}
          zoomEnabled={true}
          mapType={this.state.mapType}
          showsPointsOfInterest={false}
          showBuildings={false}
          onMapReady={this._mapReady}
          ref={ref => (this.map = ref)}>
          {locations.map(
            (locations, id, latitude, longitude, hora, linha, prestadora) => (
              console.log(locations.latitude, locations.latitude),
              (
                <MapView.Marker
                  onPress={this.pickLocationHandler}
                  ref={mark => (locations.mark = mark)}
                  key={id}
                  title={locations.linha + ' - ' + locations.prestadora}
                  pinColor={'tomato'}
                  description={
                    'Aguarde o seu transporte a partir de: ' + locations.hora
                  }
                  coordinate={{
                    latitude: JSON.parse(locations.latitude),
                    longitude: JSON.parse(locations.longitude),
                  }}
                />
              )
            )
          )}
        </MapView>
        ...
        <ScrollView
          style={styles.placesContainer}
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onMomentumScrollEnd={e => {
            const locations =
              e.nativeEvent.contentOffset.x > 0
                ? e.nativeEvent.contentOffset.x / Dimensions.get('window').width
                : 0;

            const { latitude, longitude, mark } = this.state.locations[
              locations
            ];

            this.map.animateToCoordinate(
              {
                latitude: JSON.parse(latitude),
                longitude: JSON.parse(longitude),
              },
              500
            );

            setTimeout(() => {
              mark.showCallout();
            }, 500);
          }}>
          {locations.map(locations => (
            <View key={locations.id} style={styles.place}>
              <Text style={styles.title}>Ponto {locations.id} </Text>
              <Text style={styles.text}>A partir de: {locations.hora}</Text>
              <Image
                source={require('./assets/expo.symbol.white.png')}
                style={{
                  marginLeft: Dimensions.get('window').width / 1.5,
                  width: 67,
                  height: 67,
                  tintColor: '#FF3D00',
                }}
              />
            </View>
          ))}
        </ScrollView>
      </View>
    );
  }
}

How can I fix it? for when I press the button zoom in, for example, it takes a zoom in the specific marker selected?

Here is the full code for your view: https://snack.expo.io/@matheus_cbrl/zoomin-zoomout

here is the code to pick Location by Handler marker:

pickLocationHandler = event => {
    const coords = event.nativeEvent.coordinate;
    console.log('Location picker Marker', coords);
    this.map.animateToRegion({
      ...this.state.focusedlocation,
      latitude: coords.latitude,
      longitude: coords.longitude,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta:
          (Dimensions.get('window').width / Dimensions.get('window').height) *
          0.00522,
    });

    this.setState(prevState => {
      return {
        focusedlocation: {
          ...prevState.focusedlocation,
          latitude: coords.latitude,
          longitude: coords.longitude,
        },
        locationChosen: true,
      };
    });
  };

Body:
First move to your marker, then zoom in.

Move to marker,

this.refs.map.animateToRegion({
     latitude: markerLat,
     longitude: markerLong,
})

Then zoom in with
focusedLocation.


问:
Do something if nth number
I need to create a celery task that runs some background stuff if the column in the DB value is a 'fifth number'. I'm not sure what to call it, but

```<code>if the number is 5 -> Do something
if the number is 10 -> Do something
if the number is 15 -> Do something
if the number is 20 -> Do something
if the number is 25 -> Do something
</code>```

and so on. The functions should only check if the current value is a 'fifth number' so the code only runs once. How would I go on about creating this kind of checker? I'd appreciate any kind of resource I can check out

答: The way to check if the number is a multiple of 5 is by analyzing the module of the division by 5. The expression number % 5 == 0 will return true if the number is a multiple of 5 (5, -10, 15, -25, etc., but also 0, so be on the lookout for that if 0 is not a "fifth number" as you called) but false for any other number.

Title: Do something if nth number

Body:
I need to create a celery task that runs some background stuff if the column in the DB value is a 'fifth number'. I'm not sure what to call it, but

if the number is 5 -> Do something
if the number is 10 -> Do something
if the number is 15 -> Do something
if the number is 20 -> Do something
if the number is 25 -> Do something

and so on. The functions should only check if the current value is a 'fifth number' so the code only runs once. How would I go on about creating this kind of checker? I'd appreciate any kind of resource I can check out


问:
Minimum and maximum sequential values of a vector
I need to find the minimum and the maximum values of a vector, but the minimum one needs to be positioned inside before the maximum one. So, given the vector:

```<code>v <- c (8,2,1,3,5,7,4)
</code>```

the minimum value would be '1' (the 3rd element) and the maximum '7' (the sixth element). The maximum value would not be indeed '8' (the 1th element) because it occurs before the minimum '1' (the 3rd element).

I looked at the functions 'min' and 'max' (and their faster versions pmin and pmax), but apparently they are only able to find the highest minimum and maximum values, with no restrictions in place. The same for the range function.

Is there anyone that could help?

答:
using which.min you get the index of the minimum.
This you can use to subset v up to the end of your vector.

```<code>min <- min(v)
max <- max(v[ which.min(v): length(v)])

c(min, max)
</code>```

Body:
I need to find the minimum and the maximum values of a vector, but the minimum one needs to be positioned inside before the maximum one. So, given the vector:

v <- c (8,2,1,3,5,7,4)

the minimum value would be '1' (the 3rd element) and the maximum '7' (the sixth element). The maximum value would not be indeed '8' (the 1th element) because it occurs before the minimum '1' (the 3rd element).

I looked at the functions 'min' and 'max' (and their faster versions pmin and pmax), but apparently they are only able to find the highest minimum and maximum values, with no restrictions in place. The same for the range function.

Is there anyone that could help?

Body:
using which.min you get the index of the minimum.
This you can use to subset v up to the end of your vector.

min <- min(v)
max <- max(v[ which.min(v): length(v)])

c(min, max)


问:
Django user model (user to user relation)
I would like to ask more experienced coleagues about setting relations between users in standard django user model.

In my app I currently keep user data on 3 classes (User, Employee, Manager) as you can see on the below picture.

I would like to simplify that model, but I'm not sure can I somehow do that on User class only. Is it possible to do something like this ?

from django.contrib.auth.models import User

class User(models.Model):
    manager = models.ForeignKey(User, related_name="employees", on_delete=models.CASCADE)
```

答:
You can use "self" string for this:

```<code>class User(models.Model):
    manager = models.ForeignKey("self", related_name="employees", on_delete=models.CASCADE)
</code>```

Body:
You can use "self" string for this:

class User(models.Model):
    manager = models.ForeignKey("self", related_name="employees", on_delete=models.CASCADE)


问:
ES6 destructuring not returning correct result
I an trying to destructure two object with the same property names but only the names of the first set are observed.

```<code>let a, b,
 ({ a,b } = myObject1);
({ a,b } = myObject2);
</code>```

ie; only the values for myObject1 are in the console.log()

Does anyone know how to destructure properties of the same name from different objects ? I do not want to manually assign each variable.

I had tried

```<code>let a, b,
     ({ a,b } = myObject1);
    ({ a : test1,b: test2 } = myObject2)
console.log(test1)
</code>```

and

```<code>  let a, b,
         { a,b } = myObject1;
         { a : test1,b: test2 } = myObject2
    console.log(test1)
</code>```

But test1 is undefined

答:
Assign name to variables.</p>

```<code>let a, b,
 ({ a,b } = myObject1);
({ a: A,b:B } = myObject2);
</code>```

Body:
I an trying to destructure two object with the same property names but only the names of the first set are observed.

let a, b,
 ({ a,b } = myObject1);
({ a,b } = myObject2);

ie; only the values for myObject1 are in the console.log()

Does anyone know how to destructure properties of the same name from different objects ? I do not want to manually assign each variable.

I had tried

let a, b,
     ({ a,b } = myObject1);
    ({ a : test1,b: test2 } = myObject2)
console.log(test1)

and

  let a, b,
         { a,b } = myObject1;
         { a : test1,b: test2 } = myObject2
    console.log(test1)

But test1 is undefined

Body:
Assign name to variables.

let a, b,
 ({ a,b } = myObject1);
({ a: A,b:B } = myObject2);


问:
Flexbox wrap - first and last item displaying incorrectly on iPad
I am having an issue with flexbox wrap on iPad. When emulating iPad in Chrome developer tools I get the result I want, all the items wrapping and displaying correctly. However, when I test using Browserstack on a physical iPad the first and last item inside the flex container do not behave the same, please see the images below for comparison.

Dev Tools iPad Emulation

Browserstack iPad / Physcial Device

I have been browsing other peoples solutions on here but to no avail. Here is the SASS snippet with solutions people have provided on other questions added, but still not working. Have also added a link to the page in question below so it can be inspected easier.

This is my Css

.blogPageCards {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  .articleCard {
      flex-direction: column;
      width: calc(50% - 30px);
      margin: 0px 15px;
        &:before {
          display: none;
          content: normal;
        }
        &:after {
          display: none;
          content: normal;
        }
    }
}```

http://nevillejohnson.dev.clicky.co.uk/inspiration/

Please let me know if you need any more information. Thanks in advance.

答:
As i am unable to write comment, i am writing it here.
I think it is not working because your browser(i assume it is IOS Safari)needs css vendor prefix to implement the flexbox.

I am unsure which IOS Safari version is your Ipad using but if it is between 3.2 - 6.1 you surely must put -webkit- before the flexbox like this

```<code>.blogPageCards {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;

  .articleCard {
      -webkit-box-orient: vertical;
      -webkit-box-direction: normal;
      -ms-flex-direction: column;
      flex-direction: column;
      width: calc(50% - 30px);
      margin: 0px 15px;
        &:before {
          display: none;
          content: normal;
        }
        &:after {
          display: none;
          content: normal;
        }
    }
}
</code>```

Body:
I am having an issue with flexbox wrap on iPad. When emulating iPad in Chrome developer tools I get the result I want, all the items wrapping and displaying correctly. However, when I test using Browserstack on a physical iPad the first and last item inside the flex container do not behave the same, please see the images below for comparison.

Dev Tools iPad Emulation

Browserstack iPad / Physcial Device

I have been browsing other peoples solutions on here but to no avail. Here is the SASS snippet with solutions people have provided on other questions added, but still not working. Have also added a link to the page in question below so it can be inspected easier.

This is my Css

.blogPageCards {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  .articleCard {
      flex-direction: column;
      width: calc(50% - 30px);
      margin: 0px 15px;
        &:before {
          display: none;
          content: normal;
        }
        &:after {
          display: none;
          content: normal;
        }
    }
}

http://nevillejohnson.dev.clicky.co.uk/inspiration/

Please let me know if you need any more information. Thanks in advance.

Body:
As i am unable to write comment, i am writing it here.
I think it is not working because your browser(i assume it is IOS Safari)needs css vendor prefix to implement the flexbox.

I am unsure which IOS Safari version is your Ipad using but if it is between 3.2 - 6.1 you surely must put -webkit- before the flexbox like this

.blogPageCards {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;

  .articleCard {
      -webkit-box-orient: vertical;
      -webkit-box-direction: normal;
      -ms-flex-direction: column;
      flex-direction: column;
      width: calc(50% - 30px);
      margin: 0px 15px;
        &:before {
          display: none;
          content: normal;
        }
        &:after {
          display: none;
          content: normal;
        }
    }
}


问:
How to convert the elements inside the tuple of a list into 2d list
I have the tuple inside the list and I want to convert all the elements into 2d list. The tuple inside the list is like this

```<code> myList=[("[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]",)]
</code>```

I have no clue how to break this stuff but I want to convert like this any help would be appreciated.

```<code> myList=[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]
</code>```

答:
Try ast.literal_eval

```<code>>>> import ast
>>> myList=[("[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]",)]
>>> myList = ast.literal_eval(myList[0][0])
>>> myList
[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]
</code>```

See this for why you should use this over eval.

Body:
I have the tuple inside the list and I want to convert all the elements into 2d list. The tuple inside the list is like this

 myList=[("[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]",)]

I have no clue how to break this stuff but I want to convert like this any help would be appreciated.

 myList=[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]

Body:
Try ast.literal_eval

>>> import ast
>>> myList=[("[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]",)]
>>> myList = ast.literal_eval(myList[0][0])
>>> myList
[['MDLSBRO', 'TABY'], ['TABY', 'YAAM'], ['YAAM', 'NLRTN'], ['NLRTN', 'THIRSK'], ['THIRSK', 'YORK']]

See this for why you should use this over eval.


问:
Array filter is not returning correct for Zero?

function zeroCount(arr){
   const zero = arr.filter(el=>{
            if(el===0){
                return el ;
            }
        });
    return zero.length ; // but it returns 0. I want it to return 3.
}

console.log(zeroCount([2,3,0,5,0,2,0]));```

I want to return the no. of zero present in the array using filter.

答:
The below method helps to return the count of the falsy values in the array.

function zeroCount(arr){
   return arr.filter(elem => !elem).length;
}

console.log(zeroCount([2,3,0,5,0,2,0]));```

Body:
function zeroCount(arr){
   const zero = arr.filter(el=>{
            if(el===0){
                return el ;
            }
        });
    return zero.length ; // but it returns 0. I want it to return 3.
}

console.log(zeroCount([2,3,0,5,0,2,0]));

I want to return the no. of zero present in the array using filter.


问:
Delete closest tr and it's childs
I have the following code where I can delete the closest tr using delete function, but I want to create another function called delete-contato where it would delete the closest tr and its children that is all "email" and "telefone" associated with that "contato".

```<code>$(wrapper).on("click", ".delete-contato", function(e) {
        e.preventDefault();
        $(this).closest('tr').empty();

        x--;
    })

</code>```

This is the fiddle with the scenario and here's  snippet:

// funcao para adicionar um novo input no Contato
$(document).ready(function() {
  var max_fields = 99;
  var wrapper = $(".container-contato");
  var add_button = $(".add-contato");
  var add_email = $(".add-email");
  var add_telefone = $(".add-telefone");

  var x = 1;

  $(add_email).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

            <input type="text" name="contato_rpps.email['${x}']" placeholder="Outro Email"/>

              Delete

      `)
    }
  });

  $(add_telefone).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

            <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()" placeholder="Outro Telefone"/>

              Delete

      `)
    }
  });

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

              <input type="text" class="nome" name="contato_rpps.nome['${x}']"/>

              <input type="text" name="contato_rpps.cargo['${x}']"/>

              <input type="text" name="contato_rpps.email['${x}']"/>

              <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()"/>

              Delete

          `); //add input box

    } else {
      alert('You Reached the limits')
    }
  });

  $(wrapper).on("click", ".delete", function(e) {
    e.preventDefault();
    $(this).closest('tr').empty();

    x--;
  })

  $(wrapper).on("click", ".delete-contato", function(e) {
    e.preventDefault();

    x--;
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="add-contato">Novo Contato
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<button type="button" class="add-email">Novo Email
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<button type="button" class="add-telefone">Novo Telefone
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<div>
  <table>
    <tbody class="container-contato">
      <tr>
        <td>
          <label><br>Nome</label>
          <input type="text" name="contato_rpps.nome['1']" class="nome">
          <br>
        </td>
        <td>
          <label><br>Cargo</label>
          <input type="text" name="contato_rpps.cargo['1']" class="cargo">
        </td>
        <td>
          <label><br>Email</label>
          <input type="email" name="contato_rpps.email['1']" class="email">
        </td>
        <td>
          <label><br>Telefone</label>
          <input type="text" class="telefone" placeholder="(00) 90000-0000" onkeyup="phoneMask()" name="contato_rpps.telefone['1']" maxlength="15">
        </td>
      </tr>
    </tbody>
  </table>
</div></code>```

I don't think i explained what i want cleary so.. when you press Novo Contato a new set of inputs is created and then you press Novo Email or Novo Telefone. So after press delete on Contanto i want all those new inputs to be deleted. Nome, Cargo, Email, Telefone and others Outros Emails and Outros Telefone generated.

Right now when you delete Contato, Outro Telefone and Outro Email stays.

答:
Use .parents('tr') and remove it !

// funcao para adicionar um novo input no Contato
$(document).ready(function() {
  var max_fields = 99;
  var wrapper = $(".container-contato");
  var add_button = $(".add-contato");
  var add_email = $(".add-email");
  var add_telefone = $(".add-telefone");

  var x = 1;

  $(add_email).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

            <input type="text" name="contato_rpps.email['${x}']" placeholder="Outro Email"/>

              Delete

      `)
    }
  });

  $(add_telefone).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

            <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()" placeholder="Outro Telefone"/>

              Delete

      `)
    }
  });

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

              <input type="text" class="nome" name="contato_rpps.nome['${x}']"/>

              <input type="text" name="contato_rpps.cargo['${x}']"/>

              <input type="text" name="contato_rpps.email['${x}']"/>

              <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()"/>

              Delete

          `); //add input box

    } else {
      alert('You Reached the limits')
    }
  });

  $(wrapper).on("click", ".delete", function(e) {
    e.preventDefault();
    $(this).closest('tr').empty();

    x--;
  })

  $(wrapper).on("click", ".delete-contato", function(e) {
    e.preventDefault();

    $(this).parents('tr').remove()
    x--;
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="add-contato">Novo Contato
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<button type="button" class="add-email">Novo Email
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<button type="button" class="add-telefone">Novo Telefone
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<div>
  <table>
    <tbody class="container-contato">
      <tr>
        <td>
          <label><br>Nome</label>
          <input type="text" name="contato_rpps.nome['1']" class="nome">
          <br>
        </td>
        <td>
          <label><br>Cargo</label>
          <input type="text" name="contato_rpps.cargo['1']" class="cargo">
        </td>
        <td>
          <label><br>Email</label>
          <input type="email" name="contato_rpps.email['1']" class="email">
        </td>
        <td>
          <label><br>Telefone</label>
          <input type="text" class="telefone" placeholder="(00) 90000-0000" onkeyup="phoneMask()" name="contato_rpps.telefone['1']" maxlength="15">
        </td>
      </tr>
    </tbody>
  </table>
</div></code>```

Title: Delete closest tr and it's childs

Body:
I have the following code where I can delete the closest tr using delete function, but I want to create another function called delete-contato where it would delete the closest tr and its children that is all "email" and "telefone" associated with that "contato".

$(wrapper).on("click", ".delete-contato", function(e) {
        e.preventDefault();
        $(this).closest('tr').empty();

        x--;
    })

This is the fiddle with the scenario and here's  snippet:

// funcao para adicionar um novo input no Contato
$(document).ready(function() {
  var max_fields = 99;
  var wrapper = $(".container-contato");
  var add_button = $(".add-contato");
  var add_email = $(".add-email");
  var add_telefone = $(".add-telefone");

  var x = 1;

  $(add_email).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

            <input type="text" name="contato_rpps.email['${x}']" placeholder="Outro Email"/>

              Delete

      `)
    }
  });

  $(add_telefone).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

            <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()" placeholder="Outro Telefone"/>

              Delete

      `)
    }
  });

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

              <input type="text" class="nome" name="contato_rpps.nome['${x}']"/>

              <input type="text" name="contato_rpps.cargo['${x}']"/>

              <input type="text" name="contato_rpps.email['${x}']"/>

              <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()"/>

              Delete

          `); //add input box

    } else {
      alert('You Reached the limits')
    }
  });

  $(wrapper).on("click", ".delete", function(e) {
    e.preventDefault();
    $(this).closest('tr').empty();

    x--;
  })

  $(wrapper).on("click", ".delete-contato", function(e) {
    e.preventDefault();

    x--;
  })
});

<button class="add-contato">Novo Contato
              +
            </button>
<button type="button" class="add-email">Novo Email
              +
            </button>
<button type="button" class="add-telefone">Novo Telefone
              +
            </button>

Nome
          <input type="text" name="contato_rpps.nome['1']" class="nome">

Cargo
          <input type="text" name="contato_rpps.cargo['1']" class="cargo">

Email
          <input type="email" name="contato_rpps.email['1']" class="email">

Telefone
          <input type="text" class="telefone" placeholder="(00) 90000-0000" onkeyup="phoneMask()" name="contato_rpps.telefone['1']" maxlength="15">

I don't think i explained what i want cleary so.. when you press Novo Contato a new set of inputs is created and then you press Novo Email or Novo Telefone. So after press delete on Contanto i want all those new inputs to be deleted. Nome, Cargo, Email, Telefone and others Outros Emails and Outros Telefone generated.

Right now when you delete Contato, Outro Telefone and Outro Email stays.

Body:
Use .parents('tr') and remove it !

// funcao para adicionar um novo input no Contato
$(document).ready(function() {
  var max_fields = 99;
  var wrapper = $(".container-contato");
  var add_button = $(".add-contato");
  var add_email = $(".add-email");
  var add_telefone = $(".add-telefone");

  var x = 1;

  $(add_email).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`
        <tr>
          <td>
            <input type="text" name="contato_rpps.email['${x}']" placeholder="Outro Email"/>
          </td>
          <td>
              <a href="#" class="delete">Delete</a>
          </td>
        </tr>

      `)
    }
  });

  $(add_telefone).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`
       <tr>
          <td>
            <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()" placeholder="Outro Telefone"/>
          </td>
          <td>
              <a href="#" class="delete">Delete</a>
          </td>
        </tr>
      `)
    }
  });

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`
          <tr>
            <td>
              <input type="text" class="nome" name="contato_rpps.nome['${x}']"/>
            </td>
            <td>
              <input type="text" name="contato_rpps.cargo['${x}']"/>
            </td>
            <td>
              <input type="text" name="contato_rpps.email['${x}']"/>

            </td>
            <td>
              <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()"/>
            </td>
            <td>
              <a href="#" class="delete-contato">Delete</a>
            </td>
          </tr>
          `); //add input box

    } else {
      alert('You Reached the limits')
    }
  });

  $(wrapper).on("click", ".delete", function(e) {
    e.preventDefault();
    $(this).closest('tr').empty();

    x--;
  })

  $(wrapper).on("click", ".delete-contato", function(e) {
    e.preventDefault();

    $(this).parents('tr').remove()
    x--;
  })
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="add-contato">Novo Contato &nbsp;
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<button type="button" class="add-email">Novo Email &nbsp;
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<button type="button" class="add-telefone">Novo Telefone &nbsp;
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<div>
  <table>
    <tbody class="container-contato">
      <tr>
        <td>
          <label><br>Nome</label>
          <input type="text" name="contato_rpps.nome['1']" class="nome">
          <br>
        </td>
        <td>
          <label><br>Cargo</label>
          <input type="text" name="contato_rpps.cargo['1']" class="cargo">
        </td>
        <td>
          <label><br>Email</label>
          <input type="email" name="contato_rpps.email['1']" class="email">
        </td>
        <td>
          <label><br>Telefone</label>
          <input type="text" class="telefone" placeholder="(00) 90000-0000" onkeyup="phoneMask()" name="contato_rpps.telefone['1']" maxlength="15">
        </td>
      </tr>
    </tbody>
  </table>
</div>


问:
Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'
```<code>Schema validation failed with the following errors:
  Data path ".builders['app-shell']" should have required property 'class'.

Schema validation failed with the following errors:
  Data path ".builders['app-shell']" should have required property 'class'.
Error: Schema validation failed with the following errors:
  Data path ".builders['app-shell']" should have required property 'class'.
    at MergeMapSubscriber._registry.compile.pipe.operators_1.concatMap.validatorResult [as project] (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\@angular-devkit\core\src\workspace\workspace.js:210:42)
    at MergeMapSubscriber._tryNext (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\operators\mergeMap.js:65:27)
    at MergeMapSubscriber._next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\operators\mergeMap.js:55:18)
    at MergeMapSubscriber.Subscriber.next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\Subscriber.js:64:18)
    at MergeMapSubscriber.notifyNext (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\operators\mergeMap.js:84:26)
    at InnerSubscriber._next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\InnerSubscriber.js:25:21)
    at InnerSubscriber.Subscriber.next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\Subscriber.js:64:18)
    at MapSubscriber._next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\operators\map.js:52:26)
    at MapSubscriber.Subscriber.next (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\Subscriber.js:64:18)
    at SwitchMapSubscriber.notifyNext (D:\repo\beauty-velvettes-web\node_modules\@angular\cli\node_modules\rxjs\internal\operators\switchMap.js:77:26)
</code>```

答:
Update @angular-devkit/build-angular to "^0.13.9" . Then run npm install
and after that, run npm serve.

Specs:

Angular: 7.2.15

Angular CLI: 7.3.9

Node: 11.2.0

OS: darwin x64


问:
PYOMO: How to use abstract models with internal data
Hei all,

I am trying to set up an abstract model for a very simple QP of the form

min (x-x0)^2

s.t.

A x = b

C x <= d

I would like to use an abstract model, as I need to resolve with changing parameters (mainly x0, but potentially also A, b, C, d). I am right now struggeling with simply setting the parameters in the model instance. I do not want to use an external data file, but rather internal python variables. All examples I find online use AMPL formatted data files.

This is the code I have right now

```<code>import pyomo.environ as pe

model = pe.AbstractModel()

# the sets
model.n = pe.Param(within=pe.NonNegativeIntegers)
model.m = pe.Param(initialize = 1)
model.ss = pe.RangeSet(1, model.n)
model.os = pe.RangeSet(1, model.m)

# the starting point and the constraint parameters
model.x_hat = pe.Param(model.ss)
model.A = pe.Param(model.os, model.ss)
model.b = pe.Param(model.os)
model.C = pe.Param(model.os, model.os)
model.d = pe.Param(model.ss, model.os)

# the decision variables
model.x_projected = pe.Var(model.ss)

# the cosntraints
# A x = b
def sum_of_elements_rule(model):
    value = model.A * model.x_projected
    return value == model.d
model.sumelem = pe.Constraint(model.os, rule=sum_of_elements_rule)

# C x <= d
def positivity_constraint(model):
    return model.C*model.x_projected <= model.d

model.bounds = pe.Constraint(model.ss, rule=positivity_constraint)

# the cost
def cost_rule(model):
    return sum((model.x_projected[i] - model.x[i])**2 for i in model.ss)
model.cost = pe.Objective(rule=cost_rule)

instance = model.create_instance()
</code>```

And somehow here I am stuck. How do I set the parameters now?

Thanks and best, Theo

答:
I know this is an old post but a solution to this could have helped me so here is the solution to this problem:

```<code>## TEST
data_init= {None: dict(
        n = {None : 3},
        d = {0:0, 1:1, 2:2},
        x_hat = {0:10, 1:-1, 2:-100},
        b = {None: 10}
        )}
# create instance
instance = model.create_instance(data_init)
</code>```

This creates the instance in an equivalent way than what you did but in a more formal way.

Body:
Hei all,

I am trying to set up an abstract model for a very simple QP of the form

min (x-x0)^2

s.t.

A x = b

C x <= d

I would like to use an abstract model, as I need to resolve with changing parameters (mainly x0, but potentially also A, b, C, d). I am right now struggeling with simply setting the parameters in the model instance. I do not want to use an external data file, but rather internal python variables. All examples I find online use AMPL formatted data files.

This is the code I have right now

import pyomo.environ as pe

model = pe.AbstractModel()

# the sets
model.n = pe.Param(within=pe.NonNegativeIntegers)
model.m = pe.Param(initialize = 1)
model.ss = pe.RangeSet(1, model.n)
model.os = pe.RangeSet(1, model.m)

# the starting point and the constraint parameters
model.x_hat = pe.Param(model.ss)
model.A = pe.Param(model.os, model.ss)
model.b = pe.Param(model.os)
model.C = pe.Param(model.os, model.os)
model.d = pe.Param(model.ss, model.os)

# the decision variables
model.x_projected = pe.Var(model.ss)

# the cosntraints
# A x = b
def sum_of_elements_rule(model):
    value = model.A * model.x_projected
    return value == model.d
model.sumelem = pe.Constraint(model.os, rule=sum_of_elements_rule)

# C x <= d
def positivity_constraint(model):
    return model.C*model.x_projected <= model.d

model.bounds = pe.Constraint(model.ss, rule=positivity_constraint)

# the cost
def cost_rule(model):
    return sum((model.x_projected[i] - model.x[i])**2 for i in model.ss)
model.cost = pe.Objective(rule=cost_rule)

instance = model.create_instance()

And somehow here I am stuck. How do I set the parameters now?

Thanks and best, Theo

Body:
I know this is an old post but a solution to this could have helped me so here is the solution to this problem:

## TEST
data_init= {None: dict(
        n = {None : 3},
        d = {0:0, 1:1, 2:2},
        x_hat = {0:10, 1:-1, 2:-100},
        b = {None: 10}
        )}
# create instance
instance = model.create_instance(data_init)

This creates the instance in an equivalent way than what you did but in a more formal way.


问:
What does "CONST func(arg);" mean in C language?
This is a c program demonstrating some basic usage of the libxml2 library.  Below is quoted from the main function:

```<code>LIBXML_TEST_VERSION example1Func(argv[1]);
</code>```

What does this statement stand for?

I can only tell that LIBXML_TEST_VERSION is obviously a constant, and after that is a function call, that function returns nothing (void). But I've no idea what it means the statement in whole.

答:
It is the standard convention to name C preprocessor macros in ALL_UPPERCASE. As you suggest, this is often used for compile-time constants. However, there are other uses.

Now to your example. The original source looks like this (comments are mine):

```<code>LIBXML_TEST_VERSION    /* line 1 */
example1Func(argv[1]); /* line 2 */
</code>```

The first line is a C macro. The second line is a function call. The two are not part of the same statement as your question implies. It is unfortunate that the way LIBXML_TEST_VERSION is defined it does not require a semicolon at the end; if this were the case, there would be no confusion around whether the two lines are part of the same statement.

In case you're wondering what exactly is LIBXML_TEST_VERSION:

```<code>Macro: LIBXML_TEST_VERSION

#define LIBXML_TEST_VERSION
Macro to check that the libxml version in use is compatible
with the version the software has been compiled against
</code>```

Body:
This is a c program demonstrating some basic usage of the libxml2 library.  Below is quoted from the main function:

LIBXML_TEST_VERSION example1Func(argv[1]);

What does this statement stand for?

I can only tell that LIBXML_TEST_VERSION is obviously a constant, and after that is a function call, that function returns nothing (void). But I've no idea what it means the statement in whole.

Body:
It is the standard convention to name C preprocessor macros in ALL_UPPERCASE. As you suggest, this is often used for compile-time constants. However, there are other uses.

Now to your example. The original source looks like this (comments are mine):

LIBXML_TEST_VERSION    /* line 1 */
example1Func(argv[1]); /* line 2 */

The first line is a C macro. The second line is a function call. The two are not part of the same statement as your question implies. It is unfortunate that the way LIBXML_TEST_VERSION is defined it does not require a semicolon at the end; if this were the case, there would be no confusion around whether the two lines are part of the same statement.

In case you're wondering what exactly is LIBXML_TEST_VERSION:

Macro: LIBXML_TEST_VERSION

#define LIBXML_TEST_VERSION
Macro to check that the libxml version in use is compatible
with the version the software has been compiled against


答:
You can do:</p>

```<code>range(v[which.min(v):length(v)])

[1] 1 7
</code>```

Title: Minimum and maximum sequential values of a vector

Body:
You can do:

range(v[which.min(v):length(v)])

[1] 1 7


问:
How to import or require a js file dynamically depending on if it's development or production env?

Problem

I know that ES6 imports and NODE require() use static analysis and do not support dynamic paths. But how do we work around it? What's the solution?

My Electron app, during installation copies shortcuts.js file from development (project) folder [project_dir]/public/resources into the [app_installation_dir]/resources folder.

So the problem is:

In development the app should import ../public/resources/shortcuts.js

In production the app should import [app_installation_dir]/resources/shortcuts.js

I cannot specify the "non-dynamic" path for production since I don't know in advance what [app_installation_dir] path is going to be.

Code

I tried the following, but expectedly only the else brunch works:

const shortcuts = process.env.NODE_ENV === 'production'
  ? require(`${process.resourcesPath}/shortcuts.js`).data
  : require(../public/resources/shortcuts.js`).data
```

<p>After installing the app, in production, I'm getting the error:</p>

```Uncaught Error: Cannot find module [app_installation_dir]/resources/shortcuts.js
```

<p>since, I guess, <code>require</code> doesn't see the dynamic path as something it can import (I checked, the file exists at this path).</p>

<p>I then converted the file from <code>module.exports</code> to <code>export default {}</code> and tried the following ES6 method but I get the same error:</p>

<pre class="lang-js prettyprint-override"><code>if (process.env.NODE_ENV === 'production') {
  const importPath = path.join(process.resourcesPath, 'shortcuts.js')
  import(importPath)
    .then((data) => {
      console.log('IMPORT DATA', data)
    })
}
else if (process.env.NODE_ENV === 'development') {
  import('../public/resources/shortcuts.js')
    .then((data) => {
      console.log('IMPORT DATA', data)
    })
}
</code>```

babel.config.js

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset',
  ]
}
```

<h3>Project created</h3>

```vue create app-name
> selected [babel, eslint]

vue add electron-builder
```

答:
Interesting. I can't see why the require method would not work assuming the path is absolute. If shortcuts.js contained data that could be exported as plain JSON, maybe an idea I would try is convert that file into json and use the file system to read it and parse it.</p>

```<code>import fs from 'fs'

const shortcuts = JSON.parse(process.env.NODE_ENV === 'production'
  ? fs.readFileSync(`${process.resourcesPath}/shortcuts.json`).toString())
  : fs.readFileSync(`../public/resources/shortcuts.js`).toString()).data
</code>```

Body:
Problem

I know that ES6 imports and NODE require() use static analysis and do not support dynamic paths. But how do we work around it? What's the solution?

My Electron app, during installation copies shortcuts.js file from development (project) folder [project_dir]/public/resources into the [app_installation_dir]/resources folder.

So the problem is:

In development the app should import ../public/resources/shortcuts.js

In production the app should import [app_installation_dir]/resources/shortcuts.js

I cannot specify the "non-dynamic" path for production since I don't know in advance what [app_installation_dir] path is going to be.

Code

I tried the following, but expectedly only the else brunch works:

const shortcuts = process.env.NODE_ENV === 'production'
  ? require(`${process.resourcesPath}/shortcuts.js`).data
  : require(../public/resources/shortcuts.js`).data

After installing the app, in production, I'm getting the error:

Uncaught Error: Cannot find module [app_installation_dir]/resources/shortcuts.js

since, I guess, require doesn't see the dynamic path as something it can import (I checked, the file exists at this path).

I then converted the file from module.exports to export default {} and tried the following ES6 method but I get the same error:

if (process.env.NODE_ENV === 'production') {
  const importPath = path.join(process.resourcesPath, 'shortcuts.js')
  import(importPath)
    .then((data) => {
      console.log('IMPORT DATA', data)
    })
}
else if (process.env.NODE_ENV === 'development') {
  import('../public/resources/shortcuts.js')
    .then((data) => {
      console.log('IMPORT DATA', data)
    })
}

babel.config.js

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset',
  ]
}

Project created

vue create app-name
> selected [babel, eslint]

vue add electron-builder

Body:
Interesting. I can't see why the require method would not work assuming the path is absolute. If shortcuts.js contained data that could be exported as plain JSON, maybe an idea I would try is convert that file into json and use the file system to read it and parse it.

import fs from 'fs'

const shortcuts = JSON.parse(process.env.NODE_ENV === 'production'
  ? fs.readFileSync(`${process.resourcesPath}/shortcuts.json`).toString())
  : fs.readFileSync(`../public/resources/shortcuts.js`).toString()).data


问:
Display stored Array Objects to List in Javascript to HTML
I'm Trying to make a list display in HTML of the stored details i put in my object using Javascript.
which should look like this

```<code>name: Tester1 , age: 1
name: Tester2 , age: 2
name: Tester3 , age: 3
</code>```

I used for in loop to display all the inputted objects, but it this happened

```<code>Actual:
name: Tester1 , age: 1name: Tester1 , age: 1name: Tester2 , age: 2name: Tester1 , age: 1name: Tester2 , age: 2name: Tester3 , age: 3
</code>```

Here is the code for the Jascript

```<code>var person = [];
function profile(e) {
    //to stop form from resubmitting
    e.preventDefault();

    var pProfile = {
        name: document.getElementById('name').value,
        age: document.getElementById('age').value
    }
    person.push(pProfile);
    //used to convert result to string
    var myJSON = JSON.stringify(person);

    document.forms[0].reset();

    //display in Final Obejct div
    document.getElementById("fObject").innerHTML = myJSON;

    //display converted objects to
    for (let x in person){
         document.getElementById("rFormat").append("name: " + person[x].name + " , " + "age : " + person[x].age + "<br>");
         console.log(person[x]);
    }
}

</code>```

And this is for the HTML

```<code>    <div id="part1">
        <h3>Part 1</h2>
        <form id="profile" onsubmit="profile(event)" action="#">
            Name: <input type="text" id ="name">
            Age: <input type="text" id ="age">
            <input type="Submit" value="Add">
        </form>

        <h4>Final Object</h4>
        <div id="fObject"></div>

        <h4>Readable Format</h4>
        <div id="rFormat"></div>
    </div>
</code>```

Pretty sure that I did something wrong with the for in loop, but i don't know exactly where.
Please help. I'm new in javascript. Thanks so much.

答:
person is an array. use for of. Then use x directly.

for in is for objects. If you use it on an array, you will just get the index.

Body:
I'm Trying to make a list display in HTML of the stored details i put in my object using Javascript.
which should look like this

name: Tester1 , age: 1
name: Tester2 , age: 2
name: Tester3 , age: 3

I used for in loop to display all the inputted objects, but it this happened

Actual:
name: Tester1 , age: 1name: Tester1 , age: 1name: Tester2 , age: 2name: Tester1 , age: 1name: Tester2 , age: 2name: Tester3 , age: 3

Here is the code for the Jascript

var person = [];
function profile(e) {
    //to stop form from resubmitting
    e.preventDefault();

    var pProfile = {
        name: document.getElementById('name').value,
        age: document.getElementById('age').value
    }
    person.push(pProfile);
    //used to convert result to string
    var myJSON = JSON.stringify(person);

    document.forms[0].reset();

    //display in Final Obejct div
    document.getElementById("fObject").innerHTML = myJSON;

    //display converted objects to
    for (let x in person){
         document.getElementById("rFormat").append("name: " + person[x].name + " , " + "age : " + person[x].age + "
");
         console.log(person[x]);
    }
}

And this is for the HTML

Part 1

        <form id="profile" onsubmit="profile(event)" action="#">
            Name: <input type="text" id ="name">
            Age: <input type="text" id ="age">
            <input type="Submit" value="Add">
        </form>

Final Object

Readable Format

Pretty sure that I did something wrong with the for in loop, but i don't know exactly where.
Please help. I'm new in javascript. Thanks so much.


答:
Instead of append() try with insertAdjacentHTML() or innerHTML. You also do not need the loop (since you are updating the HTML in each click), you can simply populate the last item in the array:

var person = [{name: "Tester1",age: 1 },{name: "Tester2",age: 2 },{name: "Tester3",age: 3 }];
var person = [];
function profile(e) {
  //to stop form from resubmitting
  e.preventDefault();

  var pProfile = {
      name: document.getElementById('name').value,
      age: document.getElementById('age').value
  }
  person.push(pProfile);
  //used to convert result to string
  var myJSON = JSON.stringify(person);

  document.forms[0].reset();

  //display in Final Obejct div
  document.getElementById("fObject").innerHTML = myJSON;

  //display converted objects to
  var p = person[person.length-1]; //last item in the array
  document.getElementById("rFormat").innerHTML += "name: " + p.name + ", " + "age : " + p.age + "
";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="part1">
  <h3>Part 1</h2>
  <form id="profile" onsubmit="profile(event)" action="#">
      Name: <input type="text" id ="name">
      Age: <input type="text" id ="age">
      <input type="Submit" value="Add">
  </form>

  <h4>Final Object</h4>
  <div id="fObject"></div>

  <h4>Readable Format</h4>
  <div id="rFormat"></div>
</div></code>```

Title: Display stored Array Objects to List in Javascript to HTML

Body:
Instead of append() try with insertAdjacentHTML() or innerHTML. You also do not need the loop (since you are updating the HTML in each click), you can simply populate the last item in the array:

var person = [{name: "Tester1",age: 1 },{name: "Tester2",age: 2 },{name: "Tester3",age: 3 }];
var person = [];
function profile(e) {
  //to stop form from resubmitting
  e.preventDefault();

  var pProfile = {
      name: document.getElementById('name').value,
      age: document.getElementById('age').value
  }
  person.push(pProfile);
  //used to convert result to string
  var myJSON = JSON.stringify(person);

  document.forms[0].reset();

  //display in Final Obejct div
  document.getElementById("fObject").innerHTML = myJSON;

  //display converted objects to
  var p = person[person.length-1]; //last item in the array
  document.getElementById("rFormat").innerHTML += "name: " + p.name + ", " + "age : " + p.age + "<br>";
}

<div id="part1">
  <h3>Part 1</h2>
  <form id="profile" onsubmit="profile(event)" action="#">
      Name: <input type="text" id ="name">
      Age: <input type="text" id ="age">
      <input type="Submit" value="Add">
  </form>

  <h4>Final Object</h4>
  <div id="fObject"></div>

  <h4>Readable Format</h4>
  <div id="rFormat"></div>
</div>


问:
How to reduce the computational cost
I use GPyOpt to calculate the optimized parameters of an LSTM model based on Tensorflow. Unlike typical process, however, the validation of the parameters is implemented by minimizing variance, not bias. Hence, it is required to iterate the LSTM model running with a parameters set. In fact, my script does work well without any errors, but it takes up too much time to return the optimum parameters. I tried to find out any methods to improve the processing speed, but couldn't.

I think the other modules, for instance GridSearch or RandomizedSearch are perhaps faster than one of GpyOp, but they use Bayesian Optimization to obtain the parameters.

Is there a way to reduce the computational cost of this operation?

My PC: MackBook, 2.3 GHz Intel Core i5

My script:

```<code>import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
os.environ['PYTHONHASHSEED']='0'
os.environ['OMP_NUM_THREADS']='4'
os.environ['KMP_BLOCKTIME']='30'
os.environ['KMP_SETTINGS']='1'
os.environ['KMP_AFFINITY']='granularity=fine,verbose,compact,1,0'

import tensorflow as tf
import numpy as np
import GPyOpt

import random

NUM_PARALLEL_EXEC_UNITS=4
config=tf.ConfigProto(intra_op_parallelism_threads=NUM_PARALLEL_EXEC_UNITS,
                      inter_op_parallelism_threads=2,
                      allow_soft_placement=True,
                  device_count={'CPU':NUM_PARALLEL_EXEC_UNITS})

def parameter_opt(df_x,df_y):

    x_set_list=[]
    y_set_list=[]
    for i in range(10): #create 10 data sets for calculating variance
        t=random.randint(1,2300)
        x_set_=df_x[t:t+10,:,:] #x_set_.shape is (10,7,5)
        y_set_=df_y[t:t+10,:]
        x_set_list.append(x_set_)
        y_set_list.append(y_set_)

    pred_x=df_x[-10:,:,:]

    bounds=[{'name':'hidden_layer','type':'discrete','domain':(10,50,100,300,500)},
            {'name':'learn_rate','type':'discrete','domain':(0.1,0.01,0.001,0.0001)},
            {'name':'forget','type':'continuous','domain':(0.1,1.0)},
            {'name':'std','type':'continuous','domain':(0.01,1.0)},
            {'name':'epo','type':'discrete','domain':(50,100,200,400)},
            {'name':'cell_drop_','type':'discrete','domain':(0,1)},
            {'name':'output_keep','type':'continuous','domain':(0.1,1.0)}]

    def f(x):
        tf.reset_default_graph()

        def LSTMmse(hidden_layer,learn_rate,forget,std,epo,cell_drop_, output_keep):
            pred_array=np.empty((10,0))
            for x_set,y_set in zip(x_set_list,y_set_list):
                tf.reset_default_graph()
                .......
                #LSTM model
                #generate prediction_list consisting of 10 predictionvalue
                .........
            variance_list=np.var(prediction_list,axis=1)
            variance_ave=sum(var_list)/len(var_list)
            return variance_ave

        for x_ in x:
            vari=LSTMmse(hidden_layer=int(x_[0]),
                        learn_rate=np.float32(x_[1]),
                        forget=np.float32(x_[2]),
                        std=np.float32(x_[3]),
                        epo=int(x_[4]),
                        cell_drop_=bool(x_[5]),
                        output_keep=np.float32(x_[6]))
         return vari

    myBopt=GPyOpt.methods.BayesianOptimization(f=f,domain=bounds,acquisition_type='MPI')

    myBopt.run_optimization(max_iter=10)
    opt=myBopt.x_opt
    opt=[int(opt[0]),opt[1],opt[2],opt[3],int(opt[4]),opt[5],opt[6]]

    key=['hidden_layer','learn_rate','forget','std','epo','cell_drop','output_keep']
    value=opt
    para_dict=dict(zip(key,value))
    return para_dict

parameter_opt=parameter_opt(df_x,df_y)
print(parameter_opt)  # spending too much time
</code>```

答:
There are a few things coming to mind you may try:

GRU instead of LSTM

This cell type has one gate less and thus is more computationally efficient.

Furthermore they have a little less hyperparameters so possible search space is smaller.

Nothing conclusive but anecdotically they perform on-par with LSTMs at least for moderate length sequences.

Use CUDA

If possible use CUDA enabled device for training your network. Particularly, for tensorflow use CuDNNGRU version (for tf2.x see this, there are options for 1.x as well).

Narrow your search space

The less hyperparameters to search for, the faster it will go. learning_rate is usually very important to get right.

There is quite-known trick for approximating optimal learning rate originated by Leslie N. Smith in Cyclical Learning Rates for Training Neural Networks and popularised by fastai community.

Basic idea - you set learning rate really low (e.g. 1e-7) and increment it exponentially every n batches until threshold is hit (highest lr, around 1.0 usually).

Monitoring train or validation loss you will see it will probably skyrocket at some learning rate. You take this point and set your approximately optimal learning 10 lower than that.

You can read about it here.

Other hyperparameters could be narrowed as well when you see some values are probably no-go early on, though bayesian optimisation takes care of that partially.

Title: How to reduce the computational cost

Body:
I use GPyOpt to calculate the optimized parameters of an LSTM model based on Tensorflow. Unlike typical process, however, the validation of the parameters is implemented by minimizing variance, not bias. Hence, it is required to iterate the LSTM model running with a parameters set. In fact, my script does work well without any errors, but it takes up too much time to return the optimum parameters. I tried to find out any methods to improve the processing speed, but couldn't.

I think the other modules, for instance GridSearch or RandomizedSearch are perhaps faster than one of GpyOp, but they use Bayesian Optimization to obtain the parameters.

Is there a way to reduce the computational cost of this operation?

My PC: MackBook, 2.3 GHz Intel Core i5

My script:

import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
os.environ['PYTHONHASHSEED']='0'
os.environ['OMP_NUM_THREADS']='4'
os.environ['KMP_BLOCKTIME']='30'
os.environ['KMP_SETTINGS']='1'
os.environ['KMP_AFFINITY']='granularity=fine,verbose,compact,1,0'

import tensorflow as tf
import numpy as np
import GPyOpt

import random

NUM_PARALLEL_EXEC_UNITS=4
config=tf.ConfigProto(intra_op_parallelism_threads=NUM_PARALLEL_EXEC_UNITS,
                      inter_op_parallelism_threads=2,
                      allow_soft_placement=True,
                  device_count={'CPU':NUM_PARALLEL_EXEC_UNITS})

def parameter_opt(df_x,df_y):

    x_set_list=[]
    y_set_list=[]
    for i in range(10): #create 10 data sets for calculating variance
        t=random.randint(1,2300)
        x_set_=df_x[t:t+10,:,:] #x_set_.shape is (10,7,5)
        y_set_=df_y[t:t+10,:]
        x_set_list.append(x_set_)
        y_set_list.append(y_set_)

    pred_x=df_x[-10:,:,:]

    bounds=[{'name':'hidden_layer','type':'discrete','domain':(10,50,100,300,500)},
            {'name':'learn_rate','type':'discrete','domain':(0.1,0.01,0.001,0.0001)},
            {'name':'forget','type':'continuous','domain':(0.1,1.0)},
            {'name':'std','type':'continuous','domain':(0.01,1.0)},
            {'name':'epo','type':'discrete','domain':(50,100,200,400)},
            {'name':'cell_drop_','type':'discrete','domain':(0,1)},
            {'name':'output_keep','type':'continuous','domain':(0.1,1.0)}]

    def f(x):
        tf.reset_default_graph()

        def LSTMmse(hidden_layer,learn_rate,forget,std,epo,cell_drop_, output_keep):
            pred_array=np.empty((10,0))
            for x_set,y_set in zip(x_set_list,y_set_list):
                tf.reset_default_graph()
                .......
                #LSTM model
                #generate prediction_list consisting of 10 predictionvalue
                .........
            variance_list=np.var(prediction_list,axis=1)
            variance_ave=sum(var_list)/len(var_list)
            return variance_ave

        for x_ in x:
            vari=LSTMmse(hidden_layer=int(x_[0]),
                        learn_rate=np.float32(x_[1]),
                        forget=np.float32(x_[2]),
                        std=np.float32(x_[3]),
                        epo=int(x_[4]),
                        cell_drop_=bool(x_[5]),
                        output_keep=np.float32(x_[6]))
         return vari

    myBopt=GPyOpt.methods.BayesianOptimization(f=f,domain=bounds,acquisition_type='MPI')

    myBopt.run_optimization(max_iter=10)
    opt=myBopt.x_opt
    opt=[int(opt[0]),opt[1],opt[2],opt[3],int(opt[4]),opt[5],opt[6]]

    key=['hidden_layer','learn_rate','forget','std','epo','cell_drop','output_keep']
    value=opt
    para_dict=dict(zip(key,value))
    return para_dict

parameter_opt=parameter_opt(df_x,df_y)
print(parameter_opt)  # spending too much time


问:
Count All Non-Overlapping Occurences of a Substring in a String
I would like to write a function that counts all non-overlapping occurences of a substring in a string. This is what I have so far:

def count(substr,theStr):
    count = 0
    for i in range(len(theStr)):
        if theStr[i:i+len(substr)] == substr:
            count = count + 1
    return count
```

As one can see, my function only counts occurences of a string, but not non-overlapping occurences. For example, the inputs "ana" and "Banana" would yield a count of 2, even though there is only one non-overlapping instance of "ana" in "Banana". How can I extend my function so that it works correctly?

答:
Python has a build-in function for this:

```<code>theStr.count(substr)
</code>```

PS:
Maybe you want to have a look at the Python Style-Guide

Body:
I would like to write a function that counts all non-overlapping occurences of a substring in a string. This is what I have so far:

def count(substr,theStr):
    count = 0
    for i in range(len(theStr)):
        if theStr[i:i+len(substr)] == substr:
            count = count + 1
    return count

As one can see, my function only counts occurences of a string, but not non-overlapping occurences. For example, the inputs "ana" and "Banana" would yield a count of 2, even though there is only one non-overlapping instance of "ana" in "Banana". How can I extend my function so that it works correctly?

Body:
Python has a build-in function for this:

theStr.count(substr)

PS:
Maybe you want to have a look at the Python Style-Guide


问:
AS3 Render Shape to Bitmap with Antialias
I have a drawn a Circle Shape in AS3. I want to render the Circle into a Bitmap with nice/antialiased Edges. Because I want it to work on Mobile Devices (Air Apps are limited to stagequality = low) I need a workaround. Any custom shape to bitmap renderer available?</p>

答:
StageQuality.LOW is going to make your bitmap quality low if you're using draw() because the source will be of low quality whether it's on the DisplayList or not.

I don't think there's a way around this.. You'll have to load in circle graphics or import images to use.


问:
Static type analysis with Python dicts
Can someone explain why this code, while valid, makes the mypy static analyser complain in multiple ways:

```<code>ranges = dict()
ranges['max'] = 0
ranges['services'] = []
ranges['services'].append('a')
</code>```

Namely:

error: Incompatible types in assignment (expression has type "List[<nothing>]", target has type "int")

error: "int" has no attribute "append"
```

If I simply add a type hint to the initial variable of ranges: dict = dict() it works fine.

I am confused about why the static analyser can't work this out by itself, especially as I am using the dict keyword to initialise the dict in the first instance.

答:
As you have not provided any annotations, mypy must try to infer the types. There are some choices it can make:

ranges = dict() implies range: Dict[Any, Any]

This would accept all of your code. It would also accept ranges['services'].keys() or any other operation since it erases all type information.

ranges['max'] = 0 implies range: Dict[str, int]

This is what mypy picks. It rejects any values that are not integers, in specific your list.

ranges['services'] = [] implies range: Dict[str, list]

This only accepts your ranges['services'] field. The ranges['max'] is invalid then, given that it is not list.

ranges['max'] = 0 and ranges['services'] = [] implies range: Dict[str, Union[int, list]]

This accepts assignment of the values. It rejects ranges['services'].append('a') since ranges['services'] might be an int.

Basically, none of these work. With a plain Dict[K, V], your code cannot be well-typed.

You can use typing.TypedDict to explicitly annotate ranges. Since dict is generally not restricted to static key-value pairs, mypy will not infer this by itself.

```<code>class Ranges(TypedDict):
    max: int
    services: List[str]

ranges: Ranges = dict()
</code>```

Title: Static type analysis with Python dicts

Body:
Can someone explain why this code, while valid, makes the mypy static analyser complain in multiple ways:

ranges = dict()
ranges['max'] = 0
ranges['services'] = []
ranges['services'].append('a')

Namely:

error: Incompatible types in assignment (expression has type "List[<nothing>]", target has type "int")

error: "int" has no attribute "append"

If I simply add a type hint to the initial variable of ranges: dict = dict() it works fine.

I am confused about why the static analyser can't work this out by itself, especially as I am using the dict keyword to initialise the dict in the first instance.

Body:
As you have not provided any annotations, mypy must try to infer the types. There are some choices it can make:

ranges = dict() implies range: Dict[Any, Any]

This would accept all of your code. It would also accept ranges['services'].keys() or any other operation since it erases all type information.

ranges['max'] = 0 implies range: Dict[str, int]

This is what mypy picks. It rejects any values that are not integers, in specific your list.

ranges['services'] = [] implies range: Dict[str, list]

This only accepts your ranges['services'] field. The ranges['max'] is invalid then, given that it is not list.

ranges['max'] = 0 and ranges['services'] = [] implies range: Dict[str, Union[int, list]]

This accepts assignment of the values. It rejects ranges['services'].append('a') since ranges['services'] might be an int.

Basically, none of these work. With a plain Dict[K, V], your code cannot be well-typed.

You can use typing.TypedDict to explicitly annotate ranges. Since dict is generally not restricted to static key-value pairs, mypy will not infer this by itself.

class Ranges(TypedDict):
    max: int
    services: List[str]

ranges: Ranges = dict()


问:
el-checkbox cannot be set checked with jest or at least no change on v-model
I'm setting up some tests for my vuejs website. I'm using element-ui. I'm trying jest on my connection page. I have a checkbox linked to a "remember me". I'd to check it and check if the value of the v-model changed.

Unfortunately, it doesn't.

In my connection file, I've the checkbox :

```<code>...
  <el-checkbox v-model="connectionForm.rememberme"></el-checkbox>
...
</code>```

And the rememberme variable :

```<code>...
  data() {
    return {
      connectionForm: {
        ...
        rememberme: false
      },
...
</code>```

My test file :

```<code>
describe('Connection', () => {
  const wrapper = mount(Connection)

  it('checkbox click', () => {
    expect(wrapper.vm.connectionForm.rememberme).toBe(false)

    expect(wrapper.contains('el-checkbox')).toBe(true)
    const elCheckbox = wrapper.find('el-checkbox')

    elCheckbox.setChecked(true)
    expect(wrapper.vm.connectionForm.rememberme).toBe(true)
  })
})

</code>```

 FAIL  frontend/components/user/sessions/New.test.js
  Connexion
    ✓ has a el-button (4ms)
    ✕ checkbox click (10ms)

  ● Connexion › checkbox click

    [vue-test-utils]: wrapper.setChecked() cannot be called on this element

      26 |
    > 27 |     elCheckbox.setChecked(true)
         |                ^
      28 |     expect(wrapper.vm.connexionForm.rememberme).toBe(true)
      29 |   })
      30 | })

```

<p>doc checkbox</p>

<p>So, I changed the setChecked(true) with a .trigger('click'), still nothing. So, I changed 'click' to 'change', but still not working...</p>

<pre class="lang-sh prettyprint-override"><code> FAIL  frontend/components/user/sessions/New.test.js
  Connexion
    ✓ has a el-button (4ms)
    ✕ checkbox click (10ms)
  ● Connexion › checkbox click

    expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false

      27 |     elCheckbox.trigger('change')
    > 28 |     expect(wrapper.vm.connectionForm.rememberme).toBe(true)
         |                                                  ^
      29 |   })
      30 | })
      31 |

</code>```

If found somewhere this :

```<code>    elCheckbox.element.selected = true
</code>```

But changes nothing.

答:
Yes

wrapper.find('.el-checkbox input[type="checkbox"]').setChecked(true)

would have worked cuz el-checkbox itself has the checkbox input wrapped inside it (as one of its children) and this api seems to work on the checkbox input element. Ref: https://vue-test-utils.vuejs.org/api/wrapper/#setchecked.

Body:
I'm setting up some tests for my vuejs website. I'm using element-ui. I'm trying jest on my connection page. I have a checkbox linked to a "remember me". I'd to check it and check if the value of the v-model changed.

Unfortunately, it doesn't.

In my connection file, I've the checkbox :

...
  <el-checkbox v-model="connectionForm.rememberme"></el-checkbox>
...

And the rememberme variable :

...
  data() {
    return {
      connectionForm: {
        ...
        rememberme: false
      },
...

My test file :

describe('Connection', () => {
  const wrapper = mount(Connection)

  it('checkbox click', () => {
    expect(wrapper.vm.connectionForm.rememberme).toBe(false)

    expect(wrapper.contains('el-checkbox')).toBe(true)
    const elCheckbox = wrapper.find('el-checkbox')

    elCheckbox.setChecked(true)
    expect(wrapper.vm.connectionForm.rememberme).toBe(true)
  })
})

 FAIL  frontend/components/user/sessions/New.test.js
  Connexion
    ✓ has a el-button (4ms)
    ✕ checkbox click (10ms)

  ● Connexion › checkbox click

    [vue-test-utils]: wrapper.setChecked() cannot be called on this element

      26 |
    > 27 |     elCheckbox.setChecked(true)
         |                ^
      28 |     expect(wrapper.vm.connexionForm.rememberme).toBe(true)
      29 |   })
      30 | })

doc checkbox

So, I changed the setChecked(true) with a .trigger('click'), still nothing. So, I changed 'click' to 'change', but still not working...

 FAIL  frontend/components/user/sessions/New.test.js
  Connexion
    ✓ has a el-button (4ms)
    ✕ checkbox click (10ms)
  ● Connexion › checkbox click

    expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false

      27 |     elCheckbox.trigger('change')
    > 28 |     expect(wrapper.vm.connectionForm.rememberme).toBe(true)
         |                                                  ^
      29 |   })
      30 | })
      31 |

If found somewhere this :

    elCheckbox.element.selected = true

But changes nothing.


问:
How to replace blank lines to word?
I have list

```<code>apple
oranges

banana
</code>```

How to replace blank lines to word "empty"?

```<code>apple
oranges
empty
banana
</code>```

答:
Ctrl+H

Find what: ^$

Replace with: empty

CHECK Wrap around

CHECK Regular expression

Replace all

Explanation:

```<code>^       # beginning of line
$       # end of line
</code>```

Screenshot (before):

Screenshot (after):

Title: How to replace blank lines to word?

Body:
I have list

apple
oranges

banana

How to replace blank lines to word "empty"?

apple
oranges
empty
banana

Body:
Ctrl+H

Find what: ^$

Replace with: empty

CHECK Wrap around

CHECK Regular expression

Replace all

Explanation:

^       # beginning of line
$       # end of line

Screenshot (before):

Screenshot (after):


答:
```<code>let { a: a1, b: b1 }  = myObject1;
let { a: a2, b: b2 } = myObject2;
</code>```

Will create variables a1, b1, a2, b2 from your 2 objects.

Title: ES6 destructuring not returning correct result

Body:
I an trying to destructure two object with the same property names but only the names of the first set are observed.

let a, b,
 ({ a,b } = myObject1);
({ a,b } = myObject2);

ie; only the values for myObject1 are in the console.log()

Does anyone know how to destructure properties of the same name from different objects ? I do not want to manually assign each variable.

I had tried

let a, b,
     ({ a,b } = myObject1);
    ({ a : test1,b: test2 } = myObject2)
console.log(test1)

and

  let a, b,
         { a,b } = myObject1;
         { a : test1,b: test2 } = myObject2
    console.log(test1)

But test1 is undefined

Body:
let { a: a1, b: b1 }  = myObject1;
let { a: a2, b: b2 } = myObject2;

Will create variables a1, b1, a2, b2 from your 2 objects.