问:
Livedata Data Change Pattern
I have a doubt.If i have a method that make asynchronous call to an api and converts the results of it to livedata object and in another place i am updating my recyclerview when data changes, then every time call to this method  will update recyclerview or ,for eg:if url stays same then it won't update the recyclerview;Pls help.
Here is the code for observing data in Mainactivity onCreate method.

```<code> JsonViewModel model = new ViewModelProvider(this).get(JsonViewModel.class);
    model.getData("top_rated").observe(this, data -> {
        mRecyclerView.setAdapter(new MovieRecyclerViewAdapter(this,data));
    });
</code>```

Here is the JsonViewModel class

```<code>public class JsonViewModel extends AndroidViewModel {

private JsonLivedata data;
public JsonViewModel(@NonNull Application application) {
    super(application);
    data=new JsonLivedata();
}

public LiveData<List<Movie>> getData(String path) {
    data.loadData(path);
    return data;
}
}
</code>```

Here is the JsonLivedata class

```<code>public class JsonLivedata extends LiveData<List<Movie>> {
private static final String TAG = "JsonLivedata";

public JsonLivedata() {

}

public void loadData(String path){
    Log.d(TAG, "loadData: Called");
    new AsyncTask<String,Void,List<Movie>>(){
        @Override
        protected List<Movie> doInBackground(String... path) {
            List<Movie> allTopMovies= JsonResponseFetcher.makeAsyncQueryForMovies(path[0]);
            return allTopMovies;
        }

        @Override
        protected void onPostExecute(List<Movie> movies) {
            setValue(movies);
        }
    }.execute(path);
}

}
</code>```

And here is the method that call livedata loaddata method

```<code>changeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            model.getData("popular");
        }
    });
</code>```

Or I am doing things wrongly.Can anyone suggest

答:
First create adapter instance & set to RecyclerView

```<code>JsonViewModel model = new ViewModelProvider(this).get(JsonViewModel.class);
MovieRecyclerViewAdapter movieRecyclerViewAdapter = new MovieRecyclerViewAdapter(this, dataList)
mRecyclerView.setAdapter(movieRecyclerViewAdapter);
</code>```

Then do this on data changes

```<code>    model.getData("top_rated").observe(this, data -> {
       dataList.clear();
       dataList.addAll(data);
       movieRecyclerViewAdapter.notifyDataSetChanged();
    });
</code>```

Title: Livedata Data Change Pattern

Body:
I have a doubt.If i have a method that make asynchronous call to an api and converts the results of it to livedata object and in another place i am updating my recyclerview when data changes, then every time call to this method  will update recyclerview or ,for eg:if url stays same then it won't update the recyclerview;Pls help.
Here is the code for observing data in Mainactivity onCreate method.

 JsonViewModel model = new ViewModelProvider(this).get(JsonViewModel.class);
    model.getData("top_rated").observe(this, data -> {
        mRecyclerView.setAdapter(new MovieRecyclerViewAdapter(this,data));
    });

Here is the JsonViewModel class

public class JsonViewModel extends AndroidViewModel {

private JsonLivedata data;
public JsonViewModel(@NonNull Application application) {
    super(application);
    data=new JsonLivedata();
}

public LiveData<List<Movie>> getData(String path) {
    data.loadData(path);
    return data;
}
}

Here is the JsonLivedata class

public class JsonLivedata extends LiveData<List<Movie>> {
private static final String TAG = "JsonLivedata";

public JsonLivedata() {

}

public void loadData(String path){
    Log.d(TAG, "loadData: Called");
    new AsyncTask<String,Void,List<Movie>>(){
        @Override
        protected List<Movie> doInBackground(String... path) {
            List<Movie> allTopMovies= JsonResponseFetcher.makeAsyncQueryForMovies(path[0]);
            return allTopMovies;
        }

        @Override
        protected void onPostExecute(List<Movie> movies) {
            setValue(movies);
        }
    }.execute(path);
}

}

And here is the method that call livedata loaddata method

changeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            model.getData("popular");
        }
    });

Or I am doing things wrongly.Can anyone suggest

Body:
First create adapter instance & set to RecyclerView

JsonViewModel model = new ViewModelProvider(this).get(JsonViewModel.class);
MovieRecyclerViewAdapter movieRecyclerViewAdapter = new MovieRecyclerViewAdapter(this, dataList)
mRecyclerView.setAdapter(movieRecyclerViewAdapter);

Then do this on data changes

    model.getData("top_rated").observe(this, data -> {
       dataList.clear();
       dataList.addAll(data);
       movieRecyclerViewAdapter.notifyDataSetChanged();
    });


来源: stackexchange

问:
Use JS to add browser version to  or  as class
I'm trying to find a tried and tested script that sniffs the browser version and adds a suitably named class to the  or the  tags... like  or  or .

I don't mind if it's "firefox4" or "ff4" or "firefox_4"... just as long as I can use the class to scope my css.

I could write a script to do this myself but I was wondering if there was a widely used one out there...

Thanks.

答:
In jquery, it's as simple as:

```<code>$('html').addClass('ie7');
</code>```

In vanilla Javascript:

```<code>var h = document.getElementsByTagName('html')[0];
h.className += ' ie7'; // note the preceding space
</code>```

ContentLicense: CC BY-SA 3.0

Title: Use JS to add browser version to <html> or <body> as class

Body:
In jquery, it's as simple as:

$('html').addClass('ie7');

In vanilla Javascript:

var h = document.getElementsByTagName('html')[0];
h.className += ' ie7'; // note the preceding space


问:
Is it proper to use size_t for count in a bitshift operation?
This small, seemingly insignificant question, occurred to me recently, but after googling quite a bit, I have been unable to find even an opinion on the subject. Only loops and object sizes are referred to.

I know people like examples, so here the one that cause the question in the first place:

```<code>uint64_t deltaSwap( const uint64_t b, const size_t delta, uint64_t mask )
{
    return b ^ mask ^ ( mask &=  b ^ b >> delta ) << delta;
}
</code>```

I've been trying too optimize this for a while, knowing full well that this is not the way to write proper code, though it has given me the best result so far, at least with GCC, and then it occurred to me. If you really want to be pedantic, shouldn't delta be of type size_t?

I never really understood when to use size_t, so I never really do, but if I were to, wouldn't this be correct usage?

Update:
Here's the short explanation of what it does, although not how it does so, as I'm not really sure how to explain it:

It is a standard delta swap, which is not a new ideal, and the code works fine, this isn't really about the code (but since you asked), and all I've really done is experimenting with it, to achieve the best performance, and the version you see here, is my best result so far.

The purpose of the code is to swap two or more bits, fx if you wish to swap the first and the last bit, it could be done thusly:

```<code>deltaSwap(b, 63, 0x0000000000000001);
</code>```

or if you wish to reverse the order of the bits:

```<code>deltaSwap(b, 32, 0x00000000ffffffff);
deltaSwap(b, 16, 0x0000ffff0000ffff);
deltaSwap(b,  8, 0x00ff00ff00ff00ff);
deltaSwap(b,  4, 0x0f0f0f0f0f0f0f0f);
deltaSwap(b,  2, 0x3333333333333333);
deltaSwap(b,  1, 0x5555555555555555);
</code>```

though for this particular task, deltaswaps are probably not the best way to go.

Update 2:
Just for completion, this is the most correct onliner I can think of (haven gotten my answer), and the compiler apparently optimizes it perfectly.

```<code>uint64_t deltaSwap( const uint64_t b, const uint_fast8_t delta, const uint64_t mask )
{
    return b ^ ( mask & ( b ^ b >> delta ) ) ^ ( mask & ( b ^ b >> delta ) ) << delta;
}
</code>```

I would've shortened the variable name to get it all to fit within the 80 character with imposed by my ocd brain (and apparently this site as well), but for you all, I'm willing to suffer.

答:
From the ISO/IEC 9899:1999 section 6.5.7

If the value of the right operand is negative or is greater than
  or equal to the width of the promoted left operand,
  the behavior is undefined.

It means that in your case the requirements for the delta are

```<code>0 <= delta < number of bits in the left operand
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This small, seemingly insignificant question, occurred to me recently, but after googling quite a bit, I have been unable to find even an opinion on the subject. Only loops and object sizes are referred to.

I know people like examples, so here the one that cause the question in the first place:

uint64_t deltaSwap( const uint64_t b, const size_t delta, uint64_t mask )
{
    return b ^ mask ^ ( mask &=  b ^ b >> delta ) << delta;
}

I've been trying too optimize this for a while, knowing full well that this is not the way to write proper code, though it has given me the best result so far, at least with GCC, and then it occurred to me. If you really want to be pedantic, shouldn't delta be of type size_t?

I never really understood when to use size_t, so I never really do, but if I were to, wouldn't this be correct usage?

Update:
Here's the short explanation of what it does, although not how it does so, as I'm not really sure how to explain it:

It is a standard delta swap, which is not a new ideal, and the code works fine, this isn't really about the code (but since you asked), and all I've really done is experimenting with it, to achieve the best performance, and the version you see here, is my best result so far.

The purpose of the code is to swap two or more bits, fx if you wish to swap the first and the last bit, it could be done thusly:

deltaSwap(b, 63, 0x0000000000000001);

or if you wish to reverse the order of the bits:

deltaSwap(b, 32, 0x00000000ffffffff);
deltaSwap(b, 16, 0x0000ffff0000ffff);
deltaSwap(b,  8, 0x00ff00ff00ff00ff);
deltaSwap(b,  4, 0x0f0f0f0f0f0f0f0f);
deltaSwap(b,  2, 0x3333333333333333);
deltaSwap(b,  1, 0x5555555555555555);

though for this particular task, deltaswaps are probably not the best way to go.

Update 2:
Just for completion, this is the most correct onliner I can think of (haven gotten my answer), and the compiler apparently optimizes it perfectly.

uint64_t deltaSwap( const uint64_t b, const uint_fast8_t delta, const uint64_t mask )
{
    return b ^ ( mask & ( b ^ b >> delta ) ) ^ ( mask & ( b ^ b >> delta ) ) << delta;
}

I would've shortened the variable name to get it all to fit within the 80 character with imposed by my ocd brain (and apparently this site as well), but for you all, I'm willing to suffer.

Body:
From the ISO/IEC 9899:1999 section 6.5.7

If the value of the right operand is negative or is greater than
  or equal to the width of the promoted left operand,
  the behavior is undefined.

It means that in your case the requirements for the delta are

0 <= delta < number of bits in the left operand


问:
FileSystemResource to MultipartFile
I want to send my image from my storage using the path like this:

```<code>MultiValueMap<String, Object> image = new LinkedMultiValueMap<String, Object>();
image.add("image", new FileSystemResource("C:\\xx\\xx\\xx\\xx\\xx\\xx\\xx\\img\\xx.jpg"));
</code>```

so I call the object using the code below:

```<code>MultiValueMap<String, Object> body = new LinkedMultiValueMap<String,Object>();
body.add("image", image);
</code>```

Then, I get this error:

```<code>Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class sun.nio.ch.ChannelInputStream]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class sun.nio.ch.ChannelInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.util.LinkedMultiValueMap["image"]->java.util.LinkedList[0]->org.springframework.core.io.FileSystemResource["inputStream"])] with root cause

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class sun.nio.ch.ChannelInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.util.LinkedMultiValueMap["image"]->java.util.LinkedList[0]->org.springframework.core.io.FileSystemResource["inputStream"])
</code>```

I am using the Rest Template of spring boot, which requires me to send by POST Method the MultipartFile object. Now, I do not know how to convert into the MultipartFile type,

 so the Rest Template can accept my request post.

Note: I want to use the body.add("image", image.getResource()); but It did not show up in selection since image wasn't of MultipartFile type.

答:
This worked for me.</p>

```<code>    @GetMapping(path = "/copy", produces = MediaType.TEXT_PLAIN_VALUE)
    public ResponseEntity<String> copyFile() {

        MultiValueMap<String, Object> body
                = new LinkedMultiValueMap<>();
        body.add("image", new FileSystemResource("test.jpg"));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, Object>> requestEntity
                = new HttpEntity<>(body, headers);

        String serverUrl = "http://localhost:8080/upload";

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate
                .postForEntity(serverUrl, requestEntity, String.class);

        return response;
    }

    @PostMapping(path = "/upload", produces = MediaType.TEXT_PLAIN_VALUE)
    public String uploadFile(@RequestParam("image") MultipartFile file) {

        try {

            byte[] bytes = file.getBytes();
            Path path = Paths.get("./uploadedImages/" + file.getOriginalFilename());
            Files.write(path, bytes);

        } catch (IOException e) {
            e.printStackTrace();
            return "Error";
        }

        return "File Uploaded";
    }
