问:
iOS Drawing text in the centre of shapes
I'm trying to draw text in the centre of shapes in iOS, an example would be Microsoft Office's insert shape see: https://www.dropbox.com/s/cgqyyuvy6hcv5g8/Screenshot%202014-01-21%2013.48.17.png

I have an array of coordinates that are used to form the shape, which works fine for creating the actual shape.

My first tactic was following this stackoverflow question: Core Text With Asymmetric Shape on iOS however I can only get it to draw the text at the bottom of the shape. Is there any way to centre the text vertically and horizontally?

I then had a look at the new TextKit but I got stuck with how to subclass NSTextContainer to accept either a CGPath or an array of coordinates to create the text container to draw inside.

My backup solution is to use Core Text to draw the text at the centre coordinate of a shape, however this will cause the text to draw outside of the shape on some shapes such as a right angled triangle.

Alternatively, are there any other methods I could use to get some text somewhat in the centre of a shape?

答:
Swift 3 Version of Luca Davanzo's answer

```<code>struct UIUtility {

static func imageWithColor(color: UIColor, circular: Bool) -> UIImage? {
    let size: CGFloat = circular ? 100 : 1;
    let rect = CGRect(x: 0.0, y: 0.0, width: size, height: size)
    UIGraphicsBeginImageContext(rect.size)
    if let context = UIGraphicsGetCurrentContext() {
        context.setFillColor(color.cgColor)
        if(circular) {
            context.fillEllipse(in: rect)
        }
        else {
            context.fill(rect)
        }
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    return nil
}

static func drawText(text: NSString, font: UIFont, image: UIImage, point: CGPoint, textColor: UIColor = UIColor.white) -> UIImage? {
    UIGraphicsBeginImageContext(image.size)
    image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
    let rect = CGRect(x: point.x, y: point.y, width: image.size.width, height: image.size.height)
    text.draw(in: rect.integral, withAttributes: [ NSFontAttributeName: font, NSForegroundColorAttributeName: textColor ])
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}

static func circleImageWithText(text: String, font: UIFont, circleColor: UIColor, textColor: UIColor = UIColor.white) -> UIImage? {
    if let image = UIUtility.imageWithColor(color: circleColor, circular: true) {
        let textSize = NSString(string: text).size(attributes: [ NSFontAttributeName: font])
        let centerX = ((image.size.width) / 2.0) - (textSize.width / 2.0)
        let centerY = ((image.size.height) / 2.0) - (textSize.height / 2.0)
        let middlePoint = CGPoint(x: centerX, y: centerY)
        return UIUtility.drawText(text: text as NSString, font: font, image: image, point: middlePoint, textColor: textColor)
    }
    return nil
}
}
</code>```

Body:
Swift 3 Version of Luca Davanzo's answer

struct UIUtility {

static func imageWithColor(color: UIColor, circular: Bool) -> UIImage? {
    let size: CGFloat = circular ? 100 : 1;
    let rect = CGRect(x: 0.0, y: 0.0, width: size, height: size)
    UIGraphicsBeginImageContext(rect.size)
    if let context = UIGraphicsGetCurrentContext() {
        context.setFillColor(color.cgColor)
        if(circular) {
            context.fillEllipse(in: rect)
        }
        else {
            context.fill(rect)
        }
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    return nil
}

static func drawText(text: NSString, font: UIFont, image: UIImage, point: CGPoint, textColor: UIColor = UIColor.white) -> UIImage? {
    UIGraphicsBeginImageContext(image.size)
    image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
    let rect = CGRect(x: point.x, y: point.y, width: image.size.width, height: image.size.height)
    text.draw(in: rect.integral, withAttributes: [ NSFontAttributeName: font, NSForegroundColorAttributeName: textColor ])
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}

static func circleImageWithText(text: String, font: UIFont, circleColor: UIColor, textColor: UIColor = UIColor.white) -> UIImage? {
    if let image = UIUtility.imageWithColor(color: circleColor, circular: true) {
        let textSize = NSString(string: text).size(attributes: [ NSFontAttributeName: font])
        let centerX = ((image.size.width) / 2.0) - (textSize.width / 2.0)
        let centerY = ((image.size.height) / 2.0) - (textSize.height / 2.0)
        let middlePoint = CGPoint(x: centerX, y: centerY)
        return UIUtility.drawText(text: text as NSString, font: font, image: image, point: middlePoint, textColor: textColor)
    }
    return nil
}
}


来源: stackexchange

问:
How to use sorting in RxJava and couchbase?
I've written below mentioned method to bulk fetch data from couchbase server.

```<code>bucket.async()
            .query(N1qlQuery.simple(query))
            .doOnNext(res -> res.info().map(N1qlMetrics::elapsedTime).forEach(t -> System.out.println(t)))
            .flatMap(AsyncN1qlQueryResult::rows)
            .flatMap(row ->
            bucket.async().
            get(row.value().getString("id")))
            .map(JsonDocument::content).
            toList()
            .toBlocking()
            .single();
</code>```

This code is working fine when I pass a query

```<code>"SELECT meta().id as id FROM bucket"
</code>```

but when I use something like

```<code>"SELECT meta().id as id FROM bucket order by id ASC"
</code>```

results I am getting are not sorted. However when I run the same query on query console results are as expected. That makes me believe that I am doing something wrong in rxJava. Please help me solve this.

答:
The order is lost because of the flatMap() operator, which apply concurrent streams, but do not maintain order.

When you apply flatMap() you are creating and subscribing to a new Observable for each onNext(), meaning for each row, you're executing in parallel this line:

```<code> bucket.async().
        get(row.value().getString("id")))
</code>```

then each of the get operation will finish in a different time, and the fetched content will be emitted non-ordered.

If you want to maintain the order but don't care to lose the parallelism, you should use concatMap() that will maintain only 1 active stream, and will subscribe to each fetch operation in order.

If you do need/want parallelism, you should use concatMapEager(), that will execute each created Observable in parallel, but will emit the items in order.

ContentLicense: CC BY-SA 3.0

Body:
I've written below mentioned method to bulk fetch data from couchbase server.

bucket.async()
            .query(N1qlQuery.simple(query))
            .doOnNext(res -> res.info().map(N1qlMetrics::elapsedTime).forEach(t -> System.out.println(t)))
            .flatMap(AsyncN1qlQueryResult::rows)
            .flatMap(row ->
            bucket.async().
            get(row.value().getString("id")))
            .map(JsonDocument::content).
            toList()
            .toBlocking()
            .single();

This code is working fine when I pass a query

"SELECT meta().id as id FROM bucket"

but when I use something like

"SELECT meta().id as id FROM bucket order by id ASC"

results I am getting are not sorted. However when I run the same query on query console results are as expected. That makes me believe that I am doing something wrong in rxJava. Please help me solve this.

Body:
The order is lost because of the flatMap() operator, which apply concurrent streams, but do not maintain order.

When you apply flatMap() you are creating and subscribing to a new Observable for each onNext(), meaning for each row, you're executing in parallel this line:

 bucket.async().
        get(row.value().getString("id")))

then each of the get operation will finish in a different time, and the fetched content will be emitted non-ordered.

If you want to maintain the order but don't care to lose the parallelism, you should use concatMap() that will maintain only 1 active stream, and will subscribe to each fetch operation in order.

If you do need/want parallelism, you should use concatMapEager(), that will execute each created Observable in parallel, but will emit the items in order.


问:
Adding add scroll down and issue in extra spacing and padding
```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="com.shubham.splashscreenemulation.MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<GridView android:id="@+id/gridView" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="0dp"
android:verticalSpacing="2dp"
android:horizontalSpacing="2dp"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:clipChildren="true"
android:alwaysDrawnWithCache="true"
android:numColumns="auto_fit"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:gravity="center_horizontal"

    />
</code>```

Problem 1

How do I add scroll down feature to my app so that entire text is visible?

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.shubham.splashscreenemulation.MyDialog">

<ImageView

    android:src="@drawable/ahmedabad"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView2"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Details: "
    android:id="@+id/textView"
    android:layout_below="@+id/imageView2"
    android:layout_centerHorizontal="true" />
</android.support.v4.widget.NestedScrollView>

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Gallery"
    android:id="@+id/button"
    android:onClick="closeDialog"
    android:layout_below="@+id/textView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Famous Places"
    android:id="@+id/button2"
    android:onClick="closeDialog2"
    android:layout_below="@+id/textView"
    android:layout_toRightOf="@+id/imageView2"
    android:layout_toEndOf="@+id/imageView2" />
</code>```

Problem 2

I don't know exactly what happened and why these extra spacing and padding, however when I run GridView as separate activity works fine. I have tried most of the solutions with similar problems in other stackoverflow questions but none worked!

Please help!
Please tell me what files I need to upload. And please don't be rude as I have just started learning android.

答:
How do I add scroll down feature to my app so that entire text is visible?

To make the TextView scrollable, put it inside of a ScrollView

```<code> <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <TextView
                android:text="@string/hello_world"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

    </android.support.v4.widget.NestedScrollView>
