问:
SQLAlchemy Query with Multiple Joins
I am creating a flask app with SQLAlchemy and Postgres. I am pretty green at this so I any feedback would be appreciated. However, my direct question is with constructing a query on the following model.

```<code>from app import db
from sqlalchemy import or_, and_

# Items Table
class Item(db.Model):

    __tablename__ = "items"

    id = db.Column(db.Integer, primary_key=True)
    itemName = db.Column(db.String, unique=True, nullable=False)
    measurement = db.Column(db.String, nullable=False)
    defaultPrice = db.Column(db.Float, nullable=False)
    minimumOrder = db.Column(db.Float, nullable=False)
    maximumOrder = db.Column(db.Float, nullable=False)
    orders = db.relationship('Order', back_populates='item')
    prices = db.relationship('Price', back_populates='item')

    def __init__(self, itemName, measurement, defaultPrice,
                 minimumOrder, maximumOrder):
        self.itemName = itemName
        self.measurement = measurement
        self.defaultPrice = defaultPrice
        self.minimumOrder = minimumOrder
        self.maximumOrder = maximumOrder

    def __repr__(self):
        return '<Item {0}>'.format(self.id)

# Users Table
class User(db.Model):

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    fullName = db.Column(db.String, unique=True, nullable=False)
    userName = db.Column(db.String, unique=True, nullable=False)
    password = db.Column(db.String, nullable=False)
    role = db.Column(db.String, nullable=False)
    orders = db.relationship('Order', back_populates='user')
    prices = db.relationship('Price', back_populates='user')

    def __init__(self, fullName, userName, password, role):
        self.fullName = fullName
        self.userName = userName
        self.password = password
        self.role = role

    def __repr__(self):
        return '<User {0}>'.format(self.userName)

# Availability / Price Table
class Price(db.Model):

    __tablename__ = 'prices'

    id = db.Column(db.Integer, primary_key=True)
    userId = db.Column(db.Integer, db.ForeignKey('users.id'))
    user = db.relationship('User', back_populates='prices')
    itemId = db.Column(db.Integer, db.ForeignKey('items.id'))
    item = db.relationship('Item', back_populates='prices')
    available = db.Column(db.Boolean)
    priceMeasurement = db.Column(db.String)
    price = db.Column(db.Float)

    def __init__(self, userId, itemId, priceMeasurement, price):
        self.userId = userId
        self.itemId = itemId
        self.priceMeasurement = priceMeasurement
        self.price = price

    def __repr__(self):
        return '<Price {0}>'.format(self.price)

# Orders Table
class Order(db.Model):

    __tablename__ = 'orders'

    id = db.Column(db.Integer, primary_key=True)
    userId = db.Column(db.Integer, db.ForeignKey('users.id'))
    user = db.relationship('User', back_populates='orders')
    itemId = db.Column(db.Integer, db.ForeignKey('items.id'))
    item = db.relationship('Item', back_populates='orders')
    orderQuantity = db.Column(db.Float)
    orderMeasurement = db.Column(db.String)
    orderPrice = db.Column(db.Float)
    orderDelivery = db.Column(db.Date)
    orderPlaced = db.Column(db.Date)

    def __init__(self, userId, itemId, orderQuantity,
                 orderMeasurement, orderPrice, orderDelivery, orderPlaced):
        self.userId = userId
        self.itemId = itemId
        self.orderQuantity = orderQuantity
        self.orderMeasurement = orderMeasurement
        self.orderPrice = orderPrice
        self.orderDelivery = orderDelivery
        self.orderPlaced = orderPlaced

    def __repr__(self):
        return '<Order {0}>'.format(self.orderDelivery)
</code>```

What I would like from the query is to return a table similar to that which the following query returns:

```<code>SELECT * FROM items
JOIN prices ON prices.itemId=items.id
WHERE prices.userId = 1 AND prices.available = True
LEFT JOIN (
SELECT * FROM orders WHERE orderDelivery = '2017-07-05') as orders
ON orders.itemId=items.id
</code>```

In an SQLAlchemy query. I will pass the userId and orderDelivery variables to the query from the route and session - @app.route('/user/order/<order_date>') | session['userID'] : established at login.

Thanks

答:
If I understood you correctly, you'd like to query tuples of (Item, Price, Order) entitites, where Order comes from the subquery. This is explained in the Object Relational Tutorial under Selecting Entities from Subqueries.

```<code>In [5]: from datetime import date

In [6]: orders_sq = db.session.query(Order).\
   ...:     filter(Order.orderDelivery == date(2017, 7, 5)).\
   ...:     subquery()

In [7]: orders_alias = db.aliased(Order, orders_sq)

In [8]: query = db.session.query(Item, Price, orders_alias).\
   ...:     join(Price).\
   ...:     outerjoin(orders_alias, Item.orders).\
   ...:     filter(Price.userId == 1,
   ...:            Price.available)
</code>```

and the produced SQL when compiled against SQLite:

```<code>In [9]: print(query)
SELECT items.id AS items_id, items."itemName" AS "items_itemName", items.measurement AS items_measurement, items."defaultPrice" AS "items_defaultPrice", items."minimumOrder" AS "items_minimumOrder", items."maximumOrder" AS "items_maximumOrder", prices.id AS prices_id, prices."userId" AS "prices_userId", prices."itemId" AS "prices_itemId", prices.available AS prices_available, prices."priceMeasurement" AS "prices_priceMeasurement", prices.price AS prices_price, anon_1.id AS anon_1_id, anon_1."userId" AS "anon_1_userId", anon_1."itemId" AS "anon_1_itemId", anon_1."orderQuantity" AS "anon_1_orderQuantity", anon_1."orderMeasurement" AS "anon_1_orderMeasurement", anon_1."orderPrice" AS "anon_1_orderPrice", anon_1."orderDelivery" AS "anon_1_orderDelivery", anon_1."orderPlaced" AS "anon_1_orderPlaced"
FROM items JOIN prices ON items.id = prices."itemId" LEFT OUTER JOIN (SELECT orders.id AS id, orders."userId" AS "userId", orders."itemId" AS "itemId", orders."orderQuantity" AS "orderQuantity", orders."orderMeasurement" AS "orderMeasurement", orders."orderPrice" AS "orderPrice", orders."orderDelivery" AS "orderDelivery", orders."orderPlaced" AS "orderPlaced"
FROM orders
WHERE orders."orderDelivery" = ?) AS anon_1 ON items.id = anon_1."itemId"
WHERE prices."userId" = ? AND prices.available = 1
</code>```

Also alternatively you could simply pass your statement to Query.from_statement with a few fixes and changes:

```<code>In [45]: query2 = db.session.query(Item, Price, Order).\
    ...:     from_statement(db.text("""
    ...: SELECT * FROM items
    ...: JOIN prices ON prices.itemId=items.id
    ...: LEFT JOIN (
    ...: SELECT * FROM orders WHERE orderDelivery = :orderDelivery) as orders
    ...: ON orders.itemId=items.id
    ...: WHERE prices.userId = :userId AND prices.available
    ...: """)).\
    ...:     params(userId=1, orderDelivery='2017-07-05')
</code>```

but I'd recommend using the former approach as it is more database agnostic.

Title: SQLAlchemy Query with Multiple Joins

Body:
I am creating a flask app with SQLAlchemy and Postgres. I am pretty green at this so I any feedback would be appreciated. However, my direct question is with constructing a query on the following model.

from app import db
from sqlalchemy import or_, and_

# Items Table
class Item(db.Model):

    __tablename__ = "items"

    id = db.Column(db.Integer, primary_key=True)
    itemName = db.Column(db.String, unique=True, nullable=False)
    measurement = db.Column(db.String, nullable=False)
    defaultPrice = db.Column(db.Float, nullable=False)
    minimumOrder = db.Column(db.Float, nullable=False)
    maximumOrder = db.Column(db.Float, nullable=False)
    orders = db.relationship('Order', back_populates='item')
    prices = db.relationship('Price', back_populates='item')

    def __init__(self, itemName, measurement, defaultPrice,
                 minimumOrder, maximumOrder):
        self.itemName = itemName
        self.measurement = measurement
        self.defaultPrice = defaultPrice
        self.minimumOrder = minimumOrder
        self.maximumOrder = maximumOrder

    def __repr__(self):
        return '<Item {0}>'.format(self.id)

# Users Table
class User(db.Model):

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    fullName = db.Column(db.String, unique=True, nullable=False)
    userName = db.Column(db.String, unique=True, nullable=False)
    password = db.Column(db.String, nullable=False)
    role = db.Column(db.String, nullable=False)
    orders = db.relationship('Order', back_populates='user')
    prices = db.relationship('Price', back_populates='user')

    def __init__(self, fullName, userName, password, role):
        self.fullName = fullName
        self.userName = userName
        self.password = password
        self.role = role

    def __repr__(self):
        return '<User {0}>'.format(self.userName)

# Availability / Price Table
class Price(db.Model):

    __tablename__ = 'prices'

    id = db.Column(db.Integer, primary_key=True)
    userId = db.Column(db.Integer, db.ForeignKey('users.id'))
    user = db.relationship('User', back_populates='prices')
    itemId = db.Column(db.Integer, db.ForeignKey('items.id'))
    item = db.relationship('Item', back_populates='prices')
    available = db.Column(db.Boolean)
    priceMeasurement = db.Column(db.String)
    price = db.Column(db.Float)

    def __init__(self, userId, itemId, priceMeasurement, price):
        self.userId = userId
        self.itemId = itemId
        self.priceMeasurement = priceMeasurement
        self.price = price

    def __repr__(self):
        return '<Price {0}>'.format(self.price)