</code>```

Title: FileSystemResource to MultipartFile

Body:
I want to send my image from my storage using the path like this:

MultiValueMap<String, Object> image = new LinkedMultiValueMap<String, Object>();
image.add("image", new FileSystemResource("C:\\xx\\xx\\xx\\xx\\xx\\xx\\xx\\img\\xx.jpg"));

so I call the object using the code below:

MultiValueMap<String, Object> body = new LinkedMultiValueMap<String,Object>();
body.add("image", image);

Then, I get this error:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class sun.nio.ch.ChannelInputStream]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class sun.nio.ch.ChannelInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.util.LinkedMultiValueMap["image"]->java.util.LinkedList[0]->org.springframework.core.io.FileSystemResource["inputStream"])] with root cause

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class sun.nio.ch.ChannelInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.util.LinkedMultiValueMap["image"]->java.util.LinkedList[0]->org.springframework.core.io.FileSystemResource["inputStream"])

I am using the Rest Template of spring boot, which requires me to send by POST Method the MultipartFile object. Now, I do not know how to convert into the MultipartFile type,

 so the Rest Template can accept my request post.

Note: I want to use the body.add("image", image.getResource()); but It did not show up in selection since image wasn't of MultipartFile type.

Body:
This worked for me.

    @GetMapping(path = "/copy", produces = MediaType.TEXT_PLAIN_VALUE)
    public ResponseEntity<String> copyFile() {

        MultiValueMap<String, Object> body
                = new LinkedMultiValueMap<>();
        body.add("image", new FileSystemResource("test.jpg"));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, Object>> requestEntity
                = new HttpEntity<>(body, headers);

        String serverUrl = "http://localhost:8080/upload";

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate
                .postForEntity(serverUrl, requestEntity, String.class);

        return response;
    }

    @PostMapping(path = "/upload", produces = MediaType.TEXT_PLAIN_VALUE)
    public String uploadFile(@RequestParam("image") MultipartFile file) {

        try {

            byte[] bytes = file.getBytes();
            Path path = Paths.get("./uploadedImages/" + file.getOriginalFilename());
            Files.write(path, bytes);

        } catch (IOException e) {
            e.printStackTrace();
            return "Error";
        }

        return "File Uploaded";
    }


问:
Check if child component rendered - Jest, Enzyme
In my unit test, I want to test whether the parent component is successfully rendering its child component. Here is the code:

```<code>describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.find(Child).length).toEqual(1);
  });
});
</code>```

Parent:

```<code>const Parent = observer(({ store }) => {
  const bookList = toJS(store.planets);
  return (
    <div>
      <div className={style.planet_container}>
        {bookList.map(book => {
          return <Child key={book.name} name={book.name} />;
        })}
      </div>
    </div>
  );
});
</code>```

Above code is taken from here, but it's not working. I am getting the following error:

Expected 1, Received 0'

Where am I going wrong? I am using Enzyme 3.3 with Jest 23.1.0.

答:
You can check whether a parent component has rendered its child component using containsMatchingElement().

Based on Enzyme docs:

Returns whether or not a patternNode react element matches any element in the render tree.

Your test should look like this:

```<code>describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.containsMatchingElement(<Child />)).toEqual(true);
  });
});
</code>```

Body:
In my unit test, I want to test whether the parent component is successfully rendering its child component. Here is the code:

describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.find(Child).length).toEqual(1);
  });
});

Parent:

const Parent = observer(({ store }) => {
  const bookList = toJS(store.planets);
  return (

        {bookList.map(book => {
          return <Child key={book.name} name={book.name} />;
        })}

  );
});

Above code is taken from here, but it's not working. I am getting the following error:

Expected 1, Received 0'

Where am I going wrong? I am using Enzyme 3.3 with Jest 23.1.0.

Body:
You can check whether a parent component has rendered its child component using containsMatchingElement().

Based on Enzyme docs:

Returns whether or not a patternNode react element matches any element in the render tree.

Your test should look like this:

describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.containsMatchingElement(<Child />)).toEqual(true);
  });
});


问:
Google map Marker Clustering not open when the point near each others
I use the Google Maps API v3. I have this object below. I calculate the distance between them, it is around 1 meter, my problem is when I zoom in the last cluster never open and I can't see the points. I use marker Cluster (because I have more than 50k points).

```<code>var locations = [
  {lat: 41.2387918, lng: 65.00829530},
  {lat: 41.23880147, lng: 65.00829530}
]
</code>```

Note: I found some answers, they suggest adding a random number for each point but I want the exact location.

答:
You need to set the maxZoom of the MarkerClusterer.

From the documentation

maxZoom: number

  The maximum zoom level at which clustering is enabled or null if clustering is to be enabled at all zoom levels.

```<code>// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {
  imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
  maxZoom: 20,
});
</code>```

proof of concept fiddle

code snippet:

function initMap() {

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 3,
    center: {
      lat: -28.024,
      lng: 140.887
    }
  });
  var bounds = {
    north: 41.238854621921156,
    east: 65.00841750814823,
    south: 41.23873864802776,
    west: 65.00817309185175
  }
  map.fitBounds(bounds);
  // Create an array of alphabetical characters used to label the markers.
  var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

  // Add some markers to the map.
  // Note: The code uses the JavaScript Array.prototype.map() method to
  // create an array of markers based on a given "locations" array.
  // The map() method here has nothing to do with the Google Maps API.
  var markers = locations.map(function(location, i) {
    return new google.maps.Marker({
      position: location,
      label: labels[i % labels.length]
    });
  });

  // Add a marker clusterer to manage the markers.
  var markerCluster = new MarkerClusterer(map, markers, {
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
    maxZoom: 20,
  });
}
var locations = [{
    lat: 41.2387918,
    lng: 65.00829530
  },
  {
    lat: 41.23880147,
    lng: 65.00829530
  }
]```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

```

Body:
I use the Google Maps API v3. I have this object below. I calculate the distance between them, it is around 1 meter, my problem is when I zoom in the last cluster never open and I can't see the points. I use marker Cluster (because I have more than 50k points).

var locations = [
  {lat: 41.2387918, lng: 65.00829530},
  {lat: 41.23880147, lng: 65.00829530}
]

Note: I found some answers, they suggest adding a random number for each point but I want the exact location.

Body:
You need to set the maxZoom of the MarkerClusterer.

From the documentation

maxZoom: number

  The maximum zoom level at which clustering is enabled or null if clustering is to be enabled at all zoom levels.

// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {
  imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
  maxZoom: 20,
});

proof of concept fiddle

code snippet:

function initMap() {

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 3,
    center: {
      lat: -28.024,
      lng: 140.887
    }
  });
  var bounds = {
    north: 41.238854621921156,
    east: 65.00841750814823,
    south: 41.23873864802776,
    west: 65.00817309185175
  }
  map.fitBounds(bounds);
  // Create an array of alphabetical characters used to label the markers.
  var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

  // Add some markers to the map.
  // Note: The code uses the JavaScript Array.prototype.map() method to
  // create an array of markers based on a given "locations" array.
  // The map() method here has nothing to do with the Google Maps API.
  var markers = locations.map(function(location, i) {
    return new google.maps.Marker({
      position: location,
      label: labels[i % labels.length]
    });
  });

  // Add a marker clusterer to manage the markers.
  var markerCluster = new MarkerClusterer(map, markers, {
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
    maxZoom: 20,
  });
}
var locations = [{
    lat: 41.2387918,
    lng: 65.00829530
  },
  {
    lat: 41.23880147,
    lng: 65.00829530
  }
]

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

<div id="map"></div>
<script src="https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js"></script>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>


问:
Why doesn't zeromq work on localhost?
This code works great:

```<code>import zmq, json, time

def main():
    context = zmq.Context()
    subscriber = context.socket(zmq.SUB)
    subscriber.bind("ipc://test")
    subscriber.setsockopt(zmq.SUBSCRIBE, '')
    while True:
        print subscriber.recv()

def main():
    context = zmq.Context()
    publisher = context.socket(zmq.PUB)
    publisher.connect("ipc://test")
    while True:
        publisher.send( "hello world" )
        time.sleep( 1 )
</code>```

But this code doesn't* work:

```<code>import zmq, json, time

