问:
Yield Request call produce weird result in recursive method with scrapy
I'm trying to scrap all departures and arrivals in one day from all airports in all country using Python and Scrapy.

The JSON database used by this famous site (flight radar) need to query page by page when departure or arrival is > 100 in one airport. I also compute a timestamp based on an actual day UTC for the query.

I try to create a database with this hierarchy:

```<code>country 1
 - airport 1
    - departures
      - page 1
      - page ...
    - arrivals
      - page 1
      - page ...
- airport 2
    - departures
      - page 1
      - page ...
    - arrivals
      - page
      - page ...
...
</code>```

I use two methods to compute timestamp and url query by page :

```<code>def compute_timestamp(self):
    from datetime import datetime, date
    import calendar
    # +/- 24 heures
    d = date(2017, 4, 27)
    timestamp = calendar.timegm(d.timetuple())
    return timestamp

def build_api_call(self,code,page,timestamp):
    return 'https://api.flightradar24.com/common/v1/airport.json?code={code}&plugin\[\]=&plugin-setting\[schedule\]\[mode\]=&plugin-setting\[schedule\]\[timestamp\]={timestamp}&page={page}&limit=100&token='.format(
        code=code, page=page, timestamp=timestamp)
</code>```

I store result into CountryItem, which contain lots of AirportItem into airports. My item.py is :

```<code>class CountryItem(scrapy.Item):
    name = scrapy.Field()
    link = scrapy.Field()
    num_airports = scrapy.Field()
    airports = scrapy.Field()
    other_url= scrapy.Field()
    last_updated = scrapy.Field(serializer=str)

class AirportItem(scrapy.Item):
    name = scrapy.Field()
    code_little = scrapy.Field()
    code_total = scrapy.Field()
    lat = scrapy.Field()
    lon = scrapy.Field()
    link = scrapy.Field()
    departures = scrapy.Field()
    arrivals = scrapy.Field()
</code>```

My main parse builds a Country item for all countries (i limit here to Israel for example). Next, I yield for each country a scrapy.Request to scrape airports.

```<code>###################################
# MAIN PARSE
####################################
def parse(self, response):
    count_country = 0
    countries = []
    for country in response.xpath('//a[@data-country]'):
        item = CountryItem()
        url =  country.xpath('./@href').extract()
        name = country.xpath('./@title').extract()
        item['link'] = url[0]
        item['name'] = name[0]
        item['airports'] = []
        count_country += 1
        if name[0] == "Israel":
            countries.append(item)
            self.logger.info("Country name : %s with link %s" , item['name'] , item['link'])
            yield scrapy.Request(url[0],meta={'my_country_item':item}, callback=self.parse_airports)
</code>```

This method scrape information for each airport, and also call for each airport a scrapy.request with airport url to scrape departures and arrivals :

```<code>  ###################################
# PARSE EACH AIRPORT
####################################
def parse_airports(self, response):
    item = response.meta['my_country_item']
    item['airports'] = []

    for airport in response.xpath('//a[@data-iata]'):
        url = airport.xpath('./@href').extract()
        iata = airport.xpath('./@data-iata').extract()
        iatabis = airport.xpath('./small/text()').extract()
        name = ''.join(airport.xpath('./text()').extract()).strip()
        lat = airport.xpath("./@data-lat").extract()
        lon = airport.xpath("./@data-lon").extract()
        iAirport = AirportItem()
        iAirport['name'] = self.clean_html(name)
        iAirport['link'] = url[0]
        iAirport['lat'] = lat[0]
        iAirport['lon'] = lon[0]
        iAirport['code_little'] = iata[0]
        iAirport['code_total'] = iatabis[0]

        item['airports'].append(iAirport)

    urls = []
    for airport in item['airports']:
        json_url = self.build_api_call(airport['code_little'], 1, self.compute_timestamp())
        urls.append(json_url)
    if not urls:
        return item

    # start with first url
    next_url = urls.pop()
    return scrapy.Request(next_url, self.parse_schedule, meta={'airport_item': item, 'airport_urls': urls, 'i': 0})
</code>```

With the recursive method parse_schedule i add each airport to country item. SO members already help me on this point.

```<code>###################################
# PARSE EACH AIRPORT OF COUNTRY
###################################
def parse_schedule(self, response):
        """we want to loop this continuously to build every departure and arrivals requests"""
        item = response.meta['airport_item']
        i = response.meta['i']
        urls = response.meta['airport_urls']

        urls_departures, urls_arrivals = self.compute_urls_by_page(response, item['airports'][i]['name'], item['airports'][i]['code_little'])

        print("urls_departures = ", len(urls_departures))
        print("urls_arrivals = ", len(urls_arrivals))

        ## YIELD NOT CALLED
        yield scrapy.Request(response.url, self.parse_departures_page, meta={'airport_item': item, 'page_urls': urls_departures, 'i':0 , 'p': 0}, dont_filter=True)

        # now do next schedule items
        if not urls:
            yield item
            return
        url = urls.pop()

        yield scrapy.Request(url, self.parse_schedule, meta={'airport_item': item, 'airport_urls': urls, 'i': i + 1})
</code>```

the self.compute_urls_by_page method compute correct URLs to retrieve all departure and arrivals for one airport.

```<code>###################################
# PARSE EACH DEPARTURES / ARRIVALS
###################################
def parse_departures_page(self, response):
    item = response.meta['airport_item']
    p = response.meta['p']
    i = response.meta['i']
    page_urls = response.meta['page_urls']

    print("PAGE URL = ", page_urls)

    if not page_urls:
        yield item
        return
    page_url = page_urls.pop()

    print("GET PAGE FOR  ", item['airports'][i]['name'], ">> ", p)

    jsonload = json.loads(response.body_as_unicode())
    json_expression = jmespath.compile("result.response.airport.pluginData.schedule.departures.data")
    item['airports'][i]['departures'] = json_expression.search(jsonload)

    yield scrapy.Request(page_url, self.parse_departures_page, meta={'airport_item': item, 'page_urls': page_urls, 'i': i, 'p': p + 1})
</code>```

Next, the first yield in parse_schedule which normally call self.parse_departure_page recursive method produces weird results. Scrapy call this method, but I collect the departures page for only one airport i don't understand why... I have probably an ordering error in my request or yield source code, so perhaps you could help me to find out.

The complete code is on GitHub https://github.com/IDEES-Rouen/Flight-Scrapping/tree/master/flight/flight_project

You could run it using scrapy cawl airports commands.

Update 1 :

I try to answer the question alone using yield from, without success as you can see answer bottom ... so if you have an idea?

答:
Yes, i finally found the answer here on SO ...

When you use a recursive yield, you need to use yield from. Here one example simplified :

```<code>airport_list = ["airport1", "airport2", "airport3", "airport4"]

def parse_page_departure(airport, next_url, page_urls):

    print(airport, " / ", next_url)

    if not page_urls:
        return

    next_url = page_urls.pop()

    yield from parse_page_departure(airport, next_url, page_urls)

###################################
# PARSE EACH AIRPORT OF COUNTRY
###################################
def parse_schedule(next_airport, airport_list):

    ## GET EACH DEPARTURE PAGE

    departures_list = ["p1", "p2", "p3", "p4"]

    next_departure_url = departures_list.pop()
    yield parse_page_departure(next_airport,next_departure_url, departures_list)

    if not airport_list:
        print("no new airport")
        return

    next_airport_url = airport_list.pop()

    yield from parse_schedule(next_airport_url, airport_list)

next_airport_url = airport_list.pop()
result = parse_schedule(next_airport_url, airport_list)

for i in result:
    print(i)
    for d in i:
        print(d)
</code>```

UPDATE, Don't WORK with real program :

I try to reproduce the same yield from pattern with the real program here, but i have an error using it on scrapy.Request, don't understand why...

Here the python traceback :

```<code>Traceback (most recent call last):
  File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/utils/defer.py", line 102, in iter_errback
    yield next(it)
  File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/offsite.py", line 29, in process_spider_output
    for x in result:
  File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/referer.py", line 339, in <genexpr>
    return (_set_referer(r) for r in result or ())
  File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/urllength.py", line 37, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/depth.py", line 58, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/home/reyman/Projets/Flight-Scrapping/flight/flight_project/spiders/AirportsSpider.py", line 209, in parse_schedule
    yield from scrapy.Request(url, self.parse_schedule, meta={'airport_item': item, 'airport_urls': urls, 'i': i + 1})
TypeError: 'Request' object is not iterable
2017-06-27 17:40:50 [scrapy.core.engine] INFO: Closing spider (finished)
2017-06-27 17:40:50 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
</code>```

Body:
I'm trying to scrap all departures and arrivals in one day from all airports in all country using Python and Scrapy.

The JSON database used by this famous site (flight radar) need to query page by page when departure or arrival is > 100 in one airport. I also compute a timestamp based on an actual day UTC for the query.

I try to create a database with this hierarchy:

country 1
 - airport 1
    - departures
      - page 1
      - page ...
    - arrivals
      - page 1
      - page ...
- airport 2
    - departures
      - page 1
      - page ...
    - arrivals
      - page
      - page ...
...

I use two methods to compute timestamp and url query by page :

def compute_timestamp(self):
    from datetime import datetime, date
    import calendar
    # +/- 24 heures
    d = date(2017, 4, 27)
    timestamp = calendar.timegm(d.timetuple())
    return timestamp

def build_api_call(self,code,page,timestamp):
    return 'https://api.flightradar24.com/common/v1/airport.json?code={code}&plugin\[\]=&plugin-setting\[schedule\]\[mode\]=&plugin-setting\[schedule\]\[timestamp\]={timestamp}&page={page}&limit=100&token='.format(
        code=code, page=page, timestamp=timestamp)

I store result into CountryItem, which contain lots of AirportItem into airports. My item.py is :

class CountryItem(scrapy.Item):
    name = scrapy.Field()
    link = scrapy.Field()
    num_airports = scrapy.Field()
    airports = scrapy.Field()
    other_url= scrapy.Field()
    last_updated = scrapy.Field(serializer=str)

class AirportItem(scrapy.Item):
    name = scrapy.Field()
    code_little = scrapy.Field()
    code_total = scrapy.Field()
    lat = scrapy.Field()
    lon = scrapy.Field()
    link = scrapy.Field()
    departures = scrapy.Field()
    arrivals = scrapy.Field()

My main parse builds a Country item for all countries (i limit here to Israel for example). Next, I yield for each country a scrapy.Request to scrape airports.

