问:
How can I return category, revenue, top brands and their revenue for each category in a single row?
I would like to return category, revenue, top brand, revenue for the top brand, second brand, revenue for second brand, etc. up to 5+, ideally all in a single row for that category. Right now i have a row for each of the top brands

```<code>SELECT
      cats.category
      cats.revenue
      brands.rank
      brands.brand
      brands.revenue_brand
FROM
      (SELECT
      category, sum(revenue) as revenue_total
      FROM sales
      GROUP BY category
      ) cats
JOIN
      (SELECT
      category,
      brand,
      sum(revenue) as revenue_brand
      rank () over (PARTITION BY category ORDER BY revenue_brand DESC) as rank
      FROM sales
      GROUP BY category, brand
      ) brands on cats.category = brands.category
WHERE brands.rank <=5
</code>```

How can I create one row for each category instead of one row for each rank?

答:
This might not meet all of your expectations, and as I have no access to redshift I can't do any testing. It appears that redshift doesn't allow for ["dynamic sql"[(http://sqlblog.com/blogs/maria_zakourdaev/archive/2017/11/07/dynamic-pivot-in-amazon-redshift-don-t-blame-databases-for-disappointing-you-blame-yourself-for-expecting-too-much-from-them.aspx) and this means you simply cannot get "dynamic headings" (i.e. a heading for brand-rank-1 |  brand-rank-2 |   brand-rank-3 | etc.

With this in mind the "old fashioned" way to achieve a pivot was to use "conditional aggregates" (case expressions inside aggregation functions).

```<code>SELECT
        cats.category
      , max(case when rn = 1 then brands.brand end)
      , max(case when rn = 1 then brands.revenue_brand end)
      , max(case when rn = 2 then brands.brand end)
      , max(case when rn = 2 then brands.revenue_brand end)
      , max(case when rn = 3 then brands.brand end)
      , max(case when rn = 3 then brands.revenue_brand end)
      , max(case when rn = 4 then brands.brand end)
      , max(case when rn = 4 then brands.revenue_brand end)
      , max(case when rn = 5 then brands.brand end)
      , max(case when rn = 5 then brands.revenue_brand end)
      , cats.revenue
FROM (
      SELECT
            category
          , SUM(revenue) AS revenue_total
      FROM sales
      GROUP BY
            category
) cats
JOIN (
      SELECT
            category
          , brand
          , SUM(revenue)                                                          AS revenue_brand
          , ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue_brand DESC) AS rn
      FROM sales
      GROUP BY
            category
          , brand
) brands ON cats.category = brands.category
WHERE brands.rn <= 5
group by
        cats.category
      , cats.revenue
</code>```

Note because rank() can produce gaps in numbers and/or can have "equal rank" values, I changed to the use of row_number() instead which will always return 5 rows of 1 to 5.

Body:
I would like to return category, revenue, top brand, revenue for the top brand, second brand, revenue for second brand, etc. up to 5+, ideally all in a single row for that category. Right now i have a row for each of the top brands

SELECT
      cats.category
      cats.revenue
      brands.rank
      brands.brand
      brands.revenue_brand
FROM
      (SELECT
      category, sum(revenue) as revenue_total
      FROM sales
      GROUP BY category
      ) cats
JOIN
      (SELECT
      category,
      brand,
      sum(revenue) as revenue_brand
      rank () over (PARTITION BY category ORDER BY revenue_brand DESC) as rank
      FROM sales
      GROUP BY category, brand
      ) brands on cats.category = brands.category
WHERE brands.rank <=5

How can I create one row for each category instead of one row for each rank?

Body:
This might not meet all of your expectations, and as I have no access to redshift I can't do any testing. It appears that redshift doesn't allow for ["dynamic sql"[(http://sqlblog.com/blogs/maria_zakourdaev/archive/2017/11/07/dynamic-pivot-in-amazon-redshift-don-t-blame-databases-for-disappointing-you-blame-yourself-for-expecting-too-much-from-them.aspx) and this means you simply cannot get "dynamic headings" (i.e. a heading for brand-rank-1 |  brand-rank-2 |   brand-rank-3 | etc.

With this in mind the "old fashioned" way to achieve a pivot was to use "conditional aggregates" (case expressions inside aggregation functions).

SELECT
        cats.category
      , max(case when rn = 1 then brands.brand end)
      , max(case when rn = 1 then brands.revenue_brand end)
      , max(case when rn = 2 then brands.brand end)
      , max(case when rn = 2 then brands.revenue_brand end)
      , max(case when rn = 3 then brands.brand end)
      , max(case when rn = 3 then brands.revenue_brand end)
      , max(case when rn = 4 then brands.brand end)
      , max(case when rn = 4 then brands.revenue_brand end)
      , max(case when rn = 5 then brands.brand end)
      , max(case when rn = 5 then brands.revenue_brand end)
      , cats.revenue
FROM (
      SELECT
            category
          , SUM(revenue) AS revenue_total
      FROM sales
      GROUP BY
            category
) cats
JOIN (
      SELECT
            category
          , brand
          , SUM(revenue)                                                          AS revenue_brand
          , ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue_brand DESC) AS rn
      FROM sales
      GROUP BY
            category
          , brand
) brands ON cats.category = brands.category
WHERE brands.rn <= 5
group by
        cats.category
      , cats.revenue

Note because rank() can produce gaps in numbers and/or can have "equal rank" values, I changed to the use of row_number() instead which will always return 5 rows of 1 to 5.


来源: stackexchange

问:
Method to go in which class?
I have 2 classes, player and game and a method called get_player_games($player_id). Which class does this method belong to?

I seem to run into this problem a bit, where I'm not 100% sure which class the method should go in. Is it just a matter of preference?

Thanks

答:
Here is one way to think of it:  A game can have 1 player.  A game can have 2 players.  A game can have N players.  Does that sound good?

How about this:  A player can be a part of 1 game.  A player can be a part of 2 games.  A player can be a part of N games.

Now, think about how your application is architected.  Which one of the above works best?  The answer largely depends on whether or not it's a one to many relationship between games and players, a one to many relationship between players and games.

Of course, if it's a many to many relationship, then both classes may need that method.

ContentLicense: CC BY-SA 2.5

Title: Method to go in which class?


问:
Upgrading to Angular Material 5
I am using a beta 8 of Angular Material in my project. It was never been updated since then. Now that v5 is available, we'd like to do so. What things should I consider while doing so? Any information or pointer to it would be really helpful.

Thanks!

答:
What you have to do is the following:

Since MaterialModule has been removed, you have to import the modules required for your application separately to either another module (such as MyMaterialModule and making sure that it is after BrowserModule), a const, or adding the modules individually after BrowserModule. For more info, visit the docs.

The md selectors have been removed and replaced with mat (as well as classes). To update, install material-prefix-updater from npm:

npm i -g angular-material-prefix-updater
```

<p>After npm has installed it globally, run this command on your app's root directory (where the <code>-p</code> parameter is the app's <code>tsconfig.json</code>):</p>

<pre class="lang-bash prettyprint-override"><code>mat-switcher -p src/app/tsconfig.json # Or wherever tsconfig.json is
</code>```

For more info, visit the source code or use the --help parameter.

Note: You no longer need to specify MATERIAL_COMPATIBILITY_MODE.

ContentLicense: CC BY-SA 3.0

Title: Upgrading to Angular Material 5

Body:
What you have to do is the following:

Since MaterialModule has been removed, you have to import the modules required for your application separately to either another module (such as MyMaterialModule and making sure that it is after BrowserModule), a const, or adding the modules individually after BrowserModule. For more info, visit the docs.

The md selectors have been removed and replaced with mat (as well as classes). To update, install material-prefix-updater from npm:

npm i -g angular-material-prefix-updater

After npm has installed it globally, run this command on your app's root directory (where the -p parameter is the app's tsconfig.json):

mat-switcher -p src/app/tsconfig.json # Or wherever tsconfig.json is

For more info, visit the source code or use the --help parameter.

Note: You no longer need to specify MATERIAL_COMPATIBILITY_MODE.


问:
Rails ActiveRecord :joins with LEFT JOIN instead of INNER JOIN
I have this code

```<code>User.find(:all, :limit => 10, :joins => :user_points,
                :select => "users.*, count(user_points.id)", :group =>
                "user_points.user_id")
</code>```

which generates following sql

```<code>SELECT users.*, count(user_points.id)
FROM `users`
INNER JOIN `user_points`
ON user_points.user_id = users.id
GROUP BY user_points.user_id
LIMIT 10
</code>```

is it possible to make LEFT JOIN instead of INNER JOIN other way than User.find_by_sql and manualy typing the query?

答:
Rails 5 has a left_outer_joins method. So you can do

```<code>User.left_outer_joins(:user_points)
</code>```

or use the alias

```<code>User.left_joins(:user_points)
</code>```

Body:
I have this code

User.find(:all, :limit => 10, :joins => :user_points,
                :select => "users.*, count(user_points.id)", :group =>
                "user_points.user_id")

which generates following sql

SELECT users.*, count(user_points.id)
FROM `users`
INNER JOIN `user_points`
ON user_points.user_id = users.id
GROUP BY user_points.user_id
LIMIT 10

is it possible to make LEFT JOIN instead of INNER JOIN other way than User.find_by_sql and manualy typing the query?

Body:
Rails 5 has a left_outer_joins method. So you can do

User.left_outer_joins(:user_points)

or use the alias

User.left_joins(:user_points)


问:
Retrieving random row using drupal database wrap functionality
I am writing a fairly simple 'roleplaying name generator' block for drupal6 and I have a myriad of start/middle/end options for names in a table.

I am looking for a simple way to retrieve a random row of each while staying with the drupal database wrapper functions.

It was not hard to find mysql-specific solutions but I would like to stay portable as I have no guarantee that my users will be running mysql.

Any pointers would be spiffy!

答:
How portable do you need to be?

Conceptually, the solution is really pretty simple.

```<code>SELECT column FROM table
ORDER BY RANDOM();
</code>```

And, at that point, you can just take the first row as your random row. One problem is that different platforms use different functions. PostgreSQL (above) uses RANDOM(), MySQL uses RAND(). IIRC, SQL Server has a RAND() function, but used repeatedly within a single query it returns the same value. So SQL Server requires "ORDER BY NEWID();" (I could be wrong about SQL Server.)

Body:
How portable do you need to be?

Conceptually, the solution is really pretty simple.

SELECT column FROM table
ORDER BY RANDOM();

And, at that point, you can just take the first row as your random row. One problem is that different platforms use different functions. PostgreSQL (above) uses RANDOM(), MySQL uses RAND(). IIRC, SQL Server has a RAND() function, but used repeatedly within a single query it returns the same value. So SQL Server requires "ORDER BY NEWID();" (I could be wrong about SQL Server.)


问:
How does the Swift Dictionary subscript disambiguate Int keys and indices?
Currently I'm working on a data structure intended to store store key-value pairs uniquely and keep them sorted by key. Essentially it is a sorted dictionary and as such I am seeking to keep as much of the Collection and Dictionary semantics of Swift as I can.

In the documentation and Swift source (as best as I can find), Dictionaries have two subscripts. One is the most commonly used subscript by key (Github source):

```<code>extension Dictionary {
  ...
  public subscript(key: Key) -> Value? {
    @inline(__always)
    get {
      return _variantBuffer.maybeGet(key)
    }
    set(newValue) {
      if let x = newValue {
        // FIXME(performance): this loads and discards the old value.
        _variantBuffer.updateValue(x, forKey: key)
      }
      else {
        // FIXME(performance): this loads and discards the old value.
        removeValue(forKey: key)
      }
    }
  }
  ...
}
</code>```

And the second is a subscript by position/index (Github) source) as part of its conformance to the Collection protocol:

```<code>extension Dictionary: Collection {
  ...
  public subscript(position: Index) -> Element {
    return _variantBuffer.assertingGet(position)
  }
  ...
}
</code>```

When using these with a Dictionary keyed by something other than an Int, they behave exactly as expected because the subscripts are distinguished by different parameter types, ie: String vs Int.

```<code>let stringKeys = ["One": 1, "Two": 2, "Three": 3]
stringKeys["One"]   // 1
stringKeys[1]       // ("Two", 2)
</code>```

When Ints are used as keys, the key subscript is used as desired.

```<code>let intKeys = [1: "One, 2: "Two, 3: "Three"]
intKeys[1]   // "One"
</code>```

How does the Dictionary type accomplish this? It would seem to me that the Index and Key parameters of the subscripts are both Int and that the compiler should not know which was intended.  Indeed, when I implement the same subscripts for my custom dictionary, the compiler gives exactly that error—"Ambiguous use of 'subscript'"—when I test it with Int keys.

At first I wondered if one was a default provided in a protocol extension and overridden by a more specific implementation, but from what I can tell above that is not the case. The only other theory I have is that Index is of some other type than 'Int` such that it remains unambiguous but I can't find my way to anything that confirms this. Can anyone shed some light on this? Beyond my immediate needs, it's quite a clever bit of behavior in Swift that I'd like to understand.

Thank you to all for reading and for your help!

答:
The only other theory I have is that Index is of some other type than 'Int` such that it remains unambiguous but I can't find my way to anything that confirms this.

That's exactly how it is. Dictionary has two subscript methods:

```<code>public subscript(key: Dictionary.Key) -> Dictionary.Value?
public subscript(position: Dictionary<Key, Value>.Index) -> Dictionary.Element { get }
</code>```

The first one takes a key and returns an (optional) value,
the second one takes a Dictionary.Index
(source code)
and returns an (optional) Dictionary.Element,
i.e. a key-value pair.
Example:

```<code>let d : Dictionary = [1 : "one"]
if let idx = d.index(forKey: 1) {
    print(String(reflecting: type(of: idx))) // Swift.Dictionary<Swift.Int, Swift.String>.Index
    let kv = d[idx]
    print(String(reflecting: type(of: kv)))  // (key: Swift.Int, value: Swift.String)
}
</code>```

Dictionary.Index is also used in other methods such as

```<code>public var startIndex: Dictionary<Key, Value>.Index { get }
public var endIndex: Dictionary<Key, Value>.Index { get }
public func index(where predicate: ((key: Key, value: Value)) throws -> Bool) rethrows -> Dictionary<Key, Value>.Index?
</code>```

which are part of the Collection protocol.

Generally, the associated Index type of a Collection is not
necessarily an Int, another example is String which has its
own String.Index type.

Body:
Currently I'm working on a data structure intended to store store key-value pairs uniquely and keep them sorted by key. Essentially it is a sorted dictionary and as such I am seeking to keep as much of the Collection and Dictionary semantics of Swift as I can.

In the documentation and Swift source (as best as I can find), Dictionaries have two subscripts. One is the most commonly used subscript by key (Github source):

extension Dictionary {
  ...
  public subscript(key: Key) -> Value? {
    @inline(__always)
    get {
      return _variantBuffer.maybeGet(key)
    }
    set(newValue) {
      if let x = newValue {
        // FIXME(performance): this loads and discards the old value.
        _variantBuffer.updateValue(x, forKey: key)
      }
      else {
        // FIXME(performance): this loads and discards the old value.
        removeValue(forKey: key)
      }
    }
  }
  ...
}

And the second is a subscript by position/index (Github) source) as part of its conformance to the Collection protocol:

extension Dictionary: Collection {
  ...
  public subscript(position: Index) -> Element {
    return _variantBuffer.assertingGet(position)
  }
  ...
}

When using these with a Dictionary keyed by something other than an Int, they behave exactly as expected because the subscripts are distinguished by different parameter types, ie: String vs Int.

let stringKeys = ["One": 1, "Two": 2, "Three": 3]
stringKeys["One"]   // 1
stringKeys[1]       // ("Two", 2)

When Ints are used as keys, the key subscript is used as desired.

let intKeys = [1: "One, 2: "Two, 3: "Three"]
intKeys[1]   // "One"

How does the Dictionary type accomplish this? It would seem to me that the Index and Key parameters of the subscripts are both Int and that the compiler should not know which was intended.  Indeed, when I implement the same subscripts for my custom dictionary, the compiler gives exactly that error—"Ambiguous use of 'subscript'"—when I test it with Int keys.

At first I wondered if one was a default provided in a protocol extension and overridden by a more specific implementation, but from what I can tell above that is not the case. The only other theory I have is that Index is of some other type than 'Int` such that it remains unambiguous but I can't find my way to anything that confirms this. Can anyone shed some light on this? Beyond my immediate needs, it's quite a clever bit of behavior in Swift that I'd like to understand.

Thank you to all for reading and for your help!

Body:
The only other theory I have is that Index is of some other type than 'Int` such that it remains unambiguous but I can't find my way to anything that confirms this.

That's exactly how it is. Dictionary has two subscript methods:

public subscript(key: Dictionary.Key) -> Dictionary.Value?
public subscript(position: Dictionary<Key, Value>.Index) -> Dictionary.Element { get }

The first one takes a key and returns an (optional) value,
the second one takes a Dictionary.Index
(source code)
and returns an (optional) Dictionary.Element,
i.e. a key-value pair.
Example:

let d : Dictionary = [1 : "one"]
if let idx = d.index(forKey: 1) {
    print(String(reflecting: type(of: idx))) // Swift.Dictionary<Swift.Int, Swift.String>.Index
    let kv = d[idx]
    print(String(reflecting: type(of: kv)))  // (key: Swift.Int, value: Swift.String)
}

Dictionary.Index is also used in other methods such as

public var startIndex: Dictionary<Key, Value>.Index { get }
public var endIndex: Dictionary<Key, Value>.Index { get }
public func index(where predicate: ((key: Key, value: Value)) throws -> Bool) rethrows -> Dictionary<Key, Value>.Index?

which are part of the Collection protocol.

Generally, the associated Index type of a Collection is not
necessarily an Int, another example is String which has its
own String.Index type.


答:
The main problem is that you're only writing a single row after the header:

writer.writerow([name, times])
```

<p>Instead, you need to write <em>each</em> row of the data, which you can do in your second for loop.</p>

<p>You also need to calculate out how many <code>Shift#</code> columns there are by finding the max length of a player times list. This can be done simply by using a loop, or the built-in <code>max</code> function:</p>

<pre class="lang-py prettyprint-override"><code># the loop way
shift_count = 0
for times in players.values():
    if len(times) > shift_count:
        shift_count = len(times)

# the quicker built-in way
shift_count = max(
    len(shift_times) for shift_times in players.values()
)

# then make the column names
shift_cols = [
    "Shift{}".format(num) for num in range(1, shift_count + 1)
]
</code>```

Putting these two together:

# Move the file prep above the loop
outfile = open("ShiftData.csv","a",newline='')
writer = csv.writer(outfile)

shift_count = max(
    len(shift_times) for shift_times in players.values()
)

shift_cols = [
    "Shift{}".format(num) for num in range(1, shift_count + 1)
]

writer.writerow(["Player"] + shift_cols)

for t in players.items():
    print(t)

    row = [
        t[0],  # the first column is the player's name
    ]
    row += t[1]  # then all of the shift times next to it

    writer.writerow(row)

outfile.close()
```

Title: Python Export to Csv

Body:
This is the data i am working with (Sample):

('Bouwmeester', [(0, 37), (155, 194), (327, 420), (541, 602), (654, 717), (761, 834), (1001, 1052), (0, 27), (79, 119), (405, 460), (546, 624), (750, 798), (834, 897), (1061, 1139), (0, 33), (170, 204), (289, 328), (447, 498), (575, 576), (729, 766), (962, 995), (1073, 1113), (1163, 1200)])
('Schwartz', [(0, 40), (165, 209), (362, 417), (550, 567), (761, 809), (881, 954), (1052, 1113), (27, 54), (195, 295), (482, 546), (707, 757), (906, 1003), (1080, 1126), (0, 33), (145, 229), (353, 408), (492, 561), (576, 640), (736, 766), (820, 870), (1094, 1163)])
('Foligno', [(0, 40), (176, 209), (362, 416), (552, 567), (761, 835), (883, 954), (459, 502), (546, 583), (757, 826), (1189, 1200), (0, 33), (212, 249), (353, 413), (575, 576), (696, 722), (722, 762)])

Here is the Script I have so far:

import csv
from itertools import combinations, product

#Header = LastName  StartTime  EndTime  Duration Period TeamAbbrev Position

#Import Game
with open('2017020397.csv', newline='') as f:
    next(f)
    skaters = '\n'.join(' '.join(row) for row in csv.reader(f))
    data = skaters.splitlines()

def to_secs(ms):
    ''' Convert a mm:ss string to seconds '''
    m, s = map(int, ms.split(':'))
    return 60 * m + s

# Store a list of (start, end) times for each player
players = {}
for row in data:
    name, start, end = row.split(None, 3)[:3]
    times = to_secs(start), to_secs(end)
    players.setdefault(name, []).append(times)

for t in players.items():
    print(t)

outfile = open("ShiftData.csv","a",newline='')
writer = csv.writer(outfile)
writer.writerow(["Player","Shift1"])
writer.writerow([name, times])
outfile.close()

Output:

Player  Shift1
Dumba   (39, 39)

The output is the last data not the Whole file. Also i would like all of the shifts to output in there own cell. Example:

Player        Shift1       Shift2      Shift3       Shift4
Bouwmeester   (0, 37)    (155, 194)  (327, 420)   (541, 602)

Body:
The main problem is that you're only writing a single row after the header:

writer.writerow([name, times])

Instead, you need to write each row of the data, which you can do in your second for loop.

You also need to calculate out how many Shift# columns there are by finding the max length of a player times list. This can be done simply by using a loop, or the built-in max function:

# the loop way
shift_count = 0
for times in players.values():
    if len(times) > shift_count:
        shift_count = len(times)

# the quicker built-in way
shift_count = max(
    len(shift_times) for shift_times in players.values()
)

# then make the column names
shift_cols = [
    "Shift{}".format(num) for num in range(1, shift_count + 1)
]

Putting these two together:

# Move the file prep above the loop
outfile = open("ShiftData.csv","a",newline='')
writer = csv.writer(outfile)

shift_count = max(
    len(shift_times) for shift_times in players.values()
)

shift_cols = [
    "Shift{}".format(num) for num in range(1, shift_count + 1)
]

writer.writerow(["Player"] + shift_cols)

for t in players.items():
    print(t)

    row = [
        t[0],  # the first column is the player's name
    ]
    row += t[1]  # then all of the shift times next to it

    writer.writerow(row)

outfile.close()


问:
MapKit (MKMapView): zPosition does not work anymore on iOS11
On iOS11 the zPosition stopped working for the annotationView.layer. Every time the map region changes.

No luck with original solution: layer.zPosition = X;

No luck with bringViewToFront/SendViewToBack methods

Xcode 8.3/9

UPDATE (SOLUTION thanks Elias Aalto):

When creating MKAnnotationView:

```<code>annotationView.layer.zPosition = 50;
if (IS_OS_11_OR_LATER) {
    annotationView.layer.name = @"50";
    [annotationView.layer addObserver:MeLikeSingleton forKeyPath:@"zPosition" options:0 context:NULL];

}
</code>```

In MeLikeSingleton or whatever observer object you have there:

```<code>- (void)observeValueForKeyPath:(NSString *)keyPath
                         ofObject:(id)object
                           change:(NSDictionary *)change
                          context:(void *)context {

       if (IS_OS_11_OR_LATER) {

           if ([keyPath isEqualToString:@"zPosition"]) {
               CALayer *layer = object;
               int zPosition = FLT_MAX;
               if (layer.name) {
                   zPosition = layer.name.intValue;
               }
               layer.zPosition = zPosition;
               //DDLogInfo(@"Name:%@",layer.name);
           }

       }
}
</code>```

This solution uses the layer.name value to keep track of zOrder. In case you have many levels of zPosition (user location, cluster, pin, callout) ;)

No for loops, only KVO

I used a Singleton Object that observs the layer value changes. In case you have multiple MKMapViews used through out the app.

HOW IT WAS WORKING BEFORE IOS11

..is to use the

```<code>- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
</code>```

and set the zPosition here.

..but that (for some of us, still dunny why) does not work anymore in iOS11!

答:
We can completely ignore MKMapView's attempts to modify MKAnnotationView layer's zPosition. Since MKAnnotationView uses standard CALayer as its layer and not some private class, we can subclass it and override its zPosition. To actually set zPosition we can provide our own accessor.

It will work much faster than KVO.

```<code>class ResistantLayer: CALayer {

    override var zPosition: CGFloat {
        get { return super.zPosition }
        set {}
    }
    var resistantZPosition: CGFloat {
        get { return super.zPosition }
        set { super.zPosition = newValue }
    }
}

class ResistantAnnotationView: MKAnnotationView {

    override class var layerClass: AnyClass {
        return ResistantLayer.self
    }
    var resistantLayer: ResistantLayer {
        return self.layer as! ResistantLayer
    }
}
</code>```

UPDATE:

I've got one very inelegant method for selection of the topmost annotation view when tapping on overlapping annotations.

```<code>class MyMapView: MKMapView {

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

        // annotation views whose bounds contains touch point, sorted by visibility order
        let views =
            self.annotations(in: self.visibleMapRect)
                .flatMap { $0 as? MKAnnotation }
                .flatMap { self.view(for: $0) }
                .filter { $0.bounds.contains(self.convert(point, to: $0)) }
                .sorted(by: {
                    view0, view1 in

                    let layer0  = view0.layer
                    let layer1  = view1.layer
                    let z0      = layer0.zPosition
                    let z1      = layer1.zPosition

                    if z0 == z1 {
                        if  let subviews = view0.superview?.subviews,
                            let index0 = subviews.index(where: { $0 === view0 }),
                            let index1 = subviews.index(where: { $0 === view1 })
                        {
                            return index0 > index1
                        } else {
                            return false
                        }
                    } else {
                        return z0 > z1
                    }
                })

        // disable every annotation view except topmost one
        for item in views.enumerated() {
            if item.offset > 0 {
                item.element.isEnabled = false
            }
        }

        // re-enable annotation views after some time
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            for item in views.enumerated() {
                if item.offset > 0 {
                    item.element.isEnabled = true
                }
            }
        }

        // ok, let the map view handle tap
        return super.hitTest(point, with: event)
    }
}
</code>```

Body:
On iOS11 the zPosition stopped working for the annotationView.layer. Every time the map region changes.

No luck with original solution: layer.zPosition = X;

No luck with bringViewToFront/SendViewToBack methods

Xcode 8.3/9

UPDATE (SOLUTION thanks Elias Aalto):

When creating MKAnnotationView:

annotationView.layer.zPosition = 50;
if (IS_OS_11_OR_LATER) {
    annotationView.layer.name = @"50";
    [annotationView.layer addObserver:MeLikeSingleton forKeyPath:@"zPosition" options:0 context:NULL];

}

In MeLikeSingleton or whatever observer object you have there:

- (void)observeValueForKeyPath:(NSString *)keyPath
                         ofObject:(id)object
                           change:(NSDictionary *)change
                          context:(void *)context {

       if (IS_OS_11_OR_LATER) {

           if ([keyPath isEqualToString:@"zPosition"]) {
               CALayer *layer = object;
               int zPosition = FLT_MAX;
               if (layer.name) {
                   zPosition = layer.name.intValue;
               }
               layer.zPosition = zPosition;
               //DDLogInfo(@"Name:%@",layer.name);
           }

       }
}

This solution uses the layer.name value to keep track of zOrder. In case you have many levels of zPosition (user location, cluster, pin, callout) ;)

No for loops, only KVO

I used a Singleton Object that observs the layer value changes. In case you have multiple MKMapViews used through out the app.

HOW IT WAS WORKING BEFORE IOS11

..is to use the

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views

and set the zPosition here.

..but that (for some of us, still dunny why) does not work anymore in iOS11!

Body:
We can completely ignore MKMapView's attempts to modify MKAnnotationView layer's zPosition. Since MKAnnotationView uses standard CALayer as its layer and not some private class, we can subclass it and override its zPosition. To actually set zPosition we can provide our own accessor.

It will work much faster than KVO.

class ResistantLayer: CALayer {

    override var zPosition: CGFloat {
        get { return super.zPosition }
        set {}
    }
    var resistantZPosition: CGFloat {
        get { return super.zPosition }
        set { super.zPosition = newValue }
    }
}

class ResistantAnnotationView: MKAnnotationView {

    override class var layerClass: AnyClass {
        return ResistantLayer.self
    }
    var resistantLayer: ResistantLayer {
        return self.layer as! ResistantLayer
    }
}

UPDATE:

I've got one very inelegant method for selection of the topmost annotation view when tapping on overlapping annotations.

class MyMapView: MKMapView {

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

        // annotation views whose bounds contains touch point, sorted by visibility order
        let views =
            self.annotations(in: self.visibleMapRect)
                .flatMap { $0 as? MKAnnotation }
                .flatMap { self.view(for: $0) }
                .filter { $0.bounds.contains(self.convert(point, to: $0)) }
                .sorted(by: {
                    view0, view1 in

                    let layer0  = view0.layer
                    let layer1  = view1.layer
                    let z0      = layer0.zPosition
                    let z1      = layer1.zPosition

                    if z0 == z1 {
                        if  let subviews = view0.superview?.subviews,
                            let index0 = subviews.index(where: { $0 === view0 }),
                            let index1 = subviews.index(where: { $0 === view1 })
                        {
                            return index0 > index1
                        } else {
                            return false
                        }
                    } else {
                        return z0 > z1
                    }
                })

        // disable every annotation view except topmost one
        for item in views.enumerated() {
            if item.offset > 0 {
                item.element.isEnabled = false
            }
        }

        // re-enable annotation views after some time
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            for item in views.enumerated() {
                if item.offset > 0 {
                    item.element.isEnabled = true
                }
            }
        }

        // ok, let the map view handle tap
        return super.hitTest(point, with: event)
    }
}


问:
Laravel, jquery - Fill input box as per select box
I'm building a Laravel app with jQuery. I've a form with a select box(list of products) and text input fields.

My requirement is when I choose a product from the Select box at the top, the value of all other fields should update according to the products value that is fetched from database for the selected product.

This is my js script:

```<code>$(document).ready(function() {

    var divKey = $( "#proposed_product option:selected" ).val();

    $( "#proposed_product" ).change(function() {
        updateKeyValues();
    });

    function updateKeyValues() {
        $("#proposed_product").val(divKey);
        console.log(proposed_product); //what to do here..???

    }

});
</code>```

My laravel function to return gigs list:

```<code>public function proposegigs($id){
    $gig = Gig::findOrFail($id);
    return $gig;
</code>```

Can somebody help how to achieve this?

答:
Make an ajax call to get the data

```<code>$( "#proposed_product" ).change(function() {
    $.ajaxSetup({
       headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
       url: "{{ route('your-route') }}",
       type: "POST",
       data: {id: $( "#proposed_product :selected" ).val()}, //send data to controller
       success: function(result){
           console.log(result);
           //check the console then put the data where you want
       }
    });

    $.ajax();
});
</code>```

In your controller return json response

```<code>public function proposegigs(Request $request){
    $gig = Gig::findOrFail($request->id);
    return response()->json(['data' => $gig]);
}
</code>```

Body:
I'm building a Laravel app with jQuery. I've a form with a select box(list of products) and text input fields.

My requirement is when I choose a product from the Select box at the top, the value of all other fields should update according to the products value that is fetched from database for the selected product.

This is my js script:

$(document).ready(function() {

    var divKey = $( "#proposed_product option:selected" ).val();

    $( "#proposed_product" ).change(function() {
        updateKeyValues();
    });

    function updateKeyValues() {
        $("#proposed_product").val(divKey);
        console.log(proposed_product); //what to do here..???

    }

});

My laravel function to return gigs list:

public function proposegigs($id){
    $gig = Gig::findOrFail($id);
    return $gig;

Can somebody help how to achieve this?

Body:
Make an ajax call to get the data

$( "#proposed_product" ).change(function() {
    $.ajaxSetup({
       headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
       url: "{{ route('your-route') }}",
       type: "POST",
       data: {id: $( "#proposed_product :selected" ).val()}, //send data to controller
       success: function(result){
           console.log(result);
           //check the console then put the data where you want
       }
    });

    $.ajax();
});

In your controller return json response

public function proposegigs(Request $request){
    $gig = Gig::findOrFail($request->id);
    return response()->json(['data' => $gig]);
}


问:
In preferences, select my sound just like with RingtonePreference
I have sounds in my /raw folder and I would like my user to be able to choose one sound in preferences exactly like RingtonePreference does but only with my sounds.</p>

答:
when making a ringtone preference customization i prefer that the ringtone only play for short while, sort of like a sample sounds. user does not need to hear the entire sound play if they are just choosing a sound from a list.  Here is how i achieve this:

first create a service that will play the ringtone (well use ringtone manager to play the sound instead of media player as its handling the cancelling for us):

public class PlayRingtoneService extends Service {
    static Ringtone r;
    private Handler handler;

```<code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //activating alarm sound
    if (r != null)
        r.stop();

    String filePath = intent.getStringExtra("uri");
    r = RingtoneManager.getRingtone(this, Uri.parse(filePath));
    r.play();

    handler.removeCallbacksAndMessages(null);

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if(r!=null)
                r.stop();
        }
    },6000L); //stop sound in 6 seconds

    return super.onStartCommand(intent, flags, startId);
}