def recv():
    context = zmq.Context()
    subscriber = context.socket(zmq.SUB)
    subscriber.bind("tcp://localhost:5555")
    subscriber.setsockopt(zmq.SUBSCRIBE, '')
    while True:
        print subscriber.recv()

def send():
    context = zmq.Context()
    publisher = context.socket(zmq.PUB)
    publisher.connect("tcp://localhost:5555")
    while True:
        publisher.send( "hello world" )
        time.sleep( 1 )
</code>```

It raises this error:

ZMQError: No such device

Why, can't zeromq use localhost interfaces?

Does it only work on IPC on the same machine?

答:
The problem is at line:

```<code>subscriber.bind("tcp://localhost:5555")
</code>```

try to change to:

```<code>subscriber.bind("tcp://127.0.0.1:5555")
</code>```

Title: Why doesn't zeromq work on localhost?

Body:
This code works great:

import zmq, json, time

def main():
    context = zmq.Context()
    subscriber = context.socket(zmq.SUB)
    subscriber.bind("ipc://test")
    subscriber.setsockopt(zmq.SUBSCRIBE, '')
    while True:
        print subscriber.recv()

def main():
    context = zmq.Context()
    publisher = context.socket(zmq.PUB)
    publisher.connect("ipc://test")
    while True:
        publisher.send( "hello world" )
        time.sleep( 1 )

But this code doesn't* work:

import zmq, json, time

def recv():
    context = zmq.Context()
    subscriber = context.socket(zmq.SUB)
    subscriber.bind("tcp://localhost:5555")
    subscriber.setsockopt(zmq.SUBSCRIBE, '')
    while True:
        print subscriber.recv()

def send():
    context = zmq.Context()
    publisher = context.socket(zmq.PUB)
    publisher.connect("tcp://localhost:5555")
    while True:
        publisher.send( "hello world" )
        time.sleep( 1 )

It raises this error:

ZMQError: No such device

Why, can't zeromq use localhost interfaces?

Does it only work on IPC on the same machine?

Body:
The problem is at line:

subscriber.bind("tcp://localhost:5555")

try to change to:

subscriber.bind("tcp://127.0.0.1:5555")


问:
How do I populate a column based off two other columns upon insert
I just created my own PostgreSQL database.

I have a Person table with a first_name, last_name, and full_name column (also a person_id auto incrementing primary key)

If I insert as such:

```<code>INSERT INTO Person
(first_name, last_name)
VALUES('Michael', 'Jordan');
</code>```

What's the best approach to automatically populate full_name column as first_name + last_name ('Michael Jordan')?

答:
You can create a generated column:</p>

```<code>alter table person
    add full_name varchar(255) generated always as (concat(firstname, ' ', lastname));
</code>```

Body:
I just created my own PostgreSQL database.

I have a Person table with a first_name, last_name, and full_name column (also a person_id auto incrementing primary key)

If I insert as such:

INSERT INTO Person
(first_name, last_name)
VALUES('Michael', 'Jordan');

What's the best approach to automatically populate full_name column as first_name + last_name ('Michael Jordan')?

Body:
You can create a generated column:

alter table person
    add full_name varchar(255) generated always as (concat(firstname, ' ', lastname));


问:
How to know if url is already bookmarked
I am adding bookmark from code. Now in Firefox if user already added the url as bookmark he should not be able to bookmark it again. How can I do it? For now every time a new bookmark is getting created.</p>

答:
getBookmarkIdsForURI()

"This method retrieves the list of bookmark IDs that contain the given URI."

OwnerDisplayName: Tanmoy Rajguru

ContentLicense: CC BY-SA 2.5


问:
How to define and execute a function in python script?
```<code>def calculation_of_salary(hours_worked,pay_per_hour):

salary = hours_worked*pay_per_hour
return salary

name = "kamil"

hw = 6

pph = 10

print("calculation_of_salary")
</code>```

I know how to define but I don't know how to execute the function.
I'm fairly new to coding...
Looking for assistance

Thank you.

答:
try  this

```<code>def calculation_of_salary(hours_worked,pay_per_hour):
  salary = hours_worked*pay_per_hour
  return salary

name = "kamil"

hw = 6

pph = 10

print(calculation_of_salary(hw,pph))
</code>```

live :
https://repl.it/@RKVKanyan/RoyalMediumorchidSale

Body:
def calculation_of_salary(hours_worked,pay_per_hour):

salary = hours_worked*pay_per_hour
return salary

name = "kamil"

hw = 6

pph = 10

print("calculation_of_salary")

I know how to define but I don't know how to execute the function.
I'm fairly new to coding...
Looking for assistance

Thank you.

Body:
try  this

def calculation_of_salary(hours_worked,pay_per_hour):
  salary = hours_worked*pay_per_hour
  return salary

name = "kamil"

hw = 6

pph = 10

print(calculation_of_salary(hw,pph))

live :
https://repl.it/@RKVKanyan/RoyalMediumorchidSale


问:
Laravel random collection without an existing stored item in another collection relation
I would like to get a random item from a collection. if the random item already exist on my $candidat_exist collection i would like to random again in order to get a different item than the one stored in rencontre_officiel table

I was thinking something like this will work

```<code>        \\App\Licencies collection
        $candidat = $arbitres->random();

        $candidat_exist = \App\RencontreOfficiel::where('licencie_id' , $candidat->id)->where('rencontre_id' , $rencontre->id)->exists();

        while ($candidat_exist){
            $candidat = $arbitres->random();
        }

        dd($candidat);
