问:
place picker closes immediately
my PlacePicker is closing when I open it, it stays open for about 3 seconds, I can see the location and I can move it, but it closes, I already tried everything already activated the api in google console, I changed the key, it does not give any error in logcat and neither in the RUN tab help me!

MY ANDROID MANIFEST

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyCD70mX9tljEfiDiLaCdHEUNMvq40AJDyI"/>
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity android:name=".activity.TelefoneActivity" />
        <activity android:name=".activity.CadastrarActivity" />
        <activity android:name=".activity.MainActivity" />
        <activity android:name=".activity.PassageiroActivity" />

        <uses-library android:name="org.apache.http.legacy" android:required="false"/>

        <meta-data
            android:name="com.facebook.sdk.App.Application"
            android:value="@string/facebook_app_id" />

        <meta-data
            tools:replace="android:value"
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>

        <activity
            android:name=".activity.SplashActivity"
            android:theme="@style/AppCompat.TelaCheia">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>```
</div>
</div>
</p>

<p><strong>ACTIVITY WHERE PLACE PICKER IS IMPLEMENTED</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import static android.Manifest.permission.ACCESS_FINE_LOCATION;

public class PassageiroActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    int PLACE_PICKER_REQUEST = 1;
    private String placeId;
    TextView btnChamarMoto;
    /**
     * Mapa da aplicação
     */
    private GoogleMap mMap;

    /**
     * Responsável por disponibilizar a localização do smartphone
     */
    private GoogleApiClient mGoogleApiClient;

    /**
     * Guarda a ultima posição do smartphone.
     */
    private Location mLastLocation;

    private TextInputEditText editMeuLocal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_passageiro);
      SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
      mapFragment.getMapAsync(this);
      iniciaComponentes();
      placesApi();
      btnChamarMoto = (TextView) findViewById(R.id.btnChamarMoto);

      if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
          .addConnectionCallbacks(this) // Interface ConnectionCallbacks
          .addOnConnectionFailedListener(this) //Interface OnConnectionFailedListener
          .addApi(LocationServices.API) // Vamos a API do LocationServices
          .build();
      }
    }

    public void placePiker(View view) {

      PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
      try {

        try {
          startActivityForResult(builder.build(PassageiroActivity.this), PLACE_PICKER_REQUEST);
        } catch (GooglePlayServicesNotAvailableException e) {
          e.printStackTrace();
        }

      } catch (GooglePlayServicesRepairableException e) {
        e.printStackTrace();
      }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

      if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == RESULT_OK) {

          Place place = (Place) PlacePicker.getPlace(PassageiroActivity.this, data);
          btnChamarMoto.setText(place.getAddress());

        }
      }

    }
    protected void onStart() {
      mGoogleApiClient.connect();
      super.onStart();
    }

    protected void onStop() {
      mGoogleApiClient.disconnect();
      super.onStop();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
      mMap = googleMap;
    }

    @Override
    public void onConnected(Bundle bundle) {

      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
      }
      mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
      if (mLastLocation != null) {
        if (mMap != null) {
          // Criamos o LatLng através do Location
          final LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
          // Adicionamos um Marker com a posição...
          mMap.addMarker(new MarkerOptions().position(latLng).title("Minha Posição"));
          // Um zoom no mapa para a seua posição atual...
          mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));

        }

      }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    //Place Api
    private void placesApi() {

      Places.initialize(getApplicationContext(), "AIzaSyDxFTRAaJ-FecUs8SZj6MBYwwzD447Nces");
      final PlacesClient placesClient = Places.createClient(this);
      AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
      getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
      autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
      autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
          //
          // Double latitude = place.getLatLng().latitude;
          Log.i("Places", "Place: " + place.getName() + ", " + place.getId());
          placeId = place.getId();

        }

        @Override
        public void onError(Status status) {
          // TODO: Handle the error.
          Log.i("errorOccurred", "An error occurred: " + status);
        }

      });

    }

    private void meuLocal(PlacesClient placesClient) {
      List < Place.Field > placeFields = Arrays.asList(Place.Field.NAME);

      FindCurrentPlaceRequest request =
        FindCurrentPlaceRequest.builder(placeFields).build();

      if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Task < FindCurrentPlaceResponse > placeResponse = placesClient.findCurrentPlace(request);
        placeResponse.addOnCompleteListener(task - > {
          if (task.isSuccessful()) {
            FindCurrentPlaceResponse response = task.getResult();
            for (PlaceLikelihood placeLikelihood: response.getPlaceLikelihoods()) {
              Log.i("likelihood", String.format("Place '%s' has likelihood: %f",
                placeLikelihood.getPlace().getName(),
                placeLikelihood.getLikelihood()));
              LatLng nome = placeLikelihood.getPlace().getLatLng();

              double latitude = nome.latitude;
              double longitude = nome.longitude;
              Toast.makeText(this, "latitude: " + latitude + "longitude: " + longitude, Toast.LENGTH_SHORT).show();
            }
          } else {
            Exception exception = task.getException();
            if (exception instanceof ApiException) {
              ApiException apiException = (ApiException) exception;
              Log.e("notFound", "Place not found: " + apiException.getStatusCode());
            }
          }
        });
      } else {

      }
    }

    private void verificaIdPlaces(PlacesClient placesClient) {

      List < Place.Field > placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME);

      FetchPlaceRequest request = FetchPlaceRequest.builder(placeId, placeFields).build();
      String nome = request.getPlaceId();

      placesClient.fetchPlace(request).addOnSuccessListener((response) - > {
        Place place = response.getPlace();
        Log.i("PlaceFOund", "Place found: " + place.getName() + "," + place.getLatLng());

      }).addOnFailureListener((exception) - > {
        if (exception instanceof ApiException) {
          ApiException apiException = (ApiException) exception;
          int statusCode = apiException.getStatusCode();
          // Handle error with given status code.
          Log.e("Place not found", "Place not found: " + exception.getMessage());
        }
      });
    }

    private void iniciaComponentes() {
      btnChamarMoto = findViewById(R.id.btnChamarMoto);

    }</code>```

答:
Please check your api key

Note there is two api key , one for the debug and the other for the release , so make you sure you are using the right one for the right version

Title: place picker closes immediately

Body:
my PlacePicker is closing when I open it, it stays open for about 3 seconds, I can see the location and I can move it, but it closes, I already tried everything already activated the api in google console, I changed the key, it does not give any error in logcat and neither in the RUN tab help me!

MY ANDROID MANIFEST

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyCD70mX9tljEfiDiLaCdHEUNMvq40AJDyI"/>
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity android:name=".activity.TelefoneActivity" />
        <activity android:name=".activity.CadastrarActivity" />
        <activity android:name=".activity.MainActivity" />
        <activity android:name=".activity.PassageiroActivity" />

        <uses-library android:name="org.apache.http.legacy" android:required="false"/>

        <meta-data
            android:name="com.facebook.sdk.App.Application"
            android:value="@string/facebook_app_id" />

        <meta-data
            tools:replace="android:value"
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>

        <activity
            android:name=".activity.SplashActivity"
            android:theme="@style/AppCompat.TelaCheia">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

ACTIVITY WHERE PLACE PICKER IS IMPLEMENTED

import static android.Manifest.permission.ACCESS_FINE_LOCATION;

public class PassageiroActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    int PLACE_PICKER_REQUEST = 1;
    private String placeId;
    TextView btnChamarMoto;
    /**
     * Mapa da aplicação
     */
    private GoogleMap mMap;

    /**
     * Responsável por disponibilizar a localização do smartphone
     */
    private GoogleApiClient mGoogleApiClient;

    /**
     * Guarda a ultima posição do smartphone.
     */
    private Location mLastLocation;

    private TextInputEditText editMeuLocal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_passageiro);
      SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
      mapFragment.getMapAsync(this);
      iniciaComponentes();
      placesApi();
      btnChamarMoto = (TextView) findViewById(R.id.btnChamarMoto);

      if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
          .addConnectionCallbacks(this) // Interface ConnectionCallbacks
          .addOnConnectionFailedListener(this) //Interface OnConnectionFailedListener
          .addApi(LocationServices.API) // Vamos a API do LocationServices
          .build();
      }
    }

    public void placePiker(View view) {

      PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
      try {

        try {
          startActivityForResult(builder.build(PassageiroActivity.this), PLACE_PICKER_REQUEST);
        } catch (GooglePlayServicesNotAvailableException e) {
          e.printStackTrace();
        }

      } catch (GooglePlayServicesRepairableException e) {
        e.printStackTrace();
      }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

      if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == RESULT_OK) {

          Place place = (Place) PlacePicker.getPlace(PassageiroActivity.this, data);
          btnChamarMoto.setText(place.getAddress());

        }
      }

    }
    protected void onStart() {
      mGoogleApiClient.connect();
      super.onStart();
    }

    protected void onStop() {
      mGoogleApiClient.disconnect();
      super.onStop();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
      mMap = googleMap;
    }

    @Override
    public void onConnected(Bundle bundle) {

      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
      }
      mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
      if (mLastLocation != null) {
        if (mMap != null) {
          // Criamos o LatLng através do Location
          final LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
          // Adicionamos um Marker com a posição...
          mMap.addMarker(new MarkerOptions().position(latLng).title("Minha Posição"));
          // Um zoom no mapa para a seua posição atual...
          mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));

        }

      }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    //Place Api
    private void placesApi() {

      Places.initialize(getApplicationContext(), "AIzaSyDxFTRAaJ-FecUs8SZj6MBYwwzD447Nces");
      final PlacesClient placesClient = Places.createClient(this);
      AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
      getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
      autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
      autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
          //
          // Double latitude = place.getLatLng().latitude;
          Log.i("Places", "Place: " + place.getName() + ", " + place.getId());
          placeId = place.getId();

        }

        @Override
        public void onError(Status status) {
          // TODO: Handle the error.
          Log.i("errorOccurred", "An error occurred: " + status);
        }

      });

    }

    private void meuLocal(PlacesClient placesClient) {
      List < Place.Field > placeFields = Arrays.asList(Place.Field.NAME);

      FindCurrentPlaceRequest request =
        FindCurrentPlaceRequest.builder(placeFields).build();

      if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Task < FindCurrentPlaceResponse > placeResponse = placesClient.findCurrentPlace(request);
        placeResponse.addOnCompleteListener(task - > {
          if (task.isSuccessful()) {
            FindCurrentPlaceResponse response = task.getResult();
            for (PlaceLikelihood placeLikelihood: response.getPlaceLikelihoods()) {
              Log.i("likelihood", String.format("Place '%s' has likelihood: %f",
                placeLikelihood.getPlace().getName(),
                placeLikelihood.getLikelihood()));
              LatLng nome = placeLikelihood.getPlace().getLatLng();

              double latitude = nome.latitude;
              double longitude = nome.longitude;
              Toast.makeText(this, "latitude: " + latitude + "longitude: " + longitude, Toast.LENGTH_SHORT).show();
            }
          } else {
            Exception exception = task.getException();
            if (exception instanceof ApiException) {
              ApiException apiException = (ApiException) exception;
              Log.e("notFound", "Place not found: " + apiException.getStatusCode());
            }
          }
        });
      } else {

      }
    }

    private void verificaIdPlaces(PlacesClient placesClient) {

      List < Place.Field > placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME);

      FetchPlaceRequest request = FetchPlaceRequest.builder(placeId, placeFields).build();
      String nome = request.getPlaceId();

      placesClient.fetchPlace(request).addOnSuccessListener((response) - > {
        Place place = response.getPlace();
        Log.i("PlaceFOund", "Place found: " + place.getName() + "," + place.getLatLng());

      }).addOnFailureListener((exception) - > {
        if (exception instanceof ApiException) {
          ApiException apiException = (ApiException) exception;
          int statusCode = apiException.getStatusCode();
          // Handle error with given status code.
          Log.e("Place not found", "Place not found: " + exception.getMessage());
        }
      });
    }

    private void iniciaComponentes() {
      btnChamarMoto = findViewById(R.id.btnChamarMoto);

    }