void setThreadPriority(int priority) {

    try {
        Process.setThreadPriority(priority);
    } catch (Exception e) {
        Timber.e(e);
    }

}

@Override
public void onCreate() {
    super.onCreate();
     handler =new Handler();
    setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);

}

@Override
public void onDestroy() {
    if (r != null)
        r.stop();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
</code>```

}

also update the manifest with the service:

```<code><service android:name=".services.PlayRingtoneService" />
</code>```

then using the solutions above but modified you can create a list preference that behaves just like a ringtone preference:

```<code>public class CustomRingtoneListPreference extends ListPreference {

CharSequence[] mEntries;
CharSequence[] mEntryValues;
private int mClickedDialogEntryIndex;
private String mValue;

public CustomRingtoneListPreference(Context context) {
    super(context);
}

public CustomRingtoneListPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
}

/**
 * Returns the value of the key. This should be one of the entries in
 * {@link #getEntryValues()}.
 *
 * @return The value of the key.
 */
public String getValue() {
    return mValue;
}

/**
 * Sets the value of the key. This should be one of the entries in
 * {@link #getEntryValues()}.
 *
 * @param value The value to set for the key.
 */
public void setValue(String value) {
    mValue = value;

    persistString(value);
}

/**
 * Returns the entry corresponding to the current value.
 *
 * @return The entry corresponding to the current value, or null.
 */
public CharSequence getEntry() {
    int index = getValueIndex();
    return index >= 0 && mEntries != null ? mEntries[index] : null;
}

public int findIndexOfValue(String value) {
    if (value != null && mEntryValues != null) {
        for (int i = mEntryValues.length - 1; i >= 0; i--) {
            if (mEntryValues[i].equals(value)) {
                return i;
            }
        }
    }
    return -1;
}

private int getValueIndex() {

    return findIndexOfValue(mValue);
}

/**
 * Sets the value to the given index from the entry values.
 *
 * @param index The index of the value to set.
 */
public void setValueIndex(int index) {
    if (mEntryValues != null) {
        setValue(mEntryValues[index].toString());
    }
}

@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
    super.onPrepareDialogBuilder(builder);
    mEntries = getEntries();
    mEntryValues = getEntryValues();

    if (mEntries == null || mEntryValues == null) {
        throw new IllegalStateException(
                "ListPreference requires an entries array and an entryValues array.");
    }

    mClickedDialogEntryIndex = getValueIndex();
    builder.setSingleChoiceItems(mEntries, mClickedDialogEntryIndex,
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    mClickedDialogEntryIndex = which;

                    String value = mEntryValues[which].toString();
                        playSong(value);
                }
            });

    builder.setPositiveButton("Ok", this);
    builder.setNegativeButton("Cancel", this);
}