</code>```

my $candidat_exist is true so i would like to assign randomly another value

UPDATE :

```<code>$arbitres = Licencies::getArbitres();
</code>```

and my function getArbitres() in the model is :

```<code>   public static function getArbitres(){

        $all_licences = Licencies::whereIn('activite_licencie_id' , [24,25,50,80])
            ->where('valid_licence_id' , 3)
            ->where('saison_id' , self::getSaison()->id)
            ->where('dispo' , 1)
            ->get();

        return $licences;
</code>```

Here my model relation with Licencies model :

```<code>class RencontreOfficiel extends Model
{
    public function rencontre(){

        return $this->belongsTo('App\Rencontre' , 'rencontre_id');
    }

    public function licence(){

        return $this->belongsTo('App\Licencies' , 'licencie_id');
    }
}
</code>```

Here my class Licencies with the relation divisions

```<code>public function divisions(){
        return $this->hasMany(LicenceDesignationDivision::class , 'licence_id');
    }
</code>```

Here my $arbitres collection :

```<code> $arbitres = $arbitres->reject(function ($arbitre) use ($rencontre) {
                return $arbitre->rencontreOfficiels->contains(function ($rencontreOfficiels) use ($rencontre) {
                    return $rencontreOfficiels->rencontre_id === $rencontre->id;
                });
            })->filter(function ($arbitre){

                return $arbitre->divisions->contains('categorie_compet_id', 1);

            })->filter(function($arbitre){

                return $arbitre->level >= 3;

            });
</code>```

I need to check if i have an empty collection i need to change the categorie_compet_id value and if i still get nothing i need to change the level condition.

how could i achieve this propely  ?

答:
Instead of getting all the Licencies records you could just narrow down your search by excluding all the models that already has a relationship with a RecontreOfficiel record.

I assume that each Licencies model can have many RecontreOfficiel models.

In your Licencies you should then have the following relationship:

public function recontreOfficiels()
{
    return $this->hasMany('App\RencontreOfficiel', 'licencie_id');
}
```

<p>You could then filter the arbitres collection with:</p>

<pre class="lang-php prettyprint-override"><code># Load arbitres
$arbitres = Licencies::getArbitres();
# Load relationship with RecontreOfficiel model
$arbitres->load('recontreOfficiels');

# Reject arbitres which any of its recontreOfficieles
# is already associated with the $recontre model
$arbitres = $arbitres->reject(function ($arbitre) use ($recontre) {
    return $arbitre->recontreOfficiels->contains(function($recontreOfficiele) use ($recontre) {
        return $recontreOfficiels->recontre_id === $recontre->id;
    });
});

# Then you should end up with a list of not associated arbitres that you can pluck from
$arbitres->random();
</code>```

The best solution would be to use whereDoesntHave method when you get all the Arbitres, but that would require a major rework of your code.

Update

If you need to apply more conditions you can do so by chaining other methods after reject:

$arbitres = $arbitres->reject(function ($arbitre) use ($recontre) {
    return $arbitre->recontreOfficiels->contains(function($recontreOfficiele) use ($recontre) {
        return $recontreOfficiels->recontre_id === $recontre->id;
    });
})->where('level', '>=', 5); // Here you take only arbitres with level greater than 5
```

You can see all the available methods in the collections documentation

Body:
I would like to get a random item from a collection. if the random item already exist on my $candidat_exist collection i would like to random again in order to get a different item than the one stored in rencontre_officiel table

I was thinking something like this will work

        \\App\Licencies collection
        $candidat = $arbitres->random();

        $candidat_exist = \App\RencontreOfficiel::where('licencie_id' , $candidat->id)->where('rencontre_id' , $rencontre->id)->exists();

        while ($candidat_exist){
            $candidat = $arbitres->random();
        }

        dd($candidat);

my $candidat_exist is true so i would like to assign randomly another value

UPDATE :

$arbitres = Licencies::getArbitres();

and my function getArbitres() in the model is :

   public static function getArbitres(){

        $all_licences = Licencies::whereIn('activite_licencie_id' , [24,25,50,80])
            ->where('valid_licence_id' , 3)
            ->where('saison_id' , self::getSaison()->id)
            ->where('dispo' , 1)
            ->get();

        return $licences;

Here my model relation with Licencies model :

class RencontreOfficiel extends Model
{
    public function rencontre(){

        return $this->belongsTo('App\Rencontre' , 'rencontre_id');
    }

    public function licence(){

        return $this->belongsTo('App\Licencies' , 'licencie_id');
    }
}

Here my class Licencies with the relation divisions

public function divisions(){
        return $this->hasMany(LicenceDesignationDivision::class , 'licence_id');
    }

Here my $arbitres collection :

 $arbitres = $arbitres->reject(function ($arbitre) use ($rencontre) {
                return $arbitre->rencontreOfficiels->contains(function ($rencontreOfficiels) use ($rencontre) {
                    return $rencontreOfficiels->rencontre_id === $rencontre->id;
                });
            })->filter(function ($arbitre){

                return $arbitre->divisions->contains('categorie_compet_id', 1);

            })->filter(function($arbitre){

                return $arbitre->level >= 3;

            });

I need to check if i have an empty collection i need to change the categorie_compet_id value and if i still get nothing i need to change the level condition.

how could i achieve this propely  ?

Body:
Instead of getting all the Licencies records you could just narrow down your search by excluding all the models that already has a relationship with a RecontreOfficiel record.

I assume that each Licencies model can have many RecontreOfficiel models.

In your Licencies you should then have the following relationship:

public function recontreOfficiels()
{
    return $this->hasMany('App\RencontreOfficiel', 'licencie_id');
}

You could then filter the arbitres collection with:

# Load arbitres
$arbitres = Licencies::getArbitres();
# Load relationship with RecontreOfficiel model
$arbitres->load('recontreOfficiels');

# Reject arbitres which any of its recontreOfficieles
# is already associated with the $recontre model
$arbitres = $arbitres->reject(function ($arbitre) use ($recontre) {
    return $arbitre->recontreOfficiels->contains(function($recontreOfficiele) use ($recontre) {
        return $recontreOfficiels->recontre_id === $recontre->id;
    });
});

# Then you should end up with a list of not associated arbitres that you can pluck from
$arbitres->random();

The best solution would be to use whereDoesntHave method when you get all the Arbitres, but that would require a major rework of your code.

Update

If you need to apply more conditions you can do so by chaining other methods after reject:

$arbitres = $arbitres->reject(function ($arbitre) use ($recontre) {
    return $arbitre->recontreOfficiels->contains(function($recontreOfficiele) use ($recontre) {
        return $recontreOfficiels->recontre_id === $recontre->id;
    });
})->where('level', '>=', 5); // Here you take only arbitres with level greater than 5

You can see all the available methods in the collections documentation


问:
Is it possible to set up a gradle project with more than 2 levels?
We have been using gradle for about a year and have been somewhat successful with it. A number of features are still a little opaque, but we are getting there. I am not sure I am going about solving the problem correctly, so I will go ahead and ask the question:

All the examples that I have seen for gradle have a root project and one level of sub-projects. For a number of reasons, we would like to consolidate our git projects. All of these are gradle projects, some of which have gradle sub-projects. What we want to end up with is essentially a multi-level gradle structure. We do not want to alter the gradle setup for all those projects and instead would like to have a top level gradle that manages all the projects and corresponding subprojects. My first attempt showed that I cannot have a controlling build.gradle that orchestrates all of the projects and subprojects. Am I doing something wrong? Am I following and inherently broken paradigm?

Here is a sample structure for what I want to do:

```<code>Top Project
  build.gradle
  Project
    build.gradle
    Sub Project
      build.gradle
      src
    Sub Project
      ...
  Project
    ...
</code>```

Thank you and I hope I did not miss some obvious explanation in the documentation.

答:
Kotlin version of settings.gradle.kts

```<code>fileTree(".") {
    include("**/build.gradle")
    include("**/build.gradle.kts")
    exclude("buildSrc/**")
    exclude("build.gradle.kts")
}.map {
    relativePath(it.parent)
        .replace(File.separator, ":")
}.forEach {
    include(it)
}
</code>```

Instead of adding it manually like this (like Intellij Idea suggests):

```<code>include("modules:core")
findProject(":modules:core")?.name = "core"
</code>```

Body:
We have been using gradle for about a year and have been somewhat successful with it. A number of features are still a little opaque, but we are getting there. I am not sure I am going about solving the problem correctly, so I will go ahead and ask the question:

All the examples that I have seen for gradle have a root project and one level of sub-projects. For a number of reasons, we would like to consolidate our git projects. All of these are gradle projects, some of which have gradle sub-projects. What we want to end up with is essentially a multi-level gradle structure. We do not want to alter the gradle setup for all those projects and instead would like to have a top level gradle that manages all the projects and corresponding subprojects. My first attempt showed that I cannot have a controlling build.gradle that orchestrates all of the projects and subprojects. Am I doing something wrong? Am I following and inherently broken paradigm?

Here is a sample structure for what I want to do:

Top Project
  build.gradle
  Project
    build.gradle
    Sub Project
      build.gradle
      src
    Sub Project
      ...
  Project
    ...

Thank you and I hope I did not miss some obvious explanation in the documentation.

Body:
Kotlin version of settings.gradle.kts

fileTree(".") {
    include("**/build.gradle")
    include("**/build.gradle.kts")
    exclude("buildSrc/**")
    exclude("build.gradle.kts")
}.map {
    relativePath(it.parent)
        .replace(File.separator, ":")
}.forEach {
    include(it)
}

Instead of adding it manually like this (like Intellij Idea suggests):

include("modules:core")
findProject(":modules:core")?.name = "core"


问:
How to display an array like a hypertext in node.js
I want to display rooms array like hypertext but after the first room is created it gives an error.</p>

```<code>
let rooms = [];
app.get("/rooms", function(req, res) {
    for(let i=0;i<rooms.length;i++) {
        res.send('<a href="/room/'+rooms[i]+'">'+rooms[i]+'</a> <br>');
    }
    res.send(200)
});
app.get("/room/:roomName", function(req, res) {
    let roomName = req.params.roomName;
    rooms.push(roomName);
    res.send(roomName);
});
</code>```

答:
app.get('/rooms', (req, res) => {
  try {
    return res.status(200).json(rooms.map(room =>(`${room}`)));
  } catch(error) {
     console.error(error);
     return res.status(500).json(error); // or another status you decide.
  }
})
```

Body:
I want to display rooms array like hypertext but after the first room is created it gives an error.

let rooms = [];
app.get("/rooms", function(req, res) {
    for(let i=0;i<rooms.length;i++) {
        res.send(''+rooms[i]+'
');
    }
    res.send(200)
});
app.get("/room/:roomName", function(req, res) {
    let roomName = req.params.roomName;
    rooms.push(roomName);
    res.send(roomName);
});

Body:
app.get('/rooms', (req, res) => {
  try {
    return res.status(200).json(rooms.map(room =>(`<a href="${room}">${room}</a>`)));
  } catch(error) {
     console.error(error);
     return res.status(500).json(error); // or another status you decide.
  }
})


问:
in C# winform, I got: "only truetype fonts are supported. This is not a TrueType Font"
I have C# winform, I installed a couple of ttf fonts, but when i set the text box font to any of the ones i downloaded, i get this error Even though I'm 100% sure that the font I installed is ttf ..
why ? and how to fix this ?</p>

答:
Try</p>

```<code>private void Form1_Load(object sender, System.EventArgs e) {
    label1.Font = new Font("myFont", 12, FontStyle.Regular);
}
</code>```

Body:
Try

private void Form1_Load(object sender, System.EventArgs e) {
    label1.Font = new Font("myFont", 12, FontStyle.Regular);
}


问:
Firestore One time fetch vs Realtime listener in Recyclerview with filter
I have feed like the image in my app. I am getting list of some documents from firetsore collection and I am populating them in List and then use it in recycler view to show details of user.

When feed is clicked, I want to show ditrict3 and district4 data. Like below:

```<code> collectionRef = FirebaseFirestore.getInstance().collection("male");
 collectionRef.whereIn("district", Arrays.asList("district3", "district4"))
              .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                                if (task.isSuccessful()) {
                                    List<FilterDetails> filterDetailsList = new ArrayList<>();
                                    for (DocumentSnapshot document : task.getResult()) {
                                        FilterDetails filterDetails = document.toObject(FilterDetails.class);
                                        filterDetailsList.add(filterDetails);
                                        getParentActivity().hideLoading();
                                    }
                                    feedItemAdapter.updateData(filterDetailsList);
                                }
                            }
                        });
</code>```

When district1 will be clicked I will change whereEqualTo("district", "district1") and for different selection I will change.

User can change this more frequently and if I will do one time fetch then its going to cost me very much. But If I will use realtime snapshot then data will be read again and again if other users will change their info. Solutions I thought,
1) To get all the data before where clause and do district filtering on client side(app). But in this if there are 2000 users in each state. I would have to load that much data.
2) To do onetime fetch for whatever user clicks and then show them same list. I will make separate list for all fetches.

I am really confused upon this. Any insight would be helpful.

答:
Keep in mind that it caches recently read documents locally, and won't charge you again if future queries are read form that cache. I'd recommend running some tests with addSnapshotListener and monitoring the usage that it generates. It may be a lot less tan you imagined, and at the very least you'll have more concrete data to validate/dispel your concerns.

If you're worried still about the pricing of Cloud Firestore, I recommend doing some back-of-a-napkin calculations of realistic scenarios. I highly recommend comparing Cloud Firestore with an alternative like the Realtime Database in that case. Most cloud-based databases come with a fairly unique pricing model, and only you can decide what combination of features and price work for your app.

Body:
I have feed like the image in my app. I am getting list of some documents from firetsore collection and I am populating them in List and then use it in recycler view to show details of user.

When feed is clicked, I want to show ditrict3 and district4 data. Like below:

 collectionRef = FirebaseFirestore.getInstance().collection("male");
 collectionRef.whereIn("district", Arrays.asList("district3", "district4"))
              .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                                if (task.isSuccessful()) {
                                    List<FilterDetails> filterDetailsList = new ArrayList<>();
                                    for (DocumentSnapshot document : task.getResult()) {
                                        FilterDetails filterDetails = document.toObject(FilterDetails.class);
                                        filterDetailsList.add(filterDetails);
                                        getParentActivity().hideLoading();
                                    }
                                    feedItemAdapter.updateData(filterDetailsList);
                                }
                            }
                        });

When district1 will be clicked I will change whereEqualTo("district", "district1") and for different selection I will change.

User can change this more frequently and if I will do one time fetch then its going to cost me very much. But If I will use realtime snapshot then data will be read again and again if other users will change their info. Solutions I thought,
1) To get all the data before where clause and do district filtering on client side(app). But in this if there are 2000 users in each state. I would have to load that much data.
2) To do onetime fetch for whatever user clicks and then show them same list. I will make separate list for all fetches.

I am really confused upon this. Any insight would be helpful.


问:
Why Double::compareTo can be used as an argument of Stream.max(Comparator<? super T> comparator)
The api for Stream.max requires an argument of type Comparator<? super T>, and for Comparator, the only abstract method is

```<code>int compare(T o1, T o2)
</code>```

but Double::compareTo, the compareTo api is

```<code>public int compareTo(Double anotherDouble)
</code>```

why just provide one argument, so why can Double::compareTo use as argument of Stream

```<code>Optional<T> max(Comparator<? super T> comparator)
</code>```

答:
Check out the oracle documentation. This is a reference to an instance method. This means, it can be considered as BiFunction, that takes the instance as the first argument.

In Java Language Specification (15.13.3) we can read, that:

If the form is ReferenceType :: [TypeArguments] Identifier, the body of the invocation method similarly has the effect of a method invocation expression for a compile-time declaration which is the compile-time declaration of the method reference expression. Run-time evaluation of the method invocation expression is as specified in §15.12.4.3, §15.12.4.4, and §15.12.4.5, where:

The invocation mode is derived from the compile-time declaration as specified in §15.12.3.

If the compile-time declaration is an instance method, then the target reference is the first formal parameter of the invocation method. Otherwise, there is no target reference.

If the compile-time declaration is an instance method, then the arguments to the method invocation expression (if any) are the second and subsequent formal parameters of the invocation method. Otherwise, the arguments to the method invocation expression are the formal parameters of the invocation method.

The interesting part is bolded by me.

Body:
The api for Stream.max requires an argument of type Comparator<? super T>, and for Comparator, the only abstract method is

int compare(T o1, T o2)

but Double::compareTo, the compareTo api is

public int compareTo(Double anotherDouble)

why just provide one argument, so why can Double::compareTo use as argument of Stream

Optional<T> max(Comparator<? super T> comparator)


问:
How to set a value for pack.windowMemory?
I am trying to limit the amount of memory that git gc --aggressive is using. I set pack.windowMemory to 8 GB to do that:

```<code>git config --global pack.windowMemory 8g
</code>```

The config file now correctly shows:

```<code>[pack]
    windowMemory = 8g