###################################
# MAIN PARSE
####################################
def parse(self, response):
    count_country = 0
    countries = []
    for country in response.xpath('//a[@data-country]'):
        item = CountryItem()
        url =  country.xpath('./@href').extract()
        name = country.xpath('./@title').extract()
        item['link'] = url[0]
        item['name'] = name[0]
        item['airports'] = []
        count_country += 1
        if name[0] == "Israel":
            countries.append(item)
            self.logger.info("Country name : %s with link %s" , item['name'] , item['link'])
            yield scrapy.Request(url[0],meta={'my_country_item':item}, callback=self.parse_airports)

This method scrape information for each airport, and also call for each airport a scrapy.request with airport url to scrape departures and arrivals :

  ###################################
# PARSE EACH AIRPORT
####################################
def parse_airports(self, response):
    item = response.meta['my_country_item']
    item['airports'] = []

    for airport in response.xpath('//a[@data-iata]'):
        url = airport.xpath('./@href').extract()
        iata = airport.xpath('./@data-iata').extract()
        iatabis = airport.xpath('./small/text()').extract()
        name = ''.join(airport.xpath('./text()').extract()).strip()
        lat = airport.xpath("./@data-lat").extract()
        lon = airport.xpath("./@data-lon").extract()
        iAirport = AirportItem()
        iAirport['name'] = self.clean_html(name)
        iAirport['link'] = url[0]
        iAirport['lat'] = lat[0]
        iAirport['lon'] = lon[0]
        iAirport['code_little'] = iata[0]
        iAirport['code_total'] = iatabis[0]

        item['airports'].append(iAirport)

    urls = []
    for airport in item['airports']:
        json_url = self.build_api_call(airport['code_little'], 1, self.compute_timestamp())
        urls.append(json_url)
    if not urls:
        return item

    # start with first url
    next_url = urls.pop()
    return scrapy.Request(next_url, self.parse_schedule, meta={'airport_item': item, 'airport_urls': urls, 'i': 0})

With the recursive method parse_schedule i add each airport to country item. SO members already help me on this point.

###################################
# PARSE EACH AIRPORT OF COUNTRY
###################################
def parse_schedule(self, response):
        """we want to loop this continuously to build every departure and arrivals requests"""
        item = response.meta['airport_item']
        i = response.meta['i']
        urls = response.meta['airport_urls']

        urls_departures, urls_arrivals = self.compute_urls_by_page(response, item['airports'][i]['name'], item['airports'][i]['code_little'])

        print("urls_departures = ", len(urls_departures))
        print("urls_arrivals = ", len(urls_arrivals))

        ## YIELD NOT CALLED
        yield scrapy.Request(response.url, self.parse_departures_page, meta={'airport_item': item, 'page_urls': urls_departures, 'i':0 , 'p': 0}, dont_filter=True)

        # now do next schedule items
        if not urls:
            yield item
            return
        url = urls.pop()

        yield scrapy.Request(url, self.parse_schedule, meta={'airport_item': item, 'airport_urls': urls, 'i': i + 1})

the self.compute_urls_by_page method compute correct URLs to retrieve all departure and arrivals for one airport.

###################################
# PARSE EACH DEPARTURES / ARRIVALS
###################################
def parse_departures_page(self, response):
    item = response.meta['airport_item']
    p = response.meta['p']
    i = response.meta['i']
    page_urls = response.meta['page_urls']

    print("PAGE URL = ", page_urls)

    if not page_urls:
        yield item
        return
    page_url = page_urls.pop()

    print("GET PAGE FOR  ", item['airports'][i]['name'], ">> ", p)

    jsonload = json.loads(response.body_as_unicode())
    json_expression = jmespath.compile("result.response.airport.pluginData.schedule.departures.data")
    item['airports'][i]['departures'] = json_expression.search(jsonload)

    yield scrapy.Request(page_url, self.parse_departures_page, meta={'airport_item': item, 'page_urls': page_urls, 'i': i, 'p': p + 1})

Next, the first yield in parse_schedule which normally call self.parse_departure_page recursive method produces weird results. Scrapy call this method, but I collect the departures page for only one airport i don't understand why... I have probably an ordering error in my request or yield source code, so perhaps you could help me to find out.

The complete code is on GitHub https://github.com/IDEES-Rouen/Flight-Scrapping/tree/master/flight/flight_project

You could run it using scrapy cawl airports commands.

Update 1 :

I try to answer the question alone using yield from, without success as you can see answer bottom ... so if you have an idea?

Body:
Yes, i finally found the answer here on SO ...

When you use a recursive yield, you need to use yield from. Here one example simplified :

airport_list = ["airport1", "airport2", "airport3", "airport4"]

def parse_page_departure(airport, next_url, page_urls):

    print(airport, " / ", next_url)

    if not page_urls:
        return

    next_url = page_urls.pop()

    yield from parse_page_departure(airport, next_url, page_urls)

###################################
# PARSE EACH AIRPORT OF COUNTRY
###################################
def parse_schedule(next_airport, airport_list):

    ## GET EACH DEPARTURE PAGE

    departures_list = ["p1", "p2", "p3", "p4"]

    next_departure_url = departures_list.pop()
    yield parse_page_departure(next_airport,next_departure_url, departures_list)

    if not airport_list:
        print("no new airport")
        return

    next_airport_url = airport_list.pop()

    yield from parse_schedule(next_airport_url, airport_list)

next_airport_url = airport_list.pop()
result = parse_schedule(next_airport_url, airport_list)

for i in result:
    print(i)
    for d in i:
        print(d)

UPDATE, Don't WORK with real program :

I try to reproduce the same yield from pattern with the real program here, but i have an error using it on scrapy.Request, don't understand why...

Here the python traceback :

Traceback (most recent call last):
  File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/utils/defer.py", line 102, in iter_errback
    yield next(it)
  File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/offsite.py", line 29, in process_spider_output
    for x in result:
  File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/referer.py", line 339, in <genexpr>
    return (_set_referer(r) for r in result or ())
  File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/urllength.py", line 37, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/depth.py", line 58, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/home/reyman/Projets/Flight-Scrapping/flight/flight_project/spiders/AirportsSpider.py", line 209, in parse_schedule
    yield from scrapy.Request(url, self.parse_schedule, meta={'airport_item': item, 'airport_urls': urls, 'i': i + 1})
TypeError: 'Request' object is not iterable
2017-06-27 17:40:50 [scrapy.core.engine] INFO: Closing spider (finished)
2017-06-27 17:40:50 [scrapy.statscollectors] INFO: Dumping Scrapy stats:


来源: stackexchange

问:
How do I set up a 'long poll' using Bluemix Message Hub in NodeJS
This question is related to why do I need to poll message hub, The documentation linked with that answer shows that Kafka will support a 'long-poll' concept, but there is no clear way in the existing nodejs support for message-hub to implement such a mechanism. The demo app provided for nodejs just uses a 250mSec timer interval to handle retrieving messages from the server. I'd like to replace that with a more sophisticated long-poll approach using the Kafka support long-poll approach:
To avoid this we have parameters in our pull request that allow the consumer request to block in a "long poll" waiting until data arrives
However the existing implementation does not appear to allow for configuring any such kind of parameter, nor is it clear what the necessary parameter would be. The prototype for the get function is defined as:

```<code>MessageHub.ConsumerInstance.prototype.get(topicName [toValue])

Retrieves a message from the provided topic name.

    topicName - (String) (required), the topic to retrieve messages from.
    toValue - (Boolean) (optional), unwraps base64 encoded messages, if true. Defaults to true.

Returns a Promise object which will be fulfilled when the request to the service resolves.
</code>```

so no config options. Alternately, could you provide a link the documentation which defines the URLs and available options for those URLs which are implemented in the message-hub.js module?

答:
that one you're mentioning is an npm module built on top of the REST API that Message Hub provides  -
 which is essentially the Confluent REST Proxy API minus the AVRO support
http://docs.confluent.io/2.0.1/kafka-rest/docs/api.html

That npm is not offering you a full Kafka api. It is offering just a subset of the REST API

The long poll which the the Kafka doc refer to is the timeout in the Java Consumer poll
https://kafka.apache.org/0102/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html#poll(long)

A good client for Node.js is
https://github.com/Blizzard/node-rdkafka

Please see our coding sample in
https://github.com/ibm-messaging/message-hub-samples

ContentLicense: CC BY-SA 3.0

Body:
This question is related to why do I need to poll message hub, The documentation linked with that answer shows that Kafka will support a 'long-poll' concept, but there is no clear way in the existing nodejs support for message-hub to implement such a mechanism. The demo app provided for nodejs just uses a 250mSec timer interval to handle retrieving messages from the server. I'd like to replace that with a more sophisticated long-poll approach using the Kafka support long-poll approach:
To avoid this we have parameters in our pull request that allow the consumer request to block in a "long poll" waiting until data arrives
However the existing implementation does not appear to allow for configuring any such kind of parameter, nor is it clear what the necessary parameter would be. The prototype for the get function is defined as:

MessageHub.ConsumerInstance.prototype.get(topicName [toValue])

Retrieves a message from the provided topic name.

    topicName - (String) (required), the topic to retrieve messages from.
    toValue - (Boolean) (optional), unwraps base64 encoded messages, if true. Defaults to true.

Returns a Promise object which will be fulfilled when the request to the service resolves.

so no config options. Alternately, could you provide a link the documentation which defines the URLs and available options for those URLs which are implemented in the message-hub.js module?


问:
Android - How to properly parse string to float (price number format: integer, decimals or both)
I'm trying to parse an input string from the user and convert it into a Float

```<code>String[] inputs = {
      "100",
            "100.0",
            "100.00",
            "100.00000",
            "100.1",
            "100.10",
            "100.11",
            "100.111",
            "1.0",
            "0.1",
            "0.10",
            "0.1000",
            "0.111",
            "100,00",
            "1,000.15"
    };

    for (String input : inputs) {
        try {
            input = input.replace(",", ".");
            Float value = Float.valueOf(input);

            if (value == 0F) {
                Log.d("APP", "--> NOPE: " + value);
                continue;
            }

            String oldInput = input;

            DecimalFormat dc = new DecimalFormat(value > 1F ? "#.00" : "#0.00");
            input = dc.format(value);
            value = Float.valueOf(input);

            Log.d("APP", oldInput + " -> " + value);
        }
        catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
</code>```

Which gives me the following outputs:

```<code>100         -> 100.0
100.0       -> 100.0
100.00      -> 100.0
100.0000    -> 100.0
100.1       -> 100.1
100.10      -> 100.1
100.11      -> 100.11
100.111     -> 100.11
1.0         -> 1.0
0.1         -> 0.1
0.10        -> 0.1
0.1000      -> 0.1
0.111       -> 0.11
100,00      -> 100.0
</code>```

The problem appears when I get an input string like this:

```<code>1,000.25
</code>```

A java.lang.NumberFormatException: multiple points exception is thrown

Is 1,000.25 a valid input? (Currency from US?)

Is there a better or much more optimized way of parsing the input?

答:
Try this:</p>

```<code>float result = Float.parseFloat(string.replaceAll(",", ""));
</code>```

Body:
I'm trying to parse an input string from the user and convert it into a Float

String[] inputs = {
      "100",
            "100.0",
            "100.00",
            "100.00000",
            "100.1",
            "100.10",
            "100.11",
            "100.111",
            "1.0",
            "0.1",
            "0.10",
            "0.1000",
            "0.111",
            "100,00",
            "1,000.15"
    };

    for (String input : inputs) {
        try {
            input = input.replace(",", ".");
            Float value = Float.valueOf(input);

            if (value == 0F) {
                Log.d("APP", "--> NOPE: " + value);
                continue;
            }

            String oldInput = input;

            DecimalFormat dc = new DecimalFormat(value > 1F ? "#.00" : "#0.00");
            input = dc.format(value);
            value = Float.valueOf(input);

            Log.d("APP", oldInput + " -> " + value);
        }
        catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

Which gives me the following outputs:

100         -> 100.0
100.0       -> 100.0
100.00      -> 100.0
100.0000    -> 100.0
100.1       -> 100.1
100.10      -> 100.1
100.11      -> 100.11
100.111     -> 100.11
1.0         -> 1.0
0.1         -> 0.1
0.10        -> 0.1
0.1000      -> 0.1
0.111       -> 0.11
100,00      -> 100.0

The problem appears when I get an input string like this:

1,000.25

A java.lang.NumberFormatException: multiple points exception is thrown

Is 1,000.25 a valid input? (Currency from US?)

Is there a better or much more optimized way of parsing the input?

Body:
Try this:

float result = Float.parseFloat(string.replaceAll(",", ""));


问:
Android Firebase Authentication Google getGender
I am using Firebase Google SignIn in my Android application and I want to check the gender of every user, as the application is only for the females to use !!

Currently work is like this

```<code>// Initialize Firebase Auth
        mFirebaseAuth = FirebaseAuth.getInstance();
        mFirebaseUser = mFirebaseAuth.getCurrentUser();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
                if (mFirebaseUser == null) {
                    startActivity(new Intent(getApplicationContext(), SignActivity.class));
                    finish();
                    return;
                } else {
                    if (mFirebaseUser.getPhotoUrl() != null) {
                        Glide.with(HomeActivity.this)
                                .load(mFirebaseUser.getPhotoUrl().toString())
                                .asBitmap()
                                .into(new SimpleTarget<Bitmap>(100,100) {
                                    @Override
                                    public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
                                        bitmap = resource;
                                    }
                                });
                    }
                }
            }
        };

        // Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this ,this)
                .addApi(Auth.GOOGLE_SIGN_IN_API , gso)
                .build();
</code>```

答:
Unfortunately, Firebase doesn't have any built-in functionality to get the user's gender from your mFirebaseUser object. You would have to retrieve these data from each of the providers yourself.

Take a look at this post, to see how can the gender be extracted.

And also, take a look at Accessing Google APIs.

Body:
I am using Firebase Google SignIn in my Android application and I want to check the gender of every user, as the application is only for the females to use !!

Currently work is like this

// Initialize Firebase Auth
        mFirebaseAuth = FirebaseAuth.getInstance();
        mFirebaseUser = mFirebaseAuth.getCurrentUser();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
                if (mFirebaseUser == null) {
                    startActivity(new Intent(getApplicationContext(), SignActivity.class));
                    finish();
                    return;
                } else {
                    if (mFirebaseUser.getPhotoUrl() != null) {
                        Glide.with(HomeActivity.this)
                                .load(mFirebaseUser.getPhotoUrl().toString())
                                .asBitmap()
                                .into(new SimpleTarget<Bitmap>(100,100) {
                                    @Override
                                    public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
                                        bitmap = resource;
                                    }
                                });
                    }
                }
            }
        };

        // Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this ,this)
                .addApi(Auth.GOOGLE_SIGN_IN_API , gso)
                .build();


问:
Sorting/Selecting Multiple Tables through One Column
My intention for this string of code is simply to be able to have 3 separate tables all being referenced at the same time, but to be able to select specific rows through a single column. Normally this would be easy. However, some of these columns have the same name, depending on the table.

Without joining these tables, how can I select rows with information from one or multiple columns with the same name?

Here is the code thus-far in terms of selecting one column that has a unique name (the names of the tables/columns have been changed for privacy purposes).

```<code>SELECT *
FROM  DBASE.APPLE_ORCHARD,
DBASE.ORANGE_FIELDS,
DBASE.CHERRY_BUSHES
WHERE ORANGES = '50';
</code>```

And now, what I would supposedly like to do.

```<code>SELECT *
FROM  DBASE.APPLE_ORCHARD,
DBASE.ORANGE_FIELDS,
DBASE.CHERRY_BUSHES
WHERE WATERING = '100';
</code>```

(the assumption being that each table has their own column named "WATERING")

I'm using Oracle SQL Developer for the purposes of this project

Data-Sample:

```<code>     Orange_Fields
COLUMNS -
Oranges
Watering
Insects
Intake

     Apple_Orchard
COLUMNS -
Apples
Watering
Insects
CO2
Intake

     Cherry_Bushes
COLUMNS -
Cherries
Watering
Insects
Temperature
Intake
</code>```

I have three tables with different columns. Some of the columns have the same name, whereas some of them do not.

How can I sort the information to receive a result such as this:

```<code>SELECT *
    FROM  DBASE.APPLE_ORCHARD,
    DBASE.ORANGE_FIELDS,
    DBASE.CHERRY_BUSHES
    WHERE Intake = '50';

Intake   Apples   Oranges   Cherries   Insects
50         32                             4
50         12                             3
50                             52         8
50         16                             12
50                   13                   0
50                             84         2
50                   18                   2
</code>```

The result I am receiving however, looks more like this.

```<code>SELECT *
    FROM  DBASE.APPLE_ORCHARD,
    DBASE.ORANGE_FIELDS,
    DBASE.CHERRY_BUSHES
    WHERE ORANGES = '50';

ORA-00918: column ambiguously defined
</code>```

答:
Since each table has nothing to relate them with the others, you have to create a separate select statement for each table and then put all your select statements together, I believe this is what @jarlh was referring to, try with something like this:</p>

```<code>SELECT *
FROM (
        SELECT  intake,
                apples,
                NULL AS oranges,
                NULL AS cherries,
                insects
        FROM  dbase.apple_orchard
        UNION ALL
        SELECT  intake,
                NULL AS apples,
                oranges,
                NULL AS cherries,
                insects
        FROM dbase.orange_fields
        UNION ALL
        SELECT intake,
               NULL AS apples,
               NULL AS oranges,
               cherries AS cherries,
               insects
        FROM dbase.cherry_bushes
) WHERE intake = '50'
ORDER BY insects;
</code>```

Body:
My intention for this string of code is simply to be able to have 3 separate tables all being referenced at the same time, but to be able to select specific rows through a single column. Normally this would be easy. However, some of these columns have the same name, depending on the table.

Without joining these tables, how can I select rows with information from one or multiple columns with the same name?

Here is the code thus-far in terms of selecting one column that has a unique name (the names of the tables/columns have been changed for privacy purposes).

SELECT *
FROM  DBASE.APPLE_ORCHARD,
DBASE.ORANGE_FIELDS,
DBASE.CHERRY_BUSHES
WHERE ORANGES = '50';

And now, what I would supposedly like to do.

SELECT *
FROM  DBASE.APPLE_ORCHARD,
DBASE.ORANGE_FIELDS,
DBASE.CHERRY_BUSHES
WHERE WATERING = '100';

(the assumption being that each table has their own column named "WATERING")

I'm using Oracle SQL Developer for the purposes of this project

Data-Sample:

     Orange_Fields
COLUMNS -
Oranges
Watering
Insects
Intake

     Apple_Orchard
COLUMNS -
Apples
Watering
Insects
CO2
Intake

     Cherry_Bushes
COLUMNS -
Cherries
Watering
Insects
Temperature
Intake

I have three tables with different columns. Some of the columns have the same name, whereas some of them do not.

How can I sort the information to receive a result such as this:

SELECT *
    FROM  DBASE.APPLE_ORCHARD,
    DBASE.ORANGE_FIELDS,
    DBASE.CHERRY_BUSHES
    WHERE Intake = '50';

Intake   Apples   Oranges   Cherries   Insects
50         32                             4
50         12                             3
50                             52         8
50         16                             12
50                   13                   0
50                             84         2
50                   18                   2

The result I am receiving however, looks more like this.

SELECT *
    FROM  DBASE.APPLE_ORCHARD,
    DBASE.ORANGE_FIELDS,
    DBASE.CHERRY_BUSHES
    WHERE ORANGES = '50';

ORA-00918: column ambiguously defined

Body:
Since each table has nothing to relate them with the others, you have to create a separate select statement for each table and then put all your select statements together, I believe this is what @jarlh was referring to, try with something like this:

SELECT *
FROM (
        SELECT  intake,
                apples,
                NULL AS oranges,
                NULL AS cherries,
                insects
        FROM  dbase.apple_orchard
        UNION ALL
        SELECT  intake,
                NULL AS apples,
                oranges,
                NULL AS cherries,
                insects
        FROM dbase.orange_fields
        UNION ALL
        SELECT intake,
               NULL AS apples,
               NULL AS oranges,
               cherries AS cherries,
               insects
        FROM dbase.cherry_bushes
) WHERE intake = '50'
ORDER BY insects;


问:
How can I know file size in grocery crud?
I need to know what it is the size of a file that I save in a folder with Grocery CRUD. This is what I did in  my controller:

```<code>$this->load->config('grocery_crud');
   $this->config->set_item('grocery_crud_file_upload_allow_file_types', 'pdf|rar|');
$this->crud->set_field_upload('fichero', 'assets/files');

 $this->crud->callback_after_insert(array($this, 'file_size'));
</code>```

and the other method