private void playSong(String path) {
    Intent i = new Intent(getContext(), PlayRingtoneService.class);
    i.putExtra("uri", path);
    getContext().startService(i);

}

@Override
protected void onRestoreInstanceState(Parcelable state) {
    if (state == null || !state.getClass().equals(SavedState.class)) {
        // Didn't save state for us in onSaveInstanceState
        super.onRestoreInstanceState(state);
        return;
    }

    SavedState myState = (SavedState) state;
    super.onRestoreInstanceState(myState.getSuperState());
    setValue(myState.value);
}

@Override
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);

    if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) {
        String value = mEntryValues[mClickedDialogEntryIndex].toString();
        if (callChangeListener(value)) {
            setValue(value);
        }
    }

    Intent i = new Intent(getContext(), PlayRingtoneService.class);
    getContext().stopService(i);
}

@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
    return a.getString(index);
}

@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {

    setValue(restoreValue ? getPersistedString(mValue) : (String) defaultValue);
}

@Override
protected Parcelable onSaveInstanceState() {
    final Parcelable superState = super.onSaveInstanceState();
    if (isPersistent()) {
        // No need to save instance state since it's persistent
        return superState;
    }

    final SavedState myState = new SavedState(superState);
    myState.value = getValue();
    return myState;
}

private static class SavedState extends BaseSavedState {
    public static final Parcelable.Creator<SavedState> CREATOR =
            new Parcelable.Creator<SavedState>() {
                public SavedState createFromParcel(Parcel in) {
                    return new SavedState(in);
                }

                public SavedState[] newArray(int size) {
                    return new SavedState[size];
                }
            };
    String value;