</code>```

The documentation shows that this should work.

But git gc produces an error:

$ git gc --aggressive

fatal: bad numeric config value '8g' for 'pack.windowmemory': out of range

fatal: failed to run repack

How can I set pack.windowMemory?

答:
pack.windowmemory is a ulong.

maximum_unsigned_value_of_type(long) is 232 (32-bit) = 4,294,967,296 ≈ 4 billion.

g suffix is 1,073,741,824.
8 × 1,073,741,824 = 8,589,934,592 ≈ 8 billion.

You need to choose a value at most around 4 GB.

Body:
I am trying to limit the amount of memory that git gc --aggressive is using. I set pack.windowMemory to 8 GB to do that:

git config --global pack.windowMemory 8g

The config file now correctly shows:

[pack]
    windowMemory = 8g

The documentation shows that this should work.

But git gc produces an error:

$ git gc --aggressive

fatal: bad numeric config value '8g' for 'pack.windowmemory': out of range

fatal: failed to run repack

How can I set pack.windowMemory?


问:
java design problem for validations
I have the following requirement:
I have a validation system.  One of the things that I need to do is perform validations on XML files, meaning validating that tag X equals a given value.  I have more than one possible scenario, and in each scenario there is a different set of tags that need to be validated.

I don't want to repeat same code when testing same tags in different scenarios.

I'm trying to figure out a design that will solve this issue.

Any ideas?

Thanks.

答:
One approach would be to parse the XML into an object and then validate it in accordance with Bean Validation spec (JSR 303).  Hibernate Validator is the reference implementation.*  You can annotate your properties with validation constraints, and then specify validation groups so that certain fields get validated in certain scenarios.

There is more info here and here.

*Hibernate Validator is different from Hibernate ORM. They're only related in that Hibernate ORM uses Validator for its constraint checking.

Title: java design problem for validations


问:
How to create dynamic select option chantiers ouvrages in laravel?
I have two selects, the 1st filled by ouvrages and other by chantiers there is between them belongsTo relation, I want when I choose chantier in 1st select the 2nd filled by ouvrages corresponds, but in my case it gives me empty data.

mois.blade.php

```<code>//select chantiers
<select class="form-control" id="chantier_id">
  <option selected disabled>Select Location</option>
    @foreach($chantiers as $chantier)
  <option value="{{ $chantier->id }}">{{ $chantier->chantier}}</option>
    @endforeach
</select>
//select ouvrages
<select class="form-control" id="ouvrage_id">
   <option value="0" selected disabled>- Select -</option>
</select>
</code>```

jQuery

```<code> <script type="text/javascript">
       $(document).ready(function() {
    $('#example').DataTable();
                                  });
        $(document).ready(function(){

            $("#chantier_id").change(function(){
                var chantier = $(this).val();

                $.ajax({
                    url: "{{ route('salarie.select') }}",
                    type: 'post',
                    data: {
                          chantier:chantier,
                          "_token": "{{ csrf_token() }}"
                           },
                    dataType: 'json',
                    success:function(response){
                       console.log(response);
                        var len = response.length;
                        $("#ouvrage_id").empty();
                        for( var i = 0; i<len; i++){
                            var id = response[i]['id'];
                            var ouvrage = response[i]['ouvrage'];
                            $("#ouvrage_id").append("<option value='"+id+"'>"+ouvrage+"</option>");
                        }
                    }
                });
            });
        });
    </script>
</code>```

SalarieController.php

```<code>  public function select(request $request){
      $ouvrages = Ouvrage::where('chantier_id',$request->chantier_id);
        return response()->json(['options'=>$ouvrages]);
    }