```<code>function file_size($post_array, $primary_key) {
    if ($primary_key == $post_array['id']) {
            $nombre_db = $post_array['fichero'];
            $nombre_fichero = 'assets/files'. $nombre_db;
            $filesize = filesize($nombre_fichero);
        }
        echo $filesize;
</code>```

my file is inside diferents folder, I do not know if this is a problem, I made an echo $filesize to see the value but do not show anithing, not  a value, not an error. Please help, thanks in advance.

[Additional Information]

The callback do not enter in the method, I put inside  function file_size an echo to see if show something or enter inside, but nothing, I do not know what its wrong with my callback funtion.

答:
I solved my problem, I was trying to solve it the wrong way, instead of making a callback, what I had to do was in the function that showed me all the results and then send them to the view, call a function that calculated the File size.

I leave my answer and the link from where I got it.

```<code>$url_file_update = 'assets/';
$file_name = $url_file_update . $query->row($i)->file; // file name
$weight_file = filesize($file_name); // we get the weight in bytes
$file_size = $this->file_size($weight_file);  //  show the modified weight
</code>```

the function file_size

```<code>function file_size($peso) {
  $decimales = 2;
  $clase = array(" Bytes", " KB", " MB", " GB", " TB");
  return round($peso / pow(1024, ($i = floor(log($peso, 1024)))), $decimales) . $clase[$i];
}
</code>```

link to the documentation that I found

Body:
I need to know what it is the size of a file that I save in a folder with Grocery CRUD. This is what I did in  my controller:

$this->load->config('grocery_crud');
   $this->config->set_item('grocery_crud_file_upload_allow_file_types', 'pdf|rar|');
$this->crud->set_field_upload('fichero', 'assets/files');

 $this->crud->callback_after_insert(array($this, 'file_size'));

and the other method