来源: stackexchange

问:
Does a mojo-pipeline automatically drop columns as specified during training?
I have ran a DAI experiment & built the mojo-pipeline. Now I have brand new data with columns I originally dropped within the DAI GUI; ID column for example. Does the mojo-pipeline automatically drop these columns when scored or do I need to do this prior?</p>

答: The mojo-pipeline will ignore all columns that weren't used for training - that includes columns that were dropped in DAI and any new columns they may have been introduced into the data.</p>

ContentLicense: CC BY-SA 4.0


问:
Accepting Splunk license agreement using Ansible-Playbook
I am new to using Ansible-Playbooks, and I am running into issues in accepting license agreements with Splunk.

Any time I have shell run:

```<code>"/opt/splunkforwarder/bin/splunk start --accept-license --answer-yes"
</code>```

I get a continuous lockup that forces me to terminate the program.

```<code>TASK [acceptlicense] ****************************************************************************************************************

^C
</code>```

Going into the box and running the command manually I am told the following:

```<code>[root@##########-lab_env]# /opt/splunkforwarder/bin/splunk start --accept-license --answer-yes

This appears to be your first time running this version of Splunk.

Create credentials for the administrator account.
Characters do not appear on the screen when you type the password.
Password must contain at least:
   * 8 total printable ASCII character(s).
Please enter a new password:
</code>```

I have gone through several forums online that give help in answering what to do when met with specific prompts like this, but anytime I make an adjustment I am told something along the lines of:

ERROR! '_______' is not a valid attribute for a Task

At this point I am pretty stuck and unsure of how to continue.

My code snippet is as follows:

```<code>- hosts: "{{hostName}}"
  become: true
  become_user: root
  become_method: sudo

  tasks:

    - name: copy_splunk
      shell: cp splunkforwarder-7.1.3-51d9cac7b837-linux-2.6-x86_64.rpm /opt/.; date; ls -l /opt
      args:
        chdir: /tmp
      register: run_ll

    - debug: var=run_ll.stdout_lines

    - name: install rpm package
      shell: rpm -ivh splunkforwarder-7.1.3-51d9cac7b837-linux-2.6-x86_64.rpm
      args:
        chdir: /tmp
      ignore_errors: True
      register: install_rpm

    - debug: var=install_rpm.stdout_lines

    - name: acceptlicense
      tags:
        - install
      shell: /opt/splunkforwarder/bin/splunk start --accept-license --answer-yes
      register: accept_l

    - debug: var=accept_l.stdout_lines
</code>```

I have only done a couple of playbooks in the past, so this error is something new to me.

Does anyone have any insight?

答: You should look at the expect module. It will allow you to execute commands and respond to their respective prompts.</p>

Body:
I am new to using Ansible-Playbooks, and I am running into issues in accepting license agreements with Splunk.

Any time I have shell run:

"/opt/splunkforwarder/bin/splunk start --accept-license --answer-yes"

I get a continuous lockup that forces me to terminate the program.

TASK [acceptlicense] ****************************************************************************************************************

^C

Going into the box and running the command manually I am told the following:

[root@##########-lab_env]# /opt/splunkforwarder/bin/splunk start --accept-license --answer-yes

This appears to be your first time running this version of Splunk.

Create credentials for the administrator account.
Characters do not appear on the screen when you type the password.
Password must contain at least:
   * 8 total printable ASCII character(s).
Please enter a new password:

I have gone through several forums online that give help in answering what to do when met with specific prompts like this, but anytime I make an adjustment I am told something along the lines of:

ERROR! '_______' is not a valid attribute for a Task

At this point I am pretty stuck and unsure of how to continue.

My code snippet is as follows:

- hosts: "{{hostName}}"
  become: true
  become_user: root
  become_method: sudo

  tasks:

    - name: copy_splunk
      shell: cp splunkforwarder-7.1.3-51d9cac7b837-linux-2.6-x86_64.rpm /opt/.; date; ls -l /opt
      args:
        chdir: /tmp
      register: run_ll

    - debug: var=run_ll.stdout_lines

    - name: install rpm package
      shell: rpm -ivh splunkforwarder-7.1.3-51d9cac7b837-linux-2.6-x86_64.rpm
      args:
        chdir: /tmp
      ignore_errors: True
      register: install_rpm

    - debug: var=install_rpm.stdout_lines

    - name: acceptlicense
      tags:
        - install
      shell: /opt/splunkforwarder/bin/splunk start --accept-license --answer-yes
      register: accept_l

    - debug: var=accept_l.stdout_lines

I have only done a couple of playbooks in the past, so this error is something new to me.

Does anyone have any insight?


问:
FadeOut one element and fadeIn another element on hover
I'm trying to achieve an effect where on the hover of an element A, an element B is fadeOut and an element C is fadeIn, both inside the element A.

That's what I tried:

$('.button').hover(function() {
 info = $(this).find('.info');
 download = $(this).find('.download');

 info.stop().fadeOut(150, function() {
  download.stop().fadeIn(150);
 })
}, function() {
 download.stop().fadeOut(150, function() {
  info.stop().fadeIn(150);
 })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  background-color: orange;
  padding: 10px;
  width: 250px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin-bottom: 10px;
}

.download {
  display: none;
  font-size: 17px;
}</code>```

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

```

Hovering one element at a time seems working fine but when you try to hover more elements concurrently the animation it starts to break.

Any solution? Other approaches are accepted. Thanks.

答:
The main problem is to stop the animation before assigning another. This way there are no glitches:

$('.button').each(function(i) {
    var thisButton = $(this);
    var thisInfo = thisButton.find('.info');
    var thisDownload = thisButton.find('.download');
    thisButton.on('mouseenter', function(e) {
        thisDownload.stop();
        thisInfo.stop().fadeOut(150, function() {
            thisDownload.stop().fadeIn(150);
        });
    }).on('mouseleave', function(e) {
        thisInfo.stop();
        thisDownload.stop().fadeOut(150, function() {
            thisInfo.stop().fadeIn(150);
        });
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  background-color: orange;
  padding: 10px;
  width: 250px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin-bottom: 10px;
}

.download {
  display: none;
  font-size: 17px;
}</code>```

             Mega Limited 1GB

Download

             Mega Limited 1GB

Download

             Mega Limited 1GB

Download

```

Also on JSFiddle

Posting this because this may happen to skyline's answer:

Body:
I'm trying to achieve an effect where on the hover of an element A, an element B is fadeOut and an element C is fadeIn, both inside the element A.

That's what I tried:

$('.button').hover(function() {
 info = $(this).find('.info');
 download = $(this).find('.download');

 info.stop().fadeOut(150, function() {
  download.stop().fadeIn(150);
 })
}, function() {
 download.stop().fadeOut(150, function() {
  info.stop().fadeIn(150);
 })
})

.button {
  background-color: orange;
  padding: 10px;
  width: 250px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin-bottom: 10px;
}

.download {
  display: none;
  font-size: 17px;
}

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

     Mega Limited 1GB

Download

Hovering one element at a time seems working fine but when you try to hover more elements concurrently the animation it starts to break.

Any solution? Other approaches are accepted. Thanks.

Body:
The main problem is to stop the animation before assigning another. This way there are no glitches:

$('.button').each(function(i) {
    var thisButton = $(this);
    var thisInfo = thisButton.find('.info');
    var thisDownload = thisButton.find('.download');
    thisButton.on('mouseenter', function(e) {
        thisDownload.stop();
        thisInfo.stop().fadeOut(150, function() {
            thisDownload.stop().fadeIn(150);
        });
    }).on('mouseleave', function(e) {
        thisInfo.stop();
        thisDownload.stop().fadeOut(150, function() {
            thisInfo.stop().fadeIn(150);
        });
    });
});

.button {
  background-color: orange;
  padding: 10px;
  width: 250px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin-bottom: 10px;
}

.download {
  display: none;
  font-size: 17px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button">
    <div class="button_inner">
        <div class="info">
            <i class="fas fa-download"></i> <strong>Mega Limited</strong> 1GB
        </div>
        <div class="download">Download</div>
    </div>
</div>

<div class="button">
    <div class="button_inner">
        <div class="info">
            <i class="fas fa-download"></i> <strong>Mega Limited</strong> 1GB
        </div>
        <div class="download">Download</div>
    </div>
</div>

<div class="button">
    <div class="button_inner">
        <div class="info">
            <i class="fas fa-download"></i> <strong>Mega Limited</strong> 1GB
        </div>
        <div class="download">Download</div>
    </div>
</div>

Also on JSFiddle

Posting this because this may happen to skyline's answer:


问:
How can I simulate SerialPort interactions for testing?
I'm about to start developing a small app (C#) that communicates with a PLC and a testing unit via Serial Ports - this is my first venture into this area.

In essence, I am going to send the PLC a signal to start an operation, and then I am going to wait for the result of that operation from the test unit (which will be independently communicating with the PLC) to return a ASCII string.

Depending on the content of that string, I may want to listen to a signal from the PLC...

It's all new to me, so at the moment, I'm just researching System.IO.Ports.SerialPort; digression: are there third part products out there than simplify interaction with the Serial Port, or are the built-in classes as good as you will get? I'm thinking of ease of use as opposed to better features.

However, it will be a few weeks before the hardware is available for development and testing, so I was wondering how I could simulate communication to/from the serial port so that I can start developing my app?

[I don't yet know how the PLC and the PC are due to communicate - I understand it will be binary rather than text, but at the moment, that is all I know.]

答:
I like David's answer above but if your looking to do integration tests and actually test your serial port communication I have used and application called ViN soft virtual serial cable in the past to basically create 2 serial ports on your machine that are connected by a virtual cable.

Also if you have a serial port on your development machine you could use it to connect to another machine that has a serial port and write an application that will basically simulate the communication of the PLC.

I would prefer to use a combination of both David's method and this method to ensure proper testing.

ContentLicense: CC BY-SA 3.0


问:
Comparing position with Prev/next position in array
PROBLEM SOLVED! Thanks

This is my first question in this forum. I did not get what's the problem here.

JAVA8: I am trying to compare if the object in position X in an array of a string is the same than other in position x-1 or x+1 (at least one).
This condition has to be solved for all the positions in the array. For example, We are given AABCBC as an input, it has to be false because BCB is not satisfying our conditions, but as output, it shows ok.

```<code>//b is String[] of chars --> F.E.:["B","B","A","B"]
int len= b.length;
boolean l_r=true;
        for(int i=0;i<len;i++){
            boolean left=false;
            boolean right=false;

            if(i+1<len ){ if (b[i].equals(b[i+1])){ right=true;}}
            if(i-1>-1 ){ if (b[i].equals(b[i-1])){ left=true;}}

            if(left==false && right==false){l_r=false; break;}
        }
         if(l_r==true){rta="YES";}
         if(l_r==false){rta="NO";}
</code>```

答:
I am assuming your question is: Object at position X in an array of strings should at least match the object in either position (X-1) or position (X+1) i.e previous or next positions. It returns true if all the positions in the array satisfy this condition otherwise returns false.

```<code>int len = b.length;
boolean l_r=true;
        for(int i=0;i<len;i++)
        {
            boolean left=false;
            boolean right=false;

            if(i+1<len ){if(b[i].equals(b[i+1])){ right=true;}}
            if(i-1>-1 ){if(b[i].equals(b[i-1])){ left=true;}}

            if(left==false && right==false){l_r=false; break;}
        }
        if(l_r==true)
            System.out.println("YES");
        if(l_r==false)
            System.out.println("NO");
</code>```

Just cleaned up your code a bit, everything else(including logic) remains the same. This code returns the right answer.

Body:
PROBLEM SOLVED! Thanks

This is my first question in this forum. I did not get what's the problem here.

JAVA8: I am trying to compare if the object in position X in an array of a string is the same than other in position x-1 or x+1 (at least one).
This condition has to be solved for all the positions in the array. For example, We are given AABCBC as an input, it has to be false because BCB is not satisfying our conditions, but as output, it shows ok.

//b is String[] of chars --> F.E.:["B","B","A","B"]
int len= b.length;
boolean l_r=true;
        for(int i=0;i<len;i++){
            boolean left=false;
            boolean right=false;

            if(i+1<len ){ if (b[i].equals(b[i+1])){ right=true;}}
            if(i-1>-1 ){ if (b[i].equals(b[i-1])){ left=true;}}

            if(left==false && right==false){l_r=false; break;}
        }
         if(l_r==true){rta="YES";}
         if(l_r==false){rta="NO";}

Body:
I am assuming your question is: Object at position X in an array of strings should at least match the object in either position (X-1) or position (X+1) i.e previous or next positions. It returns true if all the positions in the array satisfy this condition otherwise returns false.

int len = b.length;
boolean l_r=true;
        for(int i=0;i<len;i++)
        {
            boolean left=false;
            boolean right=false;

            if(i+1<len ){if(b[i].equals(b[i+1])){ right=true;}}
            if(i-1>-1 ){if(b[i].equals(b[i-1])){ left=true;}}

            if(left==false && right==false){l_r=false; break;}
        }
        if(l_r==true)
            System.out.println("YES");
        if(l_r==false)
            System.out.println("NO");

Just cleaned up your code a bit, everything else(including logic) remains the same. This code returns the right answer.


问:
text-align right in flexbox
I have a flexbox, and elements in it are "p" elements.

I'm trying to align it right, but it's still not working and everything is still aligned center.

.box1{
    display: flex;
    flex-direction: column;
    text-align: right;
    justify-content: space-between;
    font-family: 'Merriweather', sans-serif;
    font-size: 60px;
    width: 30%;
}
```

Is it possible to align it right?

答:
align-items: flex-end; will align the
 elements to the right side of the container, but only if the container's width is greater than the children's width.

div {
  width: 200px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  box-sizing: border-box;
  border: solid red 3px;
}

p {
  width: 100px;
  text-align: right; // you might also want to use this so that your text is aligned to the far right side.
  box-sizing: border-box;
  border: solid lime 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>Testing 1...</p>
  <p>Testing 2...</p>
  <p>Testing 3...</p>
  <p>Testing 4...</p>
</div></code>```

Flex boxes can be a bit tricky since the justify-content property always aligns content in the same direction of the flex box (i.e. vertically for columns and horizontally for rows), whereas align-items always aligns content in the cross direction (i.e. horizontally for columns and vertically for rows). For example...

```<code>display: flex;
flex-direction: column;
justify-content:; /* aligns content vertically */
align-items:; /* aligns content horizontally */

display: flex;
/* flex-direction: row; is the default value */
justify-content:; /* aligns content horizontally */
align-items:; /* aligns content vertically */
</code>```

Title: text-align right in flexbox

Body:
I have a flexbox, and elements in it are "p" elements.

I'm trying to align it right, but it's still not working and everything is still aligned center.

.box1{
    display: flex;
    flex-direction: column;
    text-align: right;
    justify-content: space-between;
    font-family: 'Merriweather', sans-serif;
    font-size: 60px;
    width: 30%;
}

Is it possible to align it right?

Body:
align-items: flex-end; will align the <p> elements to the right side of the container, but only if the container's width is greater than the children's width.

div {
  width: 200px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  box-sizing: border-box;
  border: solid red 3px;
}

p {
  width: 100px;
  text-align: right; // you might also want to use this so that your text is aligned to the far right side.
  box-sizing: border-box;
  border: solid lime 3px;
}

<div>
  <p>Testing 1...</p>
  <p>Testing 2...</p>
  <p>Testing 3...</p>
  <p>Testing 4...</p>
</div>

Flex boxes can be a bit tricky since the justify-content property always aligns content in the same direction of the flex box (i.e. vertically for columns and horizontally for rows), whereas align-items always aligns content in the cross direction (i.e. horizontally for columns and vertically for rows). For example...

display: flex;
flex-direction: column;
justify-content:; /* aligns content vertically */
align-items:; /* aligns content horizontally */

display: flex;
/* flex-direction: row; is the default value */
justify-content:; /* aligns content horizontally */
align-items:; /* aligns content vertically */


问:
Accessing people search API under "LinkedIn Marketing Developer Program"
Really sorry for posting this question here (since due to some reason I am unable to post this on LinkedIn forums). I need to work on a project wherein I can increase the number of prospective customers for a company. We want to leverage LinkedIn's database for the same. I went through articles and the program that I got interested in was "LinkedIn Marketing Developer Program" and we will be looking forward to using it to create ads for specific audiences. But I am not able to see if I will have access to people search since this post says that I will have access to it but I cannot find confirmation on LinkedIn access documentation here. I have two queries: Is it possible to access people search API wherein we can get individuals in a particular demographic region under the "LinkedIn Marketing Developer Program"? If not this program, in general, can we get paid access to the people search API?

PS: Please do not mark this question as irrelevant as asking question on LinkedIn forum is disabled (cannot click submit button on the given link even after adding all the details to the form).

答: People Search is not offered by any of LinkedIn's Partner Programs.</p>


问:
Parsing JSON response into a struct
I'm using Alamofire and getting back the data from the API in JSON.
i want to use the data into a struct.
the response is the following:

```<code>{
  "status" : 1,
  "data" : [
{
  "classes" : [

  ],
  "day" : "Wednesday"
},
{
  "classes" : [
    {
      "time" : "1:30 PM",
      "available_spots" : 2,
      "trainer" : "Ahmed Jasim",
      "thumbnail" : "\/uploads\/classes\/6\/files\/class_6_15555066955cb72607131886.71740331.jpg",
      "id" : 6,
      "name" : "Gym Class C"
    }
  ],
  "day" : "Thursday"
},
{
  "classes" : [

  ],
  "day" : "Friday"
},
{
  "classes" : [

  ],
  "day" : "Saturday"
},
{
  "classes" : [
    {
      "available_spots" : 2,
      "id" : 1,
      "trainer" : "Ahmed Jasim",
      "name" : "Karate",
      "thumbnail" : "\/uploads\/classes\/1\/files\/class_1_15548800215cad9615e62404.41767774.jpg",
      "time" : "5:00 PM"
    }
  ],
  "day" : "Sunday"
},
{
  "classes" : [
    {
      "thumbnail" : "\/uploads\/classes\/1\/files\/class_1_15548800215cad9615e62404.41767774.jpg",
      "available_spots" : 2,
      "time" : "11:00 AM",
      "name" : "Karate",
      "id" : 1,
      "trainer" : "Ahmed Jasim"
    },
    {
      "trainer" : "Jalal Hassan",
      "available_spots" : 20,
      "thumbnail" : "\/uploads\/classes\/2\/files\/class_2_15548819805cad9dbc7b9a80.11639647.jpg",
      "time" : "4:00 PM",
      "name" : "Gym Class B",
      "id" : 2
    }
  ],
  "day" : "Monday"
},
{
  "classes" : [
    {
      "name" : "Gym Class B",
      "trainer" : "Jalal Hassan",
      "time" : "9:00 AM",
      "available_spots" : 20,
      "id" : 2,
      "thumbnail" : "\/uploads\/classes\/2\/files\/class_2_15548819805cad9dbc7b9a80.11639647.jpg"
    }
  ],
  "day" : "Tuesday"
}
 ],
 "message" : "Retrieved successfully",
 "success" : true
}
</code>```

I want to get the ' day & classes ' and use them in a struct.
the struct i'm using is as the following.

```<code>struct section {
day: String!
classes: [String]!
}
</code>```

so i want to get the day and it's classes and store them.
the call for the struct:

```<code> var sections = [Section(day: "Monday", classes: ["A","B","C"]]
</code>```

what i want to achieve is get all the days and it's classes & if the day has no classes it'll just be an empty array.

but i'm not sure if this is possible or not.

this is the code inside Alamofire request:

```<code>     let classesJSON: JSON = JSON(response.result.value!)

                if response.data != nil {

                    for index in 0..<classesJSON["data"].count {

                        var sections = Section(day: classesJSON["data"][index]["day"].stringValue, classes: [])
                        for data in classesJSON["data"].arrayValue {

                            for value in data["classes"].arrayValue {
                                sections.classes.append(value["name"].stringValue)
                               //sections.classes[index] = value["name"].stringValue
                            }
                        }
                        print(sections)
                    }

                }
</code>```

my problem is i'm getting all the classes in the response, what i want is to get the specific class for the day.

```<code>Section(day: Optional("Sunday"), classes: Optional(["Gym Class C", "Karate", "Karate", "Gym Class B", "Gym Class B"])

Section(day: Optional("Monday"), classes: Optional(["Gym Class C", "Karate", "Karate", "Gym Class B", "Gym Class B"])
</code>```

^ this is what i'm getting, but i want to seperate them so i can get the day and it's classes, not all of them

答:
You can slightly change your loop

```<code>for index in 0..<classesJSON["data"].count {
    var classes: [String] = []
    for item in classesJSON["data"][index]["classes"].arrayValue {
          classes.append(item["name"].stringValue)
    }
    let sections = Section(day: classesJSON["data"][index]["day"].stringValue, classes: classes)
    print(sections)
 }
</code>```

And make sure you change let to var for both day and classes in your struct

```<code>struct Section {
    var day: String
    var classes: [String]
}
</code>```

Title: Parsing JSON response into a struct

Body:
I'm using Alamofire and getting back the data from the API in JSON.
i want to use the data into a struct.
the response is the following:

{
  "status" : 1,
  "data" : [
{
  "classes" : [

  ],
  "day" : "Wednesday"
},
{
  "classes" : [
    {
      "time" : "1:30 PM",
      "available_spots" : 2,
      "trainer" : "Ahmed Jasim",
      "thumbnail" : "\/uploads\/classes\/6\/files\/class_6_15555066955cb72607131886.71740331.jpg",
      "id" : 6,
      "name" : "Gym Class C"
    }
  ],
  "day" : "Thursday"
},
{
  "classes" : [

  ],
  "day" : "Friday"
},
{
  "classes" : [

  ],
  "day" : "Saturday"
},
{
  "classes" : [
    {
      "available_spots" : 2,
      "id" : 1,
      "trainer" : "Ahmed Jasim",
      "name" : "Karate",
      "thumbnail" : "\/uploads\/classes\/1\/files\/class_1_15548800215cad9615e62404.41767774.jpg",
      "time" : "5:00 PM"
    }
  ],
  "day" : "Sunday"
},
{
  "classes" : [
    {
      "thumbnail" : "\/uploads\/classes\/1\/files\/class_1_15548800215cad9615e62404.41767774.jpg",
      "available_spots" : 2,
      "time" : "11:00 AM",
      "name" : "Karate",
      "id" : 1,
      "trainer" : "Ahmed Jasim"
    },
    {
      "trainer" : "Jalal Hassan",
      "available_spots" : 20,
      "thumbnail" : "\/uploads\/classes\/2\/files\/class_2_15548819805cad9dbc7b9a80.11639647.jpg",
      "time" : "4:00 PM",
      "name" : "Gym Class B",
      "id" : 2
    }
  ],
  "day" : "Monday"
},
{
  "classes" : [
    {
      "name" : "Gym Class B",
      "trainer" : "Jalal Hassan",
      "time" : "9:00 AM",
      "available_spots" : 20,
      "id" : 2,
      "thumbnail" : "\/uploads\/classes\/2\/files\/class_2_15548819805cad9dbc7b9a80.11639647.jpg"
    }
  ],
  "day" : "Tuesday"
}
 ],
 "message" : "Retrieved successfully",
 "success" : true
}

I want to get the ' day & classes ' and use them in a struct.
the struct i'm using is as the following.

struct section {
day: String!
classes: [String]!
}

so i want to get the day and it's classes and store them.
the call for the struct:

 var sections = [Section(day: "Monday", classes: ["A","B","C"]]

what i want to achieve is get all the days and it's classes & if the day has no classes it'll just be an empty array.

but i'm not sure if this is possible or not.

this is the code inside Alamofire request:

     let classesJSON: JSON = JSON(response.result.value!)

                if response.data != nil {

                    for index in 0..<classesJSON["data"].count {

                        var sections = Section(day: classesJSON["data"][index]["day"].stringValue, classes: [])
                        for data in classesJSON["data"].arrayValue {

                            for value in data["classes"].arrayValue {
                                sections.classes.append(value["name"].stringValue)
                               //sections.classes[index] = value["name"].stringValue
                            }
                        }
                        print(sections)
                    }

                }

my problem is i'm getting all the classes in the response, what i want is to get the specific class for the day.

Section(day: Optional("Sunday"), classes: Optional(["Gym Class C", "Karate", "Karate", "Gym Class B", "Gym Class B"])

Section(day: Optional("Monday"), classes: Optional(["Gym Class C", "Karate", "Karate", "Gym Class B", "Gym Class B"])

^ this is what i'm getting, but i want to seperate them so i can get the day and it's classes, not all of them

Body:
You can slightly change your loop

for index in 0..<classesJSON["data"].count {
    var classes: [String] = []
    for item in classesJSON["data"][index]["classes"].arrayValue {
          classes.append(item["name"].stringValue)
    }
    let sections = Section(day: classesJSON["data"][index]["day"].stringValue, classes: classes)
    print(sections)
 }

And make sure you change let to var for both day and classes in your struct

struct Section {
    var day: String
    var classes: [String]
}


问:
Add CLI-commands to a Cocoa app?
I am looking for a way to send commands (with arguments) from a command line tool to a running Cocoa app. Is this possible?

If my the Cocoa app is open and running I would like it to receive basic events from the terminal. How can I communicate between a CLI-target and Cocoa-target?

The only way this I have found is to use the AppleScript and add scriptability to the app. Is this the only way to go?

答:
I recently created a command-line app for a Swift app that I've distributed on the Mac App Store. I was able to do this by:

Making the App scriptable (see Implementing a Scriptable Application)

Generating a library to script the app (see Using Scripting Bridge)

Creating a separate CLI target using the library embedded from step 2

I've happend to make the code open source (aside from the app which was made scriptable). The scripted library is called EmporterKit, which also includes a Makefile to generate the scripted headers, and the CLI is called emporter-cli, which was built with a library called YDCommandKit, which makes writing CLI apps way easier.

This topic is extremely broad and the options are limited while keeping in step with modern security practices on macOS. Honestly, you should just stick to using URL schemes if possible, but if you want a full-featured command-line app, this is probably the only way to go.

Title: Add CLI-commands to a Cocoa app?


答:
Apply the text-align to the paragraphs:</p>

```<code>.box1 p {
  text-align: right;
}
</code>```

Title: text-align right in flexbox

Body:
Apply the text-align to the paragraphs:

.box1 p {
  text-align: right;
}


问:
Bit Difference between 2 binary numbers in MIPS Assembly
So I have to create an MIPS assembly program that reads 2 numbers out of 2 registers ($s0 & $s1) and calculates the number of bits that these 2 numbers differ by. And stores the result in the $s2 register.
I also have to fulfill all the above with the least amount of commands possible.
I have tried a few things on paper with XOR operations but I can't quite figure how to calculate the amount of different bits.

If anyone can help, you're more than welcome to.
Thanks in advance

Body:
Example in C using loopless pop count code:

    int x, y, z;
    // ...
    z = x^y;   // x and y are inputs
    z -= (z >> 1) & 0x55555555;                      // 16   2 bit counts
    z = (z & 0x33333333) + ((z >> 2) & 0x33333333);  //  8   4 bit counts
    z = (z + (z >> 4)) & 0x0f0f0f0f;                 //  4   8 bit counts
    z = (z * 0x01010101) >> 24;                      //  1  32 bit count


问:
How to use XCode's mergetool to resolve conflicts?
I'm in the middle of a rebase and I need to fix some merge conflicts. When I open the file in XCode, I see the source control conflict markers (<<<<<<<, etc) in the file.

How can I use XCode's mergetool to resolve these conflicts in a graphical fashion? I'm looking for this screen:

答:
Pulling the answer from here

```<code># Tell system where Xcode utilities live:
sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer

# Set "opendiff" as the default mergetool globally:
git config --global merge.tool opendiff
</code>```

Then, when git tells you that there is a conflict, you can run git mergetool and it will open XCode's mergetool (like in the question's screenshot) and you can work through the conflict.

Body:
Pulling the answer from here

# Tell system where Xcode utilities live:
sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer

# Set "opendiff" as the default mergetool globally:
git config --global merge.tool opendiff

Then, when git tells you that there is a conflict, you can run git mergetool and it will open XCode's mergetool (like in the question's screenshot) and you can work through the conflict.


问:
Why does hibernate show the commit log before the inserts and updates?
Hibernate logs show this:

```<code>[debug] o.h.e.t.i.TransactionImpl - begin
do stuff...
[debug] o.h.e.t.i.TransactionImpl - committing
do more stuff... inserts, updates etc...
[debug] o.h.e.j.i.JdbcCoordinatorImpl - HHH000420: Closing un-released batch
</code>```

When it's "supposed" to do this

```<code>[debug] o.h.e.t.i.TransactionImpl - begin
do stuff...
do more stuff... inserts, updates etc...
[debug] o.h.e.t.i.TransactionImpl - committing

</code>```

I wrapped the entire thing in a transaction, so I don't imagine it's a problem with my code. Am I missing something?

答: Hibernate have 3 states: Transient , Persistent and Detached. I think it will show commit when change from transient state to persistent state. However, it is not means the transaction really commited. Just means object has been controlled by Hibernate and ready to commit to database some time(depends on Hibernate internal mechanism).  Please correct me if I am wrong.

Body:
Hibernate logs show this:

[debug] o.h.e.t.i.TransactionImpl - begin
do stuff...
[debug] o.h.e.t.i.TransactionImpl - committing
do more stuff... inserts, updates etc...
[debug] o.h.e.j.i.JdbcCoordinatorImpl - HHH000420: Closing un-released batch

When it's "supposed" to do this

[debug] o.h.e.t.i.TransactionImpl - begin
do stuff...
do more stuff... inserts, updates etc...
[debug] o.h.e.t.i.TransactionImpl - committing

I wrapped the entire thing in a transaction, so I don't imagine it's a problem with my code. Am I missing something?


问:
Problem with jquery button click
I am facing a problem in the jquery click event.

My web page involves creating a button through javascript and assigning a class to the button ( call it A ). Now I want to detect the click of that button and I have written the following code for it :

```
 $(".A").click( function () {

    // do something

 });
```

To my surprise, this click event never gets called.

But when I make the button statically on the webpage ( during design time ), the same code works.

Is there a different approach to bind a button click with jquery in case a button is created dynamically?

答:
You need to use $.live</p>

```<code>$(".A").live('click', function () {

   // do something

});
</code>```

Title: Problem with jquery button click

Body:
I am facing a problem in the jquery click event.

My web page involves creating a button through javascript and assigning a class to the button ( call it A ). Now I want to detect the click of that button and I have written the following code for it :

 $(".A").click( function () {

    // do something

 });

To my surprise, this click event never gets called.

But when I make the button statically on the webpage ( during design time ), the same code works.

Is there a different approach to bind a button click with jquery in case a button is created dynamically?

Body:
You need to use $.live

$(".A").live('click', function () {

   // do something

});


问:
How to set String value of xAxis in MPAndroidChart?
I want to make Line Chart Graph, but i have problem to show value string in xAxis, im used Library Github from MPAndroidChart to LineChart. Please help me how to add String Value and actually to much question i want ask

```<code>private void drawLineChartLine(){

        private float[] yDataL = {40, 60, 70, 80};
        private String[] xDataL = {"Week 1", "Week 1" , "Week 3" , "Week 4"};

        ArrayList<Entry> yEntrys = new ArrayList<>();

        final ArrayList<String> xEntrys = new ArrayList<>();

        for(int i = 0; i < yDataL.length; i++){
            yEntrys.add(new Entry(yDataL[i] ,i));
        }

        for(int i = 1; i < xDataL.length; i++){
            xEntrys.add(xDataL[i]);
        }

        //create the data set
        LineDataSet lineDataset = new LineDataSet(yEntrys, "assa");

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);

        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xEntrys.get((int) value);
            }
        });

        LineData lineData = new LineData(lineDataset);
        lineChart.setData(lineData);
        lineChart.invalidate();
}
</code>```

i got error

Invalid index 40, size is 6

in Code

```<code>xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xEntrys.get((int) value);
            }
        });
</code>```

答:
The methods mentioned aboves seems to be deprecated.</p>

```<code> xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
               // return the string va
                return  your_string_basedon_value_as_index;
            }
        });
</code>```

Body:
I want to make Line Chart Graph, but i have problem to show value string in xAxis, im used Library Github from MPAndroidChart to LineChart. Please help me how to add String Value and actually to much question i want ask

private void drawLineChartLine(){

        private float[] yDataL = {40, 60, 70, 80};
        private String[] xDataL = {"Week 1", "Week 1" , "Week 3" , "Week 4"};

        ArrayList<Entry> yEntrys = new ArrayList<>();

        final ArrayList<String> xEntrys = new ArrayList<>();

        for(int i = 0; i < yDataL.length; i++){
            yEntrys.add(new Entry(yDataL[i] ,i));
        }

        for(int i = 1; i < xDataL.length; i++){
            xEntrys.add(xDataL[i]);
        }

        //create the data set
        LineDataSet lineDataset = new LineDataSet(yEntrys, "assa");

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);

        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xEntrys.get((int) value);
            }
        });

        LineData lineData = new LineData(lineDataset);
        lineChart.setData(lineData);
        lineChart.invalidate();
}

i got error

Invalid index 40, size is 6

in Code

xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xEntrys.get((int) value);
            }
        });

Body:
The methods mentioned aboves seems to be deprecated.

 xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
               // return the string va
                return  your_string_basedon_value_as_index;
            }
        });