</code>```

web.php

```<code>Route::post('/select','SalarieController@select')->name('salarie.select');
Route::get('/mois','SalarieController@mois');
</code>```

答:
You need jQuery.parse(response) to parse json

and change loop to $.each to make it easy and less complex.

```<code> <script type="text/javascript">
   $(document).ready(function() {
     $('#example').DataTable();

        $("#chantier_id").change(function(){
            var chantier = $(this).val();

            $.ajax({
                url: "{{ route('salarie.select') }}",
                type: 'post',
                data: {
                      chantier:chantier,
                      "_token": "{{ csrf_token() }}"
                       },
                dataType: 'json',
                success:function(response){
                   console.log(jQuery.parse(response));
                    $("#ouvrage_id").empty();
                    $.each( jQuery.parse(response), function( key, value ) {
                      $("#ouvrage_id").append("<option value='"+key+"'>"+value+"</option>");
                     });

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

Body:
I have two selects, the 1st filled by ouvrages and other by chantiers there is between them belongsTo relation, I want when I choose chantier in 1st select the 2nd filled by ouvrages corresponds, but in my case it gives me empty data.

mois.blade.php

//select chantiers
<select class="form-control" id="chantier_id">
  <option selected disabled>Select Location</option>
    @foreach($chantiers as $chantier)
  <option value="{{ $chantier->id }}">{{ $chantier->chantier}}</option>
    @endforeach
</select>
//select ouvrages
<select class="form-control" id="ouvrage_id">
   <option value="0" selected disabled>- Select -</option>
</select>

jQuery

SalarieController.php

  public function select(request $request){
      $ouvrages = Ouvrage::where('chantier_id',$request->chantier_id);
        return response()->json(['options'=>$ouvrages]);
    }

web.php

Route::post('/select','SalarieController@select')->name('salarie.select');
Route::get('/mois','SalarieController@mois');

Body:
You need jQuery.parse(response) to parse json

and change loop to $.each to make it easy and less complex.

 <script type="text/javascript">
   $(document).ready(function() {
     $('#example').DataTable();

        $("#chantier_id").change(function(){
            var chantier = $(this).val();

            $.ajax({
                url: "{{ route('salarie.select') }}",
                type: 'post',
                data: {
                      chantier:chantier,
                      "_token": "{{ csrf_token() }}"
                       },
                dataType: 'json',
                success:function(response){
                   console.log(jQuery.parse(response));
                    $("#ouvrage_id").empty();
                    $.each( jQuery.parse(response), function( key, value ) {
                      $("#ouvrage_id").append("<option value='"+key+"'>"+value+"</option>");
                     });

                }
            });
        });
    });
</script>


问:
How to set cursor position in EditText?
There are two EditText,while loading the page a text is set in the first EditText, So now cursor will be in the starting place of EditText, I want to set cursor position in the second EditText which contains no data. How to do this?

答:
```<code>if(myEditText.isSelected){
    myEditText.setSelection(myEditText.length())
    }
</code>```

Title: How to set cursor position in EditText?


问:
Does java.net.Socket detect client timeouts?
I'm using Scala with java.net.Socket and java.net.ServerSocket.

I want to detect when a socket connection with a client is disconnected/timed out.

I've implemented my own detection like this, which works:

```<code>var break = false
var startTime = System.currentTimeMillis()
while(!break){
  if(inputstream.ready()){
    //...parse input
    startTime = System.currentTimeMillis()
  }else if(System.currentTimeMillis() - startTime >= 5000){
    break = true
  }
}
socket.close()
</code>```

So my implementation closes the socket when a message hasn't been received from the client for 5000ms.

But I wonder whether there is something in the library that I can use to detect the timeout instead.

If a client turns off their program or their Internet connection terminates etc, is there something on the Network Layer, Transport Layer, or otherwise, that somehow my server can know immediately through the library (java.net.Socket)?

Is an Exception thrown immediately or is there some timeout detection feature?

答:
You may try socket.setSOTimeout(5000).
In this case, an exception java.io.InterruptedIOException will be thrown if a read on the input stream takes more than 5 seconds.

Body:
I'm using Scala with java.net.Socket and java.net.ServerSocket.

I want to detect when a socket connection with a client is disconnected/timed out.

I've implemented my own detection like this, which works:

var break = false
var startTime = System.currentTimeMillis()
while(!break){
  if(inputstream.ready()){
    //...parse input
    startTime = System.currentTimeMillis()
  }else if(System.currentTimeMillis() - startTime >= 5000){
    break = true
  }
}
socket.close()

So my implementation closes the socket when a message hasn't been received from the client for 5000ms.

But I wonder whether there is something in the library that I can use to detect the timeout instead.

If a client turns off their program or their Internet connection terminates etc, is there something on the Network Layer, Transport Layer, or otherwise, that somehow my server can know immediately through the library (java.net.Socket)?

Is an Exception thrown immediately or is there some timeout detection feature?


问:
Get a list of maximum values per tuple from a list of tuples
I'm just getting into Python, and having some trouble understanding the control flow and iteration logic.

I am trying to create a function which takes a list of tuples, and I want to return a new list with the maximum element per tuple.

I know I'm missing putting the maximum element into a new list, but first I am trying to get that maximum value.

```<code>def max_element_per_tuple(tuple_list):
    maximum = tuple_list[0]

    for item in tuple_list:
        if item > maximum:
            maximum = item

    return maximum

# test it
tuple_list = [(-1,0,1), (10,20,30), (100,50,25), (55,75,65)]
print(max_element_per_tuple(tuple_list))
</code>```

This returns: (100, 50, 25)

Want returned: (1, 30, 100, 75)

Or if a list (?), then: [1, 30, 100, 75]

答:
Right now you are just looping through the tuples and returning the "biggest" one - tuple comparison is done element-wise.

What you want is to add another loop level that will find the maximum of each tuple:

def max_element_per_tuple(tuple_list):
    res = []

    for tup in tuple_list:      # loops over the tuples in the list
        maximum = tup[0]
        for item in tup:        # loops over each item of the tuple
            if item > maximum:
                maximum = item
        res.append(maximum)

    return res
```

<p>This gives as expected:</p>

```>>> max_element_per_tuple([(-1, 0, 1), (10, 20, 30), (100, 50, 25), (55, 75, 65)])
[1, 30, 100, 75]
```

Body:
I'm just getting into Python, and having some trouble understanding the control flow and iteration logic.

I am trying to create a function which takes a list of tuples, and I want to return a new list with the maximum element per tuple.

I know I'm missing putting the maximum element into a new list, but first I am trying to get that maximum value.

def max_element_per_tuple(tuple_list):
    maximum = tuple_list[0]

    for item in tuple_list:
        if item > maximum:
            maximum = item

    return maximum

# test it
tuple_list = [(-1,0,1), (10,20,30), (100,50,25), (55,75,65)]
print(max_element_per_tuple(tuple_list))

This returns: (100, 50, 25)

Want returned: (1, 30, 100, 75)

Or if a list (?), then: [1, 30, 100, 75]

Body:
Right now you are just looping through the tuples and returning the "biggest" one - tuple comparison is done element-wise.

What you want is to add another loop level that will find the maximum of each tuple:

def max_element_per_tuple(tuple_list):
    res = []

    for tup in tuple_list:      # loops over the tuples in the list
        maximum = tup[0]
        for item in tup:        # loops over each item of the tuple
            if item > maximum:
                maximum = item
        res.append(maximum)

    return res

This gives as expected:

>>> max_element_per_tuple([(-1, 0, 1), (10, 20, 30), (100, 50, 25), (55, 75, 65)])
[1, 30, 100, 75]


问:
Use JS to add browser version to  or  as class
I'm trying to find a tried and tested script that sniffs the browser version and adds a suitably named class to the  or the  tags... like  or  or .

I don't mind if it's "firefox4" or "ff4" or "firefox_4"... just as long as I can use the class to scope my css.

I could write a script to do this myself but I was wondering if there was a widely used one out there...

Thanks.

答:
For IE, you can use conditional comments like how HTML5 Boilerplate does it. For the others, there are some deprecated methods in jQuery that you can exploit to determine what browser and browser version they're using, namely jQuery.browser.

And of course, as others are mentioning, you can use Modernizr, although I don't think it does sniffing of browser type and version exactly how you want. I'm pretty sure it just does feature detection.


问:
Quill toolbar is not rendering (icon paths are displayed instead of being rendered)
I'm trying to run native Quill in React. I follow quill's quickstart but unfortunately there is a problem with toolbar rendering (see below). Icon paths are displayed instead of being rendered. Please give me same directions :)

Quill component:

```<code>import Quill from 'quill/core';
import Toolbar from 'quill/modules/toolbar';
import Snow from 'quill/themes/snow';
import Bold from 'quill/formats/bold';
import Italic from 'quill/formats/italic';
import React, { Component, Fragment } from 'react';
import Header from 'quill/formats/header';

Quill.register({
  'modules/toolbar': Toolbar,
  'themes/snow': Snow,
});

class MyQuill extends Component {

  constructor(props) {
    super(props);
  }

  componentDidMount(props) {
    var quill = new Quill('#editor', {
      theme: 'snow'
    });
  }

  render() {
    return (
      <div id="editor">
        <p>Hello World!</p>
        <p>Some initial <strong>bold</strong> text</p>
      </div>
    );
  }
}
export default MyQuill;
</code>```

答:
Finally I was able to fix it (see below). Pity that such a great tool has so poor documentation.

Change from:

import Quill from 'quill/core';

to

import Quill from 'quill/dist/quill.js';

and from:

```<code>Quill.register({
  'themes/snow': Snow,
});
</code>```

to

```<code>Quill.register({
  'themes/snow.js': Snow,
});
</code>```

Body:
I'm trying to run native Quill in React. I follow quill's quickstart but unfortunately there is a problem with toolbar rendering (see below). Icon paths are displayed instead of being rendered. Please give me same directions :)

Quill component:

import Quill from 'quill/core';
import Toolbar from 'quill/modules/toolbar';
import Snow from 'quill/themes/snow';
import Bold from 'quill/formats/bold';
import Italic from 'quill/formats/italic';
import React, { Component, Fragment } from 'react';
import Header from 'quill/formats/header';

Quill.register({
  'modules/toolbar': Toolbar,
  'themes/snow': Snow,
});

class MyQuill extends Component {

  constructor(props) {
    super(props);
  }

  componentDidMount(props) {
    var quill = new Quill('#editor', {
      theme: 'snow'
    });
  }

  render() {
    return (

Hello World!

Some initial bold text

    );
  }
}
export default MyQuill;

Body:
Finally I was able to fix it (see below). Pity that such a great tool has so poor documentation.

Change from:

import Quill from 'quill/core';

to

import Quill from 'quill/dist/quill.js';

and from:

Quill.register({
  'themes/snow': Snow,
});

to

Quill.register({
  'themes/snow.js': Snow,
});


问:
IQueryable<object> LINQ Expression threw 'System.Object' to type 'Anonymous type'
I wrote linq query to get data and store in IQueryable<object>. After that I want to perform Linq Expression to remove some null data.

```<code>  IQueryable<object> employees;

    select new
         {
              temp.EMP_NO,
              personal.EMP_NAME,
              hptrx.TRX_CD,
              trx.TRX_DESC,
              CURRENT_MONTH = hptrx.AMOUNT,
              PREVIOUS_MONTH = db.HPTRXes.Where(x => x.COMP_CD == temp.COMP_CD && x.EMP_NO == temp.EMP_NO &&
                               x.TRX_CD == hptrx.TRX_CD && x.P_MTH == previousMonth && x.P_YEAR ==
                               previousYear && x.P_PERIOD == record.P_PERIOD).Select(x => x.AMOUNT).FirstOrDefault()
         });
</code>```

Below code will be executed to filter out PREVIOUS_MONTH contains null.

```<code> var propertyPreviousMonth = "PREVIOUS_MONTH";
 var sourceType = typeof(object);
 var underlyingType = employees.First().GetType();
 var propertyType = underlyingType.GetProperty(propertyPreviousMonth).PropertyType;
 var param = Expression.Parameter(sourceType);

 var left = Expression.Property(
      Expression.Convert(param, underlyingType), propertyPreviousMonth
 );
 Expression right = Expression.Constant(null);
 Expression e1 = Expression.NotEqual(left, right);
 var lambda = Expression.Lambda(e1, param);

 var expr = Expression.Call(typeof(Queryable), "Where", new Type[] { sourceType },
     employees.Expression, lambda
 );
 employees = employees.Provider.CreateQuery<object>(expr);
</code>```

However, I'm getting below error when call employees.Count()

Unable to cast the type 'System.Object' to type 'Anonymous type'. LINQ
  to Entities only supports casting EDM primitive or enumeration types.

答:
Just a suggestion, you could try:</p>

```<code>let prevMonth = db.HPTRXes.Where(x => x.COMP_CD == temp.COMP_CD && x.EMP_NO == temp.EMP_NO &&
                           x.TRX_CD == hptrx.TRX_CD && x.P_MTH == previousMonth && x.P_YEAR ==
                           previousYear && x.P_PERIOD == record.P_PERIOD).FirstOrDefault()
where prevMonth != null
select new
     {
          temp.EMP_NO,
          personal.EMP_NAME,
          hptrx.TRX_CD,
          trx.TRX_DESC,
          CURRENT_MONTH = hptrx.AMOUNT,
          PREVIOUS_MONTH = prevMonth.AMOUNT
     });
</code>```

Body:
I wrote linq query to get data and store in IQueryable<object>. After that I want to perform Linq Expression to remove some null data.

  IQueryable<object> employees;

    select new
         {
              temp.EMP_NO,
              personal.EMP_NAME,
              hptrx.TRX_CD,
              trx.TRX_DESC,
              CURRENT_MONTH = hptrx.AMOUNT,
              PREVIOUS_MONTH = db.HPTRXes.Where(x => x.COMP_CD == temp.COMP_CD && x.EMP_NO == temp.EMP_NO &&
                               x.TRX_CD == hptrx.TRX_CD && x.P_MTH == previousMonth && x.P_YEAR ==
                               previousYear && x.P_PERIOD == record.P_PERIOD).Select(x => x.AMOUNT).FirstOrDefault()
         });

Below code will be executed to filter out PREVIOUS_MONTH contains null.

 var propertyPreviousMonth = "PREVIOUS_MONTH";
 var sourceType = typeof(object);
 var underlyingType = employees.First().GetType();
 var propertyType = underlyingType.GetProperty(propertyPreviousMonth).PropertyType;
 var param = Expression.Parameter(sourceType);

 var left = Expression.Property(
      Expression.Convert(param, underlyingType), propertyPreviousMonth
 );
 Expression right = Expression.Constant(null);
 Expression e1 = Expression.NotEqual(left, right);
 var lambda = Expression.Lambda(e1, param);

 var expr = Expression.Call(typeof(Queryable), "Where", new Type[] { sourceType },
     employees.Expression, lambda
 );
 employees = employees.Provider.CreateQuery<object>(expr);

However, I'm getting below error when call employees.Count()

Unable to cast the type 'System.Object' to type 'Anonymous type'. LINQ
  to Entities only supports casting EDM primitive or enumeration types.

Body:
Just a suggestion, you could try:

let prevMonth = db.HPTRXes.Where(x => x.COMP_CD == temp.COMP_CD && x.EMP_NO == temp.EMP_NO &&
                           x.TRX_CD == hptrx.TRX_CD && x.P_MTH == previousMonth && x.P_YEAR ==
                           previousYear && x.P_PERIOD == record.P_PERIOD).FirstOrDefault()
where prevMonth != null
select new
     {
          temp.EMP_NO,
          personal.EMP_NAME,
          hptrx.TRX_CD,
          trx.TRX_DESC,
          CURRENT_MONTH = hptrx.AMOUNT,
          PREVIOUS_MONTH = prevMonth.AMOUNT
     });


问:
No NSEntityDescriptions in any model claim the NSManagedObject subclass 'PriorityList.Entry' so +entity is confused
i'm new to CoreData and i'm trying to store an entry of a todo list. When i try to creat a new Entry, it would crash. My entity name is "Entry", i selected "Extension" for codegen, but i didn't add any code to the subclass of Entry. what went wrong here? Thank you for helping!

```<code>    let container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer

func editOrAdd()
{
    if entry?.title != nil {
        ifNew = false   //edit entry
        updateUI()
    } else {
        ifNew = true    //new entry
        print(ifNew)

        if let context = container?.viewContext {
            let newEntry = Entry(context: context)  //crashed here
            newEntry.creatTime = Date()
            try? context.save()
            //test
            print("new entry creatTime: \(formatter((entry?.creatTime!)!))")
        }
    }
}
</code>```

the complete log below

2020-02-14 23:06:43.471370+0800 PriorityList[8876:698237] [error] error: No
      NSEntityDescriptions in any model claim the NSManagedObject subclass 'PriorityList.Entry' so
      +entity is confused.  Have you loaded your NSManagedObjectModel yet ?

2020-02-14 23:06:43.475084+0800 PriorityList[8876:698237] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'PriorityList.Entry' must have a valid NSEntityDescription.'

答:
after watching more tutorials and totally rebuilding my whole project the problem is solved.

i changed syntax of

```<code>let newEntry = Entry(context: context)  //crashed here
</code>```

to

```<code>let newItem = NSEntityDescription.insertNewObject(forEntityName: "Item", into: context) as! Item
</code>```

not sure what the problems are but it did worked.

Body:
i'm new to CoreData and i'm trying to store an entry of a todo list. When i try to creat a new Entry, it would crash. My entity name is "Entry", i selected "Extension" for codegen, but i didn't add any code to the subclass of Entry. what went wrong here? Thank you for helping!

    let container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer

func editOrAdd()
{
    if entry?.title != nil {
        ifNew = false   //edit entry
        updateUI()
    } else {
        ifNew = true    //new entry
        print(ifNew)

        if let context = container?.viewContext {
            let newEntry = Entry(context: context)  //crashed here
            newEntry.creatTime = Date()
            try? context.save()
            //test
            print("new entry creatTime: \(formatter((entry?.creatTime!)!))")
        }
    }
}

the complete log below

2020-02-14 23:06:43.471370+0800 PriorityList[8876:698237] [error] error: No
      NSEntityDescriptions in any model claim the NSManagedObject subclass 'PriorityList.Entry' so
      +entity is confused.  Have you loaded your NSManagedObjectModel yet ?

2020-02-14 23:06:43.475084+0800 PriorityList[8876:698237] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'PriorityList.Entry' must have a valid NSEntityDescription.'

Body:
after watching more tutorials and totally rebuilding my whole project the problem is solved.

i changed syntax of

let newEntry = Entry(context: context)  //crashed here

to

let newItem = NSEntityDescription.insertNewObject(forEntityName: "Item", into: context) as! Item

not sure what the problems are but it did worked.


问:
Why are exceptions, that are caught in the UI automation client, appearing in the UI being automated?
A little background...

I am developing a UI automation app that randomly interacts with controls on our UI. Both the app and the UI being automated are WPF applications. I am using the UI Automation accessibility framework. Occasionally I get an ElementNotAvailableException in my app which I catch and handle. When profiling our UI using ANTS 7, I have noticed these exceptions are showing up on the Gen 2 garbage heap. The new instances of the exception match the number of times I caught the exception in my app.

I have looked at the GCRoot using WinDBG, the UIAutomation pages, and I have not found a clear explanation as to why a caught exception is appearing in the app being automated. The objects are not released when the UI is being automated and even remain when I close my automation app.

Any ideas?

答:
Without knowing exactly how it is implemented, we can know that in order for UI automation to do what it does it needs to do:

instrumentation, and

interprocess communication

The instrumentation part consists of infrastructure that is literally compiled into all of the classes in the UI framework or added to the framework, hooked if you will.  It "infects" the host application and runs a mini-application inside it.

The interprocess communication part is needed to pass non-graphical information between the client and the host such as the actual contents of a text box.  This sounds simple but invokes literally injecting and exchanging types and values between the two processes.

Now when you combine these two things, an exception could be exchanged as part of interprocess communication and that exception could be held as a reference by the mini-application that is the automation framework, and you have a speculative explanation for how it could happen.

In your case, if you are curious enough, or motivated enough (perhaps by a bug), you could keep drilling into this issue with various tools.  You have the debugger, ILSpy, black-box experiments, heap tools, etc.  It's up to you how far you need to go.


问:
Get multiples of 10 and add the number
Guys i want to round the given numbers to the nearest multiple of 10. e.g. 15 should be rounded to 20 whereas 14 should be rounded to 10. After rounding the numbers, i want to find their sum.

Sample input is like (a list):
[2, 18, 10]

Sample output:
30

Sample 2:

[10, 20, 1, 1]

Output :
30

答:
Using NumPy:

```<code>import numpy as np

numbers = [1,10,20,1]
np.around(numbers, decimals=-1).sum()
</code>```

gives 30.

Title: Get multiples of 10 and add the number

Body:
Using NumPy:

import numpy as np

numbers = [1,10,20,1]
np.around(numbers, decimals=-1).sum()

gives 30.


问:
Pandas return rows with matching substring to string
I have a dataframe where i want to check for every row if one column of substring is contained in another column of string. If a character in Subposition column exists in the string of Position column, return True, other wise return False in the Check column. (L = left, R = Right , S = straight, U = u turn)</p>

```<code> Position   Subposition  Check
   L           R         False
   L           L         True
   LR          L         True
   SRU         L         False
</code>```

答:
You can zip the 2 columns and check if the second row is in the first via a list comprehension which should be pretty fast:

```<code>df['Check' ] = [b in a for a,b in zip(df['Position'],df['Subposition'])]
print(df)
</code>```

```<code>  Position Subposition  Check
0        L           R  False
1        L           L   True
2       LR           L   True
3      SRU           L  False
</code>```

Body:
I have a dataframe where i want to check for every row if one column of substring is contained in another column of string. If a character in Subposition column exists in the string of Position column, return True, other wise return False in the Check column. (L = left, R = Right , S = straight, U = u turn)

 Position   Subposition  Check
   L           R         False
   L           L         True
   LR          L         True
   SRU         L         False

Body:
You can zip the 2 columns and check if the second row is in the first via a list comprehension which should be pretty fast:

df['Check' ] = [b in a for a,b in zip(df['Position'],df['Subposition'])]
print(df)

  Position Subposition  Check
0        L           R  False
1        L           L   True
2       LR           L   True
3      SRU           L  False


问:
C++ card validation issue
I'm a bit of a coding noob and I'm trying to get a simple Luhn algorithm to do a credit card validation check. I've got this far and I can't quite see what's wrong with the way I've done it, but the answer is always true.

If anyone can help, I'd be really grateful.

```<code>#include <iostream>
#include <cstring>
using namespace std;

bool validate(char card_number[]);

int main(int argc, char *argv[])
{
   cout << validate(argv[1]) << endl;
   return 0;
}

bool validate(char card_number[])
{
   bool valid = false;
   int length = 0;
   int step_1 = 0;
   int step_2 = 0;
   int result = 0;

   while (card_number[length] != '\0') {
       length++;
   }

   for (int i = card_number[0]; i < card_number[length]; i++) {

       if (( i % 2 != 0 && i != 0)) {

           int temp = card_number[i] - '0';

           if((temp / 10) >= 1) {
               step_1 = step_1 + (temp / 10) + (temp % 10);
           } else {

               step_1 = step_1 + temp;
           }
       } else {

           step_2 = step_2 + card_number[i] - '0';
       }
   }
   result = step_1 + step_2;

   if (result % 10 == 0) {
       valid = true;
   }

   return valid;
}

</code>```

答:
As someone else said in the comments, you have to loop through array indexes, not array elements.

Also, according to Luhn's algorithm, your condition if((temp / 10) >= 1) is wrong (will never be met) since temp is a digit and it can never be higher than 9. What you have to do instead is validate that the double of the digit (temp) is higher or equal to 10.

Title: C++ card validation issue

Body:
I'm a bit of a coding noob and I'm trying to get a simple Luhn algorithm to do a credit card validation check. I've got this far and I can't quite see what's wrong with the way I've done it, but the answer is always true.

If anyone can help, I'd be really grateful.

#include <iostream>
#include <cstring>
using namespace std;

bool validate(char card_number[]);

int main(int argc, char *argv[])
{
   cout << validate(argv[1]) << endl;
   return 0;
}

bool validate(char card_number[])
{
   bool valid = false;
   int length = 0;
   int step_1 = 0;
   int step_2 = 0;
   int result = 0;

   while (card_number[length] != '\0') {
       length++;
   }

   for (int i = card_number[0]; i < card_number[length]; i++) {

       if (( i % 2 != 0 && i != 0)) {

           int temp = card_number[i] - '0';

           if((temp / 10) >= 1) {
               step_1 = step_1 + (temp / 10) + (temp % 10);
           } else {

               step_1 = step_1 + temp;
           }
       } else {

           step_2 = step_2 + card_number[i] - '0';
       }
   }
   result = step_1 + step_2;

   if (result % 10 == 0) {
       valid = true;
   }

   return valid;
}


问:
Unable to pass prop back to parent component
I'm doing a simple test where I have a name state in the parent component which I update when a button in the child is clicked. But this does not work, and I'm confused on if I'm doing something wrong.

Parent:

```<code>import React from "react";
import "./styles.css";
import Hello from "./Hello";

export default function App() {
  const [name, setName] = React.useState();

  const handle = item => {
    setName(item);
  };

  console.log(name);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Hello test={handle} />
      {name}
    </div>
  );
}

</code>```

Child:

```<code>import React from "react";

export default function App() {
  return (
    <div>
      <button onclick={() => this.props.test("TEST")}>Activate Lasers</button>
    </div>
  );
}
</code>```

What am I doing wrong?

答:
Pass the function as a prop.

```<code>import React from "react";

export default function App({ handle }) {
  return (
    <div>
      <button onClick={() => handle('TEST')}>Activate Lasers</button>
    </div>
  );
}
</code>```

and render the component like

```<code><Hello handle={handle} />
</code>```

// Get a hook function
const {useState} = React;

function Hello({ handle }) {
  return (

      <button onClick={() => handle('TEST')}>Activate Lasers</button>

  );
}

function App() {
  const [name, setName] = React.useState();

  const handle = item => {
    setName(item);
  };

  return (

Hello CodeSandbox

Start editing to see some magic happen!

      <Hello handle={handle} />
      {name}

  );
}

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div></code>```

Body:
I'm doing a simple test where I have a name state in the parent component which I update when a button in the child is clicked. But this does not work, and I'm confused on if I'm doing something wrong.

Parent:

import React from "react";
import "./styles.css";
import Hello from "./Hello";

export default function App() {
  const [name, setName] = React.useState();

  const handle = item => {
    setName(item);
  };

  console.log(name);

  return (

Hello CodeSandbox

Start editing to see some magic happen!

      <Hello test={handle} />
      {name}

  );
}

Child:

import React from "react";

export default function App() {
  return (

      <button onclick={() => this.props.test("TEST")}>Activate Lasers</button>

  );
}

What am I doing wrong?

Body:
Pass the function as a prop.

import React from "react";

export default function App({ handle }) {
  return (
    <div>
      <button onClick={() => handle('TEST')}>Activate Lasers</button>
    </div>
  );
}

and render the component like

<Hello handle={handle} />

// Get a hook function
const {useState} = React;

function Hello({ handle }) {
  return (
    <div>
      <button onClick={() => handle('TEST')}>Activate Lasers</button>
    </div>
  );
}

function App() {
  const [name, setName] = React.useState();

  const handle = item => {
    setName(item);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Hello handle={handle} />
      {name}
    </div>
  );
}

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>


问:
React, Material UI, Select, disableScrollLock, make menu position relative to anchor
```<code>import React from "react";
import "./styles.css";

import Input from "@material-ui/core/Input";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const names = [
  "Oliver Hansen",
  "Van Henry",
  "April Tucker",
  "Ralph Hubbard",
  "Omar Alexander",
  "Carlos Abbott",
  "Miriam Wagner",
  "Bradley Wilkerson",
  "Virginia Andrews",
  "Kelly Snyder"
];

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250
    }
  },
  disableScrollLock: true
};

export default function App() {
  const [personName, setPersonName] = React.useState([]);

  const handleChange = event => {
    setPersonName(event.target.value);
  };

  return (
    <div className="App" style={{ height: "1000px" }}>
      <FormControl>
        <Select
          labelId="demo-mutiple-name-label"
          id="demo-mutiple-name"
          multiple
          value={personName}
          onChange={handleChange}
          input={<Input />}
          MenuProps={MenuProps}
        >
          {names.map(name => (
            <MenuItem key={name} value={name}>
              {name}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}
</code>```

The codes can be found here as well https://codesandbox.io/s/awesome-leaf-ooko1

I am using React 16, latest Material UI core, Material UI Select Component

What I am trying to do here is when I open the drop down menu (with disableScrollLock=true), when I scroll the window, the drop down menu will be relative to the anchor element not fixed on window. How can I achieve that?

答:
I'm not acquainted with React but I've managed to find a working example with a different component.

See this answer: https://stackoverflow.com/a/54011607/152016

Coder used a ReportComboBox instead of a Select, but he tackled another problem of your snippet: growing selection size.

When in your snippet you select a lot of items, there is a UI problem.

Enough digressing, I've changed the answers' snippet to enable scrolling (by setting body { height: 3000px; } for instance, and you can see that the scrolling keeps the select box in its place: https://codesandbox.io/s/react-select-ellipsis-one-row-example-k62hy

Hope this is enough for solving the problem or at least a clue to it.

Body:
import React from "react";
import "./styles.css";

import Input from "@material-ui/core/Input";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const names = [
  "Oliver Hansen",
  "Van Henry",
  "April Tucker",
  "Ralph Hubbard",
  "Omar Alexander",
  "Carlos Abbott",
  "Miriam Wagner",
  "Bradley Wilkerson",
  "Virginia Andrews",
  "Kelly Snyder"
];

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250
    }
  },
  disableScrollLock: true
};

export default function App() {
  const [personName, setPersonName] = React.useState([]);

  const handleChange = event => {
    setPersonName(event.target.value);
  };

  return (

      <FormControl>
        <Select
          labelId="demo-mutiple-name-label"
          id="demo-mutiple-name"
          multiple
          value={personName}
          onChange={handleChange}
          input={<Input />}
          MenuProps={MenuProps}
        >
          {names.map(name => (
            <MenuItem key={name} value={name}>
              {name}
            </MenuItem>
          ))}
        </Select>
      </FormControl>

  );
}

The codes can be found here as well https://codesandbox.io/s/awesome-leaf-ooko1

I am using React 16, latest Material UI core, Material UI Select Component

What I am trying to do here is when I open the drop down menu (with disableScrollLock=true), when I scroll the window, the drop down menu will be relative to the anchor element not fixed on window. How can I achieve that?


问:
Why does my transform: translate not work on both axes?
My transform: translate(10px 10px) does not work. When I only put in the value for the x-axis, it works. Also when I use translateX and translateY they do work, but just not both. So I can only translate the images on one axis but never on both. Any ideas?

.gallery {
  text-align: center;
}

.gallery img {
  position: relative;
  width: 30%;
  height: calculate(width*66%);
  margin: 10px;
  animation-name: blendin;
  animation-duration: 3s;
  transition: ease-in-out all 300ms;
}

.gallery img:hover {
  box-shadow: 10px 10px 10px black;
  transform: translate(10px 10px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="gallery">
  <img src="elbe.jpg" alt="Elbe">
  <img src="tisch.jpg" alt="Tisch">
  <img src="spiegelung.jpg" alt="Spiegelung">
</div></code>```

答:
translate need a coma in css. So it's not:

transform: translate(10px 10px);
```

<p>but:</p>

<pre class="lang-css prettyprint-override"><code>transform: translate(10px, 10px);
</code>```

.gallery {
  text-align: center;
}

.gallery img {
  position: relative;
  width: 30%;
  height: calculate(width*66%);
  margin: 10px;
  animation-name: blendin;
  animation-duration: 3s;
  transition: ease-in-out all 300ms;
}

.gallery img:hover {
  box-shadow: 10px 10px 10px black;
  transform: translate(10px, 10px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="gallery">
  <img src="elbe.jpg" alt="Elbe">
  <img src="tisch.jpg" alt="Tisch">
  <img src="spiegelung.jpg" alt="Spiegelung">
</div></code>```

Body:
translate need a coma in css. So it's not:

transform: translate(10px 10px);

but:

transform: translate(10px, 10px);

.gallery {
  text-align: center;
}

.gallery img {
  position: relative;
  width: 30%;
  height: calculate(width*66%);
  margin: 10px;
  animation-name: blendin;
  animation-duration: 3s;
  transition: ease-in-out all 300ms;
}

.gallery img:hover {
  box-shadow: 10px 10px 10px black;
  transform: translate(10px, 10px);
}

<div class="gallery">
  <img src="elbe.jpg" alt="Elbe">
  <img src="tisch.jpg" alt="Tisch">
  <img src="spiegelung.jpg" alt="Spiegelung">
</div>


问:
How to replace all vowels in a string with a char?
Can someone elucidate a method that will swap all vowel occurrences in a string with the char 'i'.

For a user input of "Hello world!", "Hilli wirld!" should be returned.

Method below can only remove vowels, rather than replacing them with a chosen char. I do not want to use string replace. I must take a more laborious route of manipulating the array.

```<code>function withoutVowels(string) {

  var withoutVowels = "";
  for (var i = 0; i < string.length; i++) {
      if (!isVowel(string[i])) {
        withoutVowels += string[i];
      }
    }
    return withoutVowels;
}

function isVowel(char) {
  return 'aeiou'.includes(char);
}

console.log(withoutVowels('Hello World!'));
</code>```

答:
You can simply add an else statement to your existing logic. Better rename the function too.

function replaceVowels(string) {

  var withoutVowels = "";
  const replacement = "i";
  for (var i = 0; i < string.length; i++) {
      if (!isVowel(string[i])) {
        withoutVowels += string[i];
      } else {
        withoutVowels += replacement;
      }
    }
    return withoutVowels;
}

function isVowel(char) {
  return 'aeiou'.includes(char);
}

console.log(replaceVowels('Hello World!'));```

Body:
Can someone elucidate a method that will swap all vowel occurrences in a string with the char 'i'.

For a user input of "Hello world!", "Hilli wirld!" should be returned.

Method below can only remove vowels, rather than replacing them with a chosen char. I do not want to use string replace. I must take a more laborious route of manipulating the array.

function withoutVowels(string) {

  var withoutVowels = "";
  for (var i = 0; i < string.length; i++) {
      if (!isVowel(string[i])) {
        withoutVowels += string[i];
      }
    }
    return withoutVowels;
}

function isVowel(char) {
  return 'aeiou'.includes(char);
}

console.log(withoutVowels('Hello World!'));


问:
In spring are all the beans created at the time of container creation
If I have 1000 bean configurations in .xml file are all these beans created at the time of creation of the container</p>

答: By default yes. All beans get created on startup. There's the @Lazy annotation which allows you to delay the initialization until the bean gets used.


问:
What benefits does React suspense have?
I know React suspense is new and hasn't been officially released for production yet but I was wondering what the main benefits of it are/or using it would be?

I can't see anything it does as being "new" or replacing something that doesn't already exist?

I know it allows me to load stuff from top to bottom but I can do that anyway in react using my own components

can anyone give me some ideas as to what it may be good for?

答:
it has several benefits to use:

it makes code splitting easy

(with new usecase) it makes data fetching so easy! Read this

it just suspends your component rendering and renders a fallback component until your component makes itself ready to show, by that you can create a skeleton flow for your async components so easily event with a simple UI ( imagine instead of created a loading login by useState Api or something else )

these were just simple benefits of Reacts Suspense/lazy api.

Title: What benefits does React suspense have?


答:
Without using string replace, but with RegExp :)

function withoutVowels(string, replaceWith) {
  return string.split(/[aeiou]/).join(replaceWith)
}

console.log(withoutVowels('Hello World!', 'i'));```

Title: How to replace all vowels in a string with a char?