    public SavedState(Parcel source) {
        super(source);
        value = source.readString();
    }

    public SavedState(Parcelable superState) {
        super(superState);
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        super.writeToParcel(dest, flags);
        dest.writeString(value);
    }
}
</code>```

}

now in your xml use it like this:

```<code><mypackage.blah.blah.CustomRingtoneListPreference
            android:key="myRingtone"
            android:title="my title"
            android:summary="ringtone chosen %s"
            android:defaultValue="0"
            android:dependency="whatever you have"

            />
</code>```

now to actually load up the values into the list we create a utils method that can get all internal and external media and put it into our model class called songs defined like this:

```<code>public class Song {

private long id;
private Uri filePath;

private boolean externalPath;

/**
 * Creates a new Song, with specified `songID` and `filePath`.
 *
 * @note It's a unique Android identifier for a media file
 * anywhere on the system.
 */
public Song(long id, String title, String artist, Uri fileUri, boolean externalPath) {
    this.id = id;
    this.title = title;
    this.artist = artist;
    this.filePath = fileUri;
    this.externalPath = externalPath;
}

/**
 * Identifier for the song on the Android system.
 * (so we can locate the file anywhere)
 */
public long getId() {
    return id;
}

public Uri getFilePath() {
    return filePath;
}

public Song setFilePath(Uri filePath) {
    this.filePath = filePath;
    return this;
}

private String title = "";
private String artist = "";

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getArtist() {
    return artist;
}

public void setArtist(String artist) {
    this.artist = artist;
}

public boolean isExternalPath() {
    return externalPath;
}

public Song setIsExternalPath(boolean externalPath) {
    this.externalPath = externalPath;
    return this;
}
</code>```

}

Now in your Util class or just a static method if you want you do make this class which will query the media store for all audio files:

public static List getAllExternalAudioSongs(Context c) {
        List songList = new ArrayList<>();
        ContentResolver contentResolver = c.getContentResolver();

```<code>    List<Uri> contentUriLists = new ArrayList<>();
    contentUriLists.add(MediaStore.Audio.Media.INTERNAL_CONTENT_URI);
    contentUriLists.add(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
    String selection= MediaStore.Audio.Media.DURATION + ">= 3000";

    boolean externalPath = false;

    for (Uri uri : contentUriLists) {
        Cursor cursor = contentResolver.query(uri, null, selection, null, android.provider.MediaStore.Audio.Media.TITLE+ " ASC");
        if (cursor == null) {
            // query failed, handle error.
        } else if (!cursor.moveToFirst()) {
            // no media on the device
        } else {
            int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
            int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
            int artistColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);

            do {
                long id = cursor.getLong(idColumn);
                String title = cursor.getString(titleColumn);
                String artist = cursor.getString(artistColumn);
                Uri contentUri = ContentUris.withAppendedId(
                        uri, id);
                Song song = new Song(id, title, artist, contentUri, externalPath);
                songList.add(song);
            } while (cursor.moveToNext());
            externalPath=true;
        }
    }
    return songList;
}
</code>```

note: the externalPath is just if you want to differentiate internal from external audio files.

Finally, in onCreate of preferenceActivity (or fragment) you can do this:

```<code>private void setRingtoneList() {

    ListPreference listPreferenceCategory = (ListPreference) findPreference("myRingtone");
    if (listPreferenceCategory != null) {
        List<Song> songList = Utils.getAllExternalAudioSongs(getApplicationContext());
        CharSequence entries[] = new String[songList.size()];
        CharSequence entryValues[] = new String[songList.size()];
        int i = 0;
        for (Song song : songList) {
            entries[i] = song.getTitle();
            entryValues[i] = song.getFilePath().toString();
            i++;
        }
        listPreferenceCategory.setEntries(entries);
        listPreferenceCategory.setEntryValues(entryValues);
    }
}
</code>```

note: you'll need runtime permissions for external storage. and also to update the summary youll have to do that in the preference activity i believe. anyway this gives a good idea how to play sample audio instead of entire audio file.

Body:
when making a ringtone preference customization i prefer that the ringtone only play for short while, sort of like a sample sounds. user does not need to hear the entire sound play if they are just choosing a sound from a list.  Here is how i achieve this:

first create a service that will play the ringtone (well use ringtone manager to play the sound instead of media player as its handling the cancelling for us):

public class PlayRingtoneService extends Service {
    static Ringtone r;
    private Handler handler;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //activating alarm sound
    if (r != null)
        r.stop();

    String filePath = intent.getStringExtra("uri");
    r = RingtoneManager.getRingtone(this, Uri.parse(filePath));
    r.play();

    handler.removeCallbacksAndMessages(null);

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if(r!=null)
                r.stop();
        }
    },6000L); //stop sound in 6 seconds

    return super.onStartCommand(intent, flags, startId);
}

void setThreadPriority(int priority) {

    try {
        Process.setThreadPriority(priority);
    } catch (Exception e) {
        Timber.e(e);
    }

}

@Override
public void onCreate() {
    super.onCreate();
     handler =new Handler();
    setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);

}

@Override
public void onDestroy() {
    if (r != null)
        r.stop();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

}

also update the manifest with the service:

<service android:name=".services.PlayRingtoneService" />

then using the solutions above but modified you can create a list preference that behaves just like a ringtone preference:

public class CustomRingtoneListPreference extends ListPreference {

CharSequence[] mEntries;
CharSequence[] mEntryValues;
private int mClickedDialogEntryIndex;
private String mValue;

public CustomRingtoneListPreference(Context context) {
    super(context);
}

public CustomRingtoneListPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
}

/**
 * Returns the value of the key. This should be one of the entries in
 * {@link #getEntryValues()}.
 *
 * @return The value of the key.
 */
public String getValue() {
    return mValue;
}

/**
 * Sets the value of the key. This should be one of the entries in
 * {@link #getEntryValues()}.
 *
 * @param value The value to set for the key.
 */
public void setValue(String value) {
    mValue = value;

    persistString(value);
}

/**
 * Returns the entry corresponding to the current value.
 *
 * @return The entry corresponding to the current value, or null.
 */
public CharSequence getEntry() {
    int index = getValueIndex();
    return index >= 0 && mEntries != null ? mEntries[index] : null;
}

public int findIndexOfValue(String value) {
    if (value != null && mEntryValues != null) {
        for (int i = mEntryValues.length - 1; i >= 0; i--) {
            if (mEntryValues[i].equals(value)) {
                return i;
            }
        }
    }
    return -1;
}

private int getValueIndex() {

    return findIndexOfValue(mValue);
}

/**
 * Sets the value to the given index from the entry values.
 *
 * @param index The index of the value to set.
 */
public void setValueIndex(int index) {
    if (mEntryValues != null) {
        setValue(mEntryValues[index].toString());
    }
}

@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
    super.onPrepareDialogBuilder(builder);
    mEntries = getEntries();
    mEntryValues = getEntryValues();

    if (mEntries == null || mEntryValues == null) {
        throw new IllegalStateException(
                "ListPreference requires an entries array and an entryValues array.");
    }

    mClickedDialogEntryIndex = getValueIndex();
    builder.setSingleChoiceItems(mEntries, mClickedDialogEntryIndex,
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    mClickedDialogEntryIndex = which;

                    String value = mEntryValues[which].toString();
                        playSong(value);
                }
            });

    builder.setPositiveButton("Ok", this);
    builder.setNegativeButton("Cancel", this);
}

private void playSong(String path) {
    Intent i = new Intent(getContext(), PlayRingtoneService.class);
    i.putExtra("uri", path);
    getContext().startService(i);

}

@Override
protected void onRestoreInstanceState(Parcelable state) {
    if (state == null || !state.getClass().equals(SavedState.class)) {
        // Didn't save state for us in onSaveInstanceState
        super.onRestoreInstanceState(state);
        return;
    }

    SavedState myState = (SavedState) state;
    super.onRestoreInstanceState(myState.getSuperState());
    setValue(myState.value);
}

@Override
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);

    if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) {
        String value = mEntryValues[mClickedDialogEntryIndex].toString();
        if (callChangeListener(value)) {
            setValue(value);
        }
    }

    Intent i = new Intent(getContext(), PlayRingtoneService.class);
    getContext().stopService(i);
}

@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
    return a.getString(index);
}

@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {

    setValue(restoreValue ? getPersistedString(mValue) : (String) defaultValue);
}

@Override
protected Parcelable onSaveInstanceState() {
    final Parcelable superState = super.onSaveInstanceState();
    if (isPersistent()) {
        // No need to save instance state since it's persistent
        return superState;
    }

    final SavedState myState = new SavedState(superState);
    myState.value = getValue();
    return myState;
}

private static class SavedState extends BaseSavedState {
    public static final Parcelable.Creator<SavedState> CREATOR =
            new Parcelable.Creator<SavedState>() {
                public SavedState createFromParcel(Parcel in) {
                    return new SavedState(in);
                }

                public SavedState[] newArray(int size) {
                    return new SavedState[size];
                }
            };
    String value;

    public SavedState(Parcel source) {
        super(source);
        value = source.readString();
    }

    public SavedState(Parcelable superState) {
        super(superState);
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        super.writeToParcel(dest, flags);
        dest.writeString(value);
    }
}

}

now in your xml use it like this:

<mypackage.blah.blah.CustomRingtoneListPreference
            android:key="myRingtone"
            android:title="my title"
            android:summary="ringtone chosen %s"
            android:defaultValue="0"
            android:dependency="whatever you have"

            />

now to actually load up the values into the list we create a utils method that can get all internal and external media and put it into our model class called songs defined like this:

public class Song {

private long id;
private Uri filePath;

private boolean externalPath;

/**
 * Creates a new Song, with specified `songID` and `filePath`.
 *
 * @note It's a unique Android identifier for a media file
 * anywhere on the system.
 */
public Song(long id, String title, String artist, Uri fileUri, boolean externalPath) {
    this.id = id;
    this.title = title;
    this.artist = artist;
    this.filePath = fileUri;
    this.externalPath = externalPath;
}

/**
 * Identifier for the song on the Android system.
 * (so we can locate the file anywhere)
 */
public long getId() {
    return id;
}

public Uri getFilePath() {
    return filePath;
}

public Song setFilePath(Uri filePath) {
    this.filePath = filePath;
    return this;
}

private String title = "";
private String artist = "";

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getArtist() {
    return artist;
}

public void setArtist(String artist) {
    this.artist = artist;
}

public boolean isExternalPath() {
    return externalPath;
}

public Song setIsExternalPath(boolean externalPath) {
    this.externalPath = externalPath;
    return this;
}

}

Now in your Util class or just a static method if you want you do make this class which will query the media store for all audio files:

public static List getAllExternalAudioSongs(Context c) {
        List songList = new ArrayList<>();
        ContentResolver contentResolver = c.getContentResolver();

    List<Uri> contentUriLists = new ArrayList<>();
    contentUriLists.add(MediaStore.Audio.Media.INTERNAL_CONTENT_URI);
    contentUriLists.add(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
    String selection= MediaStore.Audio.Media.DURATION + ">= 3000";

    boolean externalPath = false;

    for (Uri uri : contentUriLists) {
        Cursor cursor = contentResolver.query(uri, null, selection, null, android.provider.MediaStore.Audio.Media.TITLE+ " ASC");
        if (cursor == null) {
            // query failed, handle error.
        } else if (!cursor.moveToFirst()) {
            // no media on the device
        } else {
            int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
            int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
            int artistColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);

            do {
                long id = cursor.getLong(idColumn);
                String title = cursor.getString(titleColumn);
                String artist = cursor.getString(artistColumn);
                Uri contentUri = ContentUris.withAppendedId(
                        uri, id);
                Song song = new Song(id, title, artist, contentUri, externalPath);
                songList.add(song);
            } while (cursor.moveToNext());
            externalPath=true;
        }
    }
    return songList;
}

note: the externalPath is just if you want to differentiate internal from external audio files.

Finally, in onCreate of preferenceActivity (or fragment) you can do this:

private void setRingtoneList() {

    ListPreference listPreferenceCategory = (ListPreference) findPreference("myRingtone");
    if (listPreferenceCategory != null) {
        List<Song> songList = Utils.getAllExternalAudioSongs(getApplicationContext());
        CharSequence entries[] = new String[songList.size()];
        CharSequence entryValues[] = new String[songList.size()];
        int i = 0;
        for (Song song : songList) {
            entries[i] = song.getTitle();
            entryValues[i] = song.getFilePath().toString();
            i++;
        }
        listPreferenceCategory.setEntries(entries);
        listPreferenceCategory.setEntryValues(entryValues);
    }
}

note: you'll need runtime permissions for external storage. and also to update the summary youll have to do that in the preference activity i believe. anyway this gives a good idea how to play sample audio instead of entire audio file.


问:
i got an error while calling non abstract method via child class
```<code>    class Program
    {
        static void Main(string[] args)
        {
    // in here iam create an instance of child class
            var obj = new dog("meat");
            obj.run();
            obj.sleep();

            Console.ReadLine();

        }
    }
    abstract class animal {
        protected string eating;
        abstract public void sound();

        public void run() {
            Console.WriteLine("Runnig");
        }
        public void sleep()
        {
            Console.WriteLine("sleeping");
        }
    }
    class cat : animal
    {
        public cat(string eat) {
            this.eating = eat;
        }
// this is my child class define parent class method
        protected override void sound()
        {
            Console.WriteLine("Meow");

        }
    }
    class dog : animal{

        public dog(string eat){
            this.eating = eat;
        }
        public override void sound()
        {
            Console.WriteLine("Woof");

        }
    }