</code>```

Problem 2

In your child layout, you used the layout_height as match_parent. Replace it with wrap_content

Body:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="com.shubham.splashscreenemulation.MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<GridView android:id="@+id/gridView" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="0dp"
android:verticalSpacing="2dp"
android:horizontalSpacing="2dp"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:clipChildren="true"
android:alwaysDrawnWithCache="true"
android:numColumns="auto_fit"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:gravity="center_horizontal"

    />

Problem 1

How do I add scroll down feature to my app so that entire text is visible?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.shubham.splashscreenemulation.MyDialog">

<ImageView

    android:src="@drawable/ahmedabad"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView2"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Details: "
    android:id="@+id/textView"
    android:layout_below="@+id/imageView2"
    android:layout_centerHorizontal="true" />
</android.support.v4.widget.NestedScrollView>

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Gallery"
    android:id="@+id/button"
    android:onClick="closeDialog"
    android:layout_below="@+id/textView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Famous Places"
    android:id="@+id/button2"
    android:onClick="closeDialog2"
    android:layout_below="@+id/textView"
    android:layout_toRightOf="@+id/imageView2"
    android:layout_toEndOf="@+id/imageView2" />

Problem 2

I don't know exactly what happened and why these extra spacing and padding, however when I run GridView as separate activity works fine. I have tried most of the solutions with similar problems in other stackoverflow questions but none worked!

Please help!
Please tell me what files I need to upload. And please don't be rude as I have just started learning android.

Body:
How do I add scroll down feature to my app so that entire text is visible?

To make the TextView scrollable, put it inside of a ScrollView

 <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <TextView
                android:text="@string/hello_world"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

    </android.support.v4.widget.NestedScrollView>

Problem 2

In your child layout, you used the layout_height as match_parent. Replace it with wrap_content


问:
SQL Server: many-to-many relation
So I am having a brain meltdown when trying to figure this one out. What I have is a few database's like:

tblGenre

```<code>genreID
genreName
</code>```

tblArtist

```<code>artistID
artistName
genreID
</code>```

tblAlbum

```<code>albumID
albumName
artistID
</code>```

Everything is all well and good, and working fine. Ok, now with the question...

What I am trying to figure out is how to link an artist who has multiple names. I.e. the artist 'Prince'. I have albums from him, who I would catalog under 3 different bands; Prince (artistID=5), Prince and the new power generation (artistID=17, and "Symbol" (artistID=43)...

So, When I lookup the artist "Prince", who has a artistID of 5, how can I link the other 2 bands up to this one? Would I create a seperate database the has a comma-separated values of each artistID (i.e. 5,17,43) or is there an easier way to do this?

I don't want to go as far as the album level, of who played on every album in my database. I just want to create a link of artists who have been with multiple bands. Just a few more examples of how I would want "hooked together"...

Tom Petty (Classic Rock)

Tom Petty & the Heartbreakers (Classic Rock)

Tom Petty & the Heartbreakers (Soundtrack)

Prince (Funk)

Prince & the New Power Generation (Funk)

Mark Knopfler (Classic Rock)

Mark Knopfler (Soundtrack)

Dire Straits (Classic Rock)

Thanks for the input.

答: Drew, it sounds like the tblArtist is more band than the main performer for an album.  I see you have vb listed in the question so I also assume you have a vb front end on this app.  With all these assumptions I suggest you add a varchar column to tblArtist called altArtistId. Add this column to your retun record set in your front end.  Parse the comma seperated list and return to tblArtist to get any related information.  </p>

ContentLicense: CC BY-SA 2.5

Title: SQL Server: many-to-many relation

Body:
So I am having a brain meltdown when trying to figure this one out. What I have is a few database's like:

tblGenre

genreID
genreName

tblArtist

artistID
artistName
genreID

tblAlbum

albumID
albumName
artistID

Everything is all well and good, and working fine. Ok, now with the question...

What I am trying to figure out is how to link an artist who has multiple names. I.e. the artist 'Prince'. I have albums from him, who I would catalog under 3 different bands; Prince (artistID=5), Prince and the new power generation (artistID=17, and "Symbol" (artistID=43)...

So, When I lookup the artist "Prince", who has a artistID of 5, how can I link the other 2 bands up to this one? Would I create a seperate database the has a comma-separated values of each artistID (i.e. 5,17,43) or is there an easier way to do this?

I don't want to go as far as the album level, of who played on every album in my database. I just want to create a link of artists who have been with multiple bands. Just a few more examples of how I would want "hooked together"...

Tom Petty (Classic Rock)

Tom Petty & the Heartbreakers (Classic Rock)

Tom Petty & the Heartbreakers (Soundtrack)

Prince (Funk)

Prince & the New Power Generation (Funk)

Mark Knopfler (Classic Rock)

Mark Knopfler (Soundtrack)

Dire Straits (Classic Rock)

Thanks for the input.


问:
Pivot Report Filter - if only one value avaliable select else ALL
Requesting help I am currently working on a macro based pivot table where we have 5 columns in Report filter.
What I am looking for is vba code for these five filer, it should show the value if the filter contains a single value else should remain as (All).

Currently I am using the following code for pivot filer:

```<code>    Sub InsertPivotTable()

'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long

'Delete Preivous Pivot Table Worksheet & Insert a New Blank Worksheet With Same Name
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Pivot").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Pivot"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Pivot")
Set DSheet = Worksheets("Report")

'Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)

'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), _
TableName:="ADT_PivotTable")

'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="ADT_PivotTable")

'Insert Reportfilter Fields
   With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("Resp Bus Partn ID")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("ADT-File ID")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("UWY")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("SCoB - Acc")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("Curr")
        .Orientation = xlPageField
        .Position = 1
    End With
End Sub
</code>```

答:
The answer and code are a little long, but I've added a few "Bonuses" for you, so you'll find it very useful :)

First, there is no need to delete "Pivot" sheet and re-create it just to update the PivotTable named "ADT_PivotTable", you can just update the PivotCache with the updated SourceData, and afterwards refresh the PivotTable with the updated PivotCache.

Second, I’ve added a second Sub, that check for every PivotField passed to it how many PivotItems it has, if there’s only one PivotItem then display it in the Filter, Otherwise show "All".

Sub InsertPivotTable Code

```<code>Option Explicit

Sub InsertPivotTable()

'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long

'Delete Preivous Pivot Table Worksheet & Insert a New Blank Worksheet With Same Name
On Error Resume Next
Application.DisplayAlerts = False

Set PSheet = Worksheets("Pivot")
On Error GoTo 0
If PSheet Is Nothing Then ' if "Pivot" sheet doesn't exist
    Set PSheet = Sheets.Add(Before:=ActiveSheet)
    PSheet.Name = "Pivot"
End If
Application.DisplayAlerts = True

Set DSheet = Worksheets("Report")
'Define Data Range
With DSheet
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    Set PRange = .Range("A1").Resize(LastRow, LastCol) ' set data range for Pivot Table
End With

' Set the Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)

On Error Resume Next
Set PTable = PSheet.PivotTables("ADT_PivotTable") ' Set the Pivot Table if already exists from previous code runs

On Error GoTo 0
If PTable Is Nothing Then ' <-- Pivot Table still doesn't exist >> create it for the first time
    ' create a new Pivot Table in "Pivot" sheet
    Set PTable = PSheet.PivotTables.Add(PivotCache:=PCache, TableDestination:=PSheet.Range("A1"), TableName:="ADT_PivotTable")

    With PTable
        'Insert Reportfilter Fields
        With .PivotFields("Resp Bus Partn ID")
            .Orientation = xlPageField
            .Position = 1
        End With
        With .PivotFields("ADT-File ID")
            .Orientation = xlPageField
            .Position = 1
        End With
        With .PivotFields("UWY")
            .Orientation = xlPageField
            .Position = 1
        End With
        With .PivotFields("SCoB - Acc")
            .Orientation = xlPageField
            .Position = 1
        End With
        With .PivotFields("Curr")
            .Orientation = xlPageField
            .Position = 1
        End With
    End With
Else
    ' just refresh the Pivot cache with the updated Range
    PTable.ChangePivotCache PCache
    PTable.RefreshTable
End If

' modify the Filter default view for each of the Pivot Fields below
With PTable
    SelectFilterSingleValue .PivotFields("Resp Bus Partn ID")
    SelectFilterSingleValue .PivotFields("ADT-File ID")
    SelectFilterSingleValue .PivotFields("UWY")
    SelectFilterSingleValue .PivotFields("SCoB - Acc")
    SelectFilterSingleValue .PivotFields("Curr")
End With