问:
Set an attribute of a property element
I have a image that I want to have a larger preview using a tooltip.

```<code><Image MaxWidth="585" Margin="2" Source="{Binding Preview, IsAsync=true}">
    <Image.ToolTip MaxWidth="800"> <!-- Error: Attribute "MaxWidth" is not allowed in property element -->
        <Image Source="{Binding Preview, IsAsync=true}" />
    </Image.ToolTip>
</Image>
</code>```

How do I change the MaxWidth property of the ToolTip? Second question: How can I use the parent Source value within the child binding?

答:
The issue is the ToolTip property is of type object, so it does not have a MaxWidth property. Because the ToolTip can accept an arbitrary object, to set the MaxWidth you should put a ToolTip (or another WPF element) inside of the ToolTip property and set the MaxWidth on that.

Something like:

```<code><Image MaxWidth="585" Margin="2" Source="{Binding Preview, IsAsync=true}">
    <Image.ToolTip>
        <ToolTip MaxWidth="1000" MaxHeight="600">
            <Image Source="{Binding Preview, IsAsync=true}" />
        </ToolTip>
    </Image.ToolTip>
</Image>
</code>```

Title: Set an attribute of a property element

Body:
I have a image that I want to have a larger preview using a tooltip.

<Image MaxWidth="585" Margin="2" Source="{Binding Preview, IsAsync=true}">
    <Image.ToolTip MaxWidth="800">
        <Image Source="{Binding Preview, IsAsync=true}" />
    </Image.ToolTip>