</code>```

<p>// Error : Error    1   'Abbstraction.cat.sound()': cannot change access modifiers when overriding 'public' inherited member 'Abbstraction.animal.sound()'  E:\C sharp\ObjectOrientedConcept\Abbstraction\Program.cs    39  33  Abbstraction</p>

答:
You define the abstract method signature sound() in the abstract class Animal as public.

Later you try to change the access modifier to protected. This is not allowed. You have to stick to the modifier defined in the base class.

Body:
    class Program
    {
        static void Main(string[] args)
        {
    // in here iam create an instance of child class
            var obj = new dog("meat");
            obj.run();
            obj.sleep();

            Console.ReadLine();

        }
    }
    abstract class animal {
        protected string eating;
        abstract public void sound();

        public void run() {
            Console.WriteLine("Runnig");
        }
        public void sleep()
        {
            Console.WriteLine("sleeping");
        }
    }
    class cat : animal
    {
        public cat(string eat) {
            this.eating = eat;
        }
// this is my child class define parent class method
        protected override void sound()
        {
            Console.WriteLine("Meow");

        }
    }
    class dog : animal{

        public dog(string eat){
            this.eating = eat;
        }
        public override void sound()
        {
            Console.WriteLine("Woof");

        }
    }

// Error : Error    1   'Abbstraction.cat.sound()': cannot change access modifiers when overriding 'public' inherited member 'Abbstraction.animal.sound()'  E:\C sharp\ObjectOrientedConcept\Abbstraction\Program.cs    39  33  Abbstraction


问:
How to Endpoint.broadcast to the topic and event of another channel?
I have two channels defined.
First One is

```<code>defmodule AppServerWeb.FirstChannel do
  use Phoenix.Channel

  def join("first:*", auth_key, socket) do
      send(self, {:after_join, 12})
      {:ok, socket}
  end

  def handle_info({:after_join, count}, socket) do
        App.Endpoint.broadcast "second:*", "activeusers", %{users: count}
        {:noreply, socket}
  end

  def handle_out(event, payload, socket) do
      push socket, event, payload
      {:noreply, socket}
  end