# Orders Table
class Order(db.Model):

    __tablename__ = 'orders'

    id = db.Column(db.Integer, primary_key=True)
    userId = db.Column(db.Integer, db.ForeignKey('users.id'))
    user = db.relationship('User', back_populates='orders')
    itemId = db.Column(db.Integer, db.ForeignKey('items.id'))
    item = db.relationship('Item', back_populates='orders')
    orderQuantity = db.Column(db.Float)
    orderMeasurement = db.Column(db.String)
    orderPrice = db.Column(db.Float)
    orderDelivery = db.Column(db.Date)
    orderPlaced = db.Column(db.Date)

    def __init__(self, userId, itemId, orderQuantity,
                 orderMeasurement, orderPrice, orderDelivery, orderPlaced):
        self.userId = userId
        self.itemId = itemId
        self.orderQuantity = orderQuantity
        self.orderMeasurement = orderMeasurement
        self.orderPrice = orderPrice
        self.orderDelivery = orderDelivery
        self.orderPlaced = orderPlaced

    def __repr__(self):
        return '<Order {0}>'.format(self.orderDelivery)

What I would like from the query is to return a table similar to that which the following query returns:

SELECT * FROM items
JOIN prices ON prices.itemId=items.id
WHERE prices.userId = 1 AND prices.available = True
LEFT JOIN (
SELECT * FROM orders WHERE orderDelivery = '2017-07-05') as orders
ON orders.itemId=items.id

In an SQLAlchemy query. I will pass the userId and orderDelivery variables to the query from the route and session - @app.route('/user/order/<order_date>') | session['userID'] : established at login.

Thanks

Body:
If I understood you correctly, you'd like to query tuples of (Item, Price, Order) entitites, where Order comes from the subquery. This is explained in the Object Relational Tutorial under Selecting Entities from Subqueries.

In [5]: from datetime import date

In [6]: orders_sq = db.session.query(Order).\
   ...:     filter(Order.orderDelivery == date(2017, 7, 5)).\
   ...:     subquery()

In [7]: orders_alias = db.aliased(Order, orders_sq)

In [8]: query = db.session.query(Item, Price, orders_alias).\
   ...:     join(Price).\
   ...:     outerjoin(orders_alias, Item.orders).\
   ...:     filter(Price.userId == 1,
   ...:            Price.available)

and the produced SQL when compiled against SQLite:

In [9]: print(query)
SELECT items.id AS items_id, items."itemName" AS "items_itemName", items.measurement AS items_measurement, items."defaultPrice" AS "items_defaultPrice", items."minimumOrder" AS "items_minimumOrder", items."maximumOrder" AS "items_maximumOrder", prices.id AS prices_id, prices."userId" AS "prices_userId", prices."itemId" AS "prices_itemId", prices.available AS prices_available, prices."priceMeasurement" AS "prices_priceMeasurement", prices.price AS prices_price, anon_1.id AS anon_1_id, anon_1."userId" AS "anon_1_userId", anon_1."itemId" AS "anon_1_itemId", anon_1."orderQuantity" AS "anon_1_orderQuantity", anon_1."orderMeasurement" AS "anon_1_orderMeasurement", anon_1."orderPrice" AS "anon_1_orderPrice", anon_1."orderDelivery" AS "anon_1_orderDelivery", anon_1."orderPlaced" AS "anon_1_orderPlaced"
FROM items JOIN prices ON items.id = prices."itemId" LEFT OUTER JOIN (SELECT orders.id AS id, orders."userId" AS "userId", orders."itemId" AS "itemId", orders."orderQuantity" AS "orderQuantity", orders."orderMeasurement" AS "orderMeasurement", orders."orderPrice" AS "orderPrice", orders."orderDelivery" AS "orderDelivery", orders."orderPlaced" AS "orderPlaced"
FROM orders
WHERE orders."orderDelivery" = ?) AS anon_1 ON items.id = anon_1."itemId"
WHERE prices."userId" = ? AND prices.available = 1

Also alternatively you could simply pass your statement to Query.from_statement with a few fixes and changes:

In [45]: query2 = db.session.query(Item, Price, Order).\
    ...:     from_statement(db.text("""
    ...: SELECT * FROM items
    ...: JOIN prices ON prices.itemId=items.id
    ...: LEFT JOIN (
    ...: SELECT * FROM orders WHERE orderDelivery = :orderDelivery) as orders
    ...: ON orders.itemId=items.id
    ...: WHERE prices.userId = :userId AND prices.available
    ...: """)).\
    ...:     params(userId=1, orderDelivery='2017-07-05')

but I'd recommend using the former approach as it is more database agnostic.


来源: stackexchange

问:
Do labels support model binding?
When I display a value from my ViewModel into an input field (see code below) and post the form, model binding is supported correctly. This means I can find the (modified) value into my ViewModel.

```<code><input type="text" asp-for="FirstName" value="@Model.FirstName" />
</code>```

But when I display the same value from the ViewModel into a label, then I don't find it into the ViewModel after I post the form:

```<code><label asp-for="FirstName">@Model.FirstName</label>
</code>```

Do labels support model binding? If yes, am I doing anything wrong in my code?
If not, what's the alternative when I need to keep the value into my ViewModel? Storing them into HiddenFields?

答:
Label contents are not submitted to the server. It is a basic feature of HTML.

Only form fields' contents are submitted when the form is submitted.

ContentLicense: CC BY-SA 3.0

Title: Do labels support model binding?

Body:
When I display a value from my ViewModel into an input field (see code below) and post the form, model binding is supported correctly. This means I can find the (modified) value into my ViewModel.

<input type="text" asp-for="FirstName" value="@Model.FirstName" />

But when I display the same value from the ViewModel into a label, then I don't find it into the ViewModel after I post the form:

@Model.FirstName

Do labels support model binding? If yes, am I doing anything wrong in my code?
If not, what's the alternative when I need to keep the value into my ViewModel? Storing them into HiddenFields?


问:
How do I push a new branch without pulling
So I've worked on new features and I realized that it would be too complicated to commit locally to master branch. Thus, I created a new branch as follows:

```<code>$ git stash branch project_0.2 stash@{0}
</code>```

The problem of course is that when I try to push the new branch to the server I get:

```<code>$ git push origin master
To https://svn.tudelft.nl/git/project.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://svn.tudelft.nl/git/project.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

I've been looking on the internet and everywhere I see that I should git pull and merge the changes. I tried this (before I made a backup), and I get:

```<code>$ git pull
remote: Counting objects: 1105, done.
remote: Compressing objects: 100% (304/304), done.
remote: Total 725 (delta 501), reused 552 (delta 382)
Receiving objects: 100% (725/725), 5.29 MiB | 0 bytes/s, done.
Resolving deltas: 100% (501/501), completed with 165 local objects.
From https://svn.3me.tudelft.nl/git/project
   5d6516c..fd424b5  master     -> origin/master
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/<branch> project_0.2
</code>```

I'm not sure what I should do here so I stopped. Also, the changes are so deep that it will take me forever to merge. I thought there may be a smarter way to just push the branch to the server. In this way, I can get help from the other members of my team in fixing the code. Is this possible?

答:
If you want to isolate your new features from what you have been doing in your master branch, you have to do what @UniCoder says. Create a new branch with:

```<code>git branch NewBranchName
</code>```

Activate it with:

```<code>git checkout -b NewBranchName
</code>```

Do your developments, Add the objects you need, commit the work you have done on this feature and then create the new branch as:

```<code>git push origin --set-upstream NewBranchName
</code>```

For later pushes you only have to put "git push origin"

Body:
So I've worked on new features and I realized that it would be too complicated to commit locally to master branch. Thus, I created a new branch as follows:

$ git stash branch project_0.2 stash@{0}

The problem of course is that when I try to push the new branch to the server I get:

$ git push origin master
To https://svn.tudelft.nl/git/project.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://svn.tudelft.nl/git/project.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

I've been looking on the internet and everywhere I see that I should git pull and merge the changes. I tried this (before I made a backup), and I get:

$ git pull
remote: Counting objects: 1105, done.
remote: Compressing objects: 100% (304/304), done.
remote: Total 725 (delta 501), reused 552 (delta 382)
Receiving objects: 100% (725/725), 5.29 MiB | 0 bytes/s, done.
Resolving deltas: 100% (501/501), completed with 165 local objects.
From https://svn.3me.tudelft.nl/git/project
   5d6516c..fd424b5  master     -> origin/master
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/<branch> project_0.2

I'm not sure what I should do here so I stopped. Also, the changes are so deep that it will take me forever to merge. I thought there may be a smarter way to just push the branch to the server. In this way, I can get help from the other members of my team in fixing the code. Is this possible?

Body:
If you want to isolate your new features from what you have been doing in your master branch, you have to do what @UniCoder says. Create a new branch with:

git branch NewBranchName

Activate it with:

git checkout -b NewBranchName

Do your developments, Add the objects you need, commit the work you have done on this feature and then create the new branch as:

git push origin --set-upstream NewBranchName

For later pushes you only have to put "git push origin"


问:
Generic Methods, how to call a parent method without specifying a type
I have this parent class

```<code>public abstract class Parent
{
    public string Id { get; set; }

    public static T Find<T>(string id) where T : class, new()
    {
        /* logic here ..*/
    }
}
</code>```

and this child

```<code>public class Child : Parent
{
    public string Name { get; set; }
}
</code>```

Right now, the Find() method can be called from child class like this Child.Find<Child>(myId);

What I need to change so it doesnt have to include class type like this Child.Find(myId);

EDIT

I want to make this method as extension, and get it directly without defining the class into variable. the generic classT should be it's child type.

答:
One option would be to add this method to your Child class:

```<code>public static Child Find(string id)
{
    return Parent.Find<Child>(id);
}
</code>```

Body:
I have this parent class

public abstract class Parent
{
    public string Id { get; set; }

    public static T Find<T>(string id) where T : class, new()
    {
        /* logic here ..*/
    }
}

and this child

public class Child : Parent
{
    public string Name { get; set; }
}

Right now, the Find() method can be called from child class like this Child.Find<Child>(myId);

What I need to change so it doesnt have to include class type like this Child.Find(myId);

EDIT

I want to make this method as extension, and get it directly without defining the class into variable. the generic classT should be it's child type.

Body:
One option would be to add this method to your Child class:

public static Child Find(string id)
{
    return Parent.Find<Child>(id);
}


问:
inversify: how to bind Model<Document> to container object
I am developing an application using typescript, mean stack, inversify-express-utils and inversifyjs as my IOC container.  I am receiving an error for my entries in the inversify.config.ts file for the entry that add a Model to the container.  For example,

inversify.config.ts:

```<code>container.bind<Model<Document>>(TYPES.Document).to(User).whenTargetNamed("userSchema");
</code>```

This seems to result in the following error:
"Argument of type Model is not assignable to parameter of type 'new (...args: any[]) => Model'.  Type 'IUserModel' is not assignable type 'Model'.  Property 'findByid' is missing in type 'IUserModel'."

igroupmodel.ts:

```<code>export interface IUserModel extends IUser, Document
</code>```

types.ts:

```<code>Document: Symbol("Model")
</code>```

group.js(last line):

```<code>export let User = mongoose.model<IUserModel>("User", UserSchema);
</code>```

What is the correct way to inject a mongoose model into the container?  I have been looking for an example demonstrating how to work with inversifyjs and mongoose and have not found a solution.

Update:
When I substitute to(User) with toConstantValue(User) I am no longer getting the error.  However, my log file seems to display the following error in my log files:

"Error: No matching bindings found for serviceIdentifier:
  Model"

答: You can find an example of mongoose + inversify here. The example uses the onion architecture but you should be able to use a different architecture if you don't like it...</p>

Body:
I am developing an application using typescript, mean stack, inversify-express-utils and inversifyjs as my IOC container.  I am receiving an error for my entries in the inversify.config.ts file for the entry that add a Model to the container.  For example,

inversify.config.ts:

container.bind<Model<Document>>(TYPES.Document).to(User).whenTargetNamed("userSchema");

This seems to result in the following error:
"Argument of type Model is not assignable to parameter of type 'new (...args: any[]) => Model'.  Type 'IUserModel' is not assignable type 'Model'.  Property 'findByid' is missing in type 'IUserModel'."

igroupmodel.ts:

export interface IUserModel extends IUser, Document

types.ts:

Document: Symbol("Model")

group.js(last line):

export let User = mongoose.model<IUserModel>("User", UserSchema);

What is the correct way to inject a mongoose model into the container?  I have been looking for an example demonstrating how to work with inversifyjs and mongoose and have not found a solution.

Update:
When I substitute to(User) with toConstantValue(User) I am no longer getting the error.  However, my log file seems to display the following error in my log files:

"Error: No matching bindings found for serviceIdentifier:
  Model"


问:
How to implement pagination in a Google Maps InfoWindow for multiple locations?
I have google map with muliplte location and multiple marker in same location.

My Map data will be like this

```<code>[{"DisplayText": "Test Window 1 - 1", "LatitudeLongitude": "61.095,10.547", "Location": "Oslo"},
{"DisplayText": "Test Window 1 - 2", "LatitudeLongitude": "61.095,10.547", "Location": "Oslo"},
{"DisplayText": "Test Window 2 - 1", "LatitudeLongitude": "61.585,8.369", "Location": "Ringebu Municipality"},
{"DisplayText": "Test Window 2 - 2", "LatitudeLongitude": "61.585,8.369", "Location": "Ringebu Municipality"},
{"DisplayText": "Test Window 1 - 3", "LatitudeLongitude": "61.095,10.547", "Location": "Oslo"},
{"DisplayText": "Test Window 3 - 1", "LatitudeLongitude": "61.778,11.3609", "Location": "Oslo Municipality"},
{"DisplayText": "Test Window 4 - 1", "LatitudeLongitude": "63.485,10.449", "Location": "Trondheim"}]
</code>```

I need to display data which has same lat, long in a slider within Google infowindow.

There is a FIDDLE to display like that . But I need to display multiple markers with pagination features

答:
This can be implemented manually, making use of the setContent method on the InfoWindow.

I did a similar thing years ago - to see a demo of it in action, load the following page and wait a while for the markers to come up:
http://www.auctionsearchkit.co.uk/search.php?satitle=test&site=UK . Then click on a few markers until you come to one where the infowindow has « < > » icons at the top (this is where more than one of the eBay search results is for the same seller). You can check out the Javascript on the HTML page for more details but basically (with some bits cut out) you'll need something like this:

```<code>function getInfoWindowHtml(pc) {
  var infoWindowHtml = '<span' + MOUSE_OVER_HAND
                               + ' title="View the first item at this location"'
                               + ' onclick="viewFirstItem(\'' + pc + '\')">'
                     + '«</span> '
                     + '<span' + MOUSE_OVER_HAND
                               + ' title="View the previous item at this location"'
                               + ' onclick="viewPrevItem(\'' + pc + '\')">'
                     + '<</span> '
                     + '<span' + MOUSE_OVER_HAND
                               + ' title="View the next item at this location"'
                               + ' onclick="viewNextItem(\'' + pc + '\')">'
                     + '></span> '
                     + '<span' + MOUSE_OVER_HAND
                               + ' title="View the last item at this location"'
                               + ' onclick="viewLastItem(\'' + pc + '\')">'
                     + '»</span>  ' :
                       '')
                   + '...etc...';
  }

  return infoWindowHtml;
}
</code>```

...and code like the following to open it:

```<code>  // Open the Info Window
  var html = getInfoWindowHtml(pc);
  infoWindow.setContent(html);
  infoWindow.open(map, marker);
</code>```

You'll then need to implement viewFirstItem, viewLastItem, viewNextItem and viewPrevItem functions to change the infoWindow's HTML appropriately.

Body:
I have google map with muliplte location and multiple marker in same location.

My Map data will be like this

[{"DisplayText": "Test Window 1 - 1", "LatitudeLongitude": "61.095,10.547", "Location": "Oslo"},
{"DisplayText": "Test Window 1 - 2", "LatitudeLongitude": "61.095,10.547", "Location": "Oslo"},
{"DisplayText": "Test Window 2 - 1", "LatitudeLongitude": "61.585,8.369", "Location": "Ringebu Municipality"},
{"DisplayText": "Test Window 2 - 2", "LatitudeLongitude": "61.585,8.369", "Location": "Ringebu Municipality"},
{"DisplayText": "Test Window 1 - 3", "LatitudeLongitude": "61.095,10.547", "Location": "Oslo"},
{"DisplayText": "Test Window 3 - 1", "LatitudeLongitude": "61.778,11.3609", "Location": "Oslo Municipality"},
{"DisplayText": "Test Window 4 - 1", "LatitudeLongitude": "63.485,10.449", "Location": "Trondheim"}]

I need to display data which has same lat, long in a slider within Google infowindow.

There is a FIDDLE to display like that . But I need to display multiple markers with pagination features

Body:
This can be implemented manually, making use of the setContent method on the InfoWindow.

I did a similar thing years ago - to see a demo of it in action, load the following page and wait a while for the markers to come up:
http://www.auctionsearchkit.co.uk/search.php?satitle=test&site=UK . Then click on a few markers until you come to one where the infowindow has « < > » icons at the top (this is where more than one of the eBay search results is for the same seller). You can check out the Javascript on the HTML page for more details but basically (with some bits cut out) you'll need something like this:

function getInfoWindowHtml(pc) {
  var infoWindowHtml = '<span' + MOUSE_OVER_HAND
                               + ' title="View the first item at this location"'
                               + ' onclick="viewFirstItem(\'' + pc + '\')">'
                     + '&laquo;</span>&nbsp;'
                     + '<span' + MOUSE_OVER_HAND
                               + ' title="View the previous item at this location"'
                               + ' onclick="viewPrevItem(\'' + pc + '\')">'
                     + '&lt;</span>&nbsp;'
                     + '<span' + MOUSE_OVER_HAND
                               + ' title="View the next item at this location"'
                               + ' onclick="viewNextItem(\'' + pc + '\')">'
                     + '&gt;</span>&nbsp;'
                     + '<span' + MOUSE_OVER_HAND
                               + ' title="View the last item at this location"'
                               + ' onclick="viewLastItem(\'' + pc + '\')">'
                     + '&raquo;</span>&nbsp;&nbsp;' :
                       '')
                   + '...etc...';
  }

  return infoWindowHtml;
}

...and code like the following to open it:

  // Open the Info Window
  var html = getInfoWindowHtml(pc);
  infoWindow.setContent(html);
  infoWindow.open(map, marker);

You'll then need to implement viewFirstItem, viewLastItem, viewNextItem and viewPrevItem functions to change the infoWindow's HTML appropriately.


问:
Can anybody explain the concept of pluggable adapter to me with good example?
Can anybody explain the concept of pluggable adapter to me with good example?</p>

答:
From what I understood from a quick reading of Google results, a pluggable adapter is an adapter that isn't hard-coded against a specific adaptee. On the surface (the adapter's own interface), it's all the same but it can adapt to different adaptees with different interfaces. I found this thread pretty explanatory:

Basically, it allows you to put in an
  adapter when the adaptee (receiver)
  protocol is not known at compile time
  by using reflection. When you create
  the adapter instance, you pass it the
  name of the adaptee's method to call,
  and also any metadata that's necessary
  to translate input types. When the
  adapter receives a method call of the
  target interface, it uses reflection
  to call the corresponding method
  specified on the adaptee.

And this:

The main responsibility of the Viewer
  is to populate a widget from a domain
  model without making any assumptions
  about domain itself. JFace viewer uses
  the Delegating Objects mechanism in
  Pluggable Adapter Pattern to implement
  the above requirement.

Think of it as a facehugger from Alien; when it hugs a face, all you see is the slimy back of the facehugger. You can poke it with a stick and try to pry off its arms (the adapter interface). But it basically can hug the face of any human (the adaptee), regardless of the face features. Maybe I'm pushing it a bit, but, hey, I love Alien.

OwnerDisplayName: infynyxx

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ates Goral

OwnerDisplayName: Ates Goral


问:
How do I modify my simple Python code, to take into account HTTP headers?
```<code>def URLRequest(url, params, method="POST"):
    r  = urllib2.urlopen(url, data=urllib.urlencode(params))
    return r