</Image>

How do I change the MaxWidth property of the ToolTip? Second question: How can I use the parent Source value within the child binding?

Body:
The issue is the ToolTip property is of type object, so it does not have a MaxWidth property. Because the ToolTip can accept an arbitrary object, to set the MaxWidth you should put a ToolTip (or another WPF element) inside of the ToolTip property and set the MaxWidth on that.

Something like:

<Image MaxWidth="585" Margin="2" Source="{Binding Preview, IsAsync=true}">
    <Image.ToolTip>
        <ToolTip MaxWidth="1000" MaxHeight="600">
            <Image Source="{Binding Preview, IsAsync=true}" />
        </ToolTip>
    </Image.ToolTip>
</Image>


问:
How to select a value from a DataFrame (even if there is no entry)
I'm trying to select an entry from a DataFrame structure based on some conditions. It works - as long as there is an entry that fits to the query (first example in code shown below)

But sometimes, there is no proper entry, so the return value should be an empty string (not an error message). This I cannot achieve.

```<code>from pandas import DataFrame

data = {'ID': [1, 1, 2, 2],
        'Key': ['Key1','Key2','Key1','Key2'],
        'Value': ['Value1', 'Value2', 'Value3', 'Value4']
        }

df = DataFrame(data,columns= ['ID', 'Key','Value'])

print(df.loc[(df['ID']==1) & (df['Key'] == 'Key2')].iloc[-1,-1])
# shows "Value2" (correct)

print(df.loc[(df['ID']==1) & (df['Key'] == 'Key3')].iloc[-1,-1])
# should show "" (desired output)
</code>```