end
</code>```

And second one is

```<code>defmodule AppServerWeb.SecondChannel do
  use Phoenix.Channel

  def join("second:*", auth_key, socket) do
      {:ok, socket}
  end

  def handle_out(event, payload, socket) do
      push socket, event, payload
      {:noreply, socket}
  end

end
</code>```

And in my client side I have

```<code>socket = new Phoenix.Socket("/socket", {params: {userToken: "123"}})
socket.connect();
channel1 = socket.channel("first:*", {auth: "foo"})
channel2 = socket.channel("second:*", {auth: "foo"})
channel1.join()   //successful join
channel2.join()   //successful join
channel2.on("activeusers", function (msg) {
        console.log(msg)   //This one never triggers
});
</code>```

So basically all i need is to broadcast on a topic from channel one and listen to it from a client joined to channel2, this is as far as i can go reading docs, which is not working.. where did i screw up?

答:
According to the documentation on Phoenix.Channel:

In some cases, you will want to broadcast messages without the context of a socket. This could be for broadcasting from within your channel to an external topic, or broadcasting from elsewhere in your application like a controller or another process. Such can be done via your endpoint:

```<code># within channel
def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do
  ...
  broadcast_from! socket, "new_msg", %{uid: uid, body: body}
  MyApp.Endpoint.broadcast_from! self(), "room:superadmin",
    "new_msg", %{uid: uid, body: body}
  {:noreply, socket}
end
</code>```

That said, you should use broadcast_from!/4 passing self() as the first parameter.

Body:
I have two channels defined.
First One is

defmodule AppServerWeb.FirstChannel do
  use Phoenix.Channel

  def join("first:*", auth_key, socket) do
      send(self, {:after_join, 12})
      {:ok, socket}
  end

  def handle_info({:after_join, count}, socket) do
        App.Endpoint.broadcast "second:*", "activeusers", %{users: count}
        {:noreply, socket}
  end

  def handle_out(event, payload, socket) do
      push socket, event, payload
      {:noreply, socket}
  end

end

And second one is

defmodule AppServerWeb.SecondChannel do
  use Phoenix.Channel

  def join("second:*", auth_key, socket) do
      {:ok, socket}
  end

  def handle_out(event, payload, socket) do
      push socket, event, payload
      {:noreply, socket}
  end

end

And in my client side I have

socket = new Phoenix.Socket("/socket", {params: {userToken: "123"}})
socket.connect();
channel1 = socket.channel("first:*", {auth: "foo"})
channel2 = socket.channel("second:*", {auth: "foo"})
channel1.join()   //successful join
channel2.join()   //successful join
channel2.on("activeusers", function (msg) {
        console.log(msg)   //This one never triggers
});

So basically all i need is to broadcast on a topic from channel one and listen to it from a client joined to channel2, this is as far as i can go reading docs, which is not working.. where did i screw up?

Body:
According to the documentation on Phoenix.Channel:

In some cases, you will want to broadcast messages without the context of a socket. This could be for broadcasting from within your channel to an external topic, or broadcasting from elsewhere in your application like a controller or another process. Such can be done via your endpoint:

# within channel
def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do
  ...
  broadcast_from! socket, "new_msg", %{uid: uid, body: body}
  MyApp.Endpoint.broadcast_from! self(), "room:superadmin",
    "new_msg", %{uid: uid, body: body}
  {:noreply, socket}
end

That said, you should use broadcast_from!/4 passing self() as the first parameter.


问:
Next Button is working but the Previous Button wont work (Tabs)
I'm a student and new to PHP. I'm currently working on a Skill Test project that displays one question on each tab and I included previous and next buttons that should be responsive/automatic. For example, if Im in tab 2, the previous button should lead to tab 1 and the next button to tab 3. If I go to tab 3, the prev btn should lead to tab 2 and the next btn to tab 4, and so on.. The next button is working perfectly fine but I dont have an idea why the previous button wont work. I hope someone can help me with this. Please. Thank you so much!

Here is my code:

```<code>        <script>
        function openTab(evt, tabName) {
            var i, tabcontent, tablinks;
            tabcontent = document.getElementsByClassName("tabcontent");
            for (i = 0; i < tabcontent.length; i++) {
                tabcontent[i].style.display = "none";
            }
            tablinks = document.getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace(" active", "");
            }
            document.getElementById(tabName).style.display = "block";
            evt.currentTarget.className += " active";
        }
        document.getElementById("defaultOpen").click();
        </script>

        <div class="tab">
          <button class="btn btn-default btnPrevious" data-direction="previous" type="button" onclick=""><span class="glyphicon glyphicon-triangle-left"></span></button>
          <button class="tablinks" type="button" onclick="openTab(event, 'q1')" id="defaultOpen">1</button>
          <button class="tablinks" type="button" onclick="openTab(event, 'q2')">2</button>
          <button class="tablinks" type="button" onclick="openTab(event, 'q3')">3</button>
          <button class="tablinks" type="button" onclick="openTab(event, 'q4')">4</button>
          <button class="btn btn-default btnNext" data-direction="next" type="button" onclick=""><span class="glyphicon glyphicon-triangle-right"></span></button>
        </div>

      <form action="results.php" method="POST">
        <?php if (mysqli_num_rows($result) > 0): ?>
        <?php $index = 1; ?>
            <?php foreach ($result as $results):?>
                <div id="q<?php echo ($index++); ?>" class="tabcontent">
                    <table class="table table-hover">
                    <tbody>
                        <tr class="form-group">
                            <h3 name="ques[<?php echo $test_id;?>]" style="text-indent: 40px;"> <?php echo $results['question']; ?> </h3>
                        </tr>
                        <tr class="form-group">
                            <label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
                                  <input style="font-size: 18px;" type="radio" name="ans[<?php echo $results['test_id'];?>" value="<?php echo $results['optiona'];?>"><?php echo $results['optiona'];?>
                            </label>
                            <br>
                            <label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
                                   <input style="font-size: 18px;" type="radio" name="ans[<?php echo $results['test_id'];?>" value="<?php echo $results['optionb'];?>"><?php echo $results['optionb'];?>
                            </label>
                            <br>
                            <label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
                                   <input style="font-size: 18px;" type="radio" name="ans[<?php echo $results['test_id'];?>" value="<?php echo $results['optionc'];?>"><?php echo $results['optiond'];?>
                            </label>
                            <br>
                            <label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
                                   <input style="font-size: 18px;" type="radio" ame="ans[<?php echo $results['test_id'];?>" value="<?php echo $results['optiond'];?>"><?php echo $results['optiond'];?>
                            </label>
                            <br>
                        </tr>
                    </tbody>
                    </table>
                    <center>
                        <button class="btn btn-default btnBack" data-direction="back" type="button" onclick="openTab(event, 'q<?php echo ($index-=1); ?>')"><span class="glyphicon glyphicon-triangle-left"></span>   Back</button>
                        <button class="btn btn-default btnNext" data-direction="next" type="button" onclick="openTab(event, 'q<?php echo ($index+=1); ?>')"><span class="glyphicon glyphicon-triangle-right"></span>  Next</button>
                    </center>
                </div>
            <?php endforeach ?>
        <?php endif ?>
</code>```

答:
Check this works for you

$('.btn-right').click(function(){
  $('.nav-tabs > .active').next('li').find('a').trigger('click');
});

  $('.btn-left').click(function(){
  $('.nav-tabs > .active').prev('li').find('a').trigger('click');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a.btn-left,a.btn-right{
  display:inline-block;
  padding:5px 10px;
  font-size:24px;
  cursor:pointer;
}
.tab_desc {
  min-height: 150px;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

Home

About

Cases

Experience

HOME

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Menu 1

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Menu 2

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.

Menu 3

Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

```

Body:
I'm a student and new to PHP. I'm currently working on a Skill Test project that displays one question on each tab and I included previous and next buttons that should be responsive/automatic. For example, if Im in tab 2, the previous button should lead to tab 1 and the next button to tab 3. If I go to tab 3, the prev btn should lead to tab 2 and the next btn to tab 4, and so on.. The next button is working perfectly fine but I dont have an idea why the previous button wont work. I hope someone can help me with this. Please. Thank you so much!

Here is my code:

          <button class="btn btn-default btnPrevious" data-direction="previous" type="button" onclick=""></button>
          <button class="tablinks" type="button" onclick="openTab(event, 'q1')" id="defaultOpen">1</button>
          <button class="tablinks" type="button" onclick="openTab(event, 'q2')">2</button>
          <button class="tablinks" type="button" onclick="openTab(event, 'q3')">3</button>
          <button class="tablinks" type="button" onclick="openTab(event, 'q4')">4</button>
          <button class="btn btn-default btnNext" data-direction="next" type="button" onclick=""></button>

      <form action="results.php" method="POST">
        <?php if (mysqli_num_rows($result) > 0): ?>
        <?php $index = 1; ?>
            <?php foreach ($result as $results):?>
                <div id="q<?php echo ($index++); ?>" class="tabcontent">

                            <h3 name="ques[<?php echo $test_id;?>]" style="text-indent: 40px;"> <?php echo $results['question']; ?>

                                  <input style="font-size: 18px;" type="radio" name="ans[<?php echo $results['test_id'];?>" value="<?php echo $results['optiona'];?>"><?php echo $results['optiona'];?>

                                   <input style="font-size: 18px;" type="radio" name="ans[<?php echo $results['test_id'];?>" value="<?php echo $results['optionb'];?>"><?php echo $results['optionb'];?>

                                   <input style="font-size: 18px;" type="radio" name="ans[<?php echo $results['test_id'];?>" value="<?php echo $results['optionc'];?>"><?php echo $results['optiond'];?>

                                   <input style="font-size: 18px;" type="radio" ame="ans[<?php echo $results['test_id'];?>" value="<?php echo $results['optiond'];?>"><?php echo $results['optiond'];?>

                        <button class="btn btn-default btnBack" data-direction="back" type="button" onclick="openTab(event, 'q<?php echo ($index-=1); ?>')">   Back</button>
                        <button class="btn btn-default btnNext" data-direction="next" type="button" onclick="openTab(event, 'q<?php echo ($index+=1); ?>')">  Next</button>

            <?php endforeach ?>
        <?php endif ?>