</code>```

In this method, I send a POST request to a certain URL.  What if I want to do headers as well? I want to send a dictionary of additional headers (in addition to standard headers).

答: With urllib2, you can easily use custom "Handlers" to send additional headers etc. Or see http.client.

Body:
def URLRequest(url, params, method="POST"):
    r  = urllib2.urlopen(url, data=urllib.urlencode(params))
    return r

In this method, I send a POST request to a certain URL.  What if I want to do headers as well? I want to send a dictionary of additional headers (in addition to standard headers).


问:
Occasional 'getaddrinfo: Name or service not known' error on Houston's APN#push call
I'm using Houston gem to send push notifications. APN.push(notifications) occasionally throws an error:

```<code>SocketError: getaddrinfo: Name or service not known
</code>```

The push method itself is called by sidekiq worker, if that matters.

Here's the output from the red RSpec test:

```<code># /home/?/.rvm/gems/ruby-2.3.1/gems/houston-2.2.4/lib/houston/connection.rb:36:in `initialize'
# /home/?/.rvm/gems/ruby-2.3.1/gems/houston-2.2.4/lib/houston/connection.rb:36:in `new'
# /home/?/.rvm/gems/ruby-2.3.1/gems/houston-2.2.4/lib/houston/connection.rb:36:in `open'
# /home/?/.rvm/gems/ruby-2.3.1/gems/houston-2.2.4/lib/houston/connection.rb:19:in `open'
# /home/?/.rvm/gems/ruby-2.3.1/gems/houston-2.2.4/lib/houston/client.rb:40:in `push'
# ./app/api/services/notification_service.rb:42:in `push'
# ./spec/services/notification_service_spec.rb:33:in `block (3 levels) in <top (required)>'
# ./spec/rails_helper.rb:41:in `block (3 levels) in <top (required)>'
# /home/?/.rvm/gems/ruby-2.3.1/gems/database_cleaner-1.5.3/lib/database_cleaner/generic/base.rb:16:in `cleaning'
# /home/?/.rvm/gems/ruby-2.3.1/gems/database_cleaner-1.5.3/lib/database_cleaner/base.rb:98:in `cleaning'
# /home/?/.rvm/gems/ruby-2.3.1/gems/database_cleaner-1.5.3/lib/database_cleaner/configuration.rb:86:in `block (2 levels) in cleaning'
# /home/?/.rvm/gems/ruby-2.3.1/gems/database_cleaner-1.5.3/lib/database_cleaner/configuration.rb:87:in `cleaning'
# ./spec/rails_helper.rb:40:in `block (2 levels) in <top (required)>'
</code>```

The problem occurs in all environments, causing part of notifications not being sent.

Where do I look to solve this problem?

答: Ruby isn't able to resolve your provided hostname to an IP address. Since the hostname comes from a gem, I guess that part should be OK. Would you happen to have internet connection issues?</p>

Body:
I'm using Houston gem to send push notifications. APN.push(notifications) occasionally throws an error:

SocketError: getaddrinfo: Name or service not known

The push method itself is called by sidekiq worker, if that matters.

Here's the output from the red RSpec test:

# /home/?/.rvm/gems/ruby-2.3.1/gems/houston-2.2.4/lib/houston/connection.rb:36:in `initialize'
# /home/?/.rvm/gems/ruby-2.3.1/gems/houston-2.2.4/lib/houston/connection.rb:36:in `new'
# /home/?/.rvm/gems/ruby-2.3.1/gems/houston-2.2.4/lib/houston/connection.rb:36:in `open'
# /home/?/.rvm/gems/ruby-2.3.1/gems/houston-2.2.4/lib/houston/connection.rb:19:in `open'
# /home/?/.rvm/gems/ruby-2.3.1/gems/houston-2.2.4/lib/houston/client.rb:40:in `push'
# ./app/api/services/notification_service.rb:42:in `push'
# ./spec/services/notification_service_spec.rb:33:in `block (3 levels) in <top (required)>'
# ./spec/rails_helper.rb:41:in `block (3 levels) in <top (required)>'
# /home/?/.rvm/gems/ruby-2.3.1/gems/database_cleaner-1.5.3/lib/database_cleaner/generic/base.rb:16:in `cleaning'
# /home/?/.rvm/gems/ruby-2.3.1/gems/database_cleaner-1.5.3/lib/database_cleaner/base.rb:98:in `cleaning'
# /home/?/.rvm/gems/ruby-2.3.1/gems/database_cleaner-1.5.3/lib/database_cleaner/configuration.rb:86:in `block (2 levels) in cleaning'
# /home/?/.rvm/gems/ruby-2.3.1/gems/database_cleaner-1.5.3/lib/database_cleaner/configuration.rb:87:in `cleaning'
# ./spec/rails_helper.rb:40:in `block (2 levels) in <top (required)>'

The problem occurs in all environments, causing part of notifications not being sent.

Where do I look to solve this problem?


问:
Android: How to Implement a Settings Page Within a Navigation Drawer?
So I'm in the process of creating an app which utilises a Navigation Drawer which is split into separate fragments to access each of the tabs. Now, the thing I would like to find out how to do, is to equally have a Settings/Preferences Fragment or Activity (unsure which one would be appropriate in this context) to open once the user selects the "Settings" tab within the Navigation Drawer. I've looked all over the internet for a CLEAR explanation on how to do this, as I'm not an expert on app development.

Below is a picture of the Navigation Drawer:

If any layout or class code is required, I am happy to provide it. Any help is much appreciated!

答:
You can use the PreferenceFragmentCompat, for example:

First you create a Fragment who extends PreferenceFragmentCompat and the layout associated under the folder res/xml

settings.xml

```<code><android.support.v7.preference.PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.preference.PreferenceCategory
        android:key="the_key_to_retrieve_the_preference_in_code"
        android:title="the_preference_title">

        <android.support.v7.preference.Preference
            android:key="key"
            android:summary="subtitle"
            android:title="title" />

        <android.support.v7.preference.Preference
            android:key="key2"
            android:summary="subtitle2"
            android:title="title2" />

        <android.support.v7.preference.CheckBoxPreference
             android:key="key_for_check_box"
             android:summary="subtitle"
             android:title="title" />

    </android.support.v7.preference.PreferenceCategory>
</android.support.v7.preference.PreferenceScreen>
</code>```

SettingsFragment.java

```<code>public class SettingsFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.settings);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
       // To get a preference
       PreferenceScreen preferenceScreen = getPreferenceScreen();
       Preference preference = preferenceScreen.findPreference("preference_ key_defined_in_the_xml");

     //You can set a listener
     preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                return false;
            }
        });

     //change title
     preference.setTitle("my_title");

     // etc
    }
}
</code>```

Then you create a Activity who will hold the fragment:

SettingsActivity.java

```<code>public class SettingsActivity extends AppCompatActivity {
    private Toolbar mToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        setActionBarTitle("Settings");
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
}
</code>```

settings_activity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

    <fragment
        android:id="@+id/settings_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:name="package.name.SettingsFragment"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

Be sure to add the new Settings activity to your manifest

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.app">

    <application
            android:name=".MyApplication"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

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

        <activity android:name=".SettingsActivity"></activity>

    </application>

</manifest>
```

<p>That it , then when you click on the item in your <code>NavigationDrawer</code> you set a new <code>Intent</code> and call it:</p>

```Intent intent = new Intent(this /*or the actual context*/, SettingsActivity.class);
startActivity(intent);
```

Hope this helps.
Sorry for my english.

Body:
You can use the PreferenceFragmentCompat, for example:

First you create a Fragment who extends PreferenceFragmentCompat and the layout associated under the folder res/xml

settings.xml

<android.support.v7.preference.PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.preference.PreferenceCategory
        android:key="the_key_to_retrieve_the_preference_in_code"
        android:title="the_preference_title">

        <android.support.v7.preference.Preference
            android:key="key"
            android:summary="subtitle"
            android:title="title" />

        <android.support.v7.preference.Preference
            android:key="key2"
            android:summary="subtitle2"
            android:title="title2" />

        <android.support.v7.preference.CheckBoxPreference
             android:key="key_for_check_box"
             android:summary="subtitle"
             android:title="title" />

    </android.support.v7.preference.PreferenceCategory>
</android.support.v7.preference.PreferenceScreen>

SettingsFragment.java

public class SettingsFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.settings);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
       // To get a preference
       PreferenceScreen preferenceScreen = getPreferenceScreen();
       Preference preference = preferenceScreen.findPreference("preference_ key_defined_in_the_xml");

     //You can set a listener
     preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                return false;
            }
        });

     //change title
     preference.setTitle("my_title");

     // etc
    }
}

Then you create a Activity who will hold the fragment:

SettingsActivity.java

public class SettingsActivity extends AppCompatActivity {
    private Toolbar mToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        setActionBarTitle("Settings");
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
}

settings_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

    <fragment
        android:id="@+id/settings_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:name="package.name.SettingsFragment"/>

</android.support.design.widget.CoordinatorLayout>

Be sure to add the new Settings activity to your manifest

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.app">

    <application
            android:name=".MyApplication"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

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

        <!-- add the below line to your AndroidManifest.xml -->
        <activity android:name=".SettingsActivity"></activity>

    </application>

</manifest>

That it , then when you click on the item in your NavigationDrawer you set a new Intent and call it:

Intent intent = new Intent(this /*or the actual context*/, SettingsActivity.class);
startActivity(intent);

Hope this helps.
Sorry for my english.

ContentLicense: CC BY-SA 4.0


问:
Unable to download Library using cocoaPods
I am new in swift programming . I  am trying to download libraries for the project . I have installed  cocoa pods : sudo gem install cocoa pods, created pod file with all libraries which I need : pod 'GoogleMaps'.  After pod install I got an error:

```<code> Unable to satisfy the following requirements:

 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps (= 2.3.1)` required by `Podfile.lock`

 Specs satisfying the `GoogleMaps, GoogleMaps (= 2.3.1)` dependency
 were found, but they required a higher minimum deployment target.

 [!] Automatically assigning platform ios with version 7.0 on target
  Taxi for rider because no platform was specified. Please specify a
 platform    for this target in your Podfile. See
 `https://guides.cocoapods.org/syntax/podfile.html#platform`.