Thanks in advance.

答:
Trying this a bit more explicitly using a mask that you can inspect.</p>

```<code>mask = (df['ID']==1) & (df['Key'] == 'Key3')
if mask.any():
    print(df[mask].Value.iloc[0])
else:
    print("")
</code>```

Body:
I'm trying to select an entry from a DataFrame structure based on some conditions. It works - as long as there is an entry that fits to the query (first example in code shown below)

But sometimes, there is no proper entry, so the return value should be an empty string (not an error message). This I cannot achieve.

from pandas import DataFrame

data = {'ID': [1, 1, 2, 2],
        'Key': ['Key1','Key2','Key1','Key2'],
        'Value': ['Value1', 'Value2', 'Value3', 'Value4']
        }

df = DataFrame(data,columns= ['ID', 'Key','Value'])

print(df.loc[(df['ID']==1) & (df['Key'] == 'Key2')].iloc[-1,-1])
# shows "Value2" (correct)

print(df.loc[(df['ID']==1) & (df['Key'] == 'Key3')].iloc[-1,-1])
# should show "" (desired output)

Thanks in advance.

Body:
Trying this a bit more explicitly using a mask that you can inspect.

mask = (df['ID']==1) & (df['Key'] == 'Key3')
if mask.any():
    print(df[mask].Value.iloc[0])
else:
    print("")


问:
Use PHP to get xls(Excel files) PHPOffice PHPExcel
Hy guys.

Thank you for your help. The answers in this forum are great!

In my site, i want to see the content from a xls Excel Spreadsheet.
After long searching i found this Project:
https://github.com/PHPOffice/PHPExcel/

I get the classes and tried it. Works great!

It works so good, that i can't believe, that it is free.
Is it free to use?

at the top of my site, i got this error massage:
Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in test/Classes/PHPExcel/Shared/OLE.php on line 288

答:
It looks that you are using old PHP version. Try updating it to 7.3+

And go look here - https://wordpress.org/support/topic/warning-continue-targeting-switch-is-equivalent-to-break/

They have the same problem as you.

Alsoo, on github there is information that repo is deprecated.
Maybe use this ? - https://github.com/PHPOffice/PhpSpreadsheet


问:
How does std::forward deduce the type of `_Ty`?
I'm learning about templates and particularly std::forward; when I check its implementation it uses another class template std::remove_reference in its arguments list:

template<class _Ty>
_Ty&& forward(typename remove_reference<_Ty>::type& _Arg)
{// forward an lvalue as either an lvalue or an rvalue
   // ...
}
```

btw: I've removed a few things like inline, constexpr, NO_EXCEPT and the body of the function for clarity

I read about how types are deduced when the template parameter is a pointer(_Ty*), reference(_Ty&), universal reference(_Ty) and where its just the type itself (_Ty). In this case it is a reference but it has that added removed_reference<_Ty>::type preceding it; the _Ty and the reference are split by the call to remove_reference. How does the compiler figure out the type of _Ty?

The function template has to figure out the template parameters using the arguments passed in to the function(when not explicitly defining them in the function call) but in this case remove_reference is also a class template that needs to figure out the type of _Ty as well. It seems almost like a catch 22 for me because std::forward needs to figure out _Ty using its function argument but its function argument which is std::remove_reference<_Ty> needs to already know what _Ty is. All This tells me is that I have a flawed understanding of how templates work but I don't know where.

答:
how does the compiler figure out the type of _Ty?

It doesn't. std::forward is meant to be used with the type provided explicitly. And it's enforced by accepting the function argument to std::forward with the type typename remove_reference<_Ty>::type, where _Ty is in a non-deduced context. The compiler can't deduce it.

A typical use with a forwarding reference is as follows:

```<code>template<typename T>
void foo(T&& t) {
    std::forward<T>(t);
}
</code>```

Strictly speaking, std::forward is just syntactic sugar for a cast to T&& above. It's reference collapsing the does all the magic, but a bare cast to T&& does not convey the intent to forward quite as clearly as a named operator. That is why std::forward exists.

Body:
I'm learning about templates and particularly std::forward; when I check its implementation it uses another class template std::remove_reference in its arguments list:

template<class _Ty>
_Ty&& forward(typename remove_reference<_Ty>::type& _Arg)
{// forward an lvalue as either an lvalue or an rvalue
   // ...
}

btw: I've removed a few things like inline, constexpr, NO_EXCEPT and the body of the function for clarity

I read about how types are deduced when the template parameter is a pointer(_Ty*), reference(_Ty&), universal reference(_Ty) and where its just the type itself (_Ty). In this case it is a reference but it has that added removed_reference<_Ty>::type preceding it; the _Ty and the reference are split by the call to remove_reference. How does the compiler figure out the type of _Ty?

The function template has to figure out the template parameters using the arguments passed in to the function(when not explicitly defining them in the function call) but in this case remove_reference is also a class template that needs to figure out the type of _Ty as well. It seems almost like a catch 22 for me because std::forward needs to figure out _Ty using its function argument but its function argument which is std::remove_reference<_Ty> needs to already know what _Ty is. All This tells me is that I have a flawed understanding of how templates work but I don't know where.

Body:
how does the compiler figure out the type of _Ty?

It doesn't. std::forward is meant to be used with the type provided explicitly. And it's enforced by accepting the function argument to std::forward with the type typename remove_reference<_Ty>::type, where _Ty is in a non-deduced context. The compiler can't deduce it.

A typical use with a forwarding reference is as follows:

template<typename T>
void foo(T&& t) {
    std::forward<T>(t);
}

Strictly speaking, std::forward is just syntactic sugar for a cast to T&& above. It's reference collapsing the does all the magic, but a bare cast to T&& does not convey the intent to forward quite as clearly as a named operator. That is why std::forward exists.


问:
Setting environment variables in eclipse project
I have a set of environment variables placed in a file, which I want to set when my project is launched via Eclipse.

I understand that we can set environment variables in run configuration, but there each variable has to be set manually. Is there a way through which I can set these variables from a file?

答:
You can add all file and folder paths inside the properties file (example config.properties) and then used it inside the testsetup method by

```<code>InputStream input = new FileInputStream("Path to//config.properties");
                Properties prop = new Properties();
                prop.load(input);
                System.setProperty("log4j2.configurationFile", prop.getProperty("log4j.path"));
