问:
Scrapy merge output on a field
I have a Scrapy output like this:

```<code>[{'gender': 'women',
  'name': 'NEW IN: CLOTHING',
  'products': [{'name': 'Free People Cocoon Multi Way Neck Top',
                'price': {'currency': 'GBP',
                          'outlet': '40.0',
                          'retail': '58.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: CLOTHING',
  'products': [{'name': 'Free People Cocoon Multi Way Neck Top',
                'price': {'currency': 'GBP',
                          'outlet': '40.0',
                          'retail': '58.0'}},
               {'name': 'N12H Joshua Tree Dress',
                'price': {'currency': 'GBP',
                          'outlet': '140.0',
                          'retail': '249.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: CLOTHING',
  'products': [{'name': 'Free People Cocoon Multi Way Neck Top',
                'price': {'currency': 'GBP',
                          'outlet': '40.0',
                          'retail': '58.0'}},
               {'name': 'N12H Joshua Tree Dress',
                'price': {'currency': 'GBP',
                          'outlet': '140.0',
                          'retail': '249.0'}},
               {'name': 'Twiin Method Rib Mesh Flare Sleeve Top',
                'price': {'currency': 'GBP',
                          'outlet': '22.0',
                          'retail': '32.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: CLOTHING',
  'products': [{'name': 'Free People Cocoon Multi Way Neck Top',
                'price': {'currency': 'GBP',
                          'outlet': '40.0',
                          'retail': '58.0'}},
               {'name': 'N12H Joshua Tree Dress',
                'price': {'currency': 'GBP',
                          'outlet': '140.0',
                          'retail': '249.0'}},
               {'name': 'Twiin Method Rib Mesh Flare Sleeve Top',
                'price': {'currency': 'GBP',
                          'outlet': '22.0',
                          'retail': '32.0'}},
               {'name': 'Twiin End Game Varsity Denim Trucker Jacket',
                'price': {'currency': 'GBP',
                          'outlet': '45.0',
                          'retail': '80.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: SHOES & ACCESSORIES ',
  'products': [{'name': 'Melissa Ultragirl Triple Bow Ballerina',
                'price': {'currency': 'GBP',
                          'outlet': '48.0',
                          'retail': '68.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: SHOES & ACCESSORIES ',
  'products': [{'name': 'Melissa Ultragirl Triple Bow Ballerina',
                'price': {'currency': 'GBP',
                          'outlet': '48.0',
                          'retail': '68.0'}},
               {'name': 'Zaxy Tbar Flip Flops',
                'price': {'currency': 'GBP',
                          'outlet': '20.0',
                          'retail': '26.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: SHOES & ACCESSORIES ',
  'products': [{'name': 'Melissa Ultragirl Triple Bow Ballerina',
                'price': {'currency': 'GBP',
                          'outlet': '48.0',
                          'retail': '68.0'}},
               {'name': 'Zaxy Tbar Flip Flops',
                'price': {'currency': 'GBP',
                          'outlet': '20.0',
                          'retail': '26.0'}},
               {'name': 'Estella Bartlet Silver Plated Heart Bracelet Duo Set',
                'price': {'currency': 'GBP',
                          'outlet': '15.0',
                          'retail': '31.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: SHOES & ACCESSORIES ',
  'products': [{'name': 'Melissa Ultragirl Triple Bow Ballerina',
                'price': {'currency': 'GBP',
                          'outlet': '48.0',
                          'retail': '68.0'}},
               {'name': 'Zaxy Tbar Flip Flops',
                'price': {'currency': 'GBP',
                          'outlet': '20.0',
                          'retail': '26.0'}},
               {'name': 'Estella Bartlet Silver Plated Heart Bracelet Duo Set',
                'price': {'currency': 'GBP',
                          'outlet': '15.0',
                          'retail': '31.0'}},
               {'name': 'Ashiana Embroidered Large Toiletry Bag With Wateproof '
                        'Lining',
                'price': {'currency': 'GBP',
                          'outlet': '25.0',
                          'retail': '35.0'}}]}]
</code>```

It's because on every product processing I'm using Loader.load_item().

How can I build a pipeline or output processor to make it only return the last processed item, like the following?

```<code>[{'gender': 'women',
  'name': 'NEW IN: CLOTHING',
  'products': [{'name': 'Free People Cocoon Multi Way Neck Top',
                'price': {'currency': 'GBP',
                          'outlet': '40.0',
                          'retail': '58.0'}},
               {'name': 'N12H Joshua Tree Dress',
                'price': {'currency': 'GBP',
                          'outlet': '140.0',
                          'retail': '249.0'}},
               {'name': 'Twiin Method Rib Mesh Flare Sleeve Top',
                'price': {'currency': 'GBP',
                          'outlet': '22.0',
                          'retail': '32.0'}},
               {'name': 'Twiin End Game Varsity Denim Trucker Jacket',
                'price': {'currency': 'GBP',
                          'outlet': '45.0',
                          'retail': '80.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: SHOES & ACCESSORIES ',
  'products': [{'name': 'Melissa Ultragirl Triple Bow Ballerina',
                'price': {'currency': 'GBP',
                          'outlet': '48.0',
                          'retail': '68.0'}},
               {'name': 'Zaxy Tbar Flip Flops',
                'price': {'currency': 'GBP',
                          'outlet': '20.0',
                          'retail': '26.0'}},
               {'name': 'Estella Bartlet Silver Plated Heart Bracelet Duo Set',
                'price': {'currency': 'GBP',
                          'outlet': '15.0',
                          'retail': '31.0'}},
               {'name': 'Ashiana Embroidered Large Toiletry Bag With Wateproof '
                        'Lining',
                'price': {'currency': 'GBP',
                          'outlet': '25.0',
                          'retail': '35.0'}}]}]
</code>```

The last lines processed have all the products from that session. I tried processing when the spider closes, without success.

I am almost finishing this project, researched a lot and tried many things, many questions, but none related to item stacking on a field.

My items code:

```<code>from scrapy.item import Item, Field
from scrapy.loader.processors import TakeFirst, Join, Compose, MapCompose

class Session(Item):
    name = Field()
    gender = Field()
    products = Field(
        # no idea what to put... tryed Join, Compose and MapCompose
    )

class Product(Item):
    name = Field()
    price = Field()

class Price(Item):
    outlet = Field()
    retail = Field()
    currency = Field()
</code>```

My spider code:

```<code>def parse(self, response):
    sessions = response.css("article.feature:nth-of-type(-n+2)")
    for session in sessions:
        sessionlink = session.css("a.feature__link::attr(href)").extract_first()

        lsession = ItemLoader(item=Session(), response=response)
        lsession.add_value("name", session.css("div.feature__title h3::text").extract_first())
        lsession.add_value("gender", re.split("[/]+", response.request.url)[2])

        requestsession = response.follow(sessionlink, callback=self.parse_session)
        requestsession.meta["lsession"] = lsession
        requestsession.meta["pages"] = 1
        yield requestsession

def parse_session(self, response):
    lsession = response.meta["lsession"]
    pages = response.meta["pages"]

    products = response.css("li.product-container:nth-of-type(-n+2)")

    for product in products:
        productlink = product.css("a.product-link::attr(href)").extract_first()
        requestproduct = response.follow(productlink, callback=self.parse_product)
        requestproduct.meta["lsession"] = lsession
        requestproduct.meta["productlink"] = productlink
        yield requestproduct

    nextpage = response.css("ul.pager li.next a::attr(href)").extract_first()
    if pages < 2:
        pages += 1
        requestnewpage = response.follow(nextpage, callback=self.parse_session)
        requestnewpage.meta["lsession"] = lsession
        requestnewpage.meta["pages"] = pages
        yield requestnewpage

def parse_product(self, response):
    lsession = response.meta["lsession"]
    productlink = response.meta["productlink"]

    lproduct = ItemLoader(item=Product(), response=response)

    name = response.css("div.product-hero>h1::text").extract_first()

    lproduct.replace_value("name", str(name))

    pricelink = "AN AJAX LINK TO GET THE PRICE"

    requestprice = response.follow(pricelink, callback=self.parse_price)
    requestprice.meta["lsession"] = lsession
    requestprice.meta["lproduct"] = lproduct

    yield requestprice

def parse_price(self, response):
    lsession = response.meta["lsession"]
    lproduct = response.meta["lproduct"]

    lprice = ItemLoader(item=Price(), response=response)

    pricejson = json.loads(response.body)
    outletprice = pricejson[0]["productPrice"]["current"]["value"]
    retailprice = pricejson[0]["productPrice"]["rrp"]["value"]
    currency = pricejson[0]["productPrice"]["currency"]

    lprice.replace_value("outlet", str(outletprice))
    lprice.replace_value("retail", str(retailprice))
    lprice.replace_value("currency", str(currency))
    lproduct.replace_value("price", lprice.load_item())
    lsession.add_value("products", dict(lproduct.load_item()))

    yield lsession.load_item()
</code>```

答:
YATTA!!!
Remembering my school days, I recorded about closures.
I did not know python had this kind of functional behaviour. I am a beginner at the language.

So, since I got a lot of help here, I am going to post here my solution so others can get help if needed.

I made a closure counter like this (just a basic one):

```<code>def counter():
    value = 0
    def count(op):
        nonlocal value
        if op == "add":
            value += 1
        elif op == "sub":
            value -= 1
        elif op == "get":
            return value

    return count
</code>```

Then, I started a counter for each section:

```<code>requestsession = response.follow(sessionlink, callback=self.parse_session)
requestsession.meta["lsession"] = lsession
requestsession.meta["pcounter"] = counter()
requestsession.meta["pages"] = 1
</code>```

When processing each product, I counted up, and continued to pass the counter until the price processing:

```<code>for product in products:
    pcounter("add")
    productlink = product.css("a.product-link::attr(href)").extract_first()
    requestproduct = response.follow(productlink, callback=self.parse_product)
    requestproduct.meta["lsession"] = lsession
    requestproduct.meta["pcounter"] = pcounter
    requestproduct.meta["productlink"] = productlink
    yield requestproduct
</code>```

After the price parsing I count down and, when I load the "lsession" item loader, I check if all the products were processed:

```<code>pcounter("sub")

if pcounter("get") == 0:
    yield lsession.load_item()
</code>```

Hope it will be useful for someone.

Title: Scrapy merge output on a field

Body:
I have a Scrapy output like this:

[{'gender': 'women',
  'name': 'NEW IN: CLOTHING',
  'products': [{'name': 'Free People Cocoon Multi Way Neck Top',
                'price': {'currency': 'GBP',
                          'outlet': '40.0',
                          'retail': '58.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: CLOTHING',
  'products': [{'name': 'Free People Cocoon Multi Way Neck Top',
                'price': {'currency': 'GBP',
                          'outlet': '40.0',
                          'retail': '58.0'}},
               {'name': 'N12H Joshua Tree Dress',
                'price': {'currency': 'GBP',
                          'outlet': '140.0',
                          'retail': '249.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: CLOTHING',
  'products': [{'name': 'Free People Cocoon Multi Way Neck Top',
                'price': {'currency': 'GBP',
                          'outlet': '40.0',
                          'retail': '58.0'}},
               {'name': 'N12H Joshua Tree Dress',
                'price': {'currency': 'GBP',
                          'outlet': '140.0',
                          'retail': '249.0'}},
               {'name': 'Twiin Method Rib Mesh Flare Sleeve Top',
                'price': {'currency': 'GBP',
                          'outlet': '22.0',
                          'retail': '32.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: CLOTHING',
  'products': [{'name': 'Free People Cocoon Multi Way Neck Top',
                'price': {'currency': 'GBP',
                          'outlet': '40.0',
                          'retail': '58.0'}},
               {'name': 'N12H Joshua Tree Dress',
                'price': {'currency': 'GBP',
                          'outlet': '140.0',
                          'retail': '249.0'}},
               {'name': 'Twiin Method Rib Mesh Flare Sleeve Top',
                'price': {'currency': 'GBP',
                          'outlet': '22.0',
                          'retail': '32.0'}},
               {'name': 'Twiin End Game Varsity Denim Trucker Jacket',
                'price': {'currency': 'GBP',
                          'outlet': '45.0',
                          'retail': '80.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: SHOES & ACCESSORIES ',
  'products': [{'name': 'Melissa Ultragirl Triple Bow Ballerina',
                'price': {'currency': 'GBP',
                          'outlet': '48.0',
                          'retail': '68.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: SHOES & ACCESSORIES ',
  'products': [{'name': 'Melissa Ultragirl Triple Bow Ballerina',
                'price': {'currency': 'GBP',
                          'outlet': '48.0',
                          'retail': '68.0'}},
               {'name': 'Zaxy Tbar Flip Flops',
                'price': {'currency': 'GBP',
                          'outlet': '20.0',
                          'retail': '26.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: SHOES & ACCESSORIES ',
  'products': [{'name': 'Melissa Ultragirl Triple Bow Ballerina',
                'price': {'currency': 'GBP',
                          'outlet': '48.0',
                          'retail': '68.0'}},
               {'name': 'Zaxy Tbar Flip Flops',
                'price': {'currency': 'GBP',
                          'outlet': '20.0',
                          'retail': '26.0'}},
               {'name': 'Estella Bartlet Silver Plated Heart Bracelet Duo Set',
                'price': {'currency': 'GBP',
                          'outlet': '15.0',
                          'retail': '31.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: SHOES & ACCESSORIES ',
  'products': [{'name': 'Melissa Ultragirl Triple Bow Ballerina',
                'price': {'currency': 'GBP',
                          'outlet': '48.0',
                          'retail': '68.0'}},
               {'name': 'Zaxy Tbar Flip Flops',
                'price': {'currency': 'GBP',
                          'outlet': '20.0',
                          'retail': '26.0'}},
               {'name': 'Estella Bartlet Silver Plated Heart Bracelet Duo Set',
                'price': {'currency': 'GBP',
                          'outlet': '15.0',
                          'retail': '31.0'}},
               {'name': 'Ashiana Embroidered Large Toiletry Bag With Wateproof '
                        'Lining',
                'price': {'currency': 'GBP',
                          'outlet': '25.0',
                          'retail': '35.0'}}]}]

It's because on every product processing I'm using Loader.load_item().

How can I build a pipeline or output processor to make it only return the last processed item, like the following?

[{'gender': 'women',
  'name': 'NEW IN: CLOTHING',
  'products': [{'name': 'Free People Cocoon Multi Way Neck Top',
                'price': {'currency': 'GBP',
                          'outlet': '40.0',
                          'retail': '58.0'}},
               {'name': 'N12H Joshua Tree Dress',
                'price': {'currency': 'GBP',
                          'outlet': '140.0',
                          'retail': '249.0'}},
               {'name': 'Twiin Method Rib Mesh Flare Sleeve Top',
                'price': {'currency': 'GBP',
                          'outlet': '22.0',
                          'retail': '32.0'}},
               {'name': 'Twiin End Game Varsity Denim Trucker Jacket',
                'price': {'currency': 'GBP',
                          'outlet': '45.0',
                          'retail': '80.0'}}]},
 {'gender': 'women',
  'name': 'NEW IN: SHOES & ACCESSORIES ',
  'products': [{'name': 'Melissa Ultragirl Triple Bow Ballerina',
                'price': {'currency': 'GBP',
                          'outlet': '48.0',
                          'retail': '68.0'}},
               {'name': 'Zaxy Tbar Flip Flops',
                'price': {'currency': 'GBP',
                          'outlet': '20.0',
                          'retail': '26.0'}},
               {'name': 'Estella Bartlet Silver Plated Heart Bracelet Duo Set',
                'price': {'currency': 'GBP',
                          'outlet': '15.0',
                          'retail': '31.0'}},
               {'name': 'Ashiana Embroidered Large Toiletry Bag With Wateproof '
                        'Lining',
                'price': {'currency': 'GBP',
                          'outlet': '25.0',
                          'retail': '35.0'}}]}]

The last lines processed have all the products from that session. I tried processing when the spider closes, without success.

I am almost finishing this project, researched a lot and tried many things, many questions, but none related to item stacking on a field.

My items code:

from scrapy.item import Item, Field
from scrapy.loader.processors import TakeFirst, Join, Compose, MapCompose

class Session(Item):
    name = Field()
    gender = Field()
    products = Field(
        # no idea what to put... tryed Join, Compose and MapCompose
    )

class Product(Item):
    name = Field()
    price = Field()

class Price(Item):
    outlet = Field()
    retail = Field()
    currency = Field()

My spider code:

def parse(self, response):
    sessions = response.css("article.feature:nth-of-type(-n+2)")
    for session in sessions:
        sessionlink = session.css("a.feature__link::attr(href)").extract_first()

        lsession = ItemLoader(item=Session(), response=response)
        lsession.add_value("name", session.css("div.feature__title h3::text").extract_first())
        lsession.add_value("gender", re.split("[/]+", response.request.url)[2])

        requestsession = response.follow(sessionlink, callback=self.parse_session)
        requestsession.meta["lsession"] = lsession
        requestsession.meta["pages"] = 1
        yield requestsession

def parse_session(self, response):
    lsession = response.meta["lsession"]
    pages = response.meta["pages"]

    products = response.css("li.product-container:nth-of-type(-n+2)")

    for product in products:
        productlink = product.css("a.product-link::attr(href)").extract_first()
        requestproduct = response.follow(productlink, callback=self.parse_product)
        requestproduct.meta["lsession"] = lsession
        requestproduct.meta["productlink"] = productlink
        yield requestproduct

    nextpage = response.css("ul.pager li.next a::attr(href)").extract_first()
    if pages < 2:
        pages += 1
        requestnewpage = response.follow(nextpage, callback=self.parse_session)
        requestnewpage.meta["lsession"] = lsession
        requestnewpage.meta["pages"] = pages
        yield requestnewpage

def parse_product(self, response):
    lsession = response.meta["lsession"]
    productlink = response.meta["productlink"]

    lproduct = ItemLoader(item=Product(), response=response)

    name = response.css("div.product-hero>h1::text").extract_first()

    lproduct.replace_value("name", str(name))

    pricelink = "AN AJAX LINK TO GET THE PRICE"

    requestprice = response.follow(pricelink, callback=self.parse_price)
    requestprice.meta["lsession"] = lsession
    requestprice.meta["lproduct"] = lproduct

    yield requestprice

def parse_price(self, response):
    lsession = response.meta["lsession"]
    lproduct = response.meta["lproduct"]

    lprice = ItemLoader(item=Price(), response=response)

    pricejson = json.loads(response.body)
    outletprice = pricejson[0]["productPrice"]["current"]["value"]
    retailprice = pricejson[0]["productPrice"]["rrp"]["value"]
    currency = pricejson[0]["productPrice"]["currency"]

    lprice.replace_value("outlet", str(outletprice))
    lprice.replace_value("retail", str(retailprice))
    lprice.replace_value("currency", str(currency))
    lproduct.replace_value("price", lprice.load_item())
    lsession.add_value("products", dict(lproduct.load_item()))

    yield lsession.load_item()

Body:
YATTA!!!
Remembering my school days, I recorded about closures.
I did not know python had this kind of functional behaviour. I am a beginner at the language.

So, since I got a lot of help here, I am going to post here my solution so others can get help if needed.

I made a closure counter like this (just a basic one):

def counter():
    value = 0
    def count(op):
        nonlocal value
        if op == "add":
            value += 1
        elif op == "sub":
            value -= 1
        elif op == "get":
            return value

    return count

Then, I started a counter for each section:

requestsession = response.follow(sessionlink, callback=self.parse_session)
requestsession.meta["lsession"] = lsession
requestsession.meta["pcounter"] = counter()
requestsession.meta["pages"] = 1

When processing each product, I counted up, and continued to pass the counter until the price processing:

for product in products:
    pcounter("add")
    productlink = product.css("a.product-link::attr(href)").extract_first()
    requestproduct = response.follow(productlink, callback=self.parse_product)
    requestproduct.meta["lsession"] = lsession
    requestproduct.meta["pcounter"] = pcounter
    requestproduct.meta["productlink"] = productlink
    yield requestproduct

After the price parsing I count down and, when I load the "lsession" item loader, I check if all the products were processed:

pcounter("sub")

if pcounter("get") == 0:
    yield lsession.load_item()

Hope it will be useful for someone.


来源: stackexchange

问:
How to install freeimage.dll on Windows?
How to register/install freeimage.dll on my Windows XP machine? I have download the library and open my command shell pointing to the freeimage folder. I ran regsvr32 but the library won't install .

答: Just copy it to local or windows/system directory, only ActiveX and COM servers need regsvr32.</p>

ContentLicense: CC BY-SA 2.5


问:
SiddhiQL Pattern and Window Query
I am trying to write a simple siddhi query which detects a pattern
eg: "Ice" "cream" "x" "y" "apple" "water"

where events Ice & cream both should be together and apple water should be together and x y are any random values in the window.length(6)

problem is the following query is not restricting the window.length(6) how can i achieve this?

```<code>from every (( s1=windowedStream[s1.val=='ice']-> s2= windowedStream[s2.val=='cream'] )
            -> ( a1=windowedStream[a1.val=='apple'] -> a2 = windowedStream[a2.val =='water'] ))
select s1.meta_timestamp, s1.val
insert into filteredStream
</code>```

答:
As per the existent notations, Siddhi allows you to restrict a pattern based on a time window only. Please refer the following.

https://docs.wso2.com/display/CEP420/SiddhiQL+Guide+3.1#SiddhiQLGuide3.1-Pattern

As a workaround to restricting the patterns based on a length window, you may introduce a 3rd attribute called index to the "windowedStream", where index reflects the order of event arrival (i.e. index of the 1st event is 1, index of the 2nd event is 2 and so on). Then the following query would capture the patterns occurring within a length window of 6 events.

```<code>from every (( s1=tempStream[s1.val=='ice']-> s2= tempStream[s2.val=='cream'] )
        -> ( a1=tempStream[a1.val=='apple'] -> a2 = tempStream[a2.val =='water' and a2.index- s1.index <= 6]))
select s1.meta_timestamp, s1.val
insert into filteredStream;
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Title: SiddhiQL Pattern and Window Query

Body:
I am trying to write a simple siddhi query which detects a pattern
eg: "Ice" "cream" "x" "y" "apple" "water"

where events Ice & cream both should be together and apple water should be together and x y are any random values in the window.length(6)

problem is the following query is not restricting the window.length(6) how can i achieve this?

from every (( s1=windowedStream[s1.val=='ice']-> s2= windowedStream[s2.val=='cream'] )
            -> ( a1=windowedStream[a1.val=='apple'] -> a2 = windowedStream[a2.val =='water'] ))
select s1.meta_timestamp, s1.val
insert into filteredStream

Body:
As per the existent notations, Siddhi allows you to restrict a pattern based on a time window only. Please refer the following.

https://docs.wso2.com/display/CEP420/SiddhiQL+Guide+3.1#SiddhiQLGuide3.1-Pattern

As a workaround to restricting the patterns based on a length window, you may introduce a 3rd attribute called index to the "windowedStream", where index reflects the order of event arrival (i.e. index of the 1st event is 1, index of the 2nd event is 2 and so on). Then the following query would capture the patterns occurring within a length window of 6 events.

from every (( s1=tempStream[s1.val=='ice']-> s2= tempStream[s2.val=='cream'] )
        -> ( a1=tempStream[a1.val=='apple'] -> a2 = tempStream[a2.val =='water' and a2.index- s1.index <= 6]))
select s1.meta_timestamp, s1.val
insert into filteredStream;

Hope this helps.


问:
How to trace a fatal error with Xcode and Swift?
I am trying to test a simple a program I have made while learning swift programming, but I always get a fatal error, and nothing will be shown.

I tried to copy my code to a playground, but there the custom classes I created are not recognized?

答: I found the error that one of the buttons is referencing the wrong outlet. This outlet was created by mistake, and it is name is the same as one of the Actions.</p>


问:
Rails file download via send_file is slow, is X-Sendfile or similar available in puma?
Downloading off the public folder takes 2 seconds.

Downloading the same file using the send_file method below takes nearly a minute.

```<code>  def download
    file = FileUpload.find params[:id]
    file_path = Rails.root.join('private', file.name)
    send_file(file_path,
              x_sendfile: true,
              disposition: 'attachment')
  end
</code>```

I have tried changing buffer size and so on but it's still extremely slow, slower than the database & send_data combination.

Apart from ditching Rails entirely, is there an simple solution to this?

答:
After some search I realized my question was a little silly:

Puma is, in practice, an Application server

To be precise, Puma calls itself a web server but rails usage wise it seems either Apache or Nginx is inserted between the user and Puma in most cases.

Puma itself, as of now, does not seem to support either X-Sendfile nor X-Accel-Redirect. It's up to Apache or Nginx.

Getting it work with rails5, puma, nginx in development environment

Steps are for ubuntu 16lts, puma version 3.9.1, nginx/1.10.0 (Ubuntu), Rails 5.1.1, ruby 2.4.0p0

```<code>sudo apt install nginx
sudo ufw allow 'Nginx HTTP'
sudo trash /etc/nginx/sites-enabled/defualt #renaming did not work
sudo touch /etc/nginx/sites-available/rails.conf
sudo ln -sf /etc/nginx/sites-available/rails.conf /etc/nginx/stes-enabled/rails.conf
</code>```

Edited: /etc/nginx/sites-available/rails.conf

```<code>upstream uploader {
  server localhost:3000 fail_timeout=0;
}

server {
  listen 80;
  listen [::]:80;
  #Your public folder path
  root /home/d/WebApp/uploader/public;
  location ~ ^/assets/ {
    expires max;
    gzip_static on;
    gzip_vary on;
    add_header Cache-Control public;
    break;
  }
  location / {
    proxy_pass http://uploader;# http://appNameYouChooseAbove
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    #Inform rails how to ask nginx to deliver files.
    #nginx does not take an absolute file path,
    #it needs url.
    #X-Accel-Mapping contains info needed to convert
    #an absolute file path to an url.
    proxy_set_header X-Accel-Mapping /home/d/WebApp/uploader/private=/available_only_when_redirected_here_by_upstream_server;
    #The above is used by rails to translate:
    #e.g.
    #  /home/d/WebApp/uploader/private/file.zip
    #  to
    #  available_only_when_redirected_here_by_upstream_server/file.zip
    #  When rails access the above, nginx delivers the file to the client
    proxy_set_header X-Sendfile-Type X-Accel-Redirect;
  }

  location /available_only_when_redirected_here_by_upstream_server {
      #without alias, nginx tries to open file at:
      #"root + this location + filename"
      #e.g.
      #  given file file.zip
      #  root of "/home/d/WebApp/uploader/public" as defined above.
      #  this lociation which is "available_only_when_redirected_here_by_upstream_server"
      #
      #  /home/d/WebApp/uploader/public/ava...server/file.zip
      #
      alias /home/d/WebApp/uploader/private/;
      # internal ensures this url in only available from upsteam location/application server
      internal;
  }

  error_page 500 502 503 504 /500.html;
  error_page 404 /404.html;
  error_page 422 /422.html;
  client_max_body_size 4G;
  keepalive_timeout 10;
}
</code>```

Append the below to config/environment/development.rb

```<code>config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
</code>```

Restart servers

```<code>bundle exec rails s Puma
sudo service nginx restart
</code>```

P.S

Direct access to localhost:3000 bypasses nginx; omit port number to go through nginx.

P.P.S

Edited Nginx config as it was not working;I don't know why download speed improved when it should not!

"X-Accel-Mapping header missing" means X-Accel-Redirect not working.

X-Accel-Mapping can be defined in inner context like:

```<code>location / {
  location /static {
    proxy_pass http://uploader;# http://appNameYouChooseAbove
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Accel-Mapping /...=/...;
  }
}
</code>```

and redirection targets can be created as many as needed, so it's not as bad as it appears.

Be warned, however, Nginx configuration is a wild ride. Without proxy_set_header etc, introducing inner context morphs url to root path + location form and gosh it was not very intuitive!

Body:
Downloading off the public folder takes 2 seconds.

Downloading the same file using the send_file method below takes nearly a minute.

  def download
    file = FileUpload.find params[:id]
    file_path = Rails.root.join('private', file.name)
    send_file(file_path,
              x_sendfile: true,
              disposition: 'attachment')
  end

I have tried changing buffer size and so on but it's still extremely slow, slower than the database & send_data combination.

Apart from ditching Rails entirely, is there an simple solution to this?

Body:
After some search I realized my question was a little silly:

Puma is, in practice, an Application server

To be precise, Puma calls itself a web server but rails usage wise it seems either Apache or Nginx is inserted between the user and Puma in most cases.

Puma itself, as of now, does not seem to support either X-Sendfile nor X-Accel-Redirect. It's up to Apache or Nginx.

Getting it work with rails5, puma, nginx in development environment

Steps are for ubuntu 16lts, puma version 3.9.1, nginx/1.10.0 (Ubuntu), Rails 5.1.1, ruby 2.4.0p0

sudo apt install nginx
sudo ufw allow 'Nginx HTTP'
sudo trash /etc/nginx/sites-enabled/defualt #renaming did not work
sudo touch /etc/nginx/sites-available/rails.conf
sudo ln -sf /etc/nginx/sites-available/rails.conf /etc/nginx/stes-enabled/rails.conf

Edited: /etc/nginx/sites-available/rails.conf

upstream uploader {
  server localhost:3000 fail_timeout=0;
}

server {
  listen 80;
  listen [::]:80;
  #Your public folder path
  root /home/d/WebApp/uploader/public;
  location ~ ^/assets/ {
    expires max;
    gzip_static on;
    gzip_vary on;
    add_header Cache-Control public;
    break;
  }
  location / {
    proxy_pass http://uploader;# http://appNameYouChooseAbove
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    #Inform rails how to ask nginx to deliver files.
    #nginx does not take an absolute file path,
    #it needs url.
    #X-Accel-Mapping contains info needed to convert
    #an absolute file path to an url.
    proxy_set_header X-Accel-Mapping /home/d/WebApp/uploader/private=/available_only_when_redirected_here_by_upstream_server;
    #The above is used by rails to translate:
    #e.g.
    #  /home/d/WebApp/uploader/private/file.zip
    #  to
    #  available_only_when_redirected_here_by_upstream_server/file.zip
    #  When rails access the above, nginx delivers the file to the client
    proxy_set_header X-Sendfile-Type X-Accel-Redirect;
  }

  location /available_only_when_redirected_here_by_upstream_server {
      #without alias, nginx tries to open file at:
      #"root + this location + filename"
      #e.g.
      #  given file file.zip
      #  root of "/home/d/WebApp/uploader/public" as defined above.
      #  this lociation which is "available_only_when_redirected_here_by_upstream_server"
      #
      #  /home/d/WebApp/uploader/public/ava...server/file.zip
      #
      alias /home/d/WebApp/uploader/private/;
      # internal ensures this url in only available from upsteam location/application server
      internal;
  }

  error_page 500 502 503 504 /500.html;
  error_page 404 /404.html;
  error_page 422 /422.html;
  client_max_body_size 4G;
  keepalive_timeout 10;
}

Append the below to config/environment/development.rb

config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX

Restart servers

bundle exec rails s Puma
sudo service nginx restart

P.S

Direct access to localhost:3000 bypasses nginx; omit port number to go through nginx.

P.P.S

Edited Nginx config as it was not working;I don't know why download speed improved when it should not!

"X-Accel-Mapping header missing" means X-Accel-Redirect not working.

X-Accel-Mapping can be defined in inner context like:

location / {
  location /static {
    proxy_pass http://uploader;# http://appNameYouChooseAbove
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Accel-Mapping /...=/...;
  }
}

and redirection targets can be created as many as needed, so it's not as bad as it appears.

Be warned, however, Nginx configuration is a wild ride. Without proxy_set_header etc, introducing inner context morphs url to root path + location form and gosh it was not very intuitive!


问:
Running application as windows service
I have an application that is running as window service and its running under a valid use account not under default system account ,now my worry is if in future use changes his password for that account will it effect this service??

Thanks

答: The service will stop working as the user credentials don't match.</p>

Title: Running application as windows service


问:
Storing list of instances (of self) in class level attribute?
I have a class in which I would like to store a static reference list of objects of the same class. For example:

```<code>class Apple:

    NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'),
        Apple('Pink Lady', 'Pink')]

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour
</code>```

This results in a NameError: name 'Apple' is not defined error.
Why doesn't this work?

I've changed the code to the following, which seems to work on the console:

```<code>class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

Apple.NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'),
        Apple('Pink Lady', 'Pink')]
</code>```

Is there a better way to do this?
Will this work inside and outside the module, and is this dependent on the way I import the module?

答:
You can create new class instance from class method, like this, I think this is a clean way yo do it, and also if you want to store the recent created obj besides a list of hardcords:</p>

```<code>class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

    @classmethod
    def init_with_nice_apples(self, name, colour):
        Apple.NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red')] #hardcore list
        self.__init__(self,name, colour)
        Apple.NICE_APPLES.append(self)
        return self

ap = Apple.init_with_nice_apples("Delicius", "Red")
</code>```

Body:
I have a class in which I would like to store a static reference list of objects of the same class. For example:

class Apple:

    NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'),
        Apple('Pink Lady', 'Pink')]

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

This results in a NameError: name 'Apple' is not defined error.
Why doesn't this work?

I've changed the code to the following, which seems to work on the console:

class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

Apple.NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'),
        Apple('Pink Lady', 'Pink')]

Is there a better way to do this?
Will this work inside and outside the module, and is this dependent on the way I import the module?

Body:
You can create new class instance from class method, like this, I think this is a clean way yo do it, and also if you want to store the recent created obj besides a list of hardcords:

class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

    @classmethod
    def init_with_nice_apples(self, name, colour):
        Apple.NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red')] #hardcore list
        self.__init__(self,name, colour)
        Apple.NICE_APPLES.append(self)
        return self

ap = Apple.init_with_nice_apples("Delicius", "Red")


问:
Cognos 10 Display Query Result in Header as a ParamName or ParamValue
Cognos 10.2.2
Using a Data Item Expression to generate a column that populates each column row.

```<code>if ( [X].[X].[Yr]  = '15' ) then ( '2014-2015') else
if ( [X].[X].[Yr]  = '16' ) then ( '2015-2016') else
if ( [X].[X].[Yr]  = '17' ) then ( '2016-2017') else NULL
</code>```

Simple. Works great.

Want to use the resulting value as a single value in header.

So the report title displays "2015-2016" (without quotes) if ( [X].[X].[Yr]  = '16' )

There is probably a very easy way to do this.  Will not get the last couple of hours of my life back.  Help!

答:
I think what you want to use is a singleton. You can find the object in the Toolbox.

Insert the singleton into the header, set the query property to be the data query containing the data item, and drag over the data item into the singleton.

Note: Singletons can only show one value. If you give it a data item that is variant across rows, it will simply display the value from the first row only.

Body:
Cognos 10.2.2
Using a Data Item Expression to generate a column that populates each column row.

if ( [X].[X].[Yr]  = '15' ) then ( '2014-2015') else
if ( [X].[X].[Yr]  = '16' ) then ( '2015-2016') else
if ( [X].[X].[Yr]  = '17' ) then ( '2016-2017') else NULL

Simple. Works great.

Want to use the resulting value as a single value in header.

So the report title displays "2015-2016" (without quotes) if ( [X].[X].[Yr]  = '16' )

There is probably a very easy way to do this.  Will not get the last couple of hours of my life back.  Help!


问:
How do I activate a Spring Boot profile when running from IntelliJ?
I have 5 environments:

```<code> - local (my development machine)
 - dev
 - qc
 - uat
 - live
 - staging
</code>```

I want different application properties to be used for each environment, so I have the following properties files each which have a different URL for the datasource:

```<code> - application.properties  (containing common properties)
 - application-local.properties
 - application-dev.properties
 - application-qc.properties
 - application-uat.properties
 - application-live.properties
</code>```

I am using IntelliJ and running my app using bootRun in the Gradle plugin on my local machine.  I will be using deploying the same application war file on all other environments which run Tomcat.

I have tried adding:

--spring.profiles.active=local

to the run configuration under script parameters.

I have tried adding

-Dspring.profiles.active=local

to the run configuration under VM options.

Neither work. I keep seeing the INFO message on startup say: No active profile set, falling back to default profiles: default

If I run my app from the windows command line using

```<code>gradle bootRun
</code>```

but I first set the environment variable

```<code>set SPRING_PROFILES_ACTIVE=local
</code>```

Then everything works.

So my question is, how do I activate my local spring boot profile when running bootRun from IntelliJ ?

答:
I added -Dspring.profiles.active=test to VM Options and then re-ran that configuration. It worked perfectly.

This can be set by

Choosing Run | Edit Configurations...

Go to the Configuration tab

Expand the Environment section to reveal VM options

Body:
I have 5 environments:

 - local (my development machine)
 - dev
 - qc
 - uat
 - live
 - staging

I want different application properties to be used for each environment, so I have the following properties files each which have a different URL for the datasource:

 - application.properties  (containing common properties)
 - application-local.properties
 - application-dev.properties
 - application-qc.properties
 - application-uat.properties
 - application-live.properties

I am using IntelliJ and running my app using bootRun in the Gradle plugin on my local machine.  I will be using deploying the same application war file on all other environments which run Tomcat.

I have tried adding:

--spring.profiles.active=local

to the run configuration under script parameters.

I have tried adding

-Dspring.profiles.active=local

to the run configuration under VM options.

Neither work. I keep seeing the INFO message on startup say: No active profile set, falling back to default profiles: default

If I run my app from the windows command line using

gradle bootRun

but I first set the environment variable

set SPRING_PROFILES_ACTIVE=local

Then everything works.

So my question is, how do I activate my local spring boot profile when running bootRun from IntelliJ ?

ContentLicense: CC BY-SA 4.0


问:
Callback functions in Java
Is there a way to pass a call back function in a Java method?

The behavior I'm trying to mimic is a .Net Delegate being passed to a function.

I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.

答:
If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well. </p>

```<code>public class Main {

    public interface Visitor{
        int doJob(int a, int b);
    }

    public static void main(String[] args) {
        Visitor adder = new Visitor(){
            public int doJob(int a, int b) {
                return a + b;
            }
        };

        Visitor multiplier = new Visitor(){
            public int doJob(int a, int b) {
                return a*b;
            }
        };

        System.out.println(adder.doJob(10, 20));
        System.out.println(multiplier.doJob(10, 20));

    }
}
</code>```

OwnerDisplayName: Omar Kooheji

Title: Callback functions in Java

Body:
If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well.

public class Main {

    public interface Visitor{
        int doJob(int a, int b);
    }

    public static void main(String[] args) {
        Visitor adder = new Visitor(){
            public int doJob(int a, int b) {
                return a + b;
            }
        };

        Visitor multiplier = new Visitor(){
            public int doJob(int a, int b) {
                return a*b;
            }
        };

        System.out.println(adder.doJob(10, 20));
        System.out.println(multiplier.doJob(10, 20));

    }
}


问:
Is it possible to make a div follow another element iside an iframe if the content of the iframe is from the same domain
I am thinking about using JavaScript to make a div in the parent webpage to follow the position of another element inside an iframe; the position of the element in the iframe changes when the size of the window changes (responsive design), so is it possible to make the div at the parent page change position accordingly as well? I simply don't know where to start</p>

答:
You can get the element inside the iframe:

```<code>document.getElementById('iFrame').contentWindow.document.getElementById('x');
</code>```

Once you get the element you can work with his position, to get element position with pure javascript look this.

It's simpler to do this with jquery, but maybe with javascript it's more efficient.

After all, just position your div according to the position of the element.

Body:
You can get the element inside the iframe:

document.getElementById('iFrame').contentWindow.document.getElementById('x');

Once you get the element you can work with his position, to get element position with pure javascript look this.

It's simpler to do this with jquery, but maybe with javascript it's more efficient.

After all, just position your div according to the position of the element.


问:
VBScript sendkeys, Trying to do CTRL+ALT+A
I'm testing Lexibar software for voice synthesis in our schoolboard.
This kind of software is design to help students who have learning difficulty so I need to write a VBS file that simulate the Ctrl+Alt+A.

I tried :

wshshell.sendkeys "^%{a}"

"^%a"

"^%{A}"

"^%A"

"^(%a)"

"^(%(a))"

... (But nothing worked)

If I try wshshell.sendkeys "^%{down}"  -> the screen rotate but I am not able to send Ctrl+Alt+A.

Is it blocked (Ctrl+Alt+Del is blocked).

答:
I now use powershell and it work great.
With VBS, it worked once and then it stoped working. This is the code I run:

```<code>[void][reflection.assembly]::loadwithpartialname("system.windows.forms")
[system.windows.forms.sendkeys]::sendwait("^%a")
</code>```

I used PS2EXE 0.5.1 to convert the script to a exe (SendKeys.exe), then I run it from this code:

```<code>Set wshShell = WScript.CreateObject("WScript.Shell")
wshShell.run "C:\Lexibar\SendKeys.exe",0
</code>```

I need to run it from a vbs to avoid windows to pop.
I used Vbs_To_exe to convert this one and now it work.
(converting to .exe is just for security, hide my code from students)

Body:
I now use powershell and it work great.
With VBS, it worked once and then it stoped working. This is the code I run:

[void][reflection.assembly]::loadwithpartialname("system.windows.forms")
[system.windows.forms.sendkeys]::sendwait("^%a")

I used PS2EXE 0.5.1 to convert the script to a exe (SendKeys.exe), then I run it from this code:

Set wshShell = WScript.CreateObject("WScript.Shell")
wshShell.run "C:\Lexibar\SendKeys.exe",0

I need to run it from a vbs to avoid windows to pop.
I used Vbs_To_exe to convert this one and now it work.
(converting to .exe is just for security, hide my code from students)


问:
single or double quote in javascript append
i am beginner in Jquery,
confused about using single quote or double quote to call the value of myName Textbox, i want to catch the value of text box .

this is my code, calling function save_order is not working, because failure syntax in
document.getElementById('myName').value

what is the right syntax ?

```<code><script>
var param=3;
$('#saveList').append(
'<p>FullName : <input type="text" id="myName"></p>'+
'<p><input type="button" value="SAVE" onClick="save_order('+ param +',document.getElementById('myName').value)"></p>');
</script>
</code>```

pls help me anybody
thank you

答:
The problem is in calling document.getelementById. With escaping, you can achieve your result.

```<code><script>
var param=3;
$('#saveList').append(
'<p>FullName : <input type="text" id="myName"></p>'+
'<p><input type="button" value="SAVE" onClick="save_order('+ param +',document.getElementById(\'myName\').value)"></p>');
</script>
</code>```

Check your part: document.getElementById('myName') ...

And my part: document.getElementById(\'myName\')

When you use ' as start and end character of string, you have to use \' if you want to use ' inside as string literal.

Body:
i am beginner in Jquery,
confused about using single quote or double quote to call the value of myName Textbox, i want to catch the value of text box .

this is my code, calling function save_order is not working, because failure syntax in
document.getElementById('myName').value

what is the right syntax ?

pls help me anybody
thank you

Body:
The problem is in calling document.getelementById. With escaping, you can achieve your result.

<script>
var param=3;
$('#saveList').append(
'<p>FullName : <input type="text" id="myName"></p>'+
'<p><input type="button" value="SAVE" onClick="save_order('+ param +',document.getElementById(\'myName\').value)"></p>');
</script>

Check your part: document.getElementById('myName') ...

And my part: document.getElementById(\'myName\')

When you use ' as start and end character of string, you have to use \' if you want to use ' inside as string literal.


问:
Java: Calculating perfomance per second
I have a thread pool that performs some heavy operations concurrently, the following is my code

ExampleCompute.java

```<code>class ExampleCompute {
   private List<long> allData = new ArrayList<long>();
   ExecutorService executor = Executors.newFixedThreadPool(1000);

   public calculate() {
      for(int i=0; i<myData.size; i++) {
        MyWorker worker = new MyWorker(myData.get(i));
        Future<long> currentDataPoint = executor.submit(worker);
        allData.add(currentDataPoint);
      }

      executor.shutdown();
      while (!executor.isTerminated()) {
      }
   }
}
</code>```

What I am attempting to do is print to the screen how many operations are finishing per second every N seconds.

For example

```<code>// Every 10 seconds do the following
System.out.println("Thread pool is completing 533 calculation per second");
</code>```

What would be the best way to implement this?

答:
You can use before and after method to track the time</p>

```<code>public class TrackingThreadPool extends ThreadPoolExecutor {

    private final ThreadLocal<Long> startTime = new ThreadLocal<Long>();
    private volatile long totalTime;
    private volatile long totalTasks;

    public TrackingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
            BlockingQueue<Runnable> workQueue, ThreadFactory factory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory);
    }

    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        startTime.set(new Long(System.currentTimeMillis()));
    }

    protected void afterExecute(Runnable r, Throwable t) {

        long time = System.currentTimeMillis() - startTime.get().longValue();

        synchronized (this) {
            totalTime += time;
            ++totalTasks;
        }

        super.afterExecute(r, t);
    }
}
</code>```

Title: Java: Calculating perfomance per second

Body:
I have a thread pool that performs some heavy operations concurrently, the following is my code

ExampleCompute.java

class ExampleCompute {
   private List<long> allData = new ArrayList<long>();
   ExecutorService executor = Executors.newFixedThreadPool(1000);

   public calculate() {
      for(int i=0; i<myData.size; i++) {
        MyWorker worker = new MyWorker(myData.get(i));
        Future<long> currentDataPoint = executor.submit(worker);
        allData.add(currentDataPoint);
      }

      executor.shutdown();
      while (!executor.isTerminated()) {
      }
   }
}

What I am attempting to do is print to the screen how many operations are finishing per second every N seconds.

For example

// Every 10 seconds do the following
System.out.println("Thread pool is completing 533 calculation per second");

What would be the best way to implement this?

Body:
You can use before and after method to track the time

public class TrackingThreadPool extends ThreadPoolExecutor {

    private final ThreadLocal<Long> startTime = new ThreadLocal<Long>();
    private volatile long totalTime;
    private volatile long totalTasks;

    public TrackingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
            BlockingQueue<Runnable> workQueue, ThreadFactory factory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory);
    }

    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        startTime.set(new Long(System.currentTimeMillis()));
    }

    protected void afterExecute(Runnable r, Throwable t) {

        long time = System.currentTimeMillis() - startTime.get().longValue();

        synchronized (this) {
            totalTime += time;
            ++totalTasks;
        }

        super.afterExecute(r, t);
    }
}


问:
Scala Polymorphic Function That Would Compile But Would Not Run As Expected
Given following two Scala functions, both compiles as expected.

```<code>scala> def toList[A](a: A) = List(a)
toList: [A](a: A)List[A]

scala> def foo[A](f: A => List[A], b: A) = f(b)
foo: [A](f: A => List[A], b: A)List[A]
</code>```

Yet, when you run it, it gave following error message:

```<code>scala> foo(toList, 12)
<console>:14: error: type mismatch;
 found   : Nothing => List[Nothing]
 required: Int => List[Int]
       foo(toList, 12)
</code>```

Why does Scala think toList function is of Nothing => List[Nothing] instead of Int => List[Int]?

答:
The Scala compiler will try to infer the type parameters of the method, it will look to the parameters defined int he first parenthesis and try to extract the type from them, if it can not it will pick the next parameter group to infer the type, and so on...

The best way to define that function is like this

```<code>def foo[A](b: A)(f: A => List[A]) = f(b)
</code>```

Giving the parameters in this order will allow you to avoid the need of giving some hint to the compliler. You can call this function like this:

```<code>foo(2.0d)(toList)
</code>```

And you will get a List[Double]

If you keep the other order you will need to give a hint to the compiler in order to figure out the type parameter A

```<code>foo(toList[Double], 2.0d)
</code>```

Body:
Given following two Scala functions, both compiles as expected.

scala> def toList[A](a: A) = List(a)
toList: [A](a: A)List[A]

scala> def foo[A](f: A => List[A], b: A) = f(b)
foo: [A](f: A => List[A], b: A)List[A]

Yet, when you run it, it gave following error message:

scala> foo(toList, 12)
<console>:14: error: type mismatch;
 found   : Nothing => List[Nothing]
 required: Int => List[Int]
       foo(toList, 12)

Why does Scala think toList function is of Nothing => List[Nothing] instead of Int => List[Int]?

Body:
The Scala compiler will try to infer the type parameters of the method, it will look to the parameters defined int he first parenthesis and try to extract the type from them, if it can not it will pick the next parameter group to infer the type, and so on...

The best way to define that function is like this

def foo[A](b: A)(f: A => List[A]) = f(b)

Giving the parameters in this order will allow you to avoid the need of giving some hint to the compliler. You can call this function like this:

foo(2.0d)(toList)

And you will get a List[Double]

If you keep the other order you will need to give a hint to the compiler in order to figure out the type parameter A

foo(toList[Double], 2.0d)


答:
Yes.

The password you enter in the service properties must be changed of the user changes his password, so it's a bad idea to run a service under a real live user account.

You can either set it to run on a system account, and grant that account the necessary resources for the service to function, or you can create a pseudo-system account - a user account that is restricted from everything else, except from the service resources.

Title: Running application as windows service

Body:
I have an application that is running as window service and its running under a valid use account not under default system account ,now my worry is if in future use changes his password for that account will it effect this service??

Thanks


问:
Sorting using the Smartsheet API
Python SDK for Smartsheet API (latest versions)

Here's the scenario:
I have a large (over 3000 rows) sheet. New records are added (at the bottom) in batches (typically 100 - 150 rows at a time).
There is a column with an identifier (not an auto-number).
We would like to sort on the identifier.

This is easy but manual using the GUI.
Since it is probable that a large portion of the rows will be affected, I suspect that this sorting may be something that hits or exceeds rate limits when done via the API.

Before I invest too much time in developing the solution, I'm looking for a sanity check on whether it will or might exceed those limits.

Thanks.

Craig

答: If your application is single-threaded and working with a single sheet, it's unlikely that you will encounter rate limiting. Also, the Python SDK automatically retries rate limit errors. (And the other SDKs will soon.)</p>

Title: Sorting using the Smartsheet API


问:
How to determine if a function was called with `.call` or `.apply`?
I created this function so that I could chain methods together:

```<code>export default function bindable(fn) {
    return function boundFn(...args) {
        return this === undefined ? fn(...args) : fn(this, ...args);
    }
}
</code>```

It works with the bind operator. For example, you can define a new function like,

```<code> export const flatten = bindable(arrayOfArrays => Array.prototype.concat(...arrayOfArrays));
</code>```

And then use it like this:

```<code>[[1,2,3],[4,5,6]]::flatten()
</code>```

Or like this:

```<code>flatten([[1,2,3],[4,5,6]])
</code>```

Babel REPL

This worked great at first until I realized that if I use it like in the second scenario, but import the helper method as a module, it breaks the context!

```<code> import * as Arr from './array-helper-methods';
 Arr.flatten([1,2,3]); // `this` is now `Arr`
</code>```

So my question is: is there any way that I can reliably detect if a function is called with the bind operator?

答:
A more generic (but not so good performance-wise) solution would be to check if any method of this is the boundFn function:

```<code>export default function bindable(fn) {
    return function boundFn(...args) {
        return (this == null || Object.values(this).some(x => x === boundFn))
            ? fn(...args)
            : fn(this, ...args);
    }
}
</code>```

Body:
I created this function so that I could chain methods together:

export default function bindable(fn) {
    return function boundFn(...args) {
        return this === undefined ? fn(...args) : fn(this, ...args);
    }
}

It works with the bind operator. For example, you can define a new function like,

 export const flatten = bindable(arrayOfArrays => Array.prototype.concat(...arrayOfArrays));

And then use it like this:

[[1,2,3],[4,5,6]]::flatten()

Or like this:

flatten([[1,2,3],[4,5,6]])

<a href="https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=env%2Cstage-0&targets=Node-8&browsers=&builtIns=false&debug=true&experimental=true&loose=true&spec=false&code=function%20bindable(fn)%20%7B%0A%20%20%20%20return%20function%20boundFn(...args)%20%7B%0A%20%20%20%20%20%20%20%20return%20this%20!%3D%3D%20undefined%20%26%26%20args.length%20%3C%20fn.length%20%3F%20this%3A%3Afn(this%2C%20...args)%20%3A%20this%3A%3Afn(...args)%3B%0A%20%20%20%20%7D%0A%7D%0A%0Aconst%20flatten%20%3D%20bindable(arrayOfArrays%20%3D%3E%20Array.prototype.concat(...arrayOfArrays))%3B%0A%0Aconsole.log(%5B%5B1%2C2%2C3%5D%2C%5B4%2C5%2C6%5D%5D%3A%3Aflatten())%3B%0Aconsole.log(flatten(%5B%5B1%2C2%2C3%5D%2C%5B4%2C5%2C6%5D%5D))%3B" rel="nofollow noreferrer">Babel REPL

This worked great at first until I realized that if I use it like in the second scenario, but import the helper method as a module, it breaks the context!

 import * as Arr from './array-helper-methods';
 Arr.flatten([1,2,3]); // `this` is now `Arr`

So my question is: is there any way that I can reliably detect if a function is called with the bind operator?

Body:
A more generic (but not so good performance-wise) solution would be to check if any method of this is the boundFn function:

export default function bindable(fn) {
    return function boundFn(...args) {
        return (this == null || Object.values(this).some(x => x === boundFn))
            ? fn(...args)
            : fn(this, ...args);
    }
}


答:
```<code><script>
var param=3;
$('#saveList').append(
'<p>FullName : <input type="text" id="myName"></p>'+
'<p><input type="button" value="SAVE" onClick="save_order('+ param +',document.getElementById(\'myName\').value)"></p>');
</script>
</code>```

You can do this or just use double quotes as that should work too.

Title: single or double quote in javascript append

Body:
<script>
var param=3;
$('#saveList').append(
'<p>FullName : <input type="text" id="myName"></p>'+
'<p><input type="button" value="SAVE" onClick="save_order('+ param +',document.getElementById(\'myName\').value)"></p>');
</script>

You can do this or just use double quotes as that should work too.


问:
kubernetes services stuck in not ready
I have a running container showing running but not ready and I can't for the life of my figure out what's wrong. I am on google container engine running kubectl server 1.64 and kubectl client 1.62

My healthcheck route is indicating that the healthcheck is being requested, albeit directly on the pod ip and not the service ip. I say this because when within a different pod, I am unable to curl the service that is not ready.

Nothing seems to be wrong when I look at my yaml files which I've included below. I've also included some commands I've run and their outputs.

Within the container, I can confirm secrets exist because I can echo $MYSQL_USER so I know they are being set.

Finally, my docker file is extremely simply and runs the server on port 7000 so not sure that could be it. What am I doing wrong? How can I go about debugging this?

from a different pod

wget -qO- blahblah

```<code>wget: can't connect to remote host (10.55.252.109): Operation timed out
</code>```

nslookup blahblah:

```<code>nslookup: can't resolve '(null)': Name does not resolve

Name:      blahblah-service
Address 1: 10.55.252.109 blahblah-service.staging.svc.cluster.local
</code>```

from within the gke vm

curl 10.55.252.109

```<code>Failed to connect to 10.55.252.109 port 80: Connection refused
</code>```

from my terminal:

kubectl get svc blahblah

```<code>NAME                       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
blahblah-service   10.55.252.109   <nodes>       80:31003/TCP   41m
</code>```

kubectl get endpoints blahblah-service

```<code>NAME                       ENDPOINTS   AGE
blahblah-service               29m
</code>```

kubectl get pods -l name=blahblah

```<code>NAME                                           READY     STATUS    RESTARTS   AGE
blahblah-3521139244-6tkj5   0/1       Running   0          29m
</code>```

kubectl describe svc blahblah-service

```<code>Name:           blahblah-service
Namespace:          staging
Labels:         <none>
Annotations:        <none>
Selector:           name=blahblah
Type:           NodePort
IP:             10.55.252.109
Port:           http    80/TCP
NodePort:           http    31003/TCP
Endpoints:
Session Affinity:       None
Events:         <none>
</code>```

service & deployment yamls

```<code>kind: Service
apiVersion: v1
metadata:
  name: blahblah-service
spec:
  selector:
    name: blahblah
  type: NodePort
  ports:
    - port: 80
      targetPort: "http"
      name: http

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: blahblah-deployment
spec:
  replicas: 1
  minReadySeconds: 30
  template:
    metadata:
      labels:
        name: blahblah
    spec:
      containers:
      - name: blahblah
        image: eu.gcr.io/company_name/blahblah-service
        ports:
          - containerPort: 7000
            name: http
        readinessProbe:
          httpGet:
            path: /_internal_/ok
            port: http
        env:
          - name: NODE_ENV
            valueFrom:
              configMapKeyRef:
                name: env-variables
                key: ENV_NAME
          - name: MYSQL_USER
            valueFrom:
              secretKeyRef:
                name: blahblah-mysql-secrets
                key: MYSQL_USER
          - name: MYSQL_PASS
            valueFrom:
              secretKeyRef:
                name: blahblah-mysql-secrets
                key: MYSQL_PASS
</code>```

dockerfile

```<code>FROM node:7.5.0-alpine

RUN apk update && apk upgrade \
    && apk add --no-cache --update-cache git ca-certificates openssl\
    && update-ca-certificates

RUN cd /tmp && wget https://yarnpkg.com/latest.tar.gz && tar zxf latest.tar.gz

COPY package.json /workspace/package.json
WORKDIR /workspace
COPY yarn.lock /workspace/yarn.lock
RUN /tmp/dist/bin/yarn

COPY . /workspace

ARG NODE_ENV=production
ENV NODE_ENV ${NODE_ENV}

ENV PORT 7000

EXPOSE $PORT

ENTRYPOINT exec node_modules/pm2/bin/pm2-docker start pm2.json --only blahblah-service-$NODE_ENV
</code>```

EDIT

I also noticed that it only shows not ready when another service is run at the same time. I don't see any similarities between the two services so I'm not sure how running both would conflict? Both services use a configmap and have their own secrets but I don't see why that would cause conflicts.

答:
Your service is called blahblah-service but you're trying to query it as wget -qO- blahblah, which is the name of the pod. It won't work, you should call it as http://blahblah-service.

You said:

nslookup blahblah ... from withing the GKE VM

This is not expected to work because GKE VM’s /etc/resolv.conf is not configured to use kube-dns which provides DNS to the cluster. This would work only in a Pod.

Try running another pod in the cluster, install dig/nslookup and run:

```<code>dig A blahblah-service.staging.svc.cluster.local
</code>```

you should be getting the IP address of the Service.

Title: kubernetes services stuck in not ready

Body:
I have a running container showing running but not ready and I can't for the life of my figure out what's wrong. I am on google container engine running kubectl server 1.64 and kubectl client 1.62

My healthcheck route is indicating that the healthcheck is being requested, albeit directly on the pod ip and not the service ip. I say this because when within a different pod, I am unable to curl the service that is not ready.

Nothing seems to be wrong when I look at my yaml files which I've included below. I've also included some commands I've run and their outputs.

Within the container, I can confirm secrets exist because I can echo $MYSQL_USER so I know they are being set.

Finally, my docker file is extremely simply and runs the server on port 7000 so not sure that could be it. What am I doing wrong? How can I go about debugging this?

from a different pod

wget -qO- blahblah

wget: can't connect to remote host (10.55.252.109): Operation timed out

nslookup blahblah:

nslookup: can't resolve '(null)': Name does not resolve

Name:      blahblah-service
Address 1: 10.55.252.109 blahblah-service.staging.svc.cluster.local

from within the gke vm

curl 10.55.252.109

Failed to connect to 10.55.252.109 port 80: Connection refused

from my terminal:

kubectl get svc blahblah

NAME                       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
blahblah-service   10.55.252.109   <nodes>       80:31003/TCP   41m

kubectl get endpoints blahblah-service

NAME                       ENDPOINTS   AGE
blahblah-service               29m

kubectl get pods -l name=blahblah

NAME                                           READY     STATUS    RESTARTS   AGE
blahblah-3521139244-6tkj5   0/1       Running   0          29m

kubectl describe svc blahblah-service

Name:           blahblah-service
Namespace:          staging
Labels:         <none>
Annotations:        <none>
Selector:           name=blahblah
Type:           NodePort
IP:             10.55.252.109
Port:           http    80/TCP
NodePort:           http    31003/TCP
Endpoints:
Session Affinity:       None
Events:         <none>

service & deployment yamls

kind: Service
apiVersion: v1
metadata:
  name: blahblah-service
spec:
  selector:
    name: blahblah
  type: NodePort
  ports:
    - port: 80
      targetPort: "http"
      name: http

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: blahblah-deployment
spec:
  replicas: 1
  minReadySeconds: 30
  template:
    metadata:
      labels:
        name: blahblah
    spec:
      containers:
      - name: blahblah
        image: eu.gcr.io/company_name/blahblah-service
        ports:
          - containerPort: 7000
            name: http
        readinessProbe:
          httpGet:
            path: /_internal_/ok
            port: http
        env:
          - name: NODE_ENV
            valueFrom:
              configMapKeyRef:
                name: env-variables
                key: ENV_NAME
          - name: MYSQL_USER
            valueFrom:
              secretKeyRef:
                name: blahblah-mysql-secrets
                key: MYSQL_USER
          - name: MYSQL_PASS
            valueFrom:
              secretKeyRef:
                name: blahblah-mysql-secrets
                key: MYSQL_PASS

dockerfile

FROM node:7.5.0-alpine

RUN apk update && apk upgrade \
    && apk add --no-cache --update-cache git ca-certificates openssl\
    && update-ca-certificates

RUN cd /tmp && wget https://yarnpkg.com/latest.tar.gz && tar zxf latest.tar.gz

COPY package.json /workspace/package.json
WORKDIR /workspace
COPY yarn.lock /workspace/yarn.lock
RUN /tmp/dist/bin/yarn

COPY . /workspace

ARG NODE_ENV=production
ENV NODE_ENV ${NODE_ENV}

ENV PORT 7000

EXPOSE $PORT

ENTRYPOINT exec node_modules/pm2/bin/pm2-docker start pm2.json --only blahblah-service-$NODE_ENV

EDIT

I also noticed that it only shows not ready when another service is run at the same time. I don't see any similarities between the two services so I'm not sure how running both would conflict? Both services use a configmap and have their own secrets but I don't see why that would cause conflicts.

Body:
Your service is called blahblah-service but you're trying to query it as wget -qO- blahblah, which is the name of the pod. It won't work, you should call it as http://blahblah-service.

You said:

nslookup blahblah ... from withing the GKE VM

This is not expected to work because GKE VM’s /etc/resolv.conf is not configured to use kube-dns which provides DNS to the cluster. This would work only in a Pod.

Try running another pod in the cluster, install dig/nslookup and run:

dig A blahblah-service.staging.svc.cluster.local

you should be getting the IP address of the Service.


问:
Transfer data from aws s3 to gcs by using gsutil - SSL Certification Error
I am trying to transfer data from AWS S3 to GCS.
I changed the private key and secrete key in boto file and when I try the following command getting the error.

Command: gsutil ls s3://axz

Error Message:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform/gsutil\gsutil", line 22, in
    gsutil.RunMain()
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\gsutil.py", line 114, in RunMain
    sys.exit(gslib.main.main())
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\gslib__main__.py", line 383, in main
    perf_trace_token=perf_trace_token)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\gslib__main__.py", line 577, in _RunNamedCommandAndHandleExceptions
    collect_analytics=True)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\gslib\command_runner.py", line 299, in RunNamedCommand
    return_code = command_inst.RunCommand()
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\gslib\commands\ls.py", line 526, in RunCommand
    exp_dirs, exp_objs, exp_bytes = ls_helper.ExpandUrlAndPrint(storage_url)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\gslib\ls_helper.py", line 180, in ExpandUrlAndPrint
    print_initial_newline=False)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\gslib\ls_helper.py", line 252, in _RecurseExpandUrlAndPrint
    bucket_listing_fields=self.bucket_listing_fields):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\gslib\wildcard_iterator.py", line 476, in IterAll
    expand_top_level_buckets=expand_top_level_buckets):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\gslib\wildcard_iterator.py", line 157, in iter
    fields=bucket_listing_fields):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\gslib\boto_translation.py", line 380, in ListObjects
    for key in objects_iter:
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\third_party\boto\boto\s3\bucketlistresultset.py", line 34, in bucket_lister
    encoding_type=encoding_type)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\third_party\boto\boto\s3\bucket.py", line 473, in get_all_keys
    '', headers, params)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\third_party\boto\boto\s3\bucket.py", line 399, in _get_all
    query_args=query_args)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\third_party\boto\boto\s3\connection.py", line 668, in make_request
    retry_handler=retry_handler
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\third_party\boto\boto\connection.py", line 1071, in make_request
    retry_handler=retry_handler)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\gsutil\third_party\boto\boto\connection.py", line 1030, in _mexe
    raise ex
**ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)

答:
This likely comes from a difference between the SSL certificate bundles on your machines - that's generally been the issue for others that have encountered this error, e.g. https://github.com/aws/aws-cli/issues/1545

If you're unable to update your certificate bundle, you might also try explicitly disabling certificate validation (be warned, this opens you up for man-in-the-middle attacks) by setting the https_validate_certificates Boto option:

```<code>gsutil -o 'Boto:https_validate_certificates=False' [...]
</code>```

Edit:

You might also want to try generating your own certificate bundle file via

https://github.com/curl/curl/blob/master/lib/mk-ca-bundle.pl

and seeing if making gsutil use that will help:

```<code>gsutil -o 'Boto:ca_certificates_file=C:\path\to\ca-bundle.crt' [...]
</code>```

Body:
This likely comes from a difference between the SSL certificate bundles on your machines - that's generally been the issue for others that have encountered this error, e.g. https://github.com/aws/aws-cli/issues/1545

If you're unable to update your certificate bundle, you might also try explicitly disabling certificate validation (be warned, this opens you up for man-in-the-middle attacks) by setting the https_validate_certificates Boto option:

gsutil -o 'Boto:https_validate_certificates=False' [...]

Edit:

You might also want to try generating your own certificate bundle file via

https://github.com/curl/curl/blob/master/lib/mk-ca-bundle.pl

and seeing if making gsutil use that will help:

gsutil -o 'Boto:ca_certificates_file=C:\path\to\ca-bundle.crt' [...]


问:
Converting an int type to a uint8
The Nim Tutorial page states:

Lossless Automatic type conversion is performed in expressions where different kinds of integer types are used.

So, I thought that creating an int in the range of a uint8 would allow me to pass it to procs expecingt an uint8.

However, the following code raises the annotated errors:

```<code>import random

proc show(x: uint8) {.discardable.} = echo x

let a: int = 255
show(a)  # type mismatch: got (int) but expected one of proc show(x: uint8)

let b: uint8 = random(256)  # type mismatch: got (int) but expected 'uint8'
show(b)
</code>```

I am very confused by the first one, which is telling me it expected a procinstead of an int. The second one is clearer, but I expected an autoconversion at this point, since random generates an int in the uint8 range (0..256) (documentation).

Is there a way to convert int to uint8?

答:
The random proc is defined to return an int. The fact that the max value is 256 in this example is not encoded in the type system (it could have been if random was taking static[int] as an argument).

"lossless conversion" means that a value of a smaller integer type can be converted to a value of a larger integer type (e.g. from int8 to int32). In the examples here, you are trying to perform a conversion in the other direction. You can get around the errors by making the conversions explicit:

```<code>let a = uint8(rand(256))
show a
# or
let b = rand(256)
show uint32(b)
</code>```

p.p. you don't need to add the discardable pragma to procs which don't return values.

Title: Converting an int type to a uint8

Body:
The Nim Tutorial page states:

Lossless Automatic type conversion is performed in expressions where different kinds of integer types are used.

So, I thought that creating an int in the range of a uint8 would allow me to pass it to procs expecingt an uint8.

However, the following code raises the annotated errors:

import random

proc show(x: uint8) {.discardable.} = echo x

let a: int = 255
show(a)  # type mismatch: got (int) but expected one of proc show(x: uint8)

let b: uint8 = random(256)  # type mismatch: got (int) but expected 'uint8'
show(b)

I am very confused by the first one, which is telling me it expected a procinstead of an int. The second one is clearer, but I expected an autoconversion at this point, since random generates an int in the uint8 range (0..256) (documentation).

Is there a way to convert int to uint8?

Body:
The random proc is defined to return an int. The fact that the max value is 256 in this example is not encoded in the type system (it could have been if random was taking static[int] as an argument).

"lossless conversion" means that a value of a smaller integer type can be converted to a value of a larger integer type (e.g. from int8 to int32). In the examples here, you are trying to perform a conversion in the other direction. You can get around the errors by making the conversions explicit:

let a = uint8(rand(256))
show a
# or
let b = rand(256)
show uint32(b)

p.p. you don't need to add the discardable pragma to procs which don't return values.


问:
Spring binding multiple attributes to same @ModelAttribute
I have a preview page which takes add or edit models and displays the preview.

```<code>@RequestMapping(value = "/preview", method = RequestMethod.POST)
    public ModelAndView preview(@ModelAttribute("editForm") FormModel editFormModel) {
        //action
    }

@RequestMapping(value = "/preview", method = RequestMethod.POST)
    public ModelAndView preview(@ModelAttribute("addForm") FormModel addFormModel) {
        //action
    }
</code>```

I need to call preview from add form page and edit form page. The models I'm going to pass are same but come from different forms.

(1) Is there a way ModelAttribute supports this kind of multi-attribute name mapping?
(2) How can I think about redesigning this? Thinking about (a) Renaming the form name/attribute before form submit to use the same attribute name. (b) Remove ModelAttribute altogether - That's not an option for me as I'm using spring mvc form binding.

Note: I'm using editForm/addForm as session attributes.

答:
Not actually solutions but work arounds.

Approach 1:

```<code>@RequestMapping(value = "/preview", method = RequestMethod.PUT)
public ModelAndView preview(@ModelAttribute("editForm") FormModel editFormModel) {
    //action
}

@RequestMapping(value = "/preview", method = RequestMethod.POST)
public ModelAndView preview(@ModelAttribute("addForm") FormModel addFormModel) {
    //action
}
</code>```

Approach 2:

```<code>@RequestMapping(value = "/editpreview", method = RequestMethod.PUT)
public ModelAndView preview(@ModelAttribute("editForm") FormModel editFormModel) {
    //action
}

@RequestMapping(value = "/addpreview", method = RequestMethod.POST)
public ModelAndView preview(@ModelAttribute("addForm") FormModel addFormModel) {
    //action
}
</code>```

Body:
I have a preview page which takes add or edit models and displays the preview.

@RequestMapping(value = "/preview", method = RequestMethod.POST)
    public ModelAndView preview(@ModelAttribute("editForm") FormModel editFormModel) {
        //action
    }

@RequestMapping(value = "/preview", method = RequestMethod.POST)
    public ModelAndView preview(@ModelAttribute("addForm") FormModel addFormModel) {
        //action
    }

I need to call preview from add form page and edit form page. The models I'm going to pass are same but come from different forms.

(1) Is there a way ModelAttribute supports this kind of multi-attribute name mapping?
(2) How can I think about redesigning this? Thinking about (a) Renaming the form name/attribute before form submit to use the same attribute name. (b) Remove ModelAttribute altogether - That's not an option for me as I'm using spring mvc form binding.

Note: I'm using editForm/addForm as session attributes.

Body:
Not actually solutions but work arounds.

Approach 1:

@RequestMapping(value = "/preview", method = RequestMethod.PUT)
public ModelAndView preview(@ModelAttribute("editForm") FormModel editFormModel) {
    //action
}

@RequestMapping(value = "/preview", method = RequestMethod.POST)
public ModelAndView preview(@ModelAttribute("addForm") FormModel addFormModel) {
    //action
}

Approach 2:

@RequestMapping(value = "/editpreview", method = RequestMethod.PUT)
public ModelAndView preview(@ModelAttribute("editForm") FormModel editFormModel) {
    //action
}

@RequestMapping(value = "/addpreview", method = RequestMethod.POST)
public ModelAndView preview(@ModelAttribute("addForm") FormModel addFormModel) {
    //action
}


问:
/bin/sh: 1: Syntax error: word unexpected (expecting ")")
I have this Makefile:

```<code>TMP_DIR := tmp
RUN_OR_NOT := $(shell date '+%y%m%d%H%M')

all: version

version:
    ifeq ($(shell test -d ${TMP_DIR} && echo -n "yes";),yes)
        $(shell echo ${TMP_DIR} already exists ...)
    else
        $(shell mkdir -p ${TMP_DIR})
    endif
</code>```

I want to first check, if the directory tmp exists or not, and create it only, if it does not exist. This works, but with a strange error:

```<code> ifeq (yes,yes)
 /bin/sh: 1: Syntax error: word unexpected (expecting ")")
 Makefile:7: die Regel für Ziel „version“ scheiterte
 make: *** [version] Fehler 2
</code>```

Why is there this strange /bin/sh: 1: Syntax error: word unexpected (expecting ")") error? And how to solve this?

答:
In a makefile, the recipe is a shell script.  You are trying to put make constructs like ifeq into your recipe.  Make will pass those to the shell and the shell throws this error because it doesn't understand makefile syntax.

You should write your recipe using shell scripting, not makefile syntax:

```<code>version:
        if test -d ${TMP_DIR}; then \
            echo ${TMP_DIR} already exists ...; \
        else \
            mkdir -p ${TMP_DIR}; \
        fi
</code>```

Although why you care if the directory exists already I don't know; I would personally just use:

```<code>version:
        mkdir -p ${TMP_DIR}
</code>```

Body:
I have this Makefile:

TMP_DIR := tmp
RUN_OR_NOT := $(shell date '+%y%m%d%H%M')

all: version

version:
    ifeq ($(shell test -d ${TMP_DIR} && echo -n "yes";),yes)
        $(shell echo ${TMP_DIR} already exists ...)
    else
        $(shell mkdir -p ${TMP_DIR})
    endif

I want to first check, if the directory tmp exists or not, and create it only, if it does not exist. This works, but with a strange error:

 ifeq (yes,yes)
 /bin/sh: 1: Syntax error: word unexpected (expecting ")")
 Makefile:7: die Regel für Ziel „version“ scheiterte
 make: *** [version] Fehler 2

Why is there this strange /bin/sh: 1: Syntax error: word unexpected (expecting ")") error? And how to solve this?

Body:
In a makefile, the recipe is a shell script.  You are trying to put make constructs like ifeq into your recipe.  Make will pass those to the shell and the shell throws this error because it doesn't understand makefile syntax.

You should write your recipe using shell scripting, not makefile syntax:

version:
        if test -d ${TMP_DIR}; then \
            echo ${TMP_DIR} already exists ...; \
        else \
            mkdir -p ${TMP_DIR}; \
        fi

Although why you care if the directory exists already I don't know; I would personally just use:

version:
        mkdir -p ${TMP_DIR}


问:
Find all packages installed with easy_install/pip?
Is there a way to find all Python PyPI packages that were installed with easy_install or pip?  I mean, excluding everything that was/is installed with the distributions tools (in this case apt-get on Debian).</p>

答:
Start with:

```<code>$ pip list
</code>```

To list all packages. Once you found the package you want, use:

```<code>$ pip show <package-name>
</code>```

This will show you details about this package, including its folder. You can skip the first part if you already know the package name

Click here for more information on pip show and here for more information on pip list.

Example:

```<code>$ pip show jupyter
Name: jupyter
Version: 1.0.0
Summary: Jupyter metapackage. Install all the Jupyter components in one go.
Home-page: http://jupyter.org
Author: Jupyter Development Team
Author-email: jupyter@googlegroups.org
License: BSD
Location: /usr/local/lib/python2.7/site-packages
Requires: ipywidgets, nbconvert, notebook, jupyter-console, qtconsole, ipykernel
</code>```

Body:
Start with:

$ pip list

To list all packages. Once you found the package you want, use:

$ pip show <package-name>

This will show you details about this package, including its folder. You can skip the first part if you already know the package name

Click here for more information on pip show and here for more information on pip list.

Example:

$ pip show jupyter
Name: jupyter
Version: 1.0.0
Summary: Jupyter metapackage. Install all the Jupyter components in one go.
Home-page: http://jupyter.org
Author: Jupyter Development Team
Author-email: jupyter@googlegroups.org
License: BSD
Location: /usr/local/lib/python2.7/site-packages
Requires: ipywidgets, nbconvert, notebook, jupyter-console, qtconsole, ipykernel


问:
How to fill all screen with a tablelayout in landscape mode?
i'm using a TableLayout on my applycation. This is my XML code:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:scrollbars="none">

<include
    android:id="@id/action_bar"
    layout="@layout/actionbar_toolbar" />

<HorizontalScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/action_bar">

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TableLayout
            android:id="@+id/table"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

        </TableLayout>
    </ScrollView>
</HorizontalScrollView>
</code>```

And, i fill the table with Java code:

```<code>   TableRow tbrow = new TableRow(this);
    TextView txt_plazo = new TextView(this);
    txt_plazo.setText(" Plazo ");
    txt_plazo.setTextColor(Color.WHITE);
    txt_plazo.setTextSize(16);
    txt_plazo.setMinimumHeight(0);
    txt_plazo.setBackgroundColor(Color.DKGRAY);
    txt_plazo.setGravity(Gravity.CENTER);
    tbrow.addView(txt_plazo);

    TextView txt_saldoInicial = new TextView(this);
    txt_saldoInicial.setText(" Saldo Inicial");
    txt_saldoInicial.setTextColor(Color.WHITE);
    txt_saldoInicial.setTextSize(16);
    txt_saldoInicial.setBackgroundColor(Color.DKGRAY);
    txt_saldoInicial.setGravity(Gravity.CENTER);
    tbrow.addView(txt_saldoInicial);

    TextView txt_parcialidades = new TextView(this);
    txt_parcialidades.setText(" Parcialidades ");
    txt_parcialidades.setTextColor(Color.WHITE);
    txt_parcialidades.setTextSize(16);
    txt_parcialidades.setBackgroundColor(Color.DKGRAY);
    txt_parcialidades.setGravity(Gravity.CENTER);
    tbrow.addView(txt_parcialidades);

    TextView txt_interes = new TextView(this);
    txt_interes.setText(" Interés ");
    txt_interes.setTextSize(16);
    txt_interes.setBackgroundColor(Color.DKGRAY);
    txt_interes.setGravity(Gravity.CENTER);
    txt_interes.setTextColor(Color.WHITE);
    tbrow.addView(txt_interes);

    TextView txt_total = new TextView(this);
    txt_total.setText(" Abono Capital");
    txt_total.setTextSize(16);
    txt_total.setBackgroundColor(Color.DKGRAY);
    txt_total.setGravity(Gravity.CENTER);
    txt_total.setTextColor(Color.WHITE);
    tbrow.addView(txt_total);

    table.addView(tbrow);
    fillTable();
</code>```

Etc...

All works fine but i'm trying to view the table in landscape mode, the problem is that the table don't fill all screen. In portrait mode looks good.

P.D: android:shrinkColumns and android:stretchColumns don't work for me.

答: Use match_parent for your views.</p>

Body:
i'm using a TableLayout on my applycation. This is my XML code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:scrollbars="none">

<include
    android:id="@id/action_bar"
    layout="@layout/actionbar_toolbar" />

<HorizontalScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/action_bar">

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TableLayout
            android:id="@+id/table"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

        </TableLayout>
    </ScrollView>
</HorizontalScrollView>

And, i fill the table with Java code:

   TableRow tbrow = new TableRow(this);
    TextView txt_plazo = new TextView(this);
    txt_plazo.setText(" Plazo ");
    txt_plazo.setTextColor(Color.WHITE);
    txt_plazo.setTextSize(16);
    txt_plazo.setMinimumHeight(0);
    txt_plazo.setBackgroundColor(Color.DKGRAY);
    txt_plazo.setGravity(Gravity.CENTER);
    tbrow.addView(txt_plazo);

    TextView txt_saldoInicial = new TextView(this);
    txt_saldoInicial.setText(" Saldo Inicial");
    txt_saldoInicial.setTextColor(Color.WHITE);
    txt_saldoInicial.setTextSize(16);
    txt_saldoInicial.setBackgroundColor(Color.DKGRAY);
    txt_saldoInicial.setGravity(Gravity.CENTER);
    tbrow.addView(txt_saldoInicial);

    TextView txt_parcialidades = new TextView(this);
    txt_parcialidades.setText(" Parcialidades ");
    txt_parcialidades.setTextColor(Color.WHITE);
    txt_parcialidades.setTextSize(16);
    txt_parcialidades.setBackgroundColor(Color.DKGRAY);
    txt_parcialidades.setGravity(Gravity.CENTER);
    tbrow.addView(txt_parcialidades);

    TextView txt_interes = new TextView(this);
    txt_interes.setText(" Interés ");
    txt_interes.setTextSize(16);
    txt_interes.setBackgroundColor(Color.DKGRAY);
    txt_interes.setGravity(Gravity.CENTER);
    txt_interes.setTextColor(Color.WHITE);
    tbrow.addView(txt_interes);

    TextView txt_total = new TextView(this);
    txt_total.setText(" Abono Capital");
    txt_total.setTextSize(16);
    txt_total.setBackgroundColor(Color.DKGRAY);
    txt_total.setGravity(Gravity.CENTER);
    txt_total.setTextColor(Color.WHITE);
    tbrow.addView(txt_total);

    table.addView(tbrow);
    fillTable();

Etc...

All works fine but i'm trying to view the table in landscape mode, the problem is that the table don't fill all screen. In portrait mode looks good.

P.D: android:shrinkColumns and android:stretchColumns don't work for me.

Body: Use match_parent for your views.


问:
C++ list with array of strings
I have to make a list with people and their exam result in C++. My problem is that I don't know how to input the array.
I was trying to make 3D array of strings, but it doesn't works. It must be in function! If you have a better suggestions, I will be very grateful

My input must be something like:

Peter Evens 4.86

*other people**

*average result of the group**

*the one with the heighest grade**

*the one with lowest grade**

This is what I have done for now:

```<code>#include <iostream>
#define MAXN 200
#define MAXM 200
#define MAXX 200
using namespace std;
void input(char list[][MAXN][MAXM], int n) {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            for (int p = 0; p < n; p++)
                cin >> list[i][j][p];
        }
}
int main() {
    char list[31][MAXN][MAXM];
    int n;
    cin >> n;
    input(list, n);
    return 0;
}
</code>```

答:
You must use a vector of struct.

Define your struct this way:

```<code>typedef struct details{
    string Fname;
    string Lname;
    float marks;
} details;
</code>```

And vector should look like

```<code>vector< details > info;
</code>```

I am just showing you how to implement this in the following code:

```<code>void insertValues(vector< details >& info){

    int n;
    details d;
    cout<<"Enter the size of record: ";
    cin>>n;
    cout<<"Enter records: "<<endl;

    for(int i=0;i<n;i++){
         cin>>d.Fname>>d.Lname>>d.marks;
         info.push_back(d);
    }

}

void LowestScorer(vector< details > info){

    details d;
    vector< details >::iterator it=info.begin();
    d=*it;
    for(;it!=info.end();it++){
        if(d.marks > it->marks){
            d=*it;
        }
    }
    cout<<"Lowest Scorer: "<<d.Fname<<" "<<d.Lname<<" "<<d.marks<<endl;
}
</code>```

main should look like this:

```<code>    int main(){

    vector< details > info;

    insertValues(info);
    LowestScorer(info);
    return 0;
}
</code>```

Title: C++ list with array of strings

Body:
I have to make a list with people and their exam result in C++. My problem is that I don't know how to input the array.
I was trying to make 3D array of strings, but it doesn't works. It must be in function! If you have a better suggestions, I will be very grateful

My input must be something like:

Peter Evens 4.86

*other people**

*average result of the group**

*the one with the heighest grade**

*the one with lowest grade**

This is what I have done for now:

#include <iostream>
#define MAXN 200
#define MAXM 200
#define MAXX 200
using namespace std;
void input(char list[][MAXN][MAXM], int n) {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            for (int p = 0; p < n; p++)
                cin >> list[i][j][p];
        }
}
int main() {
    char list[31][MAXN][MAXM];
    int n;
    cin >> n;
    input(list, n);
    return 0;
}

Body:
You must use a vector of struct.

Define your struct this way:

typedef struct details{
    string Fname;
    string Lname;
    float marks;
} details;

And vector should look like

vector< details > info;

I am just showing you how to implement this in the following code:

void insertValues(vector< details >& info){

    int n;
    details d;
    cout<<"Enter the size of record: ";
    cin>>n;
    cout<<"Enter records: "<<endl;

    for(int i=0;i<n;i++){
         cin>>d.Fname>>d.Lname>>d.marks;
         info.push_back(d);
    }

}

void LowestScorer(vector< details > info){

    details d;
    vector< details >::iterator it=info.begin();
    d=*it;
    for(;it!=info.end();it++){
        if(d.marks > it->marks){
            d=*it;
        }
    }
    cout<<"Lowest Scorer: "<<d.Fname<<" "<<d.Lname<<" "<<d.marks<<endl;
}

main should look like this:

    int main(){

    vector< details > info;

    insertValues(info);
    LowestScorer(info);
    return 0;
}


问:
react-native-webp loads some wep images but not all
I am using this module react-native-webp to load webp images on ios. However, I am not seeing the images from s3 load. Using an image found from google search, works fine. There are absolutely no logs whatsoever to help debug the issue!

This is an example url that doesn't load: http://s3-ap-south-1.amazonaws.com/rupyacard/offers/pictures/000/000/007/1280/dinner.webp

And this here is one that's loading just fine! https://www.gstatic.com/webp/gallery/1.sm.webp

Can't find a reason for either to not work. I thought it might have to do with the image size but a smaller version doesn't help either. Here's a smaller variant: http://s3-ap-south-1.amazonaws.com/rupyacard/offers/pictures/000/000/007/320/dinner.webp

答:
Please give path images to HTTPS or just do following settings in xcode and clean  rebuild app

The main problem is Apple can't load HTTP images without settings.