</code>```

My pod file:

```<code>  # Uncomment the next line to define a global platform for your
  project
  # platform :ios, '9.0'

  target 'Taxi for rider' do
  # Comment the next line if you're not using Swift and don't want to
  use dynamic frameworks
  use_frameworks!

  # Pods for Taxi for rider
  pod 'Firebase'
  pod 'Firebase/Storage'
  pod 'Firebase/Auth'
  pod 'Firebase/Database'
  pod 'GoogleMaps'
  pod 'GoogleMaps'
  pod 'GooglePlaces'
  pod 'GooglePlacesAPI'
  pod 'GooglePlacePicker'
  pod 'SwiftyJSON'
  pod 'Firebase/Core'
  pod 'Firebase/Storage'

  end
</code>```

答:
Step Of Install Cocoa Pods.

Step 1 - Close your Xcode project which you install pod file. and Open terminal.

Step 2 - type cd  command and Drag your project path.

Step 3  - press Enter and type pod init conmmand then open your project folder, now you can see pod file

Step 4 - open pod file and write pod name which you install

Step 5 - save and close pod file and again open terminal and write pod install command and wait few minutes to install pod

After install pod go to your project folder and open .work space file and enjoy.

now pod is installed enjoy and used.

Body:
I am new in swift programming . I  am trying to download libraries for the project . I have installed  cocoa pods : sudo gem install cocoa pods, created pod file with all libraries which I need : pod 'GoogleMaps'.  After pod install I got an error:

 Unable to satisfy the following requirements:

 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps` required by `Podfile`
 - `GoogleMaps (= 2.3.1)` required by `Podfile.lock`

 Specs satisfying the `GoogleMaps, GoogleMaps (= 2.3.1)` dependency
 were found, but they required a higher minimum deployment target.

 [!] Automatically assigning platform ios with version 7.0 on target
  Taxi for rider because no platform was specified. Please specify a
 platform    for this target in your Podfile. See
 `https://guides.cocoapods.org/syntax/podfile.html#platform`.

My pod file:

  # Uncomment the next line to define a global platform for your
  project
  # platform :ios, '9.0'

  target 'Taxi for rider' do
  # Comment the next line if you're not using Swift and don't want to
  use dynamic frameworks
  use_frameworks!

  # Pods for Taxi for rider
  pod 'Firebase'
  pod 'Firebase/Storage'
  pod 'Firebase/Auth'
  pod 'Firebase/Database'
  pod 'GoogleMaps'
  pod 'GoogleMaps'
  pod 'GooglePlaces'
  pod 'GooglePlacesAPI'
  pod 'GooglePlacePicker'
  pod 'SwiftyJSON'
  pod 'Firebase/Core'
  pod 'Firebase/Storage'

  end


问:
How to prevent multiple initialization of static field in static method?
In my web application I need to cache some data as they are required frequently
but changes less often. To hold them I have made a sepearate static class which hold these field as static values. These field get initialized on first call. see a sample below.

```<code>public static class gtu
{
  private static string mostsearchpagedata = "";
  public static string getmostsearchpagedata()
   {
    if (mostsearchpagedata == "")
    {
        using (WebClient client = new WebClient())
        {
            mostsearchpagedata = client.DownloadString("https://xxx.yxc");
        }
    }
    return mostsearchpagedata;
}
 }
</code>```

Here webrequest is only made one time, it works ok but if they are called in quick succession when there are large no. of users and apppool has restarted,
webrequest is made multiple times depending upon mostsearchpagedata was initialized or not.

How can I make sure that webrequest happens only one time, and all other request wait till the completion of the first webrequest?

答:
You could use System.Lazy<T>:

```<code>public static class gtu
{
    private static readonly Lazy<string> mostsearchedpagedata =
       new Lazy<string>(
          () => {
                using (WebClient client = new WebClient())
                {
                   mostsearchpagedata =
                      client.DownloadString("https://xxx.yxc");
                }
          },
          // See https://msdn.microsoft.com/library/system.threading.lazythreadsafetymode(v=vs.110).aspx for more info
          // on the relevance of this.
          // Hint: since fetching a web page is potentially
          // expensive you really want to do it only once.
          LazyThreadSafeMode.ExecutionAndPublication
       );

    // Optional: provide a "wrapper" to hide the fact that Lazy is used.
    public static string MostSearchedPageData => mostsearchedpagedata.Value;

 }
</code>```

In short, the lambda code (your DownloadString essentially) will be called, when the first thread calls .Value on the Lazy-instance. Other threads will either do the same or wait for the first thread to finish (see LazyThreadSafeMode for more info). Subsequent invocations of the Value-property will get the value already stored in the Lazy-instance.

Body:
In my web application I need to cache some data as they are required frequently
but changes less often. To hold them I have made a sepearate static class which hold these field as static values. These field get initialized on first call. see a sample below.

public static class gtu
{
  private static string mostsearchpagedata = "";
  public static string getmostsearchpagedata()
   {
    if (mostsearchpagedata == "")
    {
        using (WebClient client = new WebClient())
        {
            mostsearchpagedata = client.DownloadString("https://xxx.yxc");
        }
    }
    return mostsearchpagedata;
}
 }

Here webrequest is only made one time, it works ok but if they are called in quick succession when there are large no. of users and apppool has restarted,
webrequest is made multiple times depending upon mostsearchpagedata was initialized or not.

How can I make sure that webrequest happens only one time, and all other request wait till the completion of the first webrequest?

Body:
You could use System.Lazy<T>:

public static class gtu
{
    private static readonly Lazy<string> mostsearchedpagedata =
       new Lazy<string>(
          () => {
                using (WebClient client = new WebClient())
                {
                   mostsearchpagedata =
                      client.DownloadString("https://xxx.yxc");
                }
          },
          // See https://msdn.microsoft.com/library/system.threading.lazythreadsafetymode(v=vs.110).aspx for more info
          // on the relevance of this.
          // Hint: since fetching a web page is potentially
          // expensive you really want to do it only once.
          LazyThreadSafeMode.ExecutionAndPublication
       );

    // Optional: provide a "wrapper" to hide the fact that Lazy is used.
    public static string MostSearchedPageData => mostsearchedpagedata.Value;

 }

In short, the lambda code (your DownloadString essentially) will be called, when the first thread calls .Value on the Lazy-instance. Other threads will either do the same or wait for the first thread to finish (see LazyThreadSafeMode for more info). Subsequent invocations of the Value-property will get the value already stored in the Lazy-instance.


问:
NSClassFromString not working
Here is an issue I have with this case of code:

```<code>let entityTypeDico = ["entityTypeOne": arrayOne, "entityTypeOneTwo": arrayTwo,
                      "entityTypeThree": arrayThree, "entityTypeFour": arrayFour];

for (entityName, arrayItem) in entityTypeDico {
    for x in arrayItem {
      /*do something with x and arrayItem
      I need to use the class of entityName */
      //To get it I tried to use some code like:
      NSClassFromString(entityName) // But it does not work.
    }
}
</code>```

entityTypeOne, ..... entityTypeFour are names of CoreData entities,
arrayOne, ..... arrayFour are some kind of arrays (not so important for the question).

What exact code do I need to use to get hold of the type of each entity inside the loop?

答:
Your second for loop doesnt make sense. Can you try?

```<code>for (entityName, arrayItem) in entityTypeDico {
    NSClassFromString("YourProjectName.\(entityName)")
}
</code>```

Edit 1

Currently I am working on a project where I used NSClassFromString. And that is how I used it in my code.

In my main class I use:

```<code>let carClass = NSClassFromString("MyProjectName.\(self.selectedBrand)\(self.selectedModel)") as! NSObject.Type
_ = carClass.init()
</code>```

where selectedBrand and selectedModel are picked by the user.

In the car class, I have an init function

```<code>override init() {
    super.init()

    // My codes here like initializing webview

}
</code>```

Hope it helps

Title: NSClassFromString not working

Body:
Here is an issue I have with this case of code:

let entityTypeDico = ["entityTypeOne": arrayOne, "entityTypeOneTwo": arrayTwo,
                      "entityTypeThree": arrayThree, "entityTypeFour": arrayFour];

for (entityName, arrayItem) in entityTypeDico {
    for x in arrayItem {
      /*do something with x and arrayItem
      I need to use the class of entityName */
      //To get it I tried to use some code like:
      NSClassFromString(entityName) // But it does not work.
    }
}

entityTypeOne, ..... entityTypeFour are names of CoreData entities,
arrayOne, ..... arrayFour are some kind of arrays (not so important for the question).

What exact code do I need to use to get hold of the type of each entity inside the loop?

Body:
Your second for loop doesnt make sense. Can you try?

for (entityName, arrayItem) in entityTypeDico {
    NSClassFromString("YourProjectName.\(entityName)")
}

Edit 1

Currently I am working on a project where I used NSClassFromString. And that is how I used it in my code.

In my main class I use:

let carClass = NSClassFromString("MyProjectName.\(self.selectedBrand)\(self.selectedModel)") as! NSObject.Type
_ = carClass.init()

where selectedBrand and selectedModel are picked by the user.

In the car class, I have an init function

override init() {
    super.init()

    // My codes here like initializing webview

}

Hope it helps


问:
downloading file in shiny
I want a user to download a file which is in tabular format with header along with two search widgets on top. The output is forecasted values along with 80%(High-low) and 95%(High-low) confidence interval.So there are five columns, five rows(default). However, i am having two challenges here.

Challenge 1:
When I run the app, after clicking on "Download the file" filename is coming as download data with no extension whereas I have mentioned filename should be "forecasted" with png extension and it should come as forecated.png

Challenge 2: After typing png as extension while saving the file, the file is saved but nothing gets printed.

I have searched in various forums and try to replicate them but nothing seems to be working.

Please suggest.

shiny UI

```<code>library(shiny)
downloadButton(outputId = "downloaddata" ,label ="Download the file"),
</code>```