End Sub
</code>```

Sub SelectFilterSingleValue Code

```<code>Sub SelectFilterSingleValue(ptFld As PivotField)

Dim PTItm       As PivotItem
Dim Count       As Long

With ptFld
    .EnableMultiplePageItems = True

    For Each PTItm In .PivotItems
        If PTItm.Name <> "(blank)" Then
            PTItm.Visible = True
            Count = Count + 1
        Else
            PTItm.Visible = False
        End If
    Next PTItm

    If Count > 1 Then
        .ClearAllFilters
    End If
End With

End Sub
</code>```

Body:
Requesting help I am currently working on a macro based pivot table where we have 5 columns in Report filter.
What I am looking for is vba code for these five filer, it should show the value if the filter contains a single value else should remain as (All).

Currently I am using the following code for pivot filer:

    Sub InsertPivotTable()

'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long

'Delete Preivous Pivot Table Worksheet & Insert a New Blank Worksheet With Same Name
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Pivot").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Pivot"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Pivot")
Set DSheet = Worksheets("Report")

'Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)

'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), _
TableName:="ADT_PivotTable")

'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="ADT_PivotTable")

'Insert Reportfilter Fields
   With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("Resp Bus Partn ID")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("ADT-File ID")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("UWY")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("SCoB - Acc")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("ADT_PivotTable").PivotFields("Curr")
        .Orientation = xlPageField
        .Position = 1
    End With
End Sub

Body:
The answer and code are a little long, but I've added a few "Bonuses" for you, so you'll find it very useful :)

First, there is no need to delete "Pivot" sheet and re-create it just to update the PivotTable named "ADT_PivotTable", you can just update the PivotCache with the updated SourceData, and afterwards refresh the PivotTable with the updated PivotCache.

Second, I’ve added a second Sub, that check for every PivotField passed to it how many PivotItems it has, if there’s only one PivotItem then display it in the Filter, Otherwise show "All".

Sub InsertPivotTable Code

Option Explicit

Sub InsertPivotTable()

'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long

'Delete Preivous Pivot Table Worksheet & Insert a New Blank Worksheet With Same Name
On Error Resume Next
Application.DisplayAlerts = False

Set PSheet = Worksheets("Pivot")
On Error GoTo 0
If PSheet Is Nothing Then ' if "Pivot" sheet doesn't exist
    Set PSheet = Sheets.Add(Before:=ActiveSheet)
    PSheet.Name = "Pivot"
End If
Application.DisplayAlerts = True

Set DSheet = Worksheets("Report")
'Define Data Range
With DSheet
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    Set PRange = .Range("A1").Resize(LastRow, LastCol) ' set data range for Pivot Table
End With

' Set the Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange)

On Error Resume Next
Set PTable = PSheet.PivotTables("ADT_PivotTable") ' Set the Pivot Table if already exists from previous code runs

On Error GoTo 0
If PTable Is Nothing Then ' <-- Pivot Table still doesn't exist >> create it for the first time
    ' create a new Pivot Table in "Pivot" sheet
    Set PTable = PSheet.PivotTables.Add(PivotCache:=PCache, TableDestination:=PSheet.Range("A1"), TableName:="ADT_PivotTable")

    With PTable
        'Insert Reportfilter Fields
        With .PivotFields("Resp Bus Partn ID")
            .Orientation = xlPageField
            .Position = 1
        End With
        With .PivotFields("ADT-File ID")
            .Orientation = xlPageField
            .Position = 1
        End With
        With .PivotFields("UWY")
            .Orientation = xlPageField
            .Position = 1
        End With
        With .PivotFields("SCoB - Acc")
            .Orientation = xlPageField
            .Position = 1
        End With
        With .PivotFields("Curr")
            .Orientation = xlPageField
            .Position = 1
        End With
    End With
Else
    ' just refresh the Pivot cache with the updated Range
    PTable.ChangePivotCache PCache
    PTable.RefreshTable
End If

' modify the Filter default view for each of the Pivot Fields below
With PTable
    SelectFilterSingleValue .PivotFields("Resp Bus Partn ID")
    SelectFilterSingleValue .PivotFields("ADT-File ID")
    SelectFilterSingleValue .PivotFields("UWY")
    SelectFilterSingleValue .PivotFields("SCoB - Acc")
    SelectFilterSingleValue .PivotFields("Curr")
End With

End Sub

Sub SelectFilterSingleValue Code

Sub SelectFilterSingleValue(ptFld As PivotField)

Dim PTItm       As PivotItem
Dim Count       As Long

With ptFld
    .EnableMultiplePageItems = True

    For Each PTItm In .PivotItems
        If PTItm.Name <> "(blank)" Then
            PTItm.Visible = True
            Count = Count + 1
        Else
            PTItm.Visible = False
        End If
    Next PTItm

    If Count > 1 Then
        .ClearAllFilters
    End If
End With

End Sub


问:
How to sort tableview cell by distance which calculate after the data loaded in swift
After I success grab all data from firebase, I have calculate the distance between user and post and display on tableview by using latitude and longitude grab from firebase. I trying to use the distance I have calculate to sort the tableview cell but no idea how to. I m new and I really need some advise, thanks in advance.</p>

答: When you design your UIViewController, having a UITableView, you should start from having view models, to be able to build tableView cells. So having an array of viewModels, on which depends the tableView, you just sort the array by your required criteria and trigger tableView.reloadData().


问:
How to share data between sibling vue.js components?
Can someone help me share data between vue.js components? For example, I have a Table component that contains two components: a button and an input box. When I click on the button component, I want it to return data of the row it is in, including data in the input component. Right now, I am able to click the button and have it return the row data, except what's inside of its sibling input component. Does anyone have any idea how I can do this? Here's my fiddle to demonstrate what i've achieved so far and what I'm trying to do

Below is the relevant code and here is my jsfiddle that also includes my HTML: https://jsfiddle.net/rfy7sqzf/2/

My parent Table component:

```<code>Vue.component('my_table', {
  template: '#my_table',
  props: {
    data: Array,
    columns: Array,
    actions: Array
  }
});
</code>```

My two sibling components (button1 and input)

```<code>const button1 = Vue.extend({
  template:'<button class="btn btn-primary" @click="view">View</button>',
  methods: {
    view: function () {
      console.log('--row data--', this.row_data)
    }
  },
  props: ['row_data']
})

const input = Vue.extend({
  template:'<input type="text" />'
})
</code>```

My main Vue app:

```<code>var vm = new Vue({
  el: '#el',
  data: {
      actions: [
        {
          name: 'view',
          label: 'View Company',
          tmpl: button1
        },
        {
          name: 'qty',
          label: 'Quantity',
          tmpl: input
        },
      ],
      companies: [
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
      ],
      columns: [
        {
          field: 'company_name',
          label: 'Company',
        },
        {
          field: 'company_email',
          label: ' Email'
        },
        {
          field: 'company_phone_number',
          label: 'Phone #'
        },
      ],
  },
});
</code>```

Note - I understand that I could totally do this by putting data in the parent's data object & passing the data as props, but this would only work if I had a minimal # of child/sibling components..

Thanks in advance!

答:
This is how I make tables (with actions) — http://jsfiddle.net/jonataswalker/qgjgkud8/

Basically you will make use of Scoped Slots.

Some code:

```<code>  <vue-table :fields="fields" :rows="rows">
    <template slot="actions" scope="props">
      <my-button title="View" @click.native="view(props.row)"></my-button>
      <my-button title="Edit" @click.native="edit(props.row)"></my-button>
      <my-button title="Delete" @click.native="remove(props.row)"></my-button>
    </template>
  </vue-table>