function file_size($post_array, $primary_key) {
    if ($primary_key == $post_array['id']) {
            $nombre_db = $post_array['fichero'];
            $nombre_fichero = 'assets/files'. $nombre_db;
            $filesize = filesize($nombre_fichero);
        }
        echo $filesize;

my file is inside diferents folder, I do not know if this is a problem, I made an echo $filesize to see the value but do not show anithing, not  a value, not an error. Please help, thanks in advance.

[Additional Information]

The callback do not enter in the method, I put inside  function file_size an echo to see if show something or enter inside, but nothing, I do not know what its wrong with my callback funtion.

Body:
I solved my problem, I was trying to solve it the wrong way, instead of making a callback, what I had to do was in the function that showed me all the results and then send them to the view, call a function that calculated the File size.

I leave my answer and the link from where I got it.

$url_file_update = 'assets/';
$file_name = $url_file_update . $query->row($i)->file; // file name
$weight_file = filesize($file_name); // we get the weight in bytes
$file_size = $this->file_size($weight_file);  //  show the modified weight

the function file_size

function file_size($peso) {
  $decimales = 2;
  $clase = array(" Bytes", " KB", " MB", " GB", " TB");
  return round($peso / pow(1024, ($i = floor(log($peso, 1024)))), $decimales) . $clase[$i];
}

link to the documentation that I found


问:
Adjust LocalTime according to ZoneId
Given a LocalTime in a given ZoneId, how can I find the adjusted LocalTime on UTC?

I am looking for something similar to .atZone from LocalDateTime, but couldn't find anything.

I suspect I can use it with atOffset, but I don't really understand how to use it.

So for example:

```<code>LocalTime: 15:00
ZoneId: America/Sao_Paulo (GMT -3)
Output: 18:00
</code>```

答:
You need to give a date too. In case the zone has summer time (DST), for example, this is needed to apply the correct offset (I don’t know whether São Paulo uses summer time, but Java requires a date always).

And still this takes one more step than what you might have expected, but it’s straightforward enough once you know how. For the case of demonstration I have assumed you meant 15:00 today, which you hardly did, but I trust you to fill in the desired date yourself.

```<code>    LocalTime time = LocalTime.of(15, 0);
    LocalTime utcTime = LocalDateTime.of(LocalDate.now(), time)
            .atZone(ZoneId.of("America/Sao_Paulo"))
            .withZoneSameInstant(ZoneOffset.UTC)
            .toLocalTime();
    System.out.println(utcTime);
</code>```

This prints the result you also asked for

```<code>18:00
</code>```

Title: Adjust LocalTime according to ZoneId

Body:
Given a LocalTime in a given ZoneId, how can I find the adjusted LocalTime on UTC?

I am looking for something similar to .atZone from LocalDateTime, but couldn't find anything.

I suspect I can use it with atOffset, but I don't really understand how to use it.

So for example:

LocalTime: 15:00
ZoneId: America/Sao_Paulo (GMT -3)
Output: 18:00

Body:
You need to give a date too. In case the zone has summer time (DST), for example, this is needed to apply the correct offset (I don’t know whether São Paulo uses summer time, but Java requires a date always).

And still this takes one more step than what you might have expected, but it’s straightforward enough once you know how. For the case of demonstration I have assumed you meant 15:00 today, which you hardly did, but I trust you to fill in the desired date yourself.

    LocalTime time = LocalTime.of(15, 0);
    LocalTime utcTime = LocalDateTime.of(LocalDate.now(), time)
            .atZone(ZoneId.of("America/Sao_Paulo"))
            .withZoneSameInstant(ZoneOffset.UTC)
            .toLocalTime();
    System.out.println(utcTime);

This prints the result you also asked for

18:00


问:
Matplotlib tkagg backend performance
I have a tkinter application that can plot a large number of data, where I have noticed poor pan and zoom performance when there is a large number of data on the canvas.

Looking into the tkagg_backend (as suggested by this and several other questions), the function and documentation suggests that the canvas should only be redrawn once the user is idle. However, from current and previous experience the canvas has always been updating(redrawing) mid zoom/pan. Therefore, I was looking at the specific functions that are involved and have a question regarding that.

The dynamic_update function:

```<code>def dynamic_update(self):
    'update drawing area only if idle'
    # legacy method; new method is canvas.draw_idle
    self.canvas.draw_idle()
</code>```

The canvas.draw_idle() function:

```<code>def draw_idle(self):
    'update drawing area only if idle'
    if self._idle is False:
        return

    self._idle = False

    def idle_draw(*args):
        try:
            self.draw()
        finally:
            self._idle = True

    self._idle_callback = self._tkcanvas.after_idle(idle_draw)
</code>```

The ._idle parameter is initialized as True in the backend. This point is where I got stuck as I am unable to understand how ._idle is linked to mouse activity (I assume that it is, please correct me if that's wrong).

Interestingly enough, the canvas behaves like I would expect by commenting the self.canvas.draw_idle() line (redrawing once the mouse button is unpressed), and thus not calling the entire draw_idle function.

Therefore, my question is how is _idle set or why does it redraw my entire canvas when I am not idle?

答:
When refering to "being idle" it is not the user or his mouse activity that is meant, but rather the GUI mainloop. The canvas should only be redrawn if the mainloop is not currently busy. Here, of course self._idle only refers to the matplotlib part of the GUI and what this structure inside draw_idle is supposed to do is to prevent the canvas from being drawn while it is being drawn.

This could easily happen when panning or zooming. The mouse moves to a new location, causing a readraw. While this redraw is happening, the mouse has already moved further and caused the next redraw. At that point in time the first redraw may not yet have finished, such that it would queue up. And so forth, such that at some point the GUI might become unresponsive. To prevent that, a new draw is only initialized once the previous one has finished and this behaviour is steered by self._idle being true or false.

Title: Matplotlib tkagg backend performance

Body:
I have a tkinter application that can plot a large number of data, where I have noticed poor pan and zoom performance when there is a large number of data on the canvas.

Looking into the tkagg_backend (as suggested by this and several other questions), the function and documentation suggests that the canvas should only be redrawn once the user is idle. However, from current and previous experience the canvas has always been updating(redrawing) mid zoom/pan. Therefore, I was looking at the specific functions that are involved and have a question regarding that.

The dynamic_update function:

def dynamic_update(self):
    'update drawing area only if idle'
    # legacy method; new method is canvas.draw_idle
    self.canvas.draw_idle()

The canvas.draw_idle() function:

def draw_idle(self):
    'update drawing area only if idle'
    if self._idle is False:
        return

    self._idle = False

    def idle_draw(*args):
        try:
            self.draw()
        finally:
            self._idle = True

    self._idle_callback = self._tkcanvas.after_idle(idle_draw)

The ._idle parameter is initialized as True in the backend. This point is where I got stuck as I am unable to understand how ._idle is linked to mouse activity (I assume that it is, please correct me if that's wrong).

Interestingly enough, the canvas behaves like I would expect by commenting the self.canvas.draw_idle() line (redrawing once the mouse button is unpressed), and thus not calling the entire draw_idle function.

Therefore, my question is how is _idle set or why does it redraw my entire canvas when I am not idle?


问:
Insert text at the beginning of every new line
I'm having an issue. I'm making a video transcription solution. When I hit Enter, I need to add a time flag — so that the user could type until they hit Enter again, but all I get is the time flag at the end of each line.

I appreciate any help.

Expected Result

```<code>[hh:mm:ss] my text
</code>```

Actual Result

```<code>my text [hh:mm:ss]
my new text
</code>```

Code

```<code>//if (!(start_element.hasAttribute('title'))) {
  start_element.setAttributes({
    'title': tim
  });

  var charCode = (evt.which) ? evt.which : event.keyCode;

  console.log(evt.data.keyCode);

  if (evt.data.keyCode == 13) {
    CKEDITOR.instances.editor1.insertHtml('[' + tim + ']');
  }
//}
</code>```

答:
The following code does not work here on Stack Overflow due to CKEditor using an IFrame which causes a cross-origin policy violation.

You can see a full working demo here on JSFiddle:

https://jsfiddle.net/MrPolywhirl/xy96htus/

You essentially need set a very small timeout that gets called after you press enter, before text should be inserted. For this example, I used 100 milliseconds. It works well for me.

I also tried to set the readonly for the editor to prevent typing. This does not seem to work. SO you need to trust that someone does not type really-fast after hitting enter. The issue is just that the insertHTML happens too quickly, before the line-feed is entered into the editor.

var $target = $('#modal');
var editorName = 'foobar';

clearEditorInstances();

// Add textarea to target div.
$target.append($('<form>').append($('<textarea>', {
  id: editorName,
  name: editorName
}))).hide();

// Setup editor.
$('textarea#' + editorName).ckeditor({
  height: 300,
  toolbarStartupExpanded: true,
  width: '100%',
  on: {
    instanceReady: function(e) {
      $target.show(); // Show editor, when ready.
      insertTime(this);
    },
    key: function(e) {
      if (e.data.keyCode == 13 /* Enter key */ ) {
        insertTime(this);
      }
    }
  }
});

function insertTime(editor) {
  editor.document.$.body.readonly = true;
  window.setTimeout(function() {
    var timestamp = moment().format('HH:mm:ss');
    var timeHtml = CKEDITOR.dom.element.createFromHtml('' + timestamp + ' ');
    editor.insertElement(timeHtml);
    editor.document.$.body.readonly = false;
  }, 100 /* Typing delay */ );
}

function clearEditorInstances() {
  for (name in CKEDITOR.instances) {
    CKEDITOR.instances[name].destroy();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#modal {
  position: absolute;
  left: 30px;
  top: 45px;
}</code>```

```

Body:
I'm having an issue. I'm making a video transcription solution. When I hit Enter, I need to add a time flag — so that the user could type until they hit Enter again, but all I get is the time flag at the end of each line.

I appreciate any help.

Expected Result

[hh:mm:ss] my text

Actual Result

my text [hh:mm:ss]
my new text

Code

//if (!(start_element.hasAttribute('title'))) {
  start_element.setAttributes({
    'title': tim
  });

  var charCode = (evt.which) ? evt.which : event.keyCode;

  console.log(evt.data.keyCode);

  if (evt.data.keyCode == 13) {
    CKEDITOR.instances.editor1.insertHtml('[' + tim + ']');
  }
//}

Body:
The following code does not work here on Stack Overflow due to CKEditor using an IFrame which causes a cross-origin policy violation.

You can see a full working demo here on JSFiddle:

https://jsfiddle.net/MrPolywhirl/xy96htus/

You essentially need set a very small timeout that gets called after you press enter, before text should be inserted. For this example, I used 100 milliseconds. It works well for me.

I also tried to set the readonly for the editor to prevent typing. This does not seem to work. SO you need to trust that someone does not type really-fast after hitting enter. The issue is just that the insertHTML happens too quickly, before the line-feed is entered into the editor.

var $target = $('#modal');
var editorName = 'foobar';

clearEditorInstances();

// Add textarea to target div.
$target.append($('<form>').append($('<textarea>', {
  id: editorName,
  name: editorName
}))).hide();

// Setup editor.
$('textarea#' + editorName).ckeditor({
  height: 300,
  toolbarStartupExpanded: true,
  width: '100%',
  on: {
    instanceReady: function(e) {
      $target.show(); // Show editor, when ready.
      insertTime(this);
    },
    key: function(e) {
      if (e.data.keyCode == 13 /* Enter key */ ) {
        insertTime(this);
      }
    }
  }
});

function insertTime(editor) {
  editor.document.$.body.readonly = true;
  window.setTimeout(function() {
    var timestamp = moment().format('HH:mm:ss');
    var timeHtml = CKEDITOR.dom.element.createFromHtml('<span>' + timestamp + ' </span>');
    editor.insertElement(timeHtml);
    editor.document.$.body.readonly = false;
  }, 100 /* Typing delay */ );
}

function clearEditorInstances() {
  for (name in CKEDITOR.instances) {
    CKEDITOR.instances[name].destroy();
  }
}

#modal {
  position: absolute;
  left: 30px;
  top: 45px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ckeditor/4.7.0/ckeditor.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ckeditor/4.7.0/adapters/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<div id="modal"></div>


问:
How to generate class diagram from models in EF Core?
We are building an application using ASP.NET MVC Core and Entity Framework Core and we have the whole bunch of classes in our application. In previous versions of Entity Framework, we would use this method for generating an edmx file for class diagram:

```<code>void ExportMappings(DbContext context, string edmxFile)
{
     var settings = new XmlWriterSettings { Indent = true };
     using (XmlWriter writer = XmlWriter.Create(edmxFile, settings))
     {
         System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(context, writer);
     }
}
</code>```

but it seems that there's no such feature in EF Core. I wonder if there's an equivalent version for doing this in Entity Framework Core.

答:
Why not use Visual Studio Class Designer instead?
You need to add it to your workspace with the Visual Studio Installer. On Visual Studio 2017 Installer you need to add it from the component list. See this article for more info.</p>

Body:
We are building an application using ASP.NET MVC Core and Entity Framework Core and we have the whole bunch of classes in our application. In previous versions of Entity Framework, we would use this method for generating an edmx file for class diagram:

void ExportMappings(DbContext context, string edmxFile)
{
     var settings = new XmlWriterSettings { Indent = true };
     using (XmlWriter writer = XmlWriter.Create(edmxFile, settings))
     {
         System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(context, writer);
     }
}

but it seems that there's no such feature in EF Core. I wonder if there's an equivalent version for doing this in Entity Framework Core.

ContentLicense: CC BY-SA 4.0


问:
How do I get the Index of a 2D Object Array?
I have a 2D button array (buttons) that will generate a 5 by 5 grid of buttons. I want to get the index of a single button (say, (2,2) in the center) when clicked, and find the index values of buttons surrounding the original button within a 3 x 3 radius by creating integer variables such as topcentre (which would be the index of buttons(x, y - 1) or 1,2, where x and y are the values of the clicked button.) I can then add text, etc. to those surrounding buttons.

Here's a visualization:

0,0|0,1|0,2|0,3|0,4

1,0|1,1|1,2|1,3|1,4

2,0|2,1|2,2|2,3|2,4

3,0|3,1|3,2|3,3|3,4

4,0|4,1|4,2|4,3|4,4

How can I do this?

答:
In the backend you could just use a single array.

0,0|0,1|0,2|0,3|0,4|1,0|1,1|1,2|1,3|1,4|2,0|2,1|2,2|2,3|2,4|3,0|3,1|3,2|3,3|3,4|4,0|4,1|4,2|4,3|4,4

Even if on the UI it's display as 2D.

2,2 would be index 12 ({x} * {width} + {y} = 2 * 5 + 2 = 12). To get the other index, you can substract or add.

Top Left = {index} - {width} - 1

Top = {index} - {width}

Top Right = {index} - {width} + 1

...


问:
how to exit from script if heredoc command is failing
I have a ssh heredoc in my shell script, if one of those commands in heredoc is getting error how do i exit from my shell script.

my shell script will be like this

```<code>#!/bin/bash

set -o errexit

loginto_vm() {

    ssh host@IP << ENDSSH

ls n1n

cd n1n

ENDSSH

    echo 'done'

}

loginto_vm
</code>```

here it is exiting from ssh heredoc if "n1n" is not there and printing echo statement, but i want it to exit from script

答:
You can instruct the shell to exit if anything errors like in any shell script:

```<code>$ sudo su <<EOF
set -e
echo before
bad-command
echo after
EOF
</code>```

Output:

```<code>before
sh: line 3: bad-command: command not found
</code>```

Notice after isn't printed.

Body:
I have a ssh heredoc in my shell script, if one of those commands in heredoc is getting error how do i exit from my shell script.

my shell script will be like this

#!/bin/bash

set -o errexit

loginto_vm() {

    ssh host@IP << ENDSSH

ls n1n

cd n1n

ENDSSH

    echo 'done'

}

loginto_vm

here it is exiting from ssh heredoc if "n1n" is not there and printing echo statement, but i want it to exit from script

Body:
You can instruct the shell to exit if anything errors like in any shell script:

$ sudo su <<EOF
set -e
echo before
bad-command
echo after
EOF

Output:

before
sh: line 3: bad-command: command not found

Notice after isn't printed.


问:
Printing the 3 highest integers from an array without sorting
I am trying to create a program that prints the highest integers from a collection of student's grades array, but the code keeps returning me the same values each time it returns me a value.

So far this is the code:

```<code>class BestGrades {
public static void main(String args[]){
            Scanner sc = new Scanner(System.in);

            int grade[] = new int[6];
            int best[] = new int[3];

            System.out.println("Enter the student's grade...");

            for(int i = 0; i < grade.length; i++){

                    grade[i] = sc.nextInt();

                    for(int a = 0; a < best.length; a++){
                            if(grade[i] > best[a]){
                                    best[a] = grade[i];
                            }
                    }
            }

            for(int i = 0; i < best.length; i++){
                    System.out.println("Best degrees are: "+best[i]);
            }
    }
</code>```

}

As I said, the code will always return me the same highest value 3x.
Pardon me for any mistakes, first time asking here.

答:
The way to attack a problem like this is to break it into smaller pieces. One way is top-down - when something looks too hard to do in-line, call a method (that doesn't exist) to do it. Then write that method.

```<code>  for( grade : grades) {
      replaceLowestIfHigher(grade, best);
  }
</code>```

Now we just need to write replaceLowestIfHigher():

```<code>  public void replaceLowestIfHigher(int grade, int[] target) {
      int indexOfLowest = findIndexOfLowest(target);

      if(grade > target[indexOfLowest]) {
         target[indexOfLowest] = grade;
      }
  }
</code>```

... and now we have to write findIndexOfLowest():

```<code> public int findIndexOfLowest(int[] array) {
      int indexOfLowest=0;
      for(int i=1; i<array.length; i++) {
         if(array[i] < array[indexOfLowest]) {
              indexOfLowest = i;
         }
      }
      return indexOfLowest;
 }
</code>```

The only problem with this is that you hunt through the destination array for the lowest value even though it's likely you've done it before for the same values. There are various ways you could store this knowledge - for example, you could create a class to manage the "best" array, that remembers where the lowest is, and only recalculates when the data changes:

```<code>public class BestGrades {
    private int[] grades = new int[3];
    private int indexOfLowest = 0;

    public int[] getGrades() {
        return grades;
    }

    public void replaceLowestIfHigher(int grade) {
       if(grade > grades[indexOfLowest]) {
          grades[indexOfLowest] = grade;
          updateIndexOfLowest();
       }
    }

    private void updateIndexOfLowest() {
        indexOfLowest = 0;
        for(int i=1; i<target.length; i++) {
            if(grades[i] < grades[indexOfLowest]) {
                indexOfLowest = i;
            }
         }
    }
}
</code>```

However, most mature Java programmers would use a sorted collection to achieve this.

Body:
I am trying to create a program that prints the highest integers from a collection of student's grades array, but the code keeps returning me the same values each time it returns me a value.

So far this is the code:

class BestGrades {
public static void main(String args[]){
            Scanner sc = new Scanner(System.in);

            int grade[] = new int[6];
            int best[] = new int[3];

            System.out.println("Enter the student's grade...");

            for(int i = 0; i < grade.length; i++){

                    grade[i] = sc.nextInt();

                    for(int a = 0; a < best.length; a++){
                            if(grade[i] > best[a]){
                                    best[a] = grade[i];
                            }
                    }
            }

            for(int i = 0; i < best.length; i++){
                    System.out.println("Best degrees are: "+best[i]);
            }
    }

}

As I said, the code will always return me the same highest value 3x.
Pardon me for any mistakes, first time asking here.

Body:
The way to attack a problem like this is to break it into smaller pieces. One way is top-down - when something looks too hard to do in-line, call a method (that doesn't exist) to do it. Then write that method.

  for( grade : grades) {
      replaceLowestIfHigher(grade, best);
  }

Now we just need to write replaceLowestIfHigher():

  public void replaceLowestIfHigher(int grade, int[] target) {
      int indexOfLowest = findIndexOfLowest(target);

      if(grade > target[indexOfLowest]) {
         target[indexOfLowest] = grade;
      }
  }

... and now we have to write findIndexOfLowest():

 public int findIndexOfLowest(int[] array) {
      int indexOfLowest=0;
      for(int i=1; i<array.length; i++) {
         if(array[i] < array[indexOfLowest]) {
              indexOfLowest = i;
         }
      }
      return indexOfLowest;
 }

The only problem with this is that you hunt through the destination array for the lowest value even though it's likely you've done it before for the same values. There are various ways you could store this knowledge - for example, you could create a class to manage the "best" array, that remembers where the lowest is, and only recalculates when the data changes:

public class BestGrades {
    private int[] grades = new int[3];
    private int indexOfLowest = 0;

    public int[] getGrades() {
        return grades;
    }

    public void replaceLowestIfHigher(int grade) {
       if(grade > grades[indexOfLowest]) {
          grades[indexOfLowest] = grade;
          updateIndexOfLowest();
       }
    }

    private void updateIndexOfLowest() {
        indexOfLowest = 0;
        for(int i=1; i<target.length; i++) {
            if(grades[i] < grades[indexOfLowest]) {
                indexOfLowest = i;
            }
         }
    }
}

However, most mature Java programmers would use a sorted collection to achieve this.


问:
Why Consumer thread is not able to remove messages from Vector?
I am trying to create a solution for Producer/ Consumer problem where one thread is putting message in Vector and another is removing from it.

```<code>import java.util.Vector;
public class Producer implements Runnable {
    static final int MAXQUEUE = 5;
    private Vector<String> messages;

    public Producer(Vector<String> messages) {
        super();
        this.messages = messages;
    }

    @Override
    public void run() {
        try {
            while (true)
                putMessage();
        } catch (InterruptedException e) {
        }
    }

    private synchronized void putMessage() throws InterruptedException {
        while (messages.size() == MAXQUEUE) {
            wait();
        }
        messages.addElement(new java.util.Date().toString());
        System.out.println("put message");
        notifyAll();
    }

    public static void main(String args[]) {
        Vector<String> messages = new Vector<String>();
        new Thread(new Producer(messages)).start();
        new Thread(new Consumer(messages)).start();
    }
}

class Consumer implements Runnable{
    public Consumer(Vector<String> messages) {
        super();
        this.messages = messages;
    }
    private Vector<String> messages;

    public synchronized String getMessage() throws InterruptedException {
        notifyAll();
        while (messages.size() == 0) {
            wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
        }
        String message = (String) messages.firstElement();
        messages.removeElement(message);
        return message;
    }

    @Override
    public void run() {
        try {
            while (true) {
                String message = getMessage();
                System.out.println("Got message: " + message);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Whenever I am running the program, it is printing  put message 5 times. I don't understand even after notifyAll(), it is not giving lock to consumer.

答:
Your code is not working because your two threads are not notifying/waiting on the same monitor.

They each notify and wait on their own monitor, not a shared monitor. Change code to use a shared monitor, e.g. messages, including the synchronizations.

```<code>private void putMessage() throws InterruptedException {
    synchronized (messages) { // <======
        while (messages.size() == MAXQUEUE) {
            messages.wait();  // <======
        }
        messages.addElement(new java.util.Date().toString());
        System.out.println("put message");
        messages.notifyAll(); // <======
    }
}

public String getMessage() throws InterruptedException {
    synchronized (messages) { // <======
        while (messages.size() == 0) {
            messages.wait();  // <======
        }
        String message = (String) messages.firstElement();
        messages.removeElement(message);
        messages.notifyAll(); // <======
        return message;
    }
}
</code>```

Notice that methods are no longer synchronized.

Body:
I am trying to create a solution for Producer/ Consumer problem where one thread is putting message in Vector and another is removing from it.

import java.util.Vector;
public class Producer implements Runnable {
    static final int MAXQUEUE = 5;
    private Vector<String> messages;

    public Producer(Vector<String> messages) {
        super();
        this.messages = messages;
    }

    @Override
    public void run() {
        try {
            while (true)
                putMessage();
        } catch (InterruptedException e) {
        }
    }

    private synchronized void putMessage() throws InterruptedException {
        while (messages.size() == MAXQUEUE) {
            wait();
        }
        messages.addElement(new java.util.Date().toString());
        System.out.println("put message");
        notifyAll();
    }

    public static void main(String args[]) {
        Vector<String> messages = new Vector<String>();
        new Thread(new Producer(messages)).start();
        new Thread(new Consumer(messages)).start();
    }
}

class Consumer implements Runnable{
    public Consumer(Vector<String> messages) {
        super();
        this.messages = messages;
    }
    private Vector<String> messages;

    public synchronized String getMessage() throws InterruptedException {
        notifyAll();
        while (messages.size() == 0) {
            wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
        }
        String message = (String) messages.firstElement();
        messages.removeElement(message);
        return message;
    }

    @Override
    public void run() {
        try {
            while (true) {
                String message = getMessage();
                System.out.println("Got message: " + message);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Whenever I am running the program, it is printing  put message 5 times. I don't understand even after notifyAll(), it is not giving lock to consumer.

Body:
Your code is not working because your two threads are not notifying/waiting on the same monitor.

They each notify and wait on their own monitor, not a shared monitor. Change code to use a shared monitor, e.g. messages, including the synchronizations.

private void putMessage() throws InterruptedException {
    synchronized (messages) { // <======
        while (messages.size() == MAXQUEUE) {
            messages.wait();  // <======
        }
        messages.addElement(new java.util.Date().toString());
        System.out.println("put message");
        messages.notifyAll(); // <======
    }
}

public String getMessage() throws InterruptedException {
    synchronized (messages) { // <======
        while (messages.size() == 0) {
            messages.wait();  // <======
        }
        String message = (String) messages.firstElement();
        messages.removeElement(message);
        messages.notifyAll(); // <======
        return message;
    }
}

Notice that methods are no longer synchronized.


问:
how to insert cases into a table based on a parameter without duplicating the main select query?
I have a insert statement in sql server 2008 like below:

```<code>INSERT INTO MYTABLE
SELECT Id,Name,Date
FROM #temp
...joins...
where ...conditions...
</code>```

I need to add a parameter to the code, and based on the parameter I will decide which table the output data should be inserted into. Check below:

```<code>declare @checkValue bit;
if (@checkValue = 1)
begin
   INSERT INTO MYTABLE
    SELECT Id,Name,Date
    FROM #temp
    ...joins...
    where ...conditions...
end
else
begin
    INSERT INTO MY_OTHER_TABLE
    SELECT Id,Name,Date
    FROM #temp
    ...joins...
    where ...conditions...
end
</code>```

I handled the situation like above for now, however the main query is pretty long and I do not want to duplicate it, it does not look professional to me. I am looking for a better way to deal with such an issue. Any help or advice should be appreciated. Thanks.

答:
create SP:

```<code>CREATE PROCEDURE ExampleSelect
AS
    SELECT Id,Name,Date
    FROM #temp
    ...joins...
    where ...conditions...
GO
</code>```

use insert..exec to insert data:

```<code>declare @checkValue bit;
if (@checkValue = 1)
begin
   INSERT INTO MYTABLE
   EXEC ExampleSelect
end
else
begin
    INSERT INTO MY_OTHER_TABLE
    EXEC ExampleSelect
end
</code>```

Body:
I have a insert statement in sql server 2008 like below:

INSERT INTO MYTABLE
SELECT Id,Name,Date
FROM #temp
...joins...
where ...conditions...

I need to add a parameter to the code, and based on the parameter I will decide which table the output data should be inserted into. Check below:

declare @checkValue bit;
if (@checkValue = 1)
begin
   INSERT INTO MYTABLE
    SELECT Id,Name,Date
    FROM #temp
    ...joins...
    where ...conditions...
end
else
begin
    INSERT INTO MY_OTHER_TABLE
    SELECT Id,Name,Date
    FROM #temp
    ...joins...
    where ...conditions...
end

I handled the situation like above for now, however the main query is pretty long and I do not want to duplicate it, it does not look professional to me. I am looking for a better way to deal with such an issue. Any help or advice should be appreciated. Thanks.

Body:
create SP:

CREATE PROCEDURE ExampleSelect
AS
    SELECT Id,Name,Date
    FROM #temp
    ...joins...
    where ...conditions...
GO

use insert..exec to insert data:

declare @checkValue bit;
if (@checkValue = 1)
begin
   INSERT INTO MYTABLE
   EXEC ExampleSelect
end
else
begin
    INSERT INTO MY_OTHER_TABLE
    EXEC ExampleSelect
end


问:
Could not load file or assembly HRESULT: 0x80131515 (When adding controller to MVC project that has assembly references on network drive)
I've seen this: VSTS 2010 SGEN : error : Could not load file or assembly (Exception from HRESULT: 0x80131515) and none of the answers work. It also doesn't appear when I build or anything. I can run the project fine, it happens when I try to add an entity framework templated controller:

Then I get this error:

All project files are on my network share because that is where My Documents resides for our work. Here is what I tried:

1) Turning Generator Serialization Assembly in project settings to on, off, and auto.

2) Adding sgen.exe.config to C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools with the following code:

```<code><configuration>
 <runtime>
   <loadFromRemoteSources enabled="true" />
 </runtime>
</configuration>
</code>```

3) Tried to unblock the assemblies, but I had no unblock option in the properties tab.

None of these solutions work. Does anyone have any idea how I can fix this???
This error occurs for any custom assembly from nuget or my own projects due to their location existing on the network space, but only when trying to add an EF templated controller. I can build and run the program fine.

答:
Try to unblock the file desbloquer.

This solved my problem.

Body:
I've seen this: VSTS 2010 SGEN : error : Could not load file or assembly (Exception from HRESULT: 0x80131515) and none of the answers work. It also doesn't appear when I build or anything. I can run the project fine, it happens when I try to add an entity framework templated controller:

Then I get this error:

All project files are on my network share because that is where My Documents resides for our work. Here is what I tried:

1) Turning Generator Serialization Assembly in project settings to on, off, and auto.

2) Adding sgen.exe.config to C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools with the following code:

<configuration>
 <runtime>
   <loadFromRemoteSources enabled="true" />
 </runtime>
</configuration>

3) Tried to unblock the assemblies, but I had no unblock option in the properties tab.

None of these solutions work. Does anyone have any idea how I can fix this???
This error occurs for any custom assembly from nuget or my own projects due to their location existing on the network space, but only when trying to add an EF templated controller. I can build and run the program fine.


问:
Submit drop down values into google spreadsheet with google script
I have coded a script with help from several stackoverflow examples but I get stuck when trying to go a bit further.

It seems very straightforward but I cannot seem to work it out.

So here it is:
I have coded an HTML script that initiates a dialogbox with some drop down menus. The data in the drop down menus is dynamic and taken from a range in a spreadsheet. I want for users to open the spreadsheet, run the script and choose the options from the drop down values. These drop down values will be pasted on the same spreadsheet.

The bit I got working is that the code sees the values that need to go in the drop down box, illustrates that and that there is a submit box.

However, I cannot seem to submit the values onto the spreadsheet. Please could anyone help me out or point me in the right direction?

test.gs

```<code>   function openInputDialog1() {
  var html = HtmlService.createHtmlOutputFromFile('Test').setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi()
    .showModalDialog(html, 'Add Item');
}

function getMenuListFromSheet() {
  return SpreadsheetApp.getActive().getSheetByName('Part Names')
     .getRange(1,5,6,1).getValues();
}

function getThicknessFromSheet(){
  return SpreadsheetApp.getActive().getSheetByName('Part Names')
     .getRange(1,5,6,1).getValues();
}

function itemadd(form) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Part Names');
  var LastRow=sheet.getLastRow();
  Logger.log(LastRow);
  Logger.log(form);
  sheet.getRange(LastRow+1,1,1,2).setValues(form);

  return true;

}
</code>```

Test.html

```<code><!DOCTYPE html>
<html>
<p>List of parts:</p>

<select id="menu">
  <option></option>
  <option>Google Chrome</option>
  <option>Firefox</option>
</select>

<select id="thickness">
  <option></option>
  <option>1</option>
  <option>2</option>
</select>

<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<input type="submit" value="Submit" onclick="select()">
<script>
// The code in this function runs when the page is loaded.
$(function() {
  google.script.run.withSuccessHandler(showMenu)
      .getMenuListFromSheet();
  google.script.run.withSuccessHandler(showThickness)
      .getThicknessFromSheet();

});

/**function showThings(things) {
 var list = $('#things');
 list.empty();
 for (var i = 0; i < things.length; i++) {
   list.append('<li>' + things[i] + '</li>');
}
}
**/
function showMenu(menuItems) {
  var list = $('#menu');
  list.find('option').remove();  // remove existing contents

  for (var i = 0; i < menuItems.length; i++) {
    list.append('<option>' + menuItems[i] + '</option>');
  }
}

function showThickness(menuThickness) {
  var list = $('#thickness');
  list.find('option').remove();  // remove existing contents

  for (var i = 0; i < menuThickness.length; i++) {
    list.append('<option>' + menuThickness[i] + '</option>');
  }
}

</script>
<script>
function select(){
var x = document.getElementById('menu').value;
var y = document.getElementById('thickness').value;

google.script.run
            .itemadd(x,y)

google.script.host.close();
</script>

</html>
</code>```

I know that I am somewhere not making the connection between the script and the HTML side but fail to understand where.

Thanks,
Tim

答: I haven't used gs before but from looking at other examples yours looks right, however, in the second line you have tml.Service instead of Html.Service, not sure if that will fix all your issues but that will break it.</p>

Body:
I have coded a script with help from several stackoverflow examples but I get stuck when trying to go a bit further.

It seems very straightforward but I cannot seem to work it out.

So here it is:
I have coded an HTML script that initiates a dialogbox with some drop down menus. The data in the drop down menus is dynamic and taken from a range in a spreadsheet. I want for users to open the spreadsheet, run the script and choose the options from the drop down values. These drop down values will be pasted on the same spreadsheet.

The bit I got working is that the code sees the values that need to go in the drop down box, illustrates that and that there is a submit box.

However, I cannot seem to submit the values onto the spreadsheet. Please could anyone help me out or point me in the right direction?

test.gs

   function openInputDialog1() {
  var html = HtmlService.createHtmlOutputFromFile('Test').setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi()
    .showModalDialog(html, 'Add Item');
}

function getMenuListFromSheet() {
  return SpreadsheetApp.getActive().getSheetByName('Part Names')
     .getRange(1,5,6,1).getValues();
}

function getThicknessFromSheet(){
  return SpreadsheetApp.getActive().getSheetByName('Part Names')
     .getRange(1,5,6,1).getValues();
}

function itemadd(form) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Part Names');
  var LastRow=sheet.getLastRow();
  Logger.log(LastRow);
  Logger.log(form);
  sheet.getRange(LastRow+1,1,1,2).setValues(form);

  return true;

}

Test.html

<!DOCTYPE html>

List of parts:

<select id="menu">
  <option></option>
  <option>Google Chrome</option>
  <option>Firefox</option>
</select>

<select id="thickness">
  <option></option>
  <option>1</option>
  <option>2</option>
</select>

<input type="submit" value="Submit" onclick="select()">

I know that I am somewhere not making the connection between the script and the HTML side but fail to understand where.

Thanks,
Tim


问:
How to clone object with a different Primary Key
I have this class Cart_Record, shown below. I want to update the PrimaryKey. To do that I am trying to clone the object into a new object to copy CartLines and update ID. I haven't found much in the issue queue or the documentation to help me.

```<code>public class Cart_Record : RealmObject
{
    public Cart_Record() { }

    public Cart_Record(IList<Cart_Line> cartLines, int id)
    {
        ID = id;
        foreach (var cartLine in cartLines)
            CartLines.Add(App.RealmDB.Find<Cart_Line>(cartLine.ProductId));
    }

    [PrimaryKey]
    public int ID { get; set; }

    public IList<Cart_Line> CartLines { get; }
}
</code>```

I am trying this

```<code>var appCart = App.RealmDB.All<Cart_Record>().First();

App.RealmDB.Write(() =>
{
    var cartLines = new List<Cart_Line>(appCart.CartLines);
    App.RealmDB.Remove(App.RealmDB.Find<Cart_Record>(appCart.ID));
    App.RealmDB.Add<Cart_Record>(new Cart_Record(cartLines, serverCart.ID));
});
</code>```

However I keep getting exceptions, specifically RealmObjectManagedByAnotherRealmException. I don't understand how as I am not readding the Cart_Line objects to Realm, just to the CartLine list in the new object.

What am I doing wrong?

Thanks ahead of time.

Edit: I found something that works but I would like to see if someone else have a better method. This is what works for me.

```<code>var appCart = App.RealmDB.All<Cart_Record>().First();
App.RealmDB.Write(() =>
{
    var cartLines = new List<Cart_Line>(appCart.CartLines);
    App.RealmDB.Remove(App.RealmDB.Find<Cart_Record>(appCart.ID));
    var newAppCart = App.RealmDB.Add<Cart_Record>(new Cart_Record() { ID = serverCart.ID });
    foreach (var cartLine in cartLines)
        newAppCart.CartLines.Add(cartLine);
});
</code>```

答:
I'm not sure what App.RealmDB does under the hood, but using the out-of-the-box Realm API, what you want to achieve can be done by simply adding the CartLines from the original to the updated object:

```<code>// Assume want to change Id from 1 to 2
var realm = Realm.GetInstance();
var original = realm.Find<Cart_Record>(1);

var updated = new Cart_Record { ID = 2 }; // other properties must be copied here
foreach (var cart in original.CartLines)
{
    updated.CartLines.Add(cart);
}

realm.Write(() =>
{
    realm.Remove(original);
    realm.Add(updated);
});

// updated now has all the original's CartLines
</code>```

Body:
I have this class Cart_Record, shown below. I want to update the PrimaryKey. To do that I am trying to clone the object into a new object to copy CartLines and update ID. I haven't found much in the issue queue or the documentation to help me.

public class Cart_Record : RealmObject
{
    public Cart_Record() { }

    public Cart_Record(IList<Cart_Line> cartLines, int id)
    {
        ID = id;
        foreach (var cartLine in cartLines)
            CartLines.Add(App.RealmDB.Find<Cart_Line>(cartLine.ProductId));
    }

    [PrimaryKey]
    public int ID { get; set; }

    public IList<Cart_Line> CartLines { get; }
}

I am trying this

var appCart = App.RealmDB.All<Cart_Record>().First();

App.RealmDB.Write(() =>
{
    var cartLines = new List<Cart_Line>(appCart.CartLines);
    App.RealmDB.Remove(App.RealmDB.Find<Cart_Record>(appCart.ID));
    App.RealmDB.Add<Cart_Record>(new Cart_Record(cartLines, serverCart.ID));
});

However I keep getting exceptions, specifically RealmObjectManagedByAnotherRealmException. I don't understand how as I am not readding the Cart_Line objects to Realm, just to the CartLine list in the new object.

What am I doing wrong?

Thanks ahead of time.

Edit: I found something that works but I would like to see if someone else have a better method. This is what works for me.

var appCart = App.RealmDB.All<Cart_Record>().First();
App.RealmDB.Write(() =>
{
    var cartLines = new List<Cart_Line>(appCart.CartLines);
    App.RealmDB.Remove(App.RealmDB.Find<Cart_Record>(appCart.ID));
    var newAppCart = App.RealmDB.Add<Cart_Record>(new Cart_Record() { ID = serverCart.ID });
    foreach (var cartLine in cartLines)
        newAppCart.CartLines.Add(cartLine);
});

Body:
I'm not sure what App.RealmDB does under the hood, but using the out-of-the-box Realm API, what you want to achieve can be done by simply adding the CartLines from the original to the updated object:

// Assume want to change Id from 1 to 2
var realm = Realm.GetInstance();
var original = realm.Find<Cart_Record>(1);

var updated = new Cart_Record { ID = 2 }; // other properties must be copied here
foreach (var cart in original.CartLines)
{
    updated.CartLines.Add(cart);
}

realm.Write(() =>
{
    realm.Remove(original);
    realm.Add(updated);
});

// updated now has all the original's CartLines


问:
Getting the error "duplicate entry: com/google/android/gms/internal/zzble.class" when trying to add a package
I'm trying to add the react-native-firestack package to my app. But it keeps giving the following error :

```<code>:app:mergeDebugResources UP-TO-DATE
:app:recordFilesBeforeBundleCommandDebug
:app:bundleDebugJsAndAssets SKIPPED
:app:generateBundledResourcesHashDebug
4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:incrementalDebugJavaCompilationSafeguard UP-TO-DATE
:app:compileDebugJavaWithJavac UP-TO-DATE
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources UP-TO-DATE
:app:transformClassesWithJarMergingForDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/internal/zzble.class

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 2.498 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment.
Go to https://facebook.github.io/react-native/docs/getting-started.html
and check the Android tab for setup instructions.
</code>```

I tried to add some packages to exclude group in several packages. But none worked. Here's the ./gradlew clean :app:dependencies result: https://gist.github.com/THPubs/8fe8b4b9c80e3c6cd49541d66887c742

Tried to follow other similar stack overflow question but looks like this package has a lot of dependencies. I was unable to find the conflict.

My build.gradle dependencies:

```<code>dependencies {
    compile(project(":react-native-firestack"))
    compile project(':react-native-onesignal')
    compile project(':react-native-fbsdk')
    compile project(':react-native-share')
    compile project(':react-native-video')
    compile project(':react-native-uuid-generator')
    compile project(':react-native-udp')
    compile project(':react-native-tcp')
    compile project(':react-native-camera')
    compile project(':react-native-contacts')
    compile project(':react-native-linear-gradient')
    compile project(':react-native-vector-icons')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(':react-native-image-picker')
    compile(project(":react-native-google-signin")){
    exclude group: "com.google.android.gms" // very important
    }
    compile 'com.google.android.gms:play-services-auth:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.0.1'
}
</code>```

答:
Just add following in your build.gradle</p>

```<code>    android {
            configurations {
            all*.exclude module: 'play-services-awareness'
            }
    }
</code>```

Body:
I'm trying to add the react-native-firestack package to my app. But it keeps giving the following error :

:app:mergeDebugResources UP-TO-DATE
:app:recordFilesBeforeBundleCommandDebug
:app:bundleDebugJsAndAssets SKIPPED
:app:generateBundledResourcesHashDebug
4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:incrementalDebugJavaCompilationSafeguard UP-TO-DATE
:app:compileDebugJavaWithJavac UP-TO-DATE
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources UP-TO-DATE
:app:transformClassesWithJarMergingForDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/internal/zzble.class

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 2.498 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment.
Go to https://facebook.github.io/react-native/docs/getting-started.html
and check the Android tab for setup instructions.

I tried to add some packages to exclude group in several packages. But none worked. Here's the ./gradlew clean :app:dependencies result: https://gist.github.com/THPubs/8fe8b4b9c80e3c6cd49541d66887c742

Tried to follow other similar stack overflow question but looks like this package has a lot of dependencies. I was unable to find the conflict.

My build.gradle dependencies:

dependencies {
    compile(project(":react-native-firestack"))
    compile project(':react-native-onesignal')
    compile project(':react-native-fbsdk')
    compile project(':react-native-share')
    compile project(':react-native-video')
    compile project(':react-native-uuid-generator')
    compile project(':react-native-udp')
    compile project(':react-native-tcp')
    compile project(':react-native-camera')
    compile project(':react-native-contacts')
    compile project(':react-native-linear-gradient')
    compile project(':react-native-vector-icons')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile project(':react-native-image-picker')
    compile(project(":react-native-google-signin")){
    exclude group: "com.google.android.gms" // very important
    }
    compile 'com.google.android.gms:play-services-auth:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.0.1'
}

Body:
Just add following in your build.gradle

    android {
            configurations {
            all*.exclude module: 'play-services-awareness'
            }
    }


问:
Tkinter Image icon not working or aligning properly in a Labelframe
This question concerns Python's Tkinter.

I first produced this GUI, a simple two-column set of rows in a Labelframe, with an icon on the right:

The above behaviour was correct and expected, based on this following code:

```<code>import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk

root = tk.Tk()

icon_colours_fp = r"D:\Dropbox\coding\python\experiments\icon_component.gif"
icon_col = tk.PhotoImage(file=icon_colours_fp)
# icon_col = ImageTk.PhotoImage(Image.open(icon_colours_fp))

tk.Label(root, text="Past").grid(row=0, column=0)
tk.Label(root, text="Today").grid(row=1, column=0)
tk.Label(root, text="Future").grid(row=2, column=0)

_b = ttk.Button(root, image=icon_col)
_b['image'] =icon_col
_b.grid(row=0, column=1)

root.mainloop()
</code>```

I then re-wrote the code as a class, hoping to produce something similar within a Labelframe:

```<code>import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk

class Options(tk.Frame):

    def __init__(self, parent):

        super().__init__()

        main_labelframe = ttk.LabelFrame(parent, text="Test Labelframe")
        main_labelframe.pack(fill=tk.BOTH, expand=1)

        frame_1 = tk.Frame(main_labelframe)
        frame_1_sep = ttk.Separator(main_labelframe, orient=tk.VERTICAL)
        frame_2 = tk.Frame(main_labelframe)

        frame_1.pack(side=tk.LEFT)
        frame_1_sep.pack(side=tk.LEFT, fill=tk.BOTH)
        frame_2.pack(side=tk.LEFT)

        tk.Label(frame_1, text="Past").grid(row=0, column=0)
        tk.Label(frame_1, text="Today").grid(row=1)
        tk.Label(frame_1, text="Future").grid(row=2)

        icon_colours_fp = r"D:\Dropbox\coding\python\experiments\icon_component.gif"
        icon_col = tk.PhotoImage(file=icon_colours_fp)
        _b = ttk.Button(frame_2, image=icon_col)
        _b['image'] = icon_col
        _b.grid(row=0, column=0)

class Gui(tk.Tk):

    def __init__(self):

        super().__init__()
        options = Options(self)
        options.pack()

gui = Gui()
gui.mainloop()
</code>```

The code then failed, in two respects:

The icon fails to appear.

The ttk Button becomes misaligned. (It appears in the centre, whereas by the grid, it should appear at the top.)

The failed code appears as follows:

I have experimented: among others, I changed the geometry manager to .pack(), and changed the parent of ttk.Button, but without success. Would appreciate some pointers as to where I've gone wrong, especially as to the disappearing icon.

答:
You didn't keep a reference to the image. Easiest way here is to change:

```<code>icon_col = tk.PhotoImage(file=icon_colours_fp)
b = ttk.Button(frame_2, image=icon_col)
_b['image'] = icon_col
</code>```

To:

```<code>self.icon_col = tk.PhotoImage(file=icon_colours_fp)
b = ttk.Button(frame_2, image=self.icon_col)
</code>```

Body:
This question concerns Python's Tkinter.

I first produced this GUI, a simple two-column set of rows in a Labelframe, with an icon on the right:

The above behaviour was correct and expected, based on this following code:

import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk

root = tk.Tk()

icon_colours_fp = r"D:\Dropbox\coding\python\experiments\icon_component.gif"
icon_col = tk.PhotoImage(file=icon_colours_fp)
# icon_col = ImageTk.PhotoImage(Image.open(icon_colours_fp))

tk.Label(root, text="Past").grid(row=0, column=0)
tk.Label(root, text="Today").grid(row=1, column=0)
tk.Label(root, text="Future").grid(row=2, column=0)

_b = ttk.Button(root, image=icon_col)
_b['image'] =icon_col
_b.grid(row=0, column=1)

root.mainloop()

I then re-wrote the code as a class, hoping to produce something similar within a Labelframe:

import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk

class Options(tk.Frame):

    def __init__(self, parent):

        super().__init__()

        main_labelframe = ttk.LabelFrame(parent, text="Test Labelframe")
        main_labelframe.pack(fill=tk.BOTH, expand=1)

        frame_1 = tk.Frame(main_labelframe)
        frame_1_sep = ttk.Separator(main_labelframe, orient=tk.VERTICAL)
        frame_2 = tk.Frame(main_labelframe)

        frame_1.pack(side=tk.LEFT)
        frame_1_sep.pack(side=tk.LEFT, fill=tk.BOTH)
        frame_2.pack(side=tk.LEFT)

        tk.Label(frame_1, text="Past").grid(row=0, column=0)
        tk.Label(frame_1, text="Today").grid(row=1)
        tk.Label(frame_1, text="Future").grid(row=2)

        icon_colours_fp = r"D:\Dropbox\coding\python\experiments\icon_component.gif"
        icon_col = tk.PhotoImage(file=icon_colours_fp)
        _b = ttk.Button(frame_2, image=icon_col)
        _b['image'] = icon_col
        _b.grid(row=0, column=0)

class Gui(tk.Tk):

    def __init__(self):

        super().__init__()
        options = Options(self)
        options.pack()

gui = Gui()
gui.mainloop()

The code then failed, in two respects:

The icon fails to appear.

The ttk Button becomes misaligned. (It appears in the centre, whereas by the grid, it should appear at the top.)

The failed code appears as follows:

I have experimented: among others, I changed the geometry manager to .pack(), and changed the parent of ttk.Button, but without success. Would appreciate some pointers as to where I've gone wrong, especially as to the disappearing icon.

Body:
You didn't keep a reference to the image. Easiest way here is to change:

icon_col = tk.PhotoImage(file=icon_colours_fp)
b = ttk.Button(frame_2, image=icon_col)
_b['image'] = icon_col

To:

self.icon_col = tk.PhotoImage(file=icon_colours_fp)
b = ttk.Button(frame_2, image=self.icon_col)


问:
Open source alternative to MATLAB's fmincon function?
Is there an open-source alternative to MATLAB's fmincon function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / NumPy / SciPy and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.

答:
Have a look at http://www.aemdesign.com/downloadfsqp.htm.

There you will find C code which provides the same functionality as fmincon. (However, using a different algorithm. You can read the manual if you are interested in the details.)

It's open source but not under GPL.

OwnerDisplayName: dF

LastEditorDisplayName: Dima

OwnerDisplayName: mathias

LastEditorDisplayName: mathias

ContentLicense: CC BY-SA 2.5