shiny server

```<code>output$downloaddata<-downloadHandler(

    filename = function(){
      paste("forecasted","png",sep=",")
    },
    content = function(file){
      png(file)
      h <-input$fst
      tab<-forecast(Model_mape(),h)
      datatable(as.data.frame(tab), options = list(
         columnDefs = list(list(targets = c(1, 3), searchable = FALSE)),
         pageLength = 10))
      dev.off()

    }

  )
</code>```

答:
Maybe it could help you (it's a simple instance):

Ui :

```<code>library(shiny)

shinyUI(fluidPage(

  mainPanel(plotOutput("plot1"),
           downloadButton("downloadplot","Download your plot"))

  ))
</code>```

Server :

```<code>library(shiny)

shinyServer(function(input, output) {
  your_plot = function(){
    (plot(rnorm(1000,0,1)))
  }

  output$plot1 <- renderPlot({
    your_plot()
  })

  output$downloadplot <- downloadHandler(
    filename = "plot_exemple.png",
    content = function(file) {
      png(file, width = 1200, height = 800)
      print(your_plot())
      dev.off()
    })

  })
</code>```

With this, you can easily download a png (open it in a browser).

Title: downloading file in shiny

Body:
I want a user to download a file which is in tabular format with header along with two search widgets on top. The output is forecasted values along with 80%(High-low) and 95%(High-low) confidence interval.So there are five columns, five rows(default). However, i am having two challenges here.

Challenge 1:
When I run the app, after clicking on "Download the file" filename is coming as download data with no extension whereas I have mentioned filename should be "forecasted" with png extension and it should come as forecated.png

Challenge 2: After typing png as extension while saving the file, the file is saved but nothing gets printed.

I have searched in various forums and try to replicate them but nothing seems to be working.

Please suggest.

shiny UI

library(shiny)
downloadButton(outputId = "downloaddata" ,label ="Download the file"),

shiny server

output$downloaddata<-downloadHandler(

    filename = function(){
      paste("forecasted","png",sep=",")
    },
    content = function(file){
      png(file)
      h <-input$fst
      tab<-forecast(Model_mape(),h)
      datatable(as.data.frame(tab), options = list(
         columnDefs = list(list(targets = c(1, 3), searchable = FALSE)),
         pageLength = 10))
      dev.off()

    }

  )

Body:
Maybe it could help you (it's a simple instance):

Ui :

library(shiny)

shinyUI(fluidPage(

  mainPanel(plotOutput("plot1"),
           downloadButton("downloadplot","Download your plot"))

  ))

Server :

library(shiny)

shinyServer(function(input, output) {
  your_plot = function(){
    (plot(rnorm(1000,0,1)))
  }

  output$plot1 <- renderPlot({
    your_plot()
  })

  output$downloadplot <- downloadHandler(
    filename = "plot_exemple.png",
    content = function(file) {
      png(file, width = 1200, height = 800)
      print(your_plot())
      dev.off()
    })

  })

With this, you can easily download a png (open it in a browser).


问:
Npgsql Exception- syntax error at or near "\"
I am trying to execute postgresql query (\list) to get the list of databases using npsql.

```<code>string postgresQuery = @"\list";
            ICollection<Schema> schemas = new List<Schema>();
            string ConnectionString =
"Host=xxx;Username=postgres;Password=admin;Database=test;";
            NpgsqlConnection conn = new NpgsqlConnection(ConnectionString);
            NpgsqlCommand cmd = new NpgsqlCommand(postgresQuery, conn);
            conn.Open();
   NpgsqlDataReader dataReader = cmd.ExecuteReader();
</code>```

While executing the query facing an issue that "syntax error at or near "\" ".   The string contains double-slash as follow (\list) instead of single-slash (\list). Please let me know if there is any solution for this. Thanks in advance.

答:
\list isn't a SQL query. It's is a command of the psql-tool.

To get a list of all database with SQL, use the following query:

```<code>SELECT datname FROM pg_database
WHERE datistemplate = false;
</code>```

Check How do I list all databases and tables using psql?

The fields of the pg_database table are described here

The database's owner is stored in the datdba field which references the pg_authid table. It's possible to find all databases owned by a user, as shown in How to list databases owned by rolename in postgresql with

```<code>SELECT datname
FROM pg_database
JOIN pg_authid ON pg_database.datdba = pg_authid.oid
WHERE rolname = 'username'
</code>```

Of course, the query should be parameterized:

```<code>SELECT datname
FROM pg_database
JOIN pg_authid ON pg_database.datdba = pg_authid.oid
WHERE rolname = :username
</code>```

pg_authid is described here

Body:
I am trying to execute postgresql query (\list) to get the list of databases using npsql.

string postgresQuery = @"\list";
            ICollection<Schema> schemas = new List<Schema>();
            string ConnectionString =
"Host=xxx;Username=postgres;Password=admin;Database=test;";
            NpgsqlConnection conn = new NpgsqlConnection(ConnectionString);
            NpgsqlCommand cmd = new NpgsqlCommand(postgresQuery, conn);
            conn.Open();
   NpgsqlDataReader dataReader = cmd.ExecuteReader();

While executing the query facing an issue that "syntax error at or near "\" ".   The string contains double-slash as follow (\list) instead of single-slash (\list). Please let me know if there is any solution for this. Thanks in advance.

Body:
\list isn't a SQL query. It's is a command of the psql-tool.

To get a list of all database with SQL, use the following query:

SELECT datname FROM pg_database
WHERE datistemplate = false;

Check How do I list all databases and tables using psql?

The fields of the pg_database table are described here

The database's owner is stored in the datdba field which references the pg_authid table. It's possible to find all databases owned by a user, as shown in How to list databases owned by rolename in postgresql with

SELECT datname
FROM pg_database
JOIN pg_authid ON pg_database.datdba = pg_authid.oid
WHERE rolname = 'username'

Of course, the query should be parameterized:

SELECT datname
FROM pg_database
JOIN pg_authid ON pg_database.datdba = pg_authid.oid
WHERE rolname = :username

pg_authid is described here


问:
How to show random featured products (woocommerce) in a WP custom loop?
I am trying to have a custom loop in Wordpress for Woocommerce products. I want to show a random featured product in the loop. But for some reason it doesn't get my arguments right and picks a random product from all products available.

This the code i'm using at moment. It does show a random product, but it ignores the featured part of the code.

```<code>$args = array(
    'posts_per_page'   => 1,
    'orderby'          => 'rand',
    'post_type'        => 'product',
    'meta_query'  => array(
        'key'     => '_featured',
        'value'   => 'yes'
    )
);

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>

<li>
    <a href="<?php echo the_permalink(); ?>">
        <h3><?php the_title(); ?></h3>
    </a>
</li>

<?php endwhile;
wp_reset_query(); ?>
</code>```

Can someone lead me into the right direction?

Thanks in advance!

答:
I got the same problem. Try this ! Works for me</p>

```<code><?php
         $featured_query = new WP_Query( array(
             'tax_query' => array(
                     array(
                     'taxonomy' => 'product_visibility',
                     'field'    => 'name',
                     'terms'    => 'featured',
                     'operator' => 'IN'
                 ),
          ),
     ) );
?>
</code>```

Body:
I am trying to have a custom loop in Wordpress for Woocommerce products. I want to show a random featured product in the loop. But for some reason it doesn't get my arguments right and picks a random product from all products available.

This the code i'm using at moment. It does show a random product, but it ignores the featured part of the code.

$args = array(
    'posts_per_page'   => 1,
    'orderby'          => 'rand',
    'post_type'        => 'product',
    'meta_query'  => array(
        'key'     => '_featured',
        'value'   => 'yes'
    )
);

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>

    <a href="<?php echo the_permalink(); ?>">

<?php the_title(); ?>

<?php endwhile;
wp_reset_query(); ?>

Can someone lead me into the right direction?

Thanks in advance!

Body:
I got the same problem. Try this ! Works for me

<?php
         $featured_query = new WP_Query( array(
             'tax_query' => array(
                     array(
                     'taxonomy' => 'product_visibility',
                     'field'    => 'name',
                     'terms'    => 'featured',
                     'operator' => 'IN'
                 ),
          ),
     ) );
?>


问:
CMake File Error
I have been trying to complete and compile the sdk code on the raspberry pi 3 model that I have, but have been unsuccessful at figuring out the error that is below.

Please let me know if anyone has had this error before and if you have some way to solve it.

Compiling the CXX compiler identification source file
  "CMakeCXXCompilerId.cpp" failed. Compiler:
  /home/pi/rpi_root/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  Build flags:  Id flags:

The output was: 2
  /home/pi/rpi_root/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/rpi_root/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected

Compiling the CXX compiler identification source file
  "CMakeCXXCompilerId.cpp" failed. Compiler:
  /home/pi/rpi_root/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  Build flags:  Id flags: -c

The output was: 2
  /home/pi/rpi_root/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/rpi_root/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected

Checking whether the CXX compiler is IAR using "" did not match "IAR
  .+ Compiler":
  /home/pi/rpi_root/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/rpi_root/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected Determining if the CXX compiler works
  failed with the following output: Change Dir:
  /home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make" "cmTC_1a2a7/fast" /usr/bin/make -f
  CMakeFiles/cmTC_1a2a7.dir/build.make CMakeFiles/cmTC_1a2a7.dir/build
  make[1]: Entering directory
  '/home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp'
  Building CXX object CMakeFiles/cmTC_1a2a7.dir/testCXXCompiler.cxx.o
  /home/pi/rpi_root/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  -o CMakeFiles/cmTC_1a2a7.dir/testCXXCompiler.cxx.o -c /home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp/testCXXCompiler.cxx
  /home/pi/rpi_root/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/rpi_root/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected CMakeFiles/cmTC_1a2a7.dir/build.make:65:
  recipe for target 'CMakeFiles/cmTC_1a2a7.dir/testCXXCompiler.cxx.o'
  failed make[1]: * [CMakeFiles/cmTC_1a2a7.dir/testCXXCompiler.cxx.o]
  Error 2 make[1]: Leaving directory
  '/home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp'
  Makefile:126: recipe for target 'cmTC_1a2a7/fast' failed make: *
  [cmTC_1a2a7/fast] Error 2

Compiling the CXX compiler identification source file
  "CMakeCXXCompilerId.cpp" failed. Compiler:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  Build flags:  Id flags:

The output was: 2
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected

Compiling the CXX compiler identification source file
  "CMakeCXXCompilerId.cpp" failed. Compiler:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  Build flags:  Id flags: -c

The output was: 2
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected

Checking whether the CXX compiler is IAR using "" did not match "IAR
  .+ Compiler":
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected Determining if the CXX compiler works
  failed with the following output: Change Dir:
  /home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make" "cmTC_39dde/fast" /usr/bin/make -f
  CMakeFiles/cmTC_39dde.dir/build.make CMakeFiles/cmTC_39dde.dir/build
  make[1]: Entering directory
  '/home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp'
  Building CXX object CMakeFiles/cmTC_39dde.dir/testCXXCompiler.cxx.o
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  -o CMakeFiles/cmTC_39dde.dir/testCXXCompiler.cxx.o -c /home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp/testCXXCompiler.cxx
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected CMakeFiles/cmTC_39dde.dir/build.make:65:
  recipe for target 'CMakeFiles/cmTC_39dde.dir/testCXXCompiler.cxx.o'
  failed make[1]: * [CMakeFiles/cmTC_39dde.dir/testCXXCompiler.cxx.o]
  Error 2 make[1]: Leaving directory
  '/home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp'
  Makefile:126: recipe for target 'cmTC_39dde/fast' failed make: *
  [cmTC_39dde/fast] Error 2

Compiling the CXX compiler identification source file
  "CMakeCXXCompilerId.cpp" failed. Compiler:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  Build flags:  Id flags:

The output was: 2
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected

Compiling the CXX compiler identification source file
  "CMakeCXXCompilerId.cpp" failed. Compiler:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  Build flags:  Id flags: -c

The output was: 2
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected

Checking whether the CXX compiler is IAR using "" did not match "IAR
  .+ Compiler":
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected Determining if the CXX compiler works
  failed with the following output: Change Dir:
  /home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make" "cmTC_2bd57/fast" /usr/bin/make -f
  CMakeFiles/cmTC_2bd57.dir/build.make CMakeFiles/cmTC_2bd57.dir/build
  make[1]: Entering directory
  '/home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp'
  Building CXX object CMakeFiles/cmTC_2bd57.dir/testCXXCompiler.cxx.o
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  -o CMakeFiles/cmTC_2bd57.dir/testCXXCompiler.cxx.o -c /home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp/testCXXCompiler.cxx
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected CMakeFiles/cmTC_2bd57.dir/build.make:65:
  recipe for target 'CMakeFiles/cmTC_2bd57.dir/testCXXCompiler.cxx.o'
  failed make[1]: * [CMakeFiles/cmTC_2bd57.dir/testCXXCompiler.cxx.o]
  Error 2 make[1]: Leaving directory
  '/home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp'
  Makefile:126: recipe for target 'cmTC_2bd57/fast' failed make: *
  [cmTC_2bd57/fast] Error 2

Compiling the CXX compiler identification source file
  "CMakeCXXCompilerId.cpp" failed. Compiler:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  Build flags:  Id flags:

The output was: 2
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected

Compiling the CXX compiler identification source file
  "CMakeCXXCompilerId.cpp" failed. Compiler:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  Build flags:  Id flags: -c

The output was: 2
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected

Checking whether the CXX compiler is IAR using "" did not match "IAR
  .+ Compiler":
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected Determining if the CXX compiler works
  failed with the following output: Change Dir:
  /home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make" "cmTC_8d1c9/fast" /usr/bin/make -f
  CMakeFiles/cmTC_8d1c9.dir/build.make CMakeFiles/cmTC_8d1c9.dir/build
  make[1]: Entering directory
  '/home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp'
  Building CXX object CMakeFiles/cmTC_8d1c9.dir/testCXXCompiler.cxx.o
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  -o CMakeFiles/cmTC_8d1c9.dir/testCXXCompiler.cxx.o -c /home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp/testCXXCompiler.cxx
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected CMakeFiles/cmTC_8d1c9.dir/build.make:65:
  recipe for target 'CMakeFiles/cmTC_8d1c9.dir/testCXXCompiler.cxx.o'
  failed make[1]: * [CMakeFiles/cmTC_8d1c9.dir/testCXXCompiler.cxx.o]
  Error 2 make[1]: Leaving directory
  '/home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp'
  Makefile:126: recipe for target 'cmTC_8d1c9/fast' failed make: *
  [cmTC_8d1c9/fast] Error 2

Compiling the CXX compiler identification source file
  "CMakeCXXCompilerId.cpp" failed. Compiler:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  Build flags:  Id flags:

The output was: 2
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected

Compiling the CXX compiler identification source file
  "CMakeCXXCompilerId.cpp" failed. Compiler:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  Build flags:  Id flags: -c

The output was: 2
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected

Checking whether the CXX compiler is IAR using "" did not match "IAR
  .+ Compiler":
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected Determining if the CXX compiler works
  failed with the following output: Change Dir:
  /home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make" "cmTC_904a4/fast" /usr/bin/make -f
  CMakeFiles/cmTC_904a4.dir/build.make CMakeFiles/cmTC_904a4.dir/build
  make[1]: Entering directory
  '/home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp'
  Building CXX object CMakeFiles/cmTC_904a4.dir/testCXXCompiler.cxx.o
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++
  -o CMakeFiles/cmTC_904a4.dir/testCXXCompiler.cxx.o -c /home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp/testCXXCompiler.cxx
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  1:
  /home/pi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++:
  Syntax error: "(" unexpected CMakeFiles/cmTC_904a4.dir/build.make:65:
  recipe for target 'CMakeFiles/cmTC_904a4.dir/testCXXCompiler.cxx.o'
  failed make[1]: * [CMakeFiles/cmTC_904a4.dir/testCXXCompiler.cxx.o]
  Error 2 make[1]: Leaving directory
  '/home/pi/rpi_root/Botan-1.11.27/kaa-cpp/build/CMakeFiles/CMakeTmp'
  Makefile:126: recipe for target 'cmTC_904a4/fast' failed make: *
  [cmTC_904a4/fast] Error 2

答: I faced the same problem when using C SDK. I tried to use the default gcc in Raspberry as compiler, and everything works fine. Maybe you can also try to compile the C++ SDK based on the C++ Linux guide but C++ Raspberry pi guide.</p>

Title: CMake File Error


问:
Android Numberpicker default value not coming
When the numberpicker is loaded, the default value is not appearing on the screen until touched.

Once touched, everything works fine.Any help appreciated.

Also if the formatter is removed, it works fine.

dialog.xml

```<code><NumberPicker
    android:id="@+id/number_picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />

<Button
    android:id="@+id/apply_button"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/number_picker"
    android:text="@string/ok_string" />
</code>```

Here is the activity code:

```<code>final NumberPicker np = (NumberPicker) d.findViewById(R.id.number_picker);
        np.setMaxValue(50);
        np.setMinValue(0);
        np.setWrapSelectorWheel(true);
        np.setOnValueChangedListener(this);
        np.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

        np.setFormatter(new NumberPicker.Formatter() {
            @Override
            public String format(int i) {
                if (i == 25)
                    return "0";
                else
                    return String.valueOf(i - 25);
            }
        });
        np.setValue(25);
</code>```

Thanks in advance

答: I found a solution for this bug in NumberPicker that works in APIs 18-26 without using reflection and without using setDisplayedValues() here.

Body:
When the numberpicker is loaded, the default value is not appearing on the screen until touched.

Once touched, everything works fine.Any help appreciated.

Also if the formatter is removed, it works fine.

dialog.xml

<NumberPicker
    android:id="@+id/number_picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
     />

<Button
    android:id="@+id/apply_button"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/number_picker"
    android:text="@string/ok_string" />

Here is the activity code:

final NumberPicker np = (NumberPicker) d.findViewById(R.id.number_picker);
        np.setMaxValue(50);
        np.setMinValue(0);
        np.setWrapSelectorWheel(true);
        np.setOnValueChangedListener(this);
        np.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

        np.setFormatter(new NumberPicker.Formatter() {
            @Override
            public String format(int i) {
                if (i == 25)
                    return "0";
                else
                    return String.valueOf(i - 25);
            }
        });
        np.setValue(25);

Thanks in advance


问:
How to reference the node paramater from the active choices reactive parameter in Jenkins
I basically want to drive a set of choice parameters based on the slave node parameter choice.  I tried to use the active choices reactive plugin to point to the node choice like this:

```<code>if (Node.contains("name_of_slave_node")) {
  return ["you_chose_slave_node"]
} else {
  return ["master"]
}
</code>```

Nothing I do seems to work.  I can use this type of logic and point to any other type of parameter and it works.  Im just a bit stumped as to where to go with this.  Could it be a limitation with the plugin or am I missing something with how the groovy is addressing the node parameter.  I really appreciate any advice.

答:
It can be hard to get your head around how the plug-in works. Even now I still get surprised by all the cases users apply the plug-in, and the different ways they use it.

You can definitely do what you want. The plug-in executes a Groovy script that must return an array with the values to be displayed on the UI. You also have some helper variables that the plug-in tries to make available for you. One of these variables is the jenkinsProject.

If in your project you assigned a label, then programmatically you can return values based on the node label assigned to your project (or to the node object...).

Here's a very simple example.

```<code>assignedNode = jenkinsProject.getAssignedLabelString()
list = []
if (assignedNode == null) {
    // do something
} else if (assignedNode.equals('abc')) {
    // ...
}
return list
</code>```

Here assignedNode will have the string name of the node, or null if none. If you use instead jenkinsProject.getAssignedLabel(), then you will have not a String, but a Label.

If you need further customization, the best way is to dive into the Java API, then build your Groovy script from the bottom up. Or try finding examples online (there are many for Jenkins and Groovy) and adapt them to your parameter.

Hope that helps,
Bruno

Body:
I basically want to drive a set of choice parameters based on the slave node parameter choice.  I tried to use the active choices reactive plugin to point to the node choice like this:

if (Node.contains("name_of_slave_node")) {
  return ["you_chose_slave_node"]
} else {
  return ["master"]
}

Nothing I do seems to work.  I can use this type of logic and point to any other type of parameter and it works.  Im just a bit stumped as to where to go with this.  Could it be a limitation with the plugin or am I missing something with how the groovy is addressing the node parameter.  I really appreciate any advice.

Body:
It can be hard to get your head around how the plug-in works. Even now I still get surprised by all the cases users apply the plug-in, and the different ways they use it.

You can definitely do what you want. The plug-in executes a Groovy script that must return an array with the values to be displayed on the UI. You also have some helper variables that the plug-in tries to make available for you. One of these variables is the jenkinsProject.

If in your project you assigned a label, then programmatically you can return values based on the node label assigned to your project (or to the node object...).

Here's a very simple example.

assignedNode = jenkinsProject.getAssignedLabelString()
list = []
if (assignedNode == null) {
    // do something
} else if (assignedNode.equals('abc')) {
    // ...
}
return list

Here assignedNode will have the string name of the node, or null if none. If you use instead jenkinsProject.getAssignedLabel(), then you will have not a String, but a Label.

If you need further customization, the best way is to dive into the Java API, then build your Groovy script from the bottom up. Or try finding examples online (there are many for Jenkins and Groovy) and adapt them to your parameter.

Hope that helps,
Bruno


问:
Parallel call in iOS using Azure mobile service sdk
How can I make parallel calls to Azure server, In client side, I am using Azure Mobile service SDK.

I am doing calls to server like below

```<code>   [self.table pullWithQuery:query queryId:@"somename"] settings:pullsetting completion:^(NSError *error) {

    // Let the caller know that we finished
    dispatch_async(dispatch_get_main_queue(), ^{
        completion(error);
    });
}]
</code>```

For each table/entity, I am making calls like above.
But all the calls are executing serially by Azure.

Is there any way to make it parallel?

答:
No, We can not make parallel  requests using azure SDK. When you call pullWithQuery method, that operation is added to serial queue internally by azure framework. Here is link to verify implementation files of azure framework :
https://github.com/Azure/azure-mobile-services

Body:
How can I make parallel calls to Azure server, In client side, I am using Azure Mobile service SDK.

I am doing calls to server like below

   [self.table pullWithQuery:query queryId:@"somename"] settings:pullsetting completion:^(NSError *error) {

    // Let the caller know that we finished
    dispatch_async(dispatch_get_main_queue(), ^{
        completion(error);
    });
}]

For each table/entity, I am making calls like above.
But all the calls are executing serially by Azure.

Is there any way to make it parallel?


问:
How to place a div beside input box on focus?
I have a scenario,that I used css for extending search box on focus,when I focussed on search box then the search box must decrease and the cancel button must be placed beside of search box.

Css:

```<code>.clrble .frmcntr {
background:url("images/search.png") no-repeat 110px center;
text-align: center;
border-radius: 4px;
border: medium none;
cursor: pointer;
font-size: 20px;
font-family:SFUIDisplay;
padding: 6px 10px 6px 10px;
transition: all 0.5s ease 0s;
width: 95%;
background-color:rgba(247, 247, 247, 1);
 }

: content-box;
font-size: 100%;

.clrble .frmcntr:focus {
    width: 70%;
    text-align: left;
    background-color: #fff;
    border-color: #66CC75;
    -webkit-box-shadow: 0 0 5px rgba(109,207,246,.5);
    -moz-box-shadow: 0 0 5px rgba(109,207,246,.5);
    box-shadow: 0 0 5px rgba(109,207,246,.5);
    background-color:rgba(247, 247, 247, 1);
    background:url("images/search.png") no-repeat  10px center;
    padding-left:40px;
}

.clrble .frmcntr {
    -webkit-appearance: textfield;
    -webkit-box-sizing

}
</code>```

Here is my plunker link:

https://plnkr.co/edit/Z7mfglWEoDyjbDfFDbLM?p=preview

And the expected output will be like this:

Is it possible with Angularjs or JavaScript?

答:
You can just hide and show a span with 'cancel' in it.

/* Styles go here */

.clrble .frmcntr {
  background: url("images/search.png") no-repeat 110px center;
  text-align: center;
  border-radius: 4px;
  border: medium none;
  cursor: pointer;
  font-size: 20px;
  font-family: SFUIDisplay;
  padding: 6px 10px 6px 10px;
  transition: all 0.5s ease 0s;
  width: 95%;
  background-color: rgba(247, 247, 247, 1);
}

.clrble .frmcntr:focus {
  width: 70%;
  text-align: left;
  background-color: #fff;
  border-color: #66CC75;
  -webkit-box-shadow: 0 0 5px rgba(109, 207, 246, .5);
  -moz-box-shadow: 0 0 5px rgba(109, 207, 246, .5);
  box-shadow: 0 0 5px rgba(109, 207, 246, .5);
  background-color: rgba(247, 247, 247, 1);
  background: url("images/search.png") no-repeat 10px center;
  padding-left: 40px;
}

.clrble .frmcntr {
  -webkit-appearance: textfield;
  -webkit-box-sizing: content-box;
  font-size: 100%;
}

.clrble {
  position: relative;
}

.frmcntr:focus+.btn {
  display: block;
}

.btn {
  display: none;
  position: absolute;
  right: 0;
}

.cancel {
  visibility: hidden;
  color: blue;
  font-family: sans-serif;
  font-size: 20px;
}

.frmcntr:focus + .cancel {
  visibility: visible;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>

<body>
  <div class="clrble">
    <input type="text" placeholder="Search" class="frmcntr">
    <span class="cancel">Cancel</span>
    <span class="btn">button here</span>
  </div>
</body>

</html></code>```

Body:
I have a scenario,that I used css for extending search box on focus,when I focussed on search box then the search box must decrease and the cancel button must be placed beside of search box.

Css:

.clrble .frmcntr {
background:url("images/search.png") no-repeat 110px center;
text-align: center;
border-radius: 4px;
border: medium none;
cursor: pointer;
font-size: 20px;
font-family:SFUIDisplay;
padding: 6px 10px 6px 10px;
transition: all 0.5s ease 0s;
width: 95%;
background-color:rgba(247, 247, 247, 1);
 }

: content-box;
font-size: 100%;

.clrble .frmcntr:focus {
    width: 70%;
    text-align: left;
    background-color: #fff;
    border-color: #66CC75;
    -webkit-box-shadow: 0 0 5px rgba(109,207,246,.5);
    -moz-box-shadow: 0 0 5px rgba(109,207,246,.5);
    box-shadow: 0 0 5px rgba(109,207,246,.5);
    background-color:rgba(247, 247, 247, 1);
    background:url("images/search.png") no-repeat  10px center;
    padding-left:40px;
}

.clrble .frmcntr {
    -webkit-appearance: textfield;
    -webkit-box-sizing

}

Here is my plunker link:

https://plnkr.co/edit/Z7mfglWEoDyjbDfFDbLM?p=preview

And the expected output will be like this:

Is it possible with Angularjs or JavaScript?

Body:
You can just hide and show a span with 'cancel' in it.

/* Styles go here */

.clrble .frmcntr {
  background: url("images/search.png") no-repeat 110px center;
  text-align: center;
  border-radius: 4px;
  border: medium none;
  cursor: pointer;
  font-size: 20px;
  font-family: SFUIDisplay;
  padding: 6px 10px 6px 10px;
  transition: all 0.5s ease 0s;
  width: 95%;
  background-color: rgba(247, 247, 247, 1);
}

.clrble .frmcntr:focus {
  width: 70%;
  text-align: left;
  background-color: #fff;
  border-color: #66CC75;
  -webkit-box-shadow: 0 0 5px rgba(109, 207, 246, .5);
  -moz-box-shadow: 0 0 5px rgba(109, 207, 246, .5);
  box-shadow: 0 0 5px rgba(109, 207, 246, .5);
  background-color: rgba(247, 247, 247, 1);
  background: url("images/search.png") no-repeat 10px center;
  padding-left: 40px;
}

.clrble .frmcntr {
  -webkit-appearance: textfield;
  -webkit-box-sizing: content-box;
  font-size: 100%;
}

.clrble {
  position: relative;
}

.frmcntr:focus+.btn {
  display: block;
}

.btn {
  display: none;
  position: absolute;
  right: 0;
}

.cancel {
  visibility: hidden;
  color: blue;
  font-family: sans-serif;
  font-size: 20px;
}

.frmcntr:focus + .cancel {
  visibility: visible;
}

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>

<body>
  <div class="clrble">
    <input type="text" placeholder="Search" class="frmcntr">
    <span class="cancel">Cancel</span>
    <span class="btn">button here</span>
  </div>
</body>

</html>


问:
Cakephp 3 : How to get max amout row from a table
I have table call users , like

```<code>id name amount   created
1   a   100     6-16-2016
2   b   200     5-16-2016
</code>```

I need max amount full row, I have tried below code but getting syntax error.

```<code>  $user = $this->Users->find('all',[
         'fields' => array('MAX(Users.amount)  AS amount'),
  ]);
</code>```

答:
Simplest method using CakePHP 3:

```<code>$this->Model->find('all')->select('amount')->hydrate(false)->max('amount')
</code>```

Will result in an array containing the maximum amount in that table column.

Body:
I have table call users , like

id name amount   created
1   a   100     6-16-2016
2   b   200     5-16-2016

I need max amount full row, I have tried below code but getting syntax error.

  $user = $this->Users->find('all',[
         'fields' => array('MAX(Users.amount)  AS amount'),
  ]);

Body:
Simplest method using CakePHP 3:

$this->Model->find('all')->select('amount')->hydrate(false)->max('amount')

Will result in an array containing the maximum amount in that table column.