</code>```

this way, all files/folder paths can be modifies from outside and there's no need to set environment variable from inside the project.

Body:
You can add all file and folder paths inside the properties file (example config.properties) and then used it inside the testsetup method by

InputStream input = new FileInputStream("Path to//config.properties");
                Properties prop = new Properties();
                prop.load(input);
                System.setProperty("log4j2.configurationFile", prop.getProperty("log4j.path"));

this way, all files/folder paths can be modifies from outside and there's no need to set environment variable from inside the project.


问:
How does a spinner close?
What I'm trying to accomplish is to use the spinner dropdown's closing action to trigger another event. Since the dropdown closes no matter where you touch on the screen, I guess that there is a listener that waits for a touch/click/etc. at any location, but I can't find that listener.

I can use OnItemSelectedListener to trigger an event when an entry from the dropdown is chosen, easy. I can also listen to the FrameLayout and trigger the event based on that, but it required an extra touch on the screen (maybe the first one gets absorbed by the spinner's listener(?)). There are also other buttons on the screen, so checking all of them as well would be complicated.

Do you know where is the code that actually opens and closes a spinner is?

答:
Something I tried was to subclass Spinner, and override onWindowFocusChanged. That event fires and hasWindowFocus == true when the spinner closes. That is,

```<code>class MySpinner(context: Context, attrSet: AttributeSet): Spinner(context, attrSet) {
    override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
        Toast.makeText(context.applicationContext, "WindowFocusChanged! $hasWindowFocus", Toast.LENGTH_LONG).show()
        super.onWindowFocusChanged(hasWindowFocus)
    }
}
</code>```

And your XML will need to specify MySpinner.

Title: How does a spinner close?

Body:
Something I tried was to subclass Spinner, and override onWindowFocusChanged. That event fires and hasWindowFocus == true when the spinner closes. That is,

class MySpinner(context: Context, attrSet: AttributeSet): Spinner(context, attrSet) {
    override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
        Toast.makeText(context.applicationContext, "WindowFocusChanged! $hasWindowFocus", Toast.LENGTH_LONG).show()
        super.onWindowFocusChanged(hasWindowFocus)
    }
}

And your XML will need to specify MySpinner.


问:
How do you balance working for a living and contributing to open source projects?
I have been a working programmer since the turn of the century and I have always been fascinated by the open source world. I have wanted to contribute to these projects but I find it difficult to find the time that I think these projects would require.

I find professional software development to be a huge time sink. Almost every project I have worked on has a familiar litany inflexible deadlines and inevitable round the clock last minute pushes that eat up your nights and weekends and everything else in sight. Even in the project that don't have this - the typical work day is 10 to 12 hours and after that one has errands and chores, reading up on the latest stuff, etc...

Since this happens with a fair amount of regularity - I am hesitant to join projects since I can't promise to devote a regular number of hours every week.

My question is how do you people do it?

Do you work at open source companies? Am I exaggerating the amount of time I need to spend (I am thinking a couple of hours everyday)? Am I way off base and simply not managing my time efficiently? How do you manage your time?

答:
If you're spending 12 hour days at work then there's something very wrong with your company and their approach to development time. We work on the principle of 7 hour days, but with a in-office time of 8 - 9. This allows for developers to attend meetings, eat, help each other, etc. The client then can have a more realistic deadline, a 70 hour project will take 10 days to complete, not 8.5 days.

This then leaves time to work on external projects. For doing that I will spend 3 - 5 nights a week on my open source projects.

Try setting yourself goals and deadlines as well. This means you know where you're trying to go and when you should get there.

I also try and take a day or two a month off to work on my own projects.

OwnerDisplayName: Nikhil

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Slace


答:
It does not deduce it. This is why when you use std::forward you have to give it template argument:

```<code>std::forward<T>(t);
</code>```

This is contrary to std::move, which does deduce, and typically used like this:

```<code>std::move(t);
</code>```

Title: How does std::forward deduce the type of `_Ty`?

Body:
It does not deduce it. This is why when you use std::forward you have to give it template argument:

std::forward<T>(t);

This is contrary to std::move, which does deduce, and typically used like this:

std::move(t);


答:
How does std::forward deduce the type of _Ty?

Ty doesn't have a type. Ty is a type (template parameter). The compiler doesn't deduce the type.

how does the compiler figure out the type of _Ty?

The template argument has to be passed explicitly.

If the type were deduced, then:

```<code>template<class T>
void foo(T&& t) {
    bar(std::forward(t));
}
</code>```

would pass an lvalue, since t is an lvalue. But we want to pass an rvalue, because t is an rvalue reference. Because the deduction is counter-productive, it is disabled using the remove_reference<_Ty>::type& trick, and we must write correctly:

```<code>template<class T>
void foo(T&& t) {
    bar(std::forward<T>(t));
                 // ^^^ this is how the compiler knows
}
</code>```

Body:
How does std::forward deduce the type of _Ty?

Ty doesn't have a type. Ty is a type (template parameter). The compiler doesn't deduce the type.

how does the compiler figure out the type of _Ty?

The template argument has to be passed explicitly.

If the type were deduced, then:

template<class T>
void foo(T&& t) {
    bar(std::forward(t));
}

would pass an lvalue, since t is an lvalue. But we want to pass an rvalue, because t is an rvalue reference. Because the deduction is counter-productive, it is disabled using the remove_reference<_Ty>::type& trick, and we must write correctly:

template<class T>
void foo(T&& t) {
    bar(std::forward<T>(t));
                 // ^^^ this is how the compiler knows
}


问:
Laravel 5.4 TokenMismatchException in VerifyCsrfToken.php line 68 on some device
I know it's one of the most asked question around here, but I really read everything on the first 10 pages results on google and nothing solved my problem.

On a fresh installation of laravel 5.4 , generated the auth controller, views, etc. via php artisan make:auth when I try to register (or login) in some device I get the following error:

TokenMismatchException in VerifyCsrfToken.php line 68

I'm running this application in local on debian 8.7 and php7 (could it be related to the problem in some way ?)
From my pc, iphone 7, another windows 10 desktop it works perfectly, but on a Huawei p8 lite, ipad 2 and lubuntu (quite old version) I get that error. So it's really weird because it just happends with some device (no matter whaht O.S. no matter what browser).

I can already tell you that I tried grant permissions to sessions folder, change session_domain, clearing cache (but as I said I'm trying this on a fresh installation), change {{ csrf_token }} to {!! csrf_token !!} , etc.

Just to give you more information about my system, this is the php version i'm using:

```<code>php --version
PHP 7.0.17-1~dotdeb+8.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.17-1~dotdeb+8.1, Copyright (c) 1999-2017, by Zend
Technologies
</code>```

I'm really stuck on this for days. Got no more ideas.

答:
in your .env file add

```<code>SESSION_DOMAIN=yourdomain.com
</code>```

Body:
I know it's one of the most asked question around here, but I really read everything on the first 10 pages results on google and nothing solved my problem.

On a fresh installation of laravel 5.4 , generated the auth controller, views, etc. via php artisan make:auth when I try to register (or login) in some device I get the following error:

TokenMismatchException in VerifyCsrfToken.php line 68

I'm running this application in local on debian 8.7 and php7 (could it be related to the problem in some way ?)
From my pc, iphone 7, another windows 10 desktop it works perfectly, but on a Huawei p8 lite, ipad 2 and lubuntu (quite old version) I get that error. So it's really weird because it just happends with some device (no matter whaht O.S. no matter what browser).

I can already tell you that I tried grant permissions to sessions folder, change session_domain, clearing cache (but as I said I'm trying this on a fresh installation), change {{ csrf_token }} to {!! csrf_token !!} , etc.

Just to give you more information about my system, this is the php version i'm using:

php --version
PHP 7.0.17-1~dotdeb+8.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.17-1~dotdeb+8.1, Copyright (c) 1999-2017, by Zend
Technologies

I'm really stuck on this for days. Got no more ideas.

Body:
in your .env file add

SESSION_DOMAIN=yourdomain.com


问:
Dispatch Group wait stuck forever
I have a function making multiple HTTP requests with Alamofire. I want to wait for all of them to finish in order to return a value. However, it gets stuck at dispatch.wait()

class func getActionField(fieldid: String, completion: @escaping (_ res: [String: [Double]]) -> Void) {
        var resreturn: [String: [Double]] = ["temperature":[], "humidity":[], "ph":[], "light":[]]
        let dispatch = DispatchGroup()
        dispatch.enter()
        Alamofire.request(url + "aktionsdaten/temperatur/" + fieldid, method: .get).responseJSON{ response in
            resreturn["temperature"] = response.result.value as! NSArray as? [Double] ?? [0.0,0.0]
            dispatch.leave()
        }
        dispatch.enter()
        Alamofire.request(url + "aktionsdaten/light/" + fieldid, method: .get).responseJSON{ response in
            resreturn["light"] = response.result.value as! NSArray as? [Double] ?? [0.0,0.0]
            dispatch.leave()
        }
        dispatch.enter()
        Alamofire.request(url + "aktionsdaten/ph/" + fieldid, method: .get).responseJSON{ response in
            resreturn["ph"] = response.result.value as! NSArray as? [Double] ?? [0.0,0.0]
            dispatch.leave()
        }
        dispatch.enter()
        Alamofire.request(url + "aktionsdaten/feuchtigkeit/" + fieldid, method: .get).responseJSON{ response in
            resreturn["humidity"] = response.result.value as! NSArray as? [Double] ?? [0.0,0.0]
            dispatch.leave()
        }
        dispatch.wait()
        completion(resreturn)
    }
```

答:
You have this all set up correctly, using a completion handler after all your asynchronous tasks are finished. The only problem is that you're using the DispatchGroup pattern incorrectly. Here's the correct pattern (this is pseudocode):</p>

```<code>let group = DispatchGroup()
group.enter()
queue1.async {
    // ... do task here ...
    group.leave()
}
group.enter()
queue2.async {
    // ... do task here ...
    group.leave()
}
group.enter()
queue3.async {
    // ... do task here ...
    group.leave()
}
// ... more as needed ...
group.notify(queue: DispatchQueue.main) {
    // finished! call completion handler or whatever
}

</code>```

Title: Dispatch Group wait stuck forever

Body:
You have this all set up correctly, using a completion handler after all your asynchronous tasks are finished. The only problem is that you're using the DispatchGroup pattern incorrectly. Here's the correct pattern (this is pseudocode):

let group = DispatchGroup()
group.enter()
queue1.async {
    // ... do task here ...
    group.leave()
}
group.enter()
queue2.async {
    // ... do task here ...
    group.leave()
}
group.enter()
queue3.async {
    // ... do task here ...
    group.leave()
}
// ... more as needed ...
group.notify(queue: DispatchQueue.main) {
    // finished! call completion handler or whatever
}


问:
NGINX fails at COPY --from=node /app/dist/comp-lib /usr/share/nginx/html,

COPY failed: stat /var/lib/docker/overlay2/1e9a0e53a11b406c13d4fc790336f37285927a1b87d1bac4d0e889c6d3cfed9b/merged/app/dist/comp-lib: no such file or directory

I tried running docker system prune, and restarted Docker a bunch of times.  I also gave a shot at rm -rf /var/lib/docker in the docker VM, somehow that doesn't remove the directory.

Node version: v10.15.1

Docker version: 18.09.2, build 6247962

Dockerfile:

```<code># stage-1

FROM node as builder
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build

# stage -2

FROM nginx:alpine
COPY --from=node /app/dist/comp-lib /usr/share/nginx/html
</code>```

I expect the build to be successful but the above mentioned is the error I'm experiencing.

答:
This is the dockerfile that I use for my Angular apps:

```<code>FROM johnpapa/angular-cli as angular-built
WORKDIR /usr/src/app
COPY package.json package.json
RUN npm install --silent
COPY . .
RUN ng build --prod

FROM nginx:alpine
LABEL author="Preston Lamb"
COPY --from=angular-built /usr/src/app/dist /usr/share/nginx/html
EXPOSE 80 443
CMD [ "nginx", "-g", "daemon off;" ]
</code>```

I've never had any issues with this configuration. There's more information as well in this article.

Body:
COPY failed: stat /var/lib/docker/overlay2/1e9a0e53a11b406c13d4fc790336f37285927a1b87d1bac4d0e889c6d3cfed9b/merged/app/dist/comp-lib: no such file or directory