</code>```

Body:
Can someone help me share data between vue.js components? For example, I have a Table component that contains two components: a button and an input box. When I click on the button component, I want it to return data of the row it is in, including data in the input component. Right now, I am able to click the button and have it return the row data, except what's inside of its sibling input component. Does anyone have any idea how I can do this? Here's my fiddle to demonstrate what i've achieved so far and what I'm trying to do

Below is the relevant code and here is my jsfiddle that also includes my HTML: https://jsfiddle.net/rfy7sqzf/2/

My parent Table component:

Vue.component('my_table', {
  template: '#my_table',
  props: {
    data: Array,
    columns: Array,
    actions: Array
  }
});

My two sibling components (button1 and input)

const button1 = Vue.extend({
  template:'<button class="btn btn-primary" @click="view">View</button>',
  methods: {
    view: function () {
      console.log('--row data--', this.row_data)
    }
  },
  props: ['row_data']
})

const input = Vue.extend({
  template:'<input type="text" />'
})

My main Vue app:

var vm = new Vue({
  el: '#el',
  data: {
      actions: [
        {
          name: 'view',
          label: 'View Company',
          tmpl: button1
        },
        {
          name: 'qty',
          label: 'Quantity',
          tmpl: input
        },
      ],
      companies: [
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
        {
          company_name: 'abc',
          company_email: 'some_email',
          company_phone_number: '###',
        },
      ],
      columns: [
        {
          field: 'company_name',
          label: 'Company',
        },
        {
          field: 'company_email',
          label: ' Email'
        },
        {
          field: 'company_phone_number',
          label: 'Phone #'
        },
      ],
  },
});

Note - I understand that I could totally do this by putting data in the parent's data object & passing the data as props, but this would only work if I had a minimal # of child/sibling components..

Thanks in advance!

Body:
This is how I make tables (with actions) — http://jsfiddle.net/jonataswalker/qgjgkud8/

Basically you will make use of Scoped Slots.

Some code:

  <vue-table :fields="fields" :rows="rows">
    <template slot="actions" scope="props">
      <my-button title="View" @click.native="view(props.row)"></my-button>
      <my-button title="Edit" @click.native="edit(props.row)"></my-button>
      <my-button title="Delete" @click.native="remove(props.row)"></my-button>
    </template>
  </vue-table>

ContentLicense: CC BY-SA 4.0


问:
How to add slide show animation to my sider code
I am currently working on a project for my school, I have a image slideshow.

When I click on an arrow the next image appears.

But I want it to slide and show the next picture.

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("MySlides");
  if (n > x.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = x.length
  }
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex - 1].style.display = "block";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="MySlides" src="http://lorempixel.com/400/400/sports/" width="380px;" height="380px;">
<img class="MySlides" src="http://lorempixel.com/400/400/food/" width="380px;" height="380px;" style="display:none;">
<img class="MySlides" src="http://lorempixel.com/400/400/cats/" width="380px;" height="380px;" style="display:none;">
<span>‹</span>
<span>›</span></code>```

答:
Here is my solution, with real slide effect: https://codepen.io/anon/pen/XMxGMw

var slideIndex = 0;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var slides = document.getElementsByClassName('slide');
  console.log(slides.length);
  if (n < 0) {
    slideIndex = slides.length - 1;
    n = slides.length - 1;
  } else if (n > slides.length - 1) {
    slideIndex = 0;
    n = 0;
  }
  for (i = 0; i < slides.length; i++) {
    var slide = slides[i];
    if (i < n) {
      slide.className = 'slide slide-previous';
    } else if (i === n) {
      slide.className = 'slide slide-selected';
    } else {
      slide.className = 'slide slide-next';
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#slides-container {
  position: relative;
  width: 380px;
  height: 380px;
  overflow: hidden;
}

.slide {
  position: absolute;
  top: 0;
  left: 0;
  height: 380px;
  width: 380px;
}

.slide-selected,
.slide-previous,
.slide-next {
  transition: transform 1s;
}

.slide-selected {
  z-index: 2;
  transform: translateX(0);
}

.slide-previous {
  z-index: 1;
  transform: translateX(-100%);
}

.slide-next {
  z-index: 1;
  transform: translateX(100%);
}</code>```

‹
›```

Here is a more advanced version with automation and different animation: https://codepen.io/anon/pen/ryqRKX

Body:
I am currently working on a project for my school, I have a image slideshow.

When I click on an arrow the next image appears.

But I want it to slide and show the next picture.

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("MySlides");
  if (n > x.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = x.length
  }
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex - 1].style.display = "block";
}

‹
›

Body:
Here is my solution, with real slide effect: https://codepen.io/anon/pen/XMxGMw

var slideIndex = 0;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var slides = document.getElementsByClassName('slide');
  console.log(slides.length);
  if (n < 0) {
    slideIndex = slides.length - 1;
    n = slides.length - 1;
  } else if (n > slides.length - 1) {
    slideIndex = 0;
    n = 0;
  }
  for (i = 0; i < slides.length; i++) {
    var slide = slides[i];
    if (i < n) {
      slide.className = 'slide slide-previous';
    } else if (i === n) {
      slide.className = 'slide slide-selected';
    } else {
      slide.className = 'slide slide-next';
    }
  }
}

#slides-container {
  position: relative;
  width: 380px;
  height: 380px;
  overflow: hidden;
}

.slide {
  position: absolute;
  top: 0;
  left: 0;
  height: 380px;
  width: 380px;
}

.slide-selected,
.slide-previous,
.slide-next {
  transition: transform 1s;
}

.slide-selected {
  z-index: 2;
  transform: translateX(0);
}

.slide-previous {
  z-index: 1;
  transform: translateX(-100%);
}

.slide-next {
  z-index: 1;
  transform: translateX(100%);
}

<div id="slides-container">
  <img class="slide" src="http://lorempixel.com/400/400/sports/">
  <img class="slide" src="http://lorempixel.com/400/400/food/">
  <img class="slide" src="http://lorempixel.com/400/400/cats/">
  <img class="slide" src="http://lorempixel.com/400/400/food/">
  <img class="slide" src="http://lorempixel.com/400/400/food/">
</div>
<span><a OnClick="plusDivs(-1)" class="links">&#8249;</a></span>
<span><a OnClick="plusDivs(1)"class="rechts">&#8250;</a></span>

Here is a more advanced version with automation and different animation: https://codepen.io/anon/pen/ryqRKX


问:
Pointer container class which can't be copied by value
I need a smart pointer for my project which can be send to several methods as parameter. I have checked auto_ptr and shared_ptr from boost. But IMO, that is not suitable for my requirements. Following are my findings

auto_ptr : When passed to another method, ownership will be transferred and underlying pointer will get deleted when that method's scope ends. We can workaround this by passing auto_ptr by reference, but there is no compile time mechanism to ensure it is always passed by reference. If by mistake, user forgot to pass a reference, it will make problems.

boost::shared_ptr : This looks promising and works correctly for my need. But I feel this is overkill for my project as it is a very small one.

So I decided to write a trivial templated pointer container class which can't be copied by value and take care about deleting the underlying pointer. Here it is

```<code>template <typename T>
class simple_ptr{
public:
    simple_ptr(T* t){
       pointer = t;
    }
    ~simple_ptr(){
       delete pointer;
    }
    T* operator->(){
       return pointer;
    }
private:
    T* pointer;
    simple_ptr(const simple_ptr<T>& t);
};
</code>```

Is this implementation correct? I have made copy constructor as private, so that compiler will alert when someone tries to pass it by value.

If by chance the pointer is deleted, delete operation on the destructor will throw assertion error. How can I workaround this?

I am pretty new to C++ and your suggestion are much appreciated.

Thanks

答:
You've got two choices:

boost::scoped_ptr already detailed by j_random_hacker, because it's non-copyable (doesn't share ownership like shared_ptr) and non-movable (doesn't transfer ownership like auto_ptr. auto_ptr has a copy constructor, but that one does not copy. It moves the original pointer to *this). boost::scoped_ptr is exactly what you need.

const auto_ptr doesn't allow transfer of ownership. And take your parameter by reference to const (auto_ptr<T> const&). If the writer of a function accepts by value instead, it still won't work if you try passing a const auto_ptr, because its copy constructor needs a non-const auto_ptr.

Until C++1x, boost::scoped_ptr is the best choice for your needs, or a const auto_ptr if you have to use official standard stuff (read this). In C++1x, you can use std::unique_ptr as a better alternative to auto_ptr, because you have to explicitly state when you want to transfer ownership. Trying to copy it will result in a compile time error. unique_ptr is detailed a little in this answer.

OwnerDisplayName: Appu

Body:
I need a smart pointer for my project which can be send to several methods as parameter. I have checked auto_ptr and shared_ptr from boost. But IMO, that is not suitable for my requirements. Following are my findings

auto_ptr : When passed to another method, ownership will be transferred and underlying pointer will get deleted when that method's scope ends. We can workaround this by passing auto_ptr by reference, but there is no compile time mechanism to ensure it is always passed by reference. If by mistake, user forgot to pass a reference, it will make problems.

boost::shared_ptr : This looks promising and works correctly for my need. But I feel this is overkill for my project as it is a very small one.

So I decided to write a trivial templated pointer container class which can't be copied by value and take care about deleting the underlying pointer. Here it is

template <typename T>
class simple_ptr{
public:
    simple_ptr(T* t){
       pointer = t;
    }
    ~simple_ptr(){
       delete pointer;
    }
    T* operator->(){
       return pointer;
    }
private:
    T* pointer;
    simple_ptr(const simple_ptr<T>& t);
};

Is this implementation correct? I have made copy constructor as private, so that compiler will alert when someone tries to pass it by value.

If by chance the pointer is deleted, delete operation on the destructor will throw assertion error. How can I workaround this?

I am pretty new to C++ and your suggestion are much appreciated.

Thanks

OwnerDisplayName: litb

LastEditorDisplayName: litb


问:
How to get Google map (map_icon, title, latitude, longitude) dynamically from webservice
This is my web service

where I want to get map_icon, longitude, latitude dynamically from given web service. I am stuck at this point. How can I do this please help me out.
In old code what is done is get longitude, latitude, post_title from web service on the basis of id and then assign image statically.

Frnt_mapActivity.java

```<code>public class Frnt_mapActivity extends Activity {

public String Shop_title;
public String Shop_address;
public String Shop_icons;
ProgressDialog mDialog;
JSONObject jsonobject3;
JSONArray jsonarray3;
// Google Map
private static GoogleMap googlemap;
public static ArrayList<SearchBeams> searchdata_list;
public static ArrayList<NormalSearchBeams> normlSearchList;
ArrayList<All_products_lat_long> venueList;

private int i;
private Intent intent;
HashMap<Marker, Integer> hashMap=new HashMap<Marker, Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.frnt_map_activity);

    googlemap=((MapFragment)getFragmentManager().findFragmentById(R.id.places_map)).getMap();
    googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    googlemap.setMyLocationEnabled(true);
    googlemap.getUiSettings().setZoomControlsEnabled(true);
    googlemap.getUiSettings().setMyLocationButtonEnabled(true);
    googlemap.getUiSettings().setCompassEnabled(true);
    googlemap.getUiSettings().setRotateGesturesEnabled(true);
    googlemap.getUiSettings().setZoomGesturesEnabled(true);
    googlemap.setMyLocationEnabled(true);
    intent=new Intent(Frnt_mapActivity.this,MainActivity.class);
    googlemap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

        @Override
        public void onInfoWindowClick(Marker arg0) {
            i=hashMap.get(arg0);
            intent.putExtra("PRODUCT_ID", venueList.get(i).getId());
            startActivity(intent);
            //overridePendingTransition( R.anim.slide_right, R.anim.slide_left );
        }
    });

    new Frnt_mIcons_Activity().execute();

}

class AddMarkerAsyncTask extends AsyncTask<String,String,String>{

    private All_products_lat_long venue;
    private int k;
    BitmapDescriptor bd=null;

    AddMarkerAsyncTask(All_products_lat_long venue,int k){
        this.venue=venue;
        this.k=k;
    }

    @Override
    protected String doInBackground(String... strings) {
        try{
            bd=BitmapDescriptorFactory.fromBitmap(Glide.
                    with(Frnt_mapActivity.this).
                    load(venue.getMap_icon()).
                    asBitmap().
                    into(100, 100). // Width and height
                    get());
        }catch (Exception e){
            bd=null;
            e.printStackTrace();

        }

        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        try{
            if(bd!=null){
                Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
                        .title(venue.getPost_title())
                        .icon(bd));
                hashMap.put(marker, k);
            }

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

    }
}

private void addMarkers() {

    for(int k=0; k<venueList.size(); k += 1){

        //nirmal
        try{
            Log.e("nirmal",venueList.get(k).getMap_icon());

            //new AddMarkerAsyncTask(venueList.get(k),k).execute();

            double ln = Double.parseDouble(venueList.get(k).getLongitude());
            double la = Double.parseDouble(venueList.get(k).getLatitude());
                /*String title=venueList.get(k).getPost_title()==null?"":venueList.get(k).getPost_title();
                URL url = new URL(venueList.get(k).getMap_icon());
                Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                BitmapDescriptor bd=BitmapDescriptorFactory.fromBitmap(image);*/

                /*Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(la, ln))
                        .title(title)
                        .icon(bd));
                hashMap.put(marker, k);*/

            switch (Integer.parseInt(venueList.get(k).getId()))
            {
                case 5689 :
                    Marker marker=googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.fruitandveg)));
                    hashMap.put(marker, k);
                    break;
                case 5779 :
                    Marker marker1=googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.coffee)));
                    hashMap.put(marker1, k);
                    break;
                case 5798 :
                    Marker marker3 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.takeaway)));
                    hashMap.put(marker3, k);
                    break;
                case 5810 :
                    Marker marker4 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.restaurant_steakhouse)));
                    hashMap.put(marker4, k);
                    break;
                case 6005 :
                    Marker marker5 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.clambers_playcentre)));
                    hashMap.put(marker5, k);
                    break;
                case 6011 :
                    Marker marker6 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.thetruecrimemuseum)));
                    hashMap.put(marker6, k);

                    break;
                .........
                ...........
                ............
                default :
                    break;
            }

        }catch (Exception e){
            Log.e("addMarkers",k+"");
            e.printStackTrace();
        }

    }
}

/******************FOR MAP******************/
class Frnt_mIcons_Activity extends AsyncTask<String, String, String> {

    public ArrayList<All_products_lat_long> maplist;

    @Override
    protected void onPreExecute() {
        mDialog = new ProgressDialog(Frnt_mapActivity.this);
        mDialog.setMessage("Loading...");
        mDialog.setCancelable(false);
        mDialog.show();
        super.onPreExecute();
    }

    // Slow Implementation
    private String inputStreamToString(InputStream is) {
        String s = "";
        String line = "";
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                s += line;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Return full string
        return s;
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        maplist = new ArrayList<All_products_lat_long>();

        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        DefaultHttpClient client = new DefaultHttpClient();

        SchemeRegistry registry = new SchemeRegistry();
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        registry.register(new Scheme("http", socketFactory, 443));
        SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
        DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

  // Set verifier
                HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        HttpPost httpPost = new HttpPost("http://towncitycards.com/webservice_action.php?action=all_products");

        try{

            HttpResponse response = httpClient.execute(httpPost);
            String data = inputStreamToString(response.getEntity().getContent());
            jsonobject3 = new JSONObject(data);
            jsonarray3 = new JSONArray(jsonobject3.getString("all_products"));
            venueList =new ArrayList<All_products_lat_long>();
            for(int j=0; j<jsonarray3.length();j++){
                JSONObject itemobj = jsonarray3.getJSONObject(j);
                //SHOW SEARCH RESULT
                All_products_lat_long searchItems = new All_products_lat_long();

                searchItems.setId(itemobj.getString("ID"));
                searchItems.setPost_title(itemobj.getString("post_title"));
                searchItems.setMap_icon(itemobj.getString("map_icon"));
                searchItems.setLongitude(itemobj.getString("longitude"));
                searchItems.setLatitude(itemobj.getString("latitude"));
                //          System.out.println("######Ashish is object >>"+itemobj);
                venueList.add(searchItems);
                //      System.out.println("SEARCHLISTSS@@@@@@@"+venueList.get(j).getLongitude());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onPostExecute(String result) {
        super.onPostExecute(result);

        //System.out.println("SEARCHLISTSS@@@@@@@"+venueList);
        //System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAA"+venueList);
        try{
            if(venueList.size()>0)
            {
                addMarkers();
//              Toast.makeText(Frnt_mapActivity.this,"Search for the venue11.",Toast.LENGTH_SHORT).show();

            }
            else
                Toast.makeText(Frnt_mapActivity.this,"Search for the venue.",Toast.LENGTH_SHORT).show();
            //LatLng coordinate = new LatLng(22.75852160, 75.8911550);
            LatLng coordinate = new LatLng(50.85514, 0.58382);
            CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 18);
            googlemap.animateCamera(yourLocation);
            for (int i = 0; i < jsonarray3.length(); i++) {

                jsonobject3 = jsonarray3.getJSONObject(i);

                Shop_title = jsonobject3.optString("post_title");
                Shop_address = jsonobject3.optString("map_icon");
                Shop_icons = jsonobject3.optString("map_icon");
                //}
            }

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

        if(mDialog!=null && mDialog.isShowing()){
            mDialog.dismiss();
        }
    }
}
</code>```

}

答:
There are no icons for markers in Your server response JSON, just references for it. So You should:

1) download JSON response from Your "web service" (for example like in this question answers, but better use Service);

2) for each "ID" of response get icon from URL, stored in "map_icon" field (for example like in that question answers)

3) create Google Maps marker with icon. downloaded in p.2 like in Your "old code" or that.

Update

There are several issues in Your task:

1) Your server response contains wrong URL's for "map_icon": http:// protocol prefix instead of https://, so You should replace http:// with https://;

2) some of "map_icon" URL's contains UNICODE symbols (like symbol Pound "£" in save£2.png), so You should encode it to percent-encoded format: save%C2%A32.png instead of save£2.png;

3) some of "map_icon" URL's even not exists (like

https://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/save50p.png
or
https://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/information.png) so You should ignore it (or set some default icon for it)

So, according this, described above (before update) steps can be done with AsyncTask-based class, like this:

```<code>protected class CreateProductListTask extends AsyncTask<Void, Void, List<Product>> {

    private String serverUrl;

    public CreateProductListTask(String url) {
        super();
        this.serverUrl = url;
    }

    @Override
    protected List<Product> doInBackground(Void... params)
    {

        URLConnection urlConn = null;
        BufferedReader bufferedReader = null;
        try
        {
            URL url = new URL(this.serverUrl);
            urlConn = url.openConnection();
            bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }

            JSONObject response = new JSONObject(stringBuffer.toString());

            List<Product> products = new ArrayList<>();
            HashMap<String, Bitmap> iconsMap = new HashMap<>();
            try {
                JSONArray productsJSON = response.getJSONArray("all_products");
                for (int ixProduct=0; ixProduct<productsJSON.length(); ixProduct++) {
                    JSONObject productJSON = productsJSON.getJSONObject(ixProduct);
                    String mapIconStr = productJSON.getString("map_icon");
                    URI uri = new URI(mapIconStr);
                    String[] segments = uri.getPath().split("/");
                    String iconName = segments[segments.length-1];

                    // percetn-encode URL
                    String mapIconPath = mapIconStr.substring(0, mapIconStr.indexOf(iconName));
                    String iconUrlString = mapIconPath + URLEncoder.encode(iconName, "UTF-8");

                    // replace "http:" with "https:"
                    iconUrlString = iconUrlString.replace("http:", "https:");

                    Bitmap bmp;
                    if (!iconsMap.containsKey(iconUrlString)) {
                        bmp = getBitmapFromURL(iconUrlString);
                        // populate map with unique icons
                        iconsMap.put(iconUrlString, bmp);
                    } else {
                        bmp = iconsMap.get(iconUrlString);
                    }

                    if (bmp != null) {
                        try {
                            Product product = new Product();
                            product.name = productJSON.getString("post_title");
                            product.lat = productJSON.getDouble("latitude");
                            product.lon = productJSON.getDouble("longitude");
                            product.icon = bmp;
                            products.add(product);
                        } catch (Exception ignore) {
                        }
                    }

                }

            } catch (JSONException ex) {
                Log.e("App", "Failure", ex);
            }

            return products;
        }
        catch(Exception ex)
        {
            Log.e("App", "yourDataTask", ex);
            return null;
        }
        finally
        {
            if(bufferedReader != null)
            {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onPostExecute(List<Product> products)
    {
        if(products != null) {
            for (Product product : products) {
                googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(product.lat, product.lon))
                        .title(product.name)
                        .icon(BitmapDescriptorFactory.fromBitmap(product.icon))
                        );
            }
        }
    }
}
</code>```

where Product class is:

```<code>protected class Product {
    public String name;
    public double lat;
    public double lon;
    public Bitmap icon;
}
</code>```

getBitmapFromURL() is:

```<code>public static Bitmap getBitmapFromURL(String src) {
try {
    URL url = new URL(src);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.connect();
    InputStream input = connection.getInputStream();
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1;
    bmOptions.inJustDecodeBounds = false;
    Bitmap myBitmap = BitmapFactory.decodeStream(input, null, bmOptions);
    return myBitmap;
} catch (IOException e) {
    return null;
}
</code>```

}

and You can call it that way (of course after You got reference googlemap to GoogleMap object):

```<code>CreateProductListTask responseDownloadTask = new CreateProductListTask("https://www.towncitycards.com/webservice_action.php?action=all_products");
responseDownloadTask.execute();
</code>```

Finally (after 20-30 sec because of server response delay for non existing icons) You got something like that:

And maybe You need to scale icons like in this answer of goodm

Of course, this is just example and You need Service instead of AsyncTask to download data and images from URL (see Virgil Dobjanschi about patterns).

Body:
This is my web service

where I want to get map_icon, longitude, latitude dynamically from given web service. I am stuck at this point. How can I do this please help me out.
In old code what is done is get longitude, latitude, post_title from web service on the basis of id and then assign image statically.

Frnt_mapActivity.java

public class Frnt_mapActivity extends Activity {

public String Shop_title;
public String Shop_address;
public String Shop_icons;
ProgressDialog mDialog;
JSONObject jsonobject3;
JSONArray jsonarray3;
// Google Map
private static GoogleMap googlemap;
public static ArrayList<SearchBeams> searchdata_list;
public static ArrayList<NormalSearchBeams> normlSearchList;
ArrayList<All_products_lat_long> venueList;

private int i;
private Intent intent;
HashMap<Marker, Integer> hashMap=new HashMap<Marker, Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.frnt_map_activity);

    googlemap=((MapFragment)getFragmentManager().findFragmentById(R.id.places_map)).getMap();
    googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    googlemap.setMyLocationEnabled(true);
    googlemap.getUiSettings().setZoomControlsEnabled(true);
    googlemap.getUiSettings().setMyLocationButtonEnabled(true);
    googlemap.getUiSettings().setCompassEnabled(true);
    googlemap.getUiSettings().setRotateGesturesEnabled(true);
    googlemap.getUiSettings().setZoomGesturesEnabled(true);
    googlemap.setMyLocationEnabled(true);
    intent=new Intent(Frnt_mapActivity.this,MainActivity.class);
    googlemap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

        @Override
        public void onInfoWindowClick(Marker arg0) {
            i=hashMap.get(arg0);
            intent.putExtra("PRODUCT_ID", venueList.get(i).getId());
            startActivity(intent);
            //overridePendingTransition( R.anim.slide_right, R.anim.slide_left );
        }
    });

    new Frnt_mIcons_Activity().execute();

}

class AddMarkerAsyncTask extends AsyncTask<String,String,String>{

    private All_products_lat_long venue;
    private int k;
    BitmapDescriptor bd=null;

    AddMarkerAsyncTask(All_products_lat_long venue,int k){
        this.venue=venue;
        this.k=k;
    }

    @Override
    protected String doInBackground(String... strings) {
        try{
            bd=BitmapDescriptorFactory.fromBitmap(Glide.
                    with(Frnt_mapActivity.this).
                    load(venue.getMap_icon()).
                    asBitmap().
                    into(100, 100). // Width and height
                    get());
        }catch (Exception e){
            bd=null;
            e.printStackTrace();

        }

        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        try{
            if(bd!=null){
                Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
                        .title(venue.getPost_title())
                        .icon(bd));
                hashMap.put(marker, k);
            }

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

    }
}

private void addMarkers() {

    for(int k=0; k<venueList.size(); k += 1){

        //nirmal
        try{
            Log.e("nirmal",venueList.get(k).getMap_icon());

            //new AddMarkerAsyncTask(venueList.get(k),k).execute();

            double ln = Double.parseDouble(venueList.get(k).getLongitude());
            double la = Double.parseDouble(venueList.get(k).getLatitude());
                /*String title=venueList.get(k).getPost_title()==null?"":venueList.get(k).getPost_title();
                URL url = new URL(venueList.get(k).getMap_icon());
                Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                BitmapDescriptor bd=BitmapDescriptorFactory.fromBitmap(image);*/

                /*Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(la, ln))
                        .title(title)
                        .icon(bd));
                hashMap.put(marker, k);*/

            switch (Integer.parseInt(venueList.get(k).getId()))
            {
                case 5689 :
                    Marker marker=googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.fruitandveg)));
                    hashMap.put(marker, k);
                    break;
                case 5779 :
                    Marker marker1=googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.coffee)));
                    hashMap.put(marker1, k);
                    break;
                case 5798 :
                    Marker marker3 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.takeaway)));
                    hashMap.put(marker3, k);
                    break;
                case 5810 :
                    Marker marker4 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.restaurant_steakhouse)));
                    hashMap.put(marker4, k);
                    break;
                case 6005 :
                    Marker marker5 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.clambers_playcentre)));
                    hashMap.put(marker5, k);
                    break;
                case 6011 :
                    Marker marker6 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.thetruecrimemuseum)));
                    hashMap.put(marker6, k);

                    break;
                .........
                ...........
                ............
                default :
                    break;
            }

        }catch (Exception e){
            Log.e("addMarkers",k+"");
            e.printStackTrace();
        }

    }
}

/******************FOR MAP******************/
class Frnt_mIcons_Activity extends AsyncTask<String, String, String> {

    public ArrayList<All_products_lat_long> maplist;

    @Override
    protected void onPreExecute() {
        mDialog = new ProgressDialog(Frnt_mapActivity.this);
        mDialog.setMessage("Loading...");
        mDialog.setCancelable(false);
        mDialog.show();
        super.onPreExecute();
    }