Body:
Check this works for you

$('.btn-right').click(function(){
  $('.nav-tabs > .active').next('li').find('a').trigger('click');
});

  $('.btn-left').click(function(){
  $('.nav-tabs > .active').prev('li').find('a').trigger('click');
});

a.btn-left,a.btn-right{
  display:inline-block;
  padding:5px 10px;
  font-size:24px;
  cursor:pointer;
}
.tab_desc {
  min-height: 150px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">

    <ul class="nav nav-tabs">
        <li class="active"><a data-toggle="tab" href="#home">Home</a></li>
        <li><a data-toggle="tab" href="#menu1">About</a></li>
        <li><a data-toggle="tab" href="#menu2">Cases</a></li>
        <li><a data-toggle="tab" href="#menu3">Experience</a></li>
    </ul>

    <div class="tab-content">
        <div id="home" class="tab-pane fade in active">
            <div class="tab_desc">
                <h3>HOME</h3>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
            </div>
            <div class="pull-right pagination">
                <a class="btn-right" id="btnNext"><i class="fa fa-arrow-circle-right"></i></a>
            </div>
        </div>
        <div id="menu1" class="tab-pane fade">
            <div class="tab_desc">
                <h3>Menu 1</h3>
                <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
            </div>
            <div class="pull-right pagination">
                <a class="btn-left"><i class="fa fa-arrow-circle-left"></i></a>
                <a class="btn-right"><i class="fa fa-arrow-circle-right"></i></a>
            </div>
        </div>
        <div id="menu2" class="tab-pane fade">
            <div class="tab_desc">
                <h3>Menu 2</h3>
                <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.</p>
            </div>
            <div class="pull-right pagination">
                <a class="btn-left"><i class="fa fa-arrow-circle-left"></i></a>
                <a class="btn-right"><i class="fa fa-arrow-circle-right"></i></a>
            </div>
        </div>
        <div id="menu3" class="tab-pane fade">
            <div class="tab_desc">
                <h3>Menu 3</h3>
                <p>Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
            </div>
            <div class="pull-right pagination">
                <a class="btn-left"><i class="fa fa-arrow-circle-left"></i></a>
            </div>
        </div>
    </div>
</div>


问:
Linux-Live-system inc. Ruby 1.9 on USB-Stick with r/w-Partition
well guess that many of you have great expertise on Linux. I currently have some issues with creating a linux-live-medium.

i have a box with OpenSuse-Linux Version 11.3 with all nice things. Several languages run very well: Perl, Python, PHP! All is very well! BTW - i am very glad that Perl runs very nice.

But I am not able to install Ruby 1.9. Everytime i want to do that i end up with Ruby 1.8.7. I want to testrun some ruby-code. Therefore i need Ruby with the following gems

mechanize
nokogiri
utf8_utils

I heard of a Linux-Live-medium that is able to run with all the wanted things including Ruby 1.9.
Therefore the Live-medium is installed on a USB-Stick with R/W partitions. Is this possible.

I am not a linux-expert - but with all the expertise here i think it is possible to create such a USB-Stick. (...with Ruby 1.9 and all with all that extensions)
I love to hear from you!

best regards
zero

答:
Debian/Ubuntu includes both Ruby 1.8.x and 1.9.x - and essentially duplicates most packages in 2 flavors: for 1.8 and 1.9. That might be enough for your purposes - although YMMV, of course.

Yet another solution is RVM that karudzo already mentioned.

Yet another solution is virtualization: simplest form of it would be just chrooting. Most modern Linux systems have an ability to install itself based from some root directory (SuSE has install into given directory functionality, Debian/Ubuntu have debootstrap - and then just running chroot /path/to/that/directory - you'd end up in essentially another system installed cleanly in separate directory.


问:
How to print diamond shape w/ c++
I need help, I created a short little program a while ago where it would print a simple pyramid with "*" like this:

```<code>  *
 ***
*****
</code>```

but I decided to challenge myself and see if I could create a simple diamond shape like this:

```<code>  *
 ***
*****
 ***
  *
</code>```

Here is my code so far.
I should also add that the value you input, for example 5, determines how big the diamond is.

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

int main() {

int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;

for (int i = 0; i < value; i++) {
    //print spaces v v v
    for (int x = 0; x < (value - i - 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (2 * i + 1); y++) {
        cout << "*";
    }
    cout << endl;
}

for (int i = 0; i < value; i++) {
    int number = 0;
    number+= 2;
    //print spaces v v v
    for (int x = 0; x < (value - value + i + 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (/*ATTENTION: What do I do here? Plz help*/); y++) {
        cout << "*";
    }
    cout << endl;
}

return 0;
}
</code>```

What I've been trying to do is figure out what to put inside the parenthesis where it says (//ATTENTION). I've been working for at least an hour trying to do random things, and one time it worked when I input 4, but not for 5, and it's just been very hard. This is key to building the diamond, try putting in just value and compile to see what happens. I need it to be symmetrical.

I need to know what to put inside the parenthesis please. I'm sorry this is very long but the help would be appreciated thanks.

I also apologize if my code is messy and hard to read.

答:
```<code>#include <iostream>
#include <sstream>
using namespace std;

int main() {

int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;

for (int i = 0; i < value; i++) {
    //print spaces v v v
    for (int x = 0; x < (value - i - 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (2 * i + 1); y++) {
        cout << "*";
    }
    cout << endl;
}

for (int i = 0; i < value-1; i++) {
//    int number = 0;
//    number+= 2;
//    //print spaces v v v

    for (int x = 0; x < i+1; x++) {
        cout << " ";
    }
    //print * v v v
     for (int y = 0; y < (2*(value-1-i)-1); y++) {
        cout << "*";
        }
    cout << endl;
}

return 0;
}
</code>```

I hope that you will get this .Also in the second for loop you were iterating it one extra time by iterating the loop upto value. But since the pyramid is symmetric so the no of rows in the pyramid will be 2*value-1.So I in the second loop i should vary upto value -1.

Title: How to print diamond shape w/ c++

Body:
I need help, I created a short little program a while ago where it would print a simple pyramid with "*" like this:

  *
 ***
*****

but I decided to challenge myself and see if I could create a simple diamond shape like this:

  *
 ***
*****
 ***
  *

Here is my code so far.
I should also add that the value you input, for example 5, determines how big the diamond is.

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

int main() {

int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;

for (int i = 0; i < value; i++) {
    //print spaces v v v
    for (int x = 0; x < (value - i - 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (2 * i + 1); y++) {
        cout << "*";
    }
    cout << endl;
}

for (int i = 0; i < value; i++) {
    int number = 0;
    number+= 2;
    //print spaces v v v
    for (int x = 0; x < (value - value + i + 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (/*ATTENTION: What do I do here? Plz help*/); y++) {
        cout << "*";
    }
    cout << endl;
}

return 0;
}

What I've been trying to do is figure out what to put inside the parenthesis where it says (//ATTENTION). I've been working for at least an hour trying to do random things, and one time it worked when I input 4, but not for 5, and it's just been very hard. This is key to building the diamond, try putting in just value and compile to see what happens. I need it to be symmetrical.

I need to know what to put inside the parenthesis please. I'm sorry this is very long but the help would be appreciated thanks.

I also apologize if my code is messy and hard to read.

Body:
#include <iostream>
#include <sstream>
using namespace std;

int main() {

int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;

for (int i = 0; i < value; i++) {
    //print spaces v v v
    for (int x = 0; x < (value - i - 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (2 * i + 1); y++) {
        cout << "*";
    }
    cout << endl;
}

for (int i = 0; i < value-1; i++) {
//    int number = 0;
//    number+= 2;
//    //print spaces v v v

    for (int x = 0; x < i+1; x++) {
        cout << " ";
    }
    //print * v v v
     for (int y = 0; y < (2*(value-1-i)-1); y++) {
        cout << "*";
        }
    cout << endl;
}

return 0;
}

I hope that you will get this .Also in the second for loop you were iterating it one extra time by iterating the loop upto value. But since the pyramid is symmetric so the no of rows in the pyramid will be 2*value-1.So I in the second loop i should vary upto value -1.


问:
How to have inner select inside pdo queries?
I'm not sure how to name the question exactly, and since I wasn't able to have a better title I wasn't able to search much for the same issue that might have been asked before.

I have a one to many relationship in my database, the data is spread across a few tables.

```<code>public function get_recipe_data($id){
    $sth = $this->db->prepare('SELECT * FROM
                               recipe as recipe
                               LEFT JOIN recipe_introduction as introduction
                               ON recipe.id = introduction.recipe_id
                               LEFT JOIN recipe_ingredients as ingredients
                               ON recipe.id = ingredients.recipe_id
                               LEFT JOIN recipe_ingredients_notes as notes
                               ON recipe.id = notes.recipe_id
                               LEFT JOIN recipe_macros as macros
                               ON recipe.id = macros.recipe_id
                               WHERE recipe.id = :id
    ');
    $sth->bindValue(':id', $id, PDO::PARAM_INT);
    $sth->execute();

    return $sth->fetch(PDO::FETCH_ASSOC);
}

public function convertCategoryId($category_id){
    $sth = $this->db->prepare('SELECT name FROM recipe_categories WHERE id = :category_id');
    $sth->bindValue(':category_id', $category_id, PDO::PARAM_INT);
    $sth->execute();

    return $sth->fetch(PDO::FETCH_ASSOC);
}
</code>```

In the recipe table there's a column that has an id for category name, and refers to another table.

recipe table

```<code>+----+-------+-------------+
| id | title | category_id |
+--------------------------+
| 1  |  ...  |      1      |
+----+-------+-------------+
| 2  |  ...  |      3      |
+----+-------+-------------+
</code>```

I have this other table

recipe_categories

```<code>+----+------------+
| id |    name    |
+----+------------+
| 1  |  breakfast |
+----+------------+
| 2  |    lunch   |
+----+------------+
| 3  |   dinner   |
+----+------------+
| .. |    ...     |
+----+------------+
</code>```

Right now I'm having to return the results from the first query above, and then once I have that, I run another method in the class passing the category_id from the first query, and then match it to the recipe_categories, but that's so inefficient.

Is there a way for me to be able to select the name straight off from the first query?

答:
Just join the category table to the recipe table, this will give you access to the categroty name in a single query.

```<code>SELECT
      *
FROM recipe AS recipe
INNER JOIN recipe_categories AS rcat ON recipe.category_id = rcat.id
LEFT JOIN recipe_introduction AS introduction ON recipe.id = introduction.recipe_id
LEFT JOIN recipe_ingredients AS ingredients ON recipe.id = ingredients.recipe_id
LEFT JOIN recipe_ingredients_notes AS notes ON recipe.id = notes.recipe_id
LEFT JOIN recipe_macros AS macros ON recipe.id = macros.recipe_id
WHERE recipe.id = id
</code>```

Note. Whilst it appears common practice amongst PHP users to use "select *" the best practice is you should specify each and every column that you want returned and not leave it to chance.

Body:
I'm not sure how to name the question exactly, and since I wasn't able to have a better title I wasn't able to search much for the same issue that might have been asked before.

I have a one to many relationship in my database, the data is spread across a few tables.

public function get_recipe_data($id){
    $sth = $this->db->prepare('SELECT * FROM
                               recipe as recipe
                               LEFT JOIN recipe_introduction as introduction
                               ON recipe.id = introduction.recipe_id
                               LEFT JOIN recipe_ingredients as ingredients
                               ON recipe.id = ingredients.recipe_id
                               LEFT JOIN recipe_ingredients_notes as notes
                               ON recipe.id = notes.recipe_id
                               LEFT JOIN recipe_macros as macros
                               ON recipe.id = macros.recipe_id
                               WHERE recipe.id = :id
    ');
    $sth->bindValue(':id', $id, PDO::PARAM_INT);
    $sth->execute();

    return $sth->fetch(PDO::FETCH_ASSOC);
}

public function convertCategoryId($category_id){
    $sth = $this->db->prepare('SELECT name FROM recipe_categories WHERE id = :category_id');
    $sth->bindValue(':category_id', $category_id, PDO::PARAM_INT);
    $sth->execute();

    return $sth->fetch(PDO::FETCH_ASSOC);
}

In the recipe table there's a column that has an id for category name, and refers to another table.

recipe table

+----+-------+-------------+
| id | title | category_id |
+--------------------------+
| 1  |  ...  |      1      |
+----+-------+-------------+
| 2  |  ...  |      3      |
+----+-------+-------------+

I have this other table

recipe_categories

+----+------------+
| id |    name    |
+----+------------+
| 1  |  breakfast |
+----+------------+
| 2  |    lunch   |
+----+------------+
| 3  |   dinner   |
+----+------------+
| .. |    ...     |
+----+------------+

Right now I'm having to return the results from the first query above, and then once I have that, I run another method in the class passing the category_id from the first query, and then match it to the recipe_categories, but that's so inefficient.

Is there a way for me to be able to select the name straight off from the first query?

Body:
Just join the category table to the recipe table, this will give you access to the categroty name in a single query.

SELECT
      *
FROM recipe AS recipe
INNER JOIN recipe_categories AS rcat ON recipe.category_id = rcat.id
LEFT JOIN recipe_introduction AS introduction ON recipe.id = introduction.recipe_id
LEFT JOIN recipe_ingredients AS ingredients ON recipe.id = ingredients.recipe_id
LEFT JOIN recipe_ingredients_notes AS notes ON recipe.id = notes.recipe_id
LEFT JOIN recipe_macros AS macros ON recipe.id = macros.recipe_id
WHERE recipe.id = id

Note. Whilst it appears common practice amongst PHP users to use "select *" the best practice is you should specify each and every column that you want returned and not leave it to chance.


问:
Difference between turtle.listen() and screen.listen()
Is there any difference between window.listen(), screen.listen(), and turtle.listen()?

I see them used differently in various programs but assume they can be called interchangeably.

答: I suggest you read Difference between turtle and Turtle?.  The short answer is that the turtle library provides two API's, a function-based one and an object-oriented one.  (Behind the scene, the function one is built atop the object one at load time.) The confusion begins when you mix the two.  My answer in the link explains one way to avoid doing so.</p>


问:
How do I delete duplicate rows in this (mildly) complicated MySQL database situation?
Ok.  Please bear with me, I suck at explaining things.

I have a database of contact information that is gathered through a form on a website.  Obviously, people press submit more than once accidentally (or on purpose, but fixing is a different issue) so there are a LOT of duplicate rows in this database.

So, table1 holds contact information as such:

```<code>ID  |  date  |  unique ID code  |  first name, blah blah
1      stuff    20110101ba78b      joe
</code>```

And table2 holds related data joined by the unique ID code field, as such:

```<code>ID  |  data  |  unique ID code
1      a        20110101ba78b
2      b        20110101ba78b
</code>```

So, table2 holds multiple values for each person.  That's the structure of the table (and there are about a million rows in table2, so I'd rather not change the structure right now).

So my dilemma is this:  I know it's easy to make a temporary table and SELECT DISTINCT(all fields), but I want to keep the unique ID field for at least 1 of the duplicate rows.  If I keep the unique ID field though, it is unique for each row, even if the other data is exactly the same so SELECT DISTINCT(all fields) will not work, it will keep every row.  Hopefully I explained this thoroughly.  Please ask me for more information if needed.

EDIT:  I'm sure I could get rid of the ID field for each table, but as far as I'm concerned it's just .... there to be there.

答:
This to update Table 2 to use the lowest uniqueID number for identical contact info:

```
UPDATE Table2
SET Table2.uniqueID = (
    SELECT T1.UniqueID
    FROM Table1 T1, Table1 T2
    WHERE T1.unique ID &lt T2.unique ID
    AND T1.firstname = T2.firstname
    AND T1.date = T2.date
    AND T1.blah, blah = T2.blah, blah
)
WHERE Table2.uniqueID = (
    Select T1.UniqueID
    from Table1 T1, CopyOfTable1 T2
    where T1.firstname = T2.firstname
    and T1.date = T2.date
    and T1.blah, blah = T2.blah, blah
);

```

This to remove all except ONE (with the lowest uniqueID) duplicate contact info records:

```
delete T1
from Table1 T1, CopyOfTable1 T2
where T1.unique ID > T2.unique ID
and T1.firstname = T2.firstname
and T1.date = T2.date
and T1.blah, blah = T2.blah, blah
```

Body:
Ok.  Please bear with me, I suck at explaining things.

I have a database of contact information that is gathered through a form on a website.  Obviously, people press submit more than once accidentally (or on purpose, but fixing is a different issue) so there are a LOT of duplicate rows in this database.

So, table1 holds contact information as such:

ID  |  date  |  unique ID code  |  first name, blah blah
1      stuff    20110101ba78b      joe

And table2 holds related data joined by the unique ID code field, as such:

ID  |  data  |  unique ID code
1      a        20110101ba78b
2      b        20110101ba78b

So, table2 holds multiple values for each person.  That's the structure of the table (and there are about a million rows in table2, so I'd rather not change the structure right now).

So my dilemma is this:  I know it's easy to make a temporary table and SELECT DISTINCT(all fields), but I want to keep the unique ID field for at least 1 of the duplicate rows.  If I keep the unique ID field though, it is unique for each row, even if the other data is exactly the same so SELECT DISTINCT(all fields) will not work, it will keep every row.  Hopefully I explained this thoroughly.  Please ask me for more information if needed.

EDIT:  I'm sure I could get rid of the ID field for each table, but as far as I'm concerned it's just .... there to be there.

Body:
This to update Table 2 to use the lowest uniqueID number for identical contact info:

UPDATE Table2
SET Table2.uniqueID = (
    SELECT T1.UniqueID
    FROM Table1 T1, Table1 T2
    WHERE T1.unique ID &lt T2.unique ID
    AND T1.firstname = T2.firstname
    AND T1.date = T2.date
    AND T1.blah, blah = T2.blah, blah
)
WHERE Table2.uniqueID = (
    Select T1.UniqueID
    from Table1 T1, CopyOfTable1 T2
    where T1.firstname = T2.firstname
    and T1.date = T2.date
    and T1.blah, blah = T2.blah, blah
);

This to remove all except ONE (with the lowest uniqueID) duplicate contact info records:

delete T1
from Table1 T1, CopyOfTable1 T2
where T1.unique ID > T2.unique ID
and T1.firstname = T2.firstname
and T1.date = T2.date
and T1.blah, blah = T2.blah, blah


问:
Why do I get zero when pushing_back floats to a vector?
While I was testing someting, I have created a vector of type float, and put the values 1/i into that vector;however, while reading the values, the output is printed as integers and not as float.

```<code>#include <stdio.h>
#include <vector>
#include <iterator>

int main(int argc, char const *argv[])
{
    std::vector<float> testVec;
    for (int i = 1; i < 5; ++i)
    {
        float v = 1/i;
        testVec.push_back(v);
    }

    std::vector< float >::iterator it = testVec.begin();
    for (; it!=testVec.end(); ++it)
    {
        printf("The value of the iterator: %f, *it);
    }
    return 0;
}
</code>```

So, what is the problem with this ? Is it related with the iterator ? I mean I have not much experienced with them.

答:
The reason behind your issue is that 1/i where i is of type integer is integer arithmetic and will give integer as output.

1.0 in place of 1 would help you. :)

Body:
While I was testing someting, I have created a vector of type float, and put the values 1/i into that vector;however, while reading the values, the output is printed as integers and not as float.

#include <stdio.h>
#include <vector>
#include <iterator>

int main(int argc, char const *argv[])
{
    std::vector<float> testVec;
    for (int i = 1; i < 5; ++i)
    {
        float v = 1/i;
        testVec.push_back(v);
    }

    std::vector< float >::iterator it = testVec.begin();
    for (; it!=testVec.end(); ++it)
    {
        printf("The value of the iterator: %f, *it);
    }
    return 0;
}

So, what is the problem with this ? Is it related with the iterator ? I mean I have not much experienced with them.