I tried running docker system prune, and restarted Docker a bunch of times.  I also gave a shot at rm -rf /var/lib/docker in the docker VM, somehow that doesn't remove the directory.

Node version: v10.15.1

Docker version: 18.09.2, build 6247962

Dockerfile:

# stage-1

FROM node as builder
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build

# stage -2

FROM nginx:alpine
COPY --from=node /app/dist/comp-lib /usr/share/nginx/html

I expect the build to be successful but the above mentioned is the error I'm experiencing.

Body:
This is the dockerfile that I use for my Angular apps:

FROM johnpapa/angular-cli as angular-built
WORKDIR /usr/src/app
COPY package.json package.json
RUN npm install --silent
COPY . .
RUN ng build --prod

FROM nginx:alpine
LABEL author="Preston Lamb"
COPY --from=angular-built /usr/src/app/dist /usr/share/nginx/html
EXPOSE 80 443
CMD [ "nginx", "-g", "daemon off;" ]

I've never had any issues with this configuration. There's more information as well in this article.


问:
how return to top button works
I have looked around many places  return to top  button .when i click on that that takes me to top of the page.

some time some links taking me to particular place how does this works

is this html tack ticks or javascript..can i do this without page loading ?

答:
Lastly you can use javascript too:

```<code><a href="#" onclick="document.getElementById('someId').scrollIntoView(); return false</a>
</code>```

but assuming all modern browsers can do some id it is less needed nowadays

Title: how return to top button works

Body:
Lastly you can use javascript too:

<a href="#" onclick="document.getElementById('someId').scrollIntoView(); return false</a>

but assuming all modern browsers can do some id it is less needed nowadays


问:
Angular ngx-translate usage in typescript
I'm using this @ngx-translate/core i18n service and it works fine in templates (.html) with this syntax:

{{'my.i18n.key'|translate}}

Now I want to translate something in my component typescript file (.ts) but I don't know how to use it.

I can create translate object in my constructor:

constructor(private translate: TranslateService) {}

and now how to translate 'my.i18n.key' ?

答:
This works for me ( i am using Angular 7).
Just import the Translate service on the constructor and then call it from inside myfunction like this :

```<code>  getTranslation(){
    let translation = "";
    let clientTranslation = this.translate.get('auth.client').subscribe(cliente =>{
        translation = cliente;
        document.getElementById("clientTest").setAttribute('value', translation);
    }
}
</code>```

I was using the translation on a form so i pass it to the input with
   setAttribute, hope this example could help.

Body:
This works for me ( i am using Angular 7).
Just import the Translate service on the constructor and then call it from inside myfunction like this :

  getTranslation(){
    let translation = "";
    let clientTranslation = this.translate.get('auth.client').subscribe(cliente =>{
        translation = cliente;
        document.getElementById("clientTest").setAttribute('value', translation);
    }
}

I was using the translation on a form so i pass it to the input with
   setAttribute, hope this example could help.


问:
Alternative way to resize image in Azure Function (imageResizer not working)
I'm trying to resize an image that I get from a remote url but apparently I've had no luck yet.

Using System.Drawing I get an error (probably sandbox related) and using imageResizer it will give me an error

```<code>System.TypeLoadException: Could not load type 'System.Web.Hosting.HostingEnvironment' from assembly 'System.Web
</code>```

What can be a easy solution just to get a stream (or byte[]), resize and output the resized image?

答:
Use Nugets not system.drawing.
Here is the full example:

https://powerapps.microsoft.com/fr-fr/blog/auto-generate-thumbnails-using-an-azure-function-and-azure-blob-storage/

And this one uses Event Grid
https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/event-grid/resize-images-on-storage-blob-upload-event.md

Body:
I'm trying to resize an image that I get from a remote url but apparently I've had no luck yet.

Using System.Drawing I get an error (probably sandbox related) and using imageResizer it will give me an error

System.TypeLoadException: Could not load type 'System.Web.Hosting.HostingEnvironment' from assembly 'System.Web

What can be a easy solution just to get a stream (or byte[]), resize and output the resized image?


问:
Disable Native Lazy Load Images in Chrome on Android
It seems on my Android tablet, that chrome has implemented a native feature, that lazy load images only if there are near the viewport.
I already had implemented loading images via srcset and js. This worked always fantastic on every Browser including Chrome on Desktop. Reviewing my page in Chrome 71.0.3578.99 leads to a fundamental jumpy experience with delays.

Can I disable the feature somehow (e.g. MetaTag or attribute)? Do someone know a place where start to read about this? Can't find documentation.

答: You can enable/disable lazy loading in dedicated interface accessible within the browser. Type chrome://flags and search for disable-lazy-image-loading and disable-lazy-frame-loading. For all accessible settings, type: chrome://chrome-urls.


问:
mapbox map layer control with javascript
i am trying to create a web map from mapbox.
i have created my custom map style and generateed in this code.
here i am trying to control layer color by some button.
i have created the custom map of my own with four more layers named da_underconstruction, da_approve, da_completed, da_applied. the other two layers are built in water and building. by this app water can be changed but the other layers i cannot change. can anybody have a look and help me find out what am i doing wrong?
NB: to run the code the copy paste it in a html file and open with browser.
Thanks in advance.

i have tried different style maps.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>Change a layer's color with buttons</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.0.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.0.0/mapbox-gl.css' rel='stylesheet' />
    <style>
        body { margin:0; padding:0; }
        #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
</head>
<body>

<style>
.map-overlay {
    font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
    position: absolute;
    width: 200px;
    top: 0;
    left: 0;
    padding: 10px;
}

.map-overlay .map-overlay-inner {
    background-color: #fff;
    box-shadow:0 1px 2px rgba(0, 0, 0, 0.10);
    border-radius: 3px;
    padding: 10px;
    margin-bottom: 10px;
}

.map-overlay-inner fieldset {
    border: none;
    padding: 0;
    margin: 0 0 10px;
}

.map-overlay-inner fieldset:last-child {
    margin: 0;
}

.map-overlay-inner select {
    width: 100%;
}

.map-overlay-inner label {
    display: block;
    font-weight: bold;
    margin: 0 0 5px;
}

.map-overlay-inner button {
    display: inline-block;
    width: 36px;
    height: 20px;
    border: none;
    cursor: pointer;
}

.map-overlay-inner button:focus {
    outline: none;
}

.map-overlay-inner button:hover {
    box-shadow:inset 0 0 0 3px rgba(0, 0, 0, 0.10);
}
</style>

<div id='map'></div>
<div class='map-overlay top'>
    <div class='map-overlay-inner'>
        <fieldset>
            <label>Select layer</label>
            <select id='layer' name='layer'>
                <option value='da_approved'>da_approved</option>

                 <option value='da_completed'>da_completed</option>
                  <option value='da_applied'>da_applied</option>
                   <option value='da_underconstruction'>da_underconstruction</option>
                   <option value='building'>Buildings</option>
                   <option value='water'>water</option>
            </select>
        </fieldset>
        <fieldset>
            <label>Choose a color</label>
            <div id='swatches'></div>
        </fieldset>
    </div>
</div>

<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibnNiemhkIiwiYSI6ImNqdnhudHdkejA2anI0NHBpamNqbzIxaHcifQ.w7fVujcKAIAF0WTN9A8HZg';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/nsbzhd/cjw4md68g226y1cp3k6iwobna',
    center: [144.961786, -37.817656],
    zoom: 15.78,
    pitch:60.00
});

var swatches = document.getElementById('swatches');
var layer = document.getElementById('layer');
var colors = [
    '#ffffcc',
    '#a1dab4',
    '#41b6c4',
    '#2c7fb8',
    '#253494',
    '#fed976',
    '#feb24c',
    '#fd8d3c',
    '#f03b20',
    '#bd0026'
];

colors.forEach(function(color) {
    var swatch = document.createElement('button');
    swatch.style.backgroundColor = color;
    swatch.addEventListener('click', function() {
        map.setPaintProperty(layer.value, 'fill-color', color);
    });
    swatches.appendChild(swatch);
});
</script>

</body>
</html>
</code>```

i am trying to control the color of the da_construced,da_approved,da_applied  but here only water's color can be controled.

答:
Disclaimer: I work for Mapbox.

Hi fallen_programmer,

It looks like you're using the wrong property for the fill on line 133:

map.setPaintProperty(layer.value, 'fill-color', color);

if you change that to fill-extrusion-color, it works.

map.setPaintProperty(layer.value, 'fill-extrusion-color', color);

Hope that helps!

Best,
Brandi

Body:
i am trying to create a web map from mapbox.
i have created my custom map style and generateed in this code.
here i am trying to control layer color by some button.
i have created the custom map of my own with four more layers named da_underconstruction, da_approve, da_completed, da_applied. the other two layers are built in water and building. by this app water can be changed but the other layers i cannot change. can anybody have a look and help me find out what am i doing wrong?
NB: to run the code the copy paste it in a html file and open with browser.
Thanks in advance.

i have tried different style maps.

<!DOCTYPE html>

    <meta charset='utf-8' />
    <title>Change a layer's color with buttons</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />

    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.0.0/mapbox-gl.css' rel='stylesheet' />

        <fieldset>
            Select layer
            <select id='layer' name='layer'>
                <option value='da_approved'>da_approved</option>

                 <option value='da_completed'>da_completed</option>
                  <option value='da_applied'>da_applied</option>
                   <option value='da_underconstruction'>da_underconstruction</option>
                   <option value='building'>Buildings</option>
                   <option value='water'>water</option>
            </select>
        </fieldset>
        <fieldset>
            Choose a color

        </fieldset>

i am trying to control the color of the da_construced,da_approved,da_applied  but here only water's color can be controled.