    // Slow Implementation
    private String inputStreamToString(InputStream is) {
        String s = "";
        String line = "";
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                s += line;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Return full string
        return s;
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        maplist = new ArrayList<All_products_lat_long>();

        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        DefaultHttpClient client = new DefaultHttpClient();

        SchemeRegistry registry = new SchemeRegistry();
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        registry.register(new Scheme("http", socketFactory, 443));
        SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
        DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

  // Set verifier
                HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        HttpPost httpPost = new HttpPost("http://towncitycards.com/webservice_action.php?action=all_products");

        try{

            HttpResponse response = httpClient.execute(httpPost);
            String data = inputStreamToString(response.getEntity().getContent());
            jsonobject3 = new JSONObject(data);
            jsonarray3 = new JSONArray(jsonobject3.getString("all_products"));
            venueList =new ArrayList<All_products_lat_long>();
            for(int j=0; j<jsonarray3.length();j++){
                JSONObject itemobj = jsonarray3.getJSONObject(j);
                //SHOW SEARCH RESULT
                All_products_lat_long searchItems = new All_products_lat_long();

                searchItems.setId(itemobj.getString("ID"));
                searchItems.setPost_title(itemobj.getString("post_title"));
                searchItems.setMap_icon(itemobj.getString("map_icon"));
                searchItems.setLongitude(itemobj.getString("longitude"));
                searchItems.setLatitude(itemobj.getString("latitude"));
                //          System.out.println("######Ashish is object >>"+itemobj);
                venueList.add(searchItems);
                //      System.out.println("SEARCHLISTSS@@@@@@@"+venueList.get(j).getLongitude());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onPostExecute(String result) {
        super.onPostExecute(result);

        //System.out.println("SEARCHLISTSS@@@@@@@"+venueList);
        //System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAA"+venueList);
        try{
            if(venueList.size()>0)
            {
                addMarkers();
//              Toast.makeText(Frnt_mapActivity.this,"Search for the venue11.",Toast.LENGTH_SHORT).show();

            }
            else
                Toast.makeText(Frnt_mapActivity.this,"Search for the venue.",Toast.LENGTH_SHORT).show();
            //LatLng coordinate = new LatLng(22.75852160, 75.8911550);
            LatLng coordinate = new LatLng(50.85514, 0.58382);
            CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 18);
            googlemap.animateCamera(yourLocation);
            for (int i = 0; i < jsonarray3.length(); i++) {

                jsonobject3 = jsonarray3.getJSONObject(i);

                Shop_title = jsonobject3.optString("post_title");
                Shop_address = jsonobject3.optString("map_icon");
                Shop_icons = jsonobject3.optString("map_icon");
                //}
            }

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

        if(mDialog!=null && mDialog.isShowing()){
            mDialog.dismiss();
        }
    }
}

}

Body:
There are no icons for markers in Your server response JSON, just references for it. So You should:

1) download JSON response from Your "web service" (for example like in this question answers, but better use Service);

2) for each "ID" of response get icon from URL, stored in "map_icon" field (for example like in that question answers)

3) create Google Maps marker with icon. downloaded in p.2 like in Your "old code" or that.

Update

There are several issues in Your task:

1) Your server response contains wrong URL's for "map_icon": http:// protocol prefix instead of https://, so You should replace http:// with https://;

2) some of "map_icon" URL's contains UNICODE symbols (like symbol Pound "£" in save£2.png), so You should encode it to percent-encoded format: save%C2%A32.png instead of save£2.png;

3) some of "map_icon" URL's even not exists (like

https://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/save50p.png
or
https://towncitycards.com/wp-content/uploads/2015/01/googlemapicons/information.png) so You should ignore it (or set some default icon for it)

So, according this, described above (before update) steps can be done with AsyncTask-based class, like this:

protected class CreateProductListTask extends AsyncTask<Void, Void, List<Product>> {

    private String serverUrl;

    public CreateProductListTask(String url) {
        super();
        this.serverUrl = url;
    }

    @Override
    protected List<Product> doInBackground(Void... params)
    {

        URLConnection urlConn = null;
        BufferedReader bufferedReader = null;
        try
        {
            URL url = new URL(this.serverUrl);
            urlConn = url.openConnection();
            bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }

            JSONObject response = new JSONObject(stringBuffer.toString());

            List<Product> products = new ArrayList<>();
            HashMap<String, Bitmap> iconsMap = new HashMap<>();
            try {
                JSONArray productsJSON = response.getJSONArray("all_products");
                for (int ixProduct=0; ixProduct<productsJSON.length(); ixProduct++) {
                    JSONObject productJSON = productsJSON.getJSONObject(ixProduct);
                    String mapIconStr = productJSON.getString("map_icon");
                    URI uri = new URI(mapIconStr);
                    String[] segments = uri.getPath().split("/");
                    String iconName = segments[segments.length-1];

                    // percetn-encode URL
                    String mapIconPath = mapIconStr.substring(0, mapIconStr.indexOf(iconName));
                    String iconUrlString = mapIconPath + URLEncoder.encode(iconName, "UTF-8");

                    // replace "http:" with "https:"
                    iconUrlString = iconUrlString.replace("http:", "https:");

                    Bitmap bmp;
                    if (!iconsMap.containsKey(iconUrlString)) {
                        bmp = getBitmapFromURL(iconUrlString);
                        // populate map with unique icons
                        iconsMap.put(iconUrlString, bmp);
                    } else {
                        bmp = iconsMap.get(iconUrlString);
                    }

                    if (bmp != null) {
                        try {
                            Product product = new Product();
                            product.name = productJSON.getString("post_title");
                            product.lat = productJSON.getDouble("latitude");
                            product.lon = productJSON.getDouble("longitude");
                            product.icon = bmp;
                            products.add(product);
                        } catch (Exception ignore) {
                        }
                    }

                }

            } catch (JSONException ex) {
                Log.e("App", "Failure", ex);
            }

            return products;
        }
        catch(Exception ex)
        {
            Log.e("App", "yourDataTask", ex);
            return null;
        }
        finally
        {
            if(bufferedReader != null)
            {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onPostExecute(List<Product> products)
    {
        if(products != null) {
            for (Product product : products) {
                googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(product.lat, product.lon))
                        .title(product.name)
                        .icon(BitmapDescriptorFactory.fromBitmap(product.icon))
                        );
            }
        }
    }
}

where Product class is:

protected class Product {
    public String name;
    public double lat;
    public double lon;
    public Bitmap icon;
}

getBitmapFromURL() is:

public static Bitmap getBitmapFromURL(String src) {
try {
    URL url = new URL(src);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.connect();
    InputStream input = connection.getInputStream();
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1;
    bmOptions.inJustDecodeBounds = false;
    Bitmap myBitmap = BitmapFactory.decodeStream(input, null, bmOptions);
    return myBitmap;
} catch (IOException e) {
    return null;
}

}

and You can call it that way (of course after You got reference googlemap to GoogleMap object):

CreateProductListTask responseDownloadTask = new CreateProductListTask("https://www.towncitycards.com/webservice_action.php?action=all_products");
responseDownloadTask.execute();

Finally (after 20-30 sec because of server response delay for non existing icons) You got something like that:

And maybe You need to scale icons like in this answer of goodm

Of course, this is just example and You need Service instead of AsyncTask to download data and images from URL (see Virgil Dobjanschi about patterns).


问:
react native fbsdk MODULE_NOT_FOUND after link commend
I searched for this error on the git repo and online but I didn't find anything what brings me to here. React native is totally new for me so if I missed something stupid, my apologize.

I'm trying to install & link react-native-fbsdk in my react-native project: https://github.com/facebook/react-native-fbsdk

I went through these steps:

```<code>react-native init [YourApp]
</code>```

Result: done, project created

```<code>react-native install react-native-fbsdk
</code>```

Output: Scanning 712 folders for symlinks in C:\wamp\www\chatapp\node_modules (26ms)
rnpm-install info Module react-native-fbsdk has been successfully installed & linked

```<code>react-native link react-native-fbsdk
</code>```

Output: Scanning 712 folders for symlinks in C:\wamp\www\chatapp\node_modules (29ms)
{ [Error: Cannot find module 'C:\wamp\www\chatapp\node_modules\react-native-fbsdk\package.json'] code: 'MODULE_NOT_FOUND' }

Print screen:

Of course when I try to build my app with react-native run-android I got this:

```<code>...
:app:processDebugResources
:app:generateDebugSources
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac
C:\wamp\www\chatapp\android\app\src\main\java\com\chatapp\MainApplication.java:16: error: cannot find symbol
import com.facebook.FacebookSdk;
...
</code>```

More Info:

React native version: 0.42.3

npm -version 4.2.0

I didn't find "react-native-fbsdk" folder under
my node_modules folder.

Windows 8.1

I'm working with Android Studio

Android SDK Platform-Tools 25.0.4

Android SDK Tools 25.2.3

Thank you in advance.
Leo.

EDIT + UPDATE: Added react-native tag. Facebook team investigated this and it looks like an issue with React Native itself.
https://developers.facebook.com/bugs/1889723254644374

答:
After few days with the community I found the problem!

This line is not valid commend for react native!

```<code>react-native install react-native-fbsdk
</code>```

Instead we need to write:

```<code>npm i -S react-native-fbsdk
</code>```

and then

```<code>react-native link react-native-fbsdk
</code>```

Body:
I searched for this error on the git repo and online but I didn't find anything what brings me to here. React native is totally new for me so if I missed something stupid, my apologize.

I'm trying to install & link react-native-fbsdk in my react-native project: https://github.com/facebook/react-native-fbsdk

I went through these steps:

react-native init [YourApp]

Result: done, project created

react-native install react-native-fbsdk

Output: Scanning 712 folders for symlinks in C:\wamp\www\chatapp\node_modules (26ms)
rnpm-install info Module react-native-fbsdk has been successfully installed & linked

react-native link react-native-fbsdk

Output: Scanning 712 folders for symlinks in C:\wamp\www\chatapp\node_modules (29ms)
{ [Error: Cannot find module 'C:\wamp\www\chatapp\node_modules\react-native-fbsdk\package.json'] code: 'MODULE_NOT_FOUND' }

Print screen:

Of course when I try to build my app with react-native run-android I got this:

...
:app:processDebugResources
:app:generateDebugSources
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac
C:\wamp\www\chatapp\android\app\src\main\java\com\chatapp\MainApplication.java:16: error: cannot find symbol
import com.facebook.FacebookSdk;
...

More Info:

React native version: 0.42.3

npm -version 4.2.0

I didn't find "react-native-fbsdk" folder under
my node_modules folder.

Windows 8.1

I'm working with Android Studio

Android SDK Platform-Tools 25.0.4

Android SDK Tools 25.2.3

Thank you in advance.
Leo.

EDIT + UPDATE: Added react-native tag. Facebook team investigated this and it looks like an issue with React Native itself.
https://developers.facebook.com/bugs/1889723254644374

Body:
After few days with the community I found the problem!

This line is not valid commend for react native!

react-native install react-native-fbsdk

Instead we need to write:

npm i -S react-native-fbsdk

and then

react-native link react-native-fbsdk


问:
$cond in mongodb query
Assume I have something like
(I know the example query is not logical, but I tried to minimize the situation)

```<code>for(var j=0; j < 3; j++){
  db.collection.update({name: "alex"}, {surname: "brown"})
}
</code>```

Here is my question. If j=2 I want to increment document's age.

To do this I wrote;

```<code>for(var j=0; j < 3; j++){
  if(j !==2){
    db.collection.update({name: "alex"}, {surname: "brown"})
  }else{
   db.collection.update({name: "alex"}, {surname: "brown" , $inc: { age: 1}})
  }
}
</code>```

How can I do this by using $cond or if/else condition in a more practical way in mongodb?

答:
$cond is only used in aggregations, thus it won't help you achieve your goal.

a more elegant way to do that might be:

```<code>var update = {
    surname: "brown"
}

for(var j = 0; j < 3; j++) {
  if(j === 2){
    update["$inc"] = { age: 1 }
  }

   db.collection.update({name: "alex"}, update)
  }
}
</code>```

Title: $cond in mongodb query

Body:
Assume I have something like
(I know the example query is not logical, but I tried to minimize the situation)

for(var j=0; j < 3; j++){
  db.collection.update({name: "alex"}, {surname: "brown"})
}

Here is my question. If j=2 I want to increment document's age.

To do this I wrote;

for(var j=0; j < 3; j++){
  if(j !==2){
    db.collection.update({name: "alex"}, {surname: "brown"})
  }else{
   db.collection.update({name: "alex"}, {surname: "brown" , $inc: { age: 1}})
  }
}

How can I do this by using $cond or if/else condition in a more practical way in mongodb?

Body:
$cond is only used in aggregations, thus it won't help you achieve your goal.

a more elegant way to do that might be:

var update = {
    surname: "brown"
}

for(var j = 0; j < 3; j++) {
  if(j === 2){
    update["$inc"] = { age: 1 }
  }

   db.collection.update({name: "alex"}, update)
  }
}


问:
Using single column table
I'm creating a database to store the events of mobile apps recovered from multiple sources. Problem is that rows from the event table don't have much meaning to the user as it's mostly a succession of integers. Forcing them to make multiple joins or multiple queries.

```<code>CREATE TABLE source (
    id              serial PRIMARY KEY,
    value           string NOT NULL
);

CREATE TABLE application (
    id              serial PRIMARY KEY,
    value           string NOT NULL
);

CREATE TABLE platform (
    id              serial PRIMARY KEY,
    value           string NOT NULL
);

CREATE TABLE country (
    id              serial PRIMARY KEY,
    value           string NOT NULL
);

CREATE TABLE event (
    id              serial PRIMARY KEY,
    source_id       integer REFERENCES source(id),
    application_id  integer REFERENCES application(id),
    platform_id     integer REFERENCES platform(id),
    country_id      integer REFERENCES country(id),

    ...

    updated_at      date NOT NULL,
    value           decimal(100, 2) NOT NULL
);
</code>```

I thought of directly using the value of the "secondary" tables as a primary key (as it's unique and not null) that I would reference in the event table. It would look like that:

```<code>CREATE TABLE source (
    value              string PRIMARY KEY
);

CREATE TABLE application (
    value              string PRIMARY KEY
);

CREATE TABLE platform (
    value              string PRIMARY KEY
);

CREATE TABLE country (
    value              string PRIMARY KEY
);

CREATE TABLE event (
    id              serial PRIMARY KEY,
    source          string REFERENCES source(value),
    application     string REFERENCES application(value),
    platform        string REFERENCES platform(value),
    country         string REFERENCES country(value),

    ...

    updated_at      date NOT NULL,
    value           decimal(100, 2) NOT NULL
);
</code>```

I think it might also be good this way as I don't really see an added value at using a surrogate key in this situation. Also prevents me from using views which might have slower performances as it executes a query every time I use the view in a query.

What do you think of this option ?

答:
"real" systems usually use surrogate keys.  There are multiple reasons why:

Integers are more efficient for indexes, because they are fixed length.

Integers are more efficient for foreign key references, because they are only four bytes (strings are often larger).

String values may change and then referring tables need to be updated.

Auto generated primary keys contain other information, such as the order of insertion.

End users do not directly access tables.  If such functionality is needed, then views are fine.

There is nothing per se wrong with using strings.  But in practice, they are not used for this purpose.

Title: Using single column table

Body:
I'm creating a database to store the events of mobile apps recovered from multiple sources. Problem is that rows from the event table don't have much meaning to the user as it's mostly a succession of integers. Forcing them to make multiple joins or multiple queries.

CREATE TABLE source (
    id              serial PRIMARY KEY,
    value           string NOT NULL
);

CREATE TABLE application (
    id              serial PRIMARY KEY,
    value           string NOT NULL
);

CREATE TABLE platform (
    id              serial PRIMARY KEY,
    value           string NOT NULL
);

CREATE TABLE country (
    id              serial PRIMARY KEY,
    value           string NOT NULL
);

CREATE TABLE event (
    id              serial PRIMARY KEY,
    source_id       integer REFERENCES source(id),
    application_id  integer REFERENCES application(id),
    platform_id     integer REFERENCES platform(id),
    country_id      integer REFERENCES country(id),

    ...

    updated_at      date NOT NULL,
    value           decimal(100, 2) NOT NULL
);

I thought of directly using the value of the "secondary" tables as a primary key (as it's unique and not null) that I would reference in the event table. It would look like that:

CREATE TABLE source (
    value              string PRIMARY KEY
);

CREATE TABLE application (
    value              string PRIMARY KEY
);

CREATE TABLE platform (
    value              string PRIMARY KEY
);

CREATE TABLE country (
    value              string PRIMARY KEY
);

CREATE TABLE event (
    id              serial PRIMARY KEY,
    source          string REFERENCES source(value),
    application     string REFERENCES application(value),
    platform        string REFERENCES platform(value),
    country         string REFERENCES country(value),

    ...

    updated_at      date NOT NULL,
    value           decimal(100, 2) NOT NULL
);

I think it might also be good this way as I don't really see an added value at using a surrogate key in this situation. Also prevents me from using views which might have slower performances as it executes a query every time I use the view in a query.

What do you think of this option ?


问:
PowerBuilder and Visual Studio files in same StarTeam project?
We have a system that is largely written in PowerBuilder 11.5 and we are using a single StarTeam project to hold the source code.

Now we are wanting to add some related websites developed in ASP.NET with Visual Studio 2010 to source control as well. We would like them to be able to share the same set of Change Requests as the PowerBuilder code. Since in StarTeam Change Requests sets are tied to a StarTeam project this means we will have to put the web sites into the same StarTeam project as the PowerBuilder files.

Are there any pitfalls related to putting projects from different development environments into the same StarTeam project?

答:
CRs are not limited to a single project.  You can create CRs and share them wherever you want on the same server instance, even between projects.  You'd need to be careful to not branch the shared version so any CR property changes are visible to both sides.  This isn't automatic, but possible at least.

Having the two projects share a single view is probably easier, especially if a single change needs to edit files in both products.