问:
NgMap: Why are my markers (ng-repeat directive) passing through multiple parameters?
I'm using the NgMap library to use the google maps api in my angular app.

I'm adding markers using an ng-repeat directive, each with an on-click tag that calls to the controller and logs to the console.

```<code><ng-map zoom="11" center="[40.74, -74.18]">
  <marker ng-repeat="p in vm.positions"
    position="{{p.pos}}"
    on-click="vm.showData(p)" //this is my on-click event, passing through the ng-repeated object
    title="pos: {{p.pos}}"></marker>
</ng-map>
</code>```

For some reason, every time I pass a parameter to my controller function it's actually the marker object being passed through, not the argument I'm passing from the view.

```<code> vm.showData = function (marker, param){
      console.log(marker) //WHY IS MARKER BEING PASSED THROUGH?!
      console.log(param.name); //THE SECOND ARGUMENT IS THE ONE I WANT, WHY ISN'T IT THE FIRST?
 }
</code>```

Eventually after banging my head against the wall, I decided to check if any other arguments were being passed through to the controller function. Low and behold the second argument was the one I expected to be passed through to begin with.

Why isn't the first argument the one I'm expecting?! Is it something to do with the ngMap library, angular, or just a javascript nuance I'm unaware of?

A working plunker can be found here: https://embed.plnkr.co/TQpm4O/

答:
After some digging, it looks like its something intentional by NgMap. It's an event, not the marker itself.

From the Docs:

Events are applied to map, markers, and shapes.
  All event-related attributes are preceded by 'on-', i.e. on-click, on-mouseover, etc

As a side note, to get the actual Marker Object from NgMap, you can use this.

So your code can also look like this.

angular.module('ngMap').controller('MyCtrl', function() {
    var vm=this;
    vm.data =[
      {foo:1, bar:1},
      {foo:2, bar:2},
      {foo:3, bar:3},
      {foo:4, bar:4},
      {foo:5, bar:5},
      {foo:6, bar:6},
      {foo:7, bar:7}
    ];
    vm.positions =[
      {pos:[40.71, -74.21], name: "dave 1" },
      {pos:[40.72, -74.20], name: "dave 2" },
      {pos:[40.73, -74.19], name: "dave 3" },
      {pos:[40.74, -74.18], name: "dave 4" },
      {pos:[40.75, -74.17], name: "dave 5" },
      {pos:[40.76, -74.16], name: "dave 6" },
      {pos:[40.77, -74.15], name: "dave 7" }
    ];
    vm.showData = function (event){
      console.log(this.position.lat());
      console.log(this.position.lng());
      console.log(this.title);
    }
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="ngMap">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script src="https://maps.google.com/maps/api/js?libraries=placeses,visualization,drawing,geometry,places"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
</head>

<body>
  <div ng-controller="MyCtrl as vm">
    <ng-map zoom="11" center="[40.74, -74.18]">
      <marker ng-repeat="p in vm.positions"
        position="{{p.pos}}"
        on-click="vm.showData()"
        title="pos: {{p.name}}"></marker>
        <!-- Changed p.pos to p.name -->
        <!-- You can even remove p from vm.showData() -->
    </ng-map>
  </div>
</body>
</html></code>```

Body:
I'm using the NgMap library to use the google maps api in my angular app.

I'm adding markers using an ng-repeat directive, each with an on-click tag that calls to the controller and logs to the console.

<ng-map zoom="11" center="[40.74, -74.18]">
  <marker ng-repeat="p in vm.positions"
    position="{{p.pos}}"
    on-click="vm.showData(p)" //this is my on-click event, passing through the ng-repeated object
    title="pos: {{p.pos}}"></marker>
</ng-map>

For some reason, every time I pass a parameter to my controller function it's actually the marker object being passed through, not the argument I'm passing from the view.

 vm.showData = function (marker, param){
      console.log(marker) //WHY IS MARKER BEING PASSED THROUGH?!
      console.log(param.name); //THE SECOND ARGUMENT IS THE ONE I WANT, WHY ISN'T IT THE FIRST?
 }

Eventually after banging my head against the wall, I decided to check if any other arguments were being passed through to the controller function. Low and behold the second argument was the one I expected to be passed through to begin with.

Why isn't the first argument the one I'm expecting?! Is it something to do with the ngMap library, angular, or just a javascript nuance I'm unaware of?

A working plunker can be found here: https://embed.plnkr.co/TQpm4O/

Body:
After some digging, it looks like its something intentional by NgMap. It's an event, not the marker itself.

From the Docs:

Events are applied to map, markers, and shapes.
  All event-related attributes are preceded by 'on-', i.e. on-click, on-mouseover, etc

As a side note, to get the actual Marker Object from NgMap, you can use this.

So your code can also look like this.

angular.module('ngMap').controller('MyCtrl', function() {
    var vm=this;
    vm.data =[
      {foo:1, bar:1},
      {foo:2, bar:2},
      {foo:3, bar:3},
      {foo:4, bar:4},
      {foo:5, bar:5},
      {foo:6, bar:6},
      {foo:7, bar:7}
    ];
    vm.positions =[
      {pos:[40.71, -74.21], name: "dave 1" },
      {pos:[40.72, -74.20], name: "dave 2" },
      {pos:[40.73, -74.19], name: "dave 3" },
      {pos:[40.74, -74.18], name: "dave 4" },
      {pos:[40.75, -74.17], name: "dave 5" },
      {pos:[40.76, -74.16], name: "dave 6" },
      {pos:[40.77, -74.15], name: "dave 7" }
    ];
    vm.showData = function (event){
      console.log(this.position.lat());
      console.log(this.position.lng());
      console.log(this.title);
    }
  });

<!DOCTYPE html>
<html ng-app="ngMap">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script src="https://maps.google.com/maps/api/js?libraries=placeses,visualization,drawing,geometry,places"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
</head>

<body>
  <div ng-controller="MyCtrl as vm">
    <ng-map zoom="11" center="[40.74, -74.18]">
      <marker ng-repeat="p in vm.positions"
        position="{{p.pos}}"
        on-click="vm.showData()"
        title="pos: {{p.name}}"></marker>
        <!-- Changed p.pos to p.name -->
        <!-- You can even remove p from vm.showData() -->
    </ng-map>
  </div>
</body>
</html>


来源: stackexchange

问:
css modules object import returns empty
I am trying to use css modules inside react, but it is not working.

The log of this code:

```<code>import React from 'react'
import styles from '../../css/test.css'

class Test extends React.Component {
    render() {
        console.log(styles)
        return (
            <div className={styles.app}>
                <p>This text will be blue</p>
            </div>
        );
    }
}

export default Test
</code>```

returns Object {}

and the rendered code are tags with no class:

```<code><div><p>This text will be blue</p></div>
</code>```

The css code is available at site, here is my test.css:

```<code>.test p {
  color: blue;
}
</code>```

If I changed the div to have class='test', the color of p changes to blue

Here is my webpack.config.js

```<code>var path = require('path')
var webpack = require('webpack')
var HappyPack = require('happypack')
var BundleTracker = require('webpack-bundle-tracker')
var path = require('path')
var ExtractTextPlugin = require("extract-text-webpack-plugin")

function _path(p) {
  return path.join(__dirname, p);
}

module.exports = {

    context: __dirname,
    entry: [
        './assets/js/index'
    ],

    output: {
        path: path.resolve('./assets/bundles/'),
        filename: '[name].js'
    },

    devtool: 'inline-eval-cheap-source-map',

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'}),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        }),
        new HappyPack({
            id: 'jsx',
            threads: 4,
            loaders: ["babel-loader"]
        }),
        new ExtractTextPlugin("[name].css", { allChunks: true })

    ],

    module: {
        loaders: [

             {
                test: /\.css$/,
                include: path.resolve(__dirname, './assets/css/'),
                loader: ExtractTextPlugin.extract("style-loader", "css-loader!resolve-url-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]")
            },

            {
                test: /\.scss$/,
                include: path.resolve(__dirname, './assets/css/'),
                loader: ExtractTextPlugin.extract("style-loader", "css-loader!resolve-url-loader!sass-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]")
            },

            {
                test: /\.jsx?$/,
                include: path.resolve(__dirname, './assets/js/'),
                exclude: /node_modules/,
                loaders: ["happypack/loader?id=jsx"]
            },
            {
                test: /\.png$/,
                loader: 'file-loader',
                query: {
                    name: '/static/img/[name].[ext]'
                }
            }
        ]
    },

    resolve: {
        modulesDirectories: ['node_modules'],
        extensions: ['', '.js', '.jsx'],
        alias: {
          'inputmask' : _path('node_modules/jquery-mask-plugin/dist/jquery.mask')
        },
    }
}
</code>```

Can anyone help me?

Thanks in advance.

答:
A lot of time passed since this question, so my webpack was update many times with another technologies.

This webpack config is working:

```<code>...
module.exports = {
  entry,
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
  devtool:
    process.env.NODE_ENV === 'production' ? 'source-map' : 'inline-source-map',

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: path.resolve(__dirname, './app/view/'),
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.pcss$/,
        include: path.resolve(__dirname, './app/view/'),
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader:
              'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
          },
          {
            loader: 'postcss-loader',
            options: {
              plugins: function() {
                return [
                  require('postcss-import'),
                  require('postcss-mixins'),
                  require('postcss-cssnext')({
                    browsers: ['last 2 versions']
                  }),
                  require('postcss-nested'),
                  require('postcss-brand-colors')
                ];
              }
            }
          }
        ],
        exclude: /node_modules/
      },
      {
        test: /\.(png|svg|jpg|webp)$/,
        use: {
          loader: 'file-loader'
        }
      }
    ]
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    modules: [path.resolve(__dirname, 'node_modules')]
  },
  plugins
};
</code>```

I guess that there is an issue with older versions at webpack with this line:

```<code>'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
</code>```

Try importLoaders and importLoader

You can see my repo too.

ContentLicense: CC BY-SA 3.0

Title: css modules object import returns empty

Body:
I am trying to use css modules inside react, but it is not working.

The log of this code:

import React from 'react'
import styles from '../../css/test.css'

class Test extends React.Component {
    render() {
        console.log(styles)
        return (

This text will be blue

        );
    }
}

export default Test

returns Object {}

and the rendered code are tags with no class:

This text will be blue

The css code is available at site, here is my test.css:

.test p {
  color: blue;
}

If I changed the div to have class='test', the color of p changes to blue

Here is my webpack.config.js

var path = require('path')
var webpack = require('webpack')
var HappyPack = require('happypack')
var BundleTracker = require('webpack-bundle-tracker')
var path = require('path')
var ExtractTextPlugin = require("extract-text-webpack-plugin")

function _path(p) {
  return path.join(__dirname, p);
}

module.exports = {

    context: __dirname,
    entry: [
        './assets/js/index'
    ],

    output: {
        path: path.resolve('./assets/bundles/'),
        filename: '[name].js'
    },

    devtool: 'inline-eval-cheap-source-map',

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'}),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        }),
        new HappyPack({
            id: 'jsx',
            threads: 4,
            loaders: ["babel-loader"]
        }),
        new ExtractTextPlugin("[name].css", { allChunks: true })

    ],

    module: {
        loaders: [

             {
                test: /\.css$/,
                include: path.resolve(__dirname, './assets/css/'),
                loader: ExtractTextPlugin.extract("style-loader", "css-loader!resolve-url-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]")
            },

            {
                test: /\.scss$/,
                include: path.resolve(__dirname, './assets/css/'),
                loader: ExtractTextPlugin.extract("style-loader", "css-loader!resolve-url-loader!sass-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]")
            },

            {
                test: /\.jsx?$/,
                include: path.resolve(__dirname, './assets/js/'),
                exclude: /node_modules/,
                loaders: ["happypack/loader?id=jsx"]
            },
            {
                test: /\.png$/,
                loader: 'file-loader',
                query: {
                    name: '/static/img/[name].[ext]'
                }
            }
        ]
    },

    resolve: {
        modulesDirectories: ['node_modules'],
        extensions: ['', '.js', '.jsx'],
        alias: {
          'inputmask' : _path('node_modules/jquery-mask-plugin/dist/jquery.mask')
        },
    }
}

Can anyone help me?

Thanks in advance.

Body:
A lot of time passed since this question, so my webpack was update many times with another technologies.

This webpack config is working:

...
module.exports = {
  entry,
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
  devtool:
    process.env.NODE_ENV === 'production' ? 'source-map' : 'inline-source-map',

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: path.resolve(__dirname, './app/view/'),
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.pcss$/,
        include: path.resolve(__dirname, './app/view/'),
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader:
              'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
          },
          {
            loader: 'postcss-loader',
            options: {
              plugins: function() {
                return [
                  require('postcss-import'),
                  require('postcss-mixins'),
                  require('postcss-cssnext')({
                    browsers: ['last 2 versions']
                  }),
                  require('postcss-nested'),
                  require('postcss-brand-colors')
                ];
              }
            }
          }
        ],
        exclude: /node_modules/
      },
      {
        test: /\.(png|svg|jpg|webp)$/,
        use: {
          loader: 'file-loader'
        }
      }
    ]
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    modules: [path.resolve(__dirname, 'node_modules')]
  },
  plugins
};

I guess that there is an issue with older versions at webpack with this line:

'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'

Try importLoaders and importLoader

You can see my repo too.


问:
Swift 4 Conversion error - NSAttributedStringKey: Any
I converted my app recently and I keep getting the error

"Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey: Any]?'

barButtonItem.setTitleTextAttributes(attributes, for: .normal)

Whole code:

```<code> class func getBarButtonItem(title:String) -> UIBarButtonItem {
    let barButtonItem = UIBarButtonItem.init(title: title, style: .plain, target: nil, action: nil)
    let attributes = [NSAttributedStringKey.font.rawValue:  UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.white] as! [String : Any]
    barButtonItem.setTitleTextAttributes(attributes, for: .normal)

    return barButtonItem
}
</code>```

答:
As noted in previous answers, NSAttributedStringKey was changed to a struct in Swift 4. However, other objects that use NSAttributedStringKey apparently didn't get updated at the same time.

The easiest fix, without having to change any of your other code, is to append .rawValue to all your occurrences of NSAttributedStringKey setters - turning the key names into Strings:

```<code>let attributes = [
    NSAttributedStringKey.font.rawValue:  UIFont(name: "Helvetica-Bold", size: 15.0)!,
    NSAttributedStringKey.foregroundColor.rawValue: UIColor.white
] as [String : Any]
</code>```

Note that you won't need the ! at the as now, either.

Alternatively, you can skip the as cast at the end by declaring the array to be [String : Any] upfront:

```<code>let attributes: [String : Any] = [
    NSAttributedStringKey.font.rawValue:  UIFont(name: "Helvetica-Bold", size: 15.0)!,
    NSAttributedStringKey.foregroundColor.rawValue: UIColor.white
]
</code>```

Of course, you still need to append the .rawValue for each NSAttributedStringKey item you set.

Body:
I converted my app recently and I keep getting the error

"Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey: Any]?'

barButtonItem.setTitleTextAttributes(attributes, for: .normal)

Whole code:

 class func getBarButtonItem(title:String) -> UIBarButtonItem {
    let barButtonItem = UIBarButtonItem.init(title: title, style: .plain, target: nil, action: nil)
    let attributes = [NSAttributedStringKey.font.rawValue:  UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.white] as! [String : Any]
    barButtonItem.setTitleTextAttributes(attributes, for: .normal)

    return barButtonItem
}

Body:
As noted in previous answers, NSAttributedStringKey was changed to a struct in Swift 4. However, other objects that use NSAttributedStringKey apparently didn't get updated at the same time.

The easiest fix, without having to change any of your other code, is to append .rawValue to all your occurrences of NSAttributedStringKey setters - turning the key names into Strings:

let attributes = [
    NSAttributedStringKey.font.rawValue:  UIFont(name: "Helvetica-Bold", size: 15.0)!,
    NSAttributedStringKey.foregroundColor.rawValue: UIColor.white
] as [String : Any]

Note that you won't need the ! at the as now, either.

Alternatively, you can skip the as cast at the end by declaring the array to be [String : Any] upfront:

let attributes: [String : Any] = [
    NSAttributedStringKey.font.rawValue:  UIFont(name: "Helvetica-Bold", size: 15.0)!,
    NSAttributedStringKey.foregroundColor.rawValue: UIColor.white
]

Of course, you still need to append the .rawValue for each NSAttributedStringKey item you set.


问:
Usage of += operator with lambda operator
I have the following code:

```<code>recognizer = new GestureRecognizer();
recognizer.Tapped += (args) =>
{
    // Send an OnSelect message to the focused object and its ancestors.
    if (FocusedObject != null)
    {
        FocusedObject.SendMessageUpwards("OnSelect",
            SendMessageOptions.DontRequireReceiver);
    }
};
</code>```

I am working in a project for Unity and I am not that experienced with the syntax of this operation:

```<code>recognizer.Tapped += (args) =>
{
    // Send an OnSelect message to the focused object and its ancestors.
    if (FocusedObject != null)
    {
        FocusedObject.SendMessageUpwards("OnSelect",
            SendMessageOptions.DontRequireReceiver);
    }
</code>```

I understand that Tapped is the event listener for taps. However, I don't understand the following things:

1) Why are they using a += operator to add a lambda function. How can you add a lambda function like that? I've always used += on primitive types.

2) Where does "args" come from?

3) When does that lambda function run?

答:
Why are they using a += operator to add a lambda function?

The point here is not the lambda method but the event and registering delegates to it. It overrloads the += operator to subscribe more event listeners. The Tapped property is an event (see links below).

From the documentation of the += operator:

The += operator is also used to specify a method that will be called in response to an event; such methods are called event handlers. The use of the += operator in this context is referred to as subscribing to an event.

Where does "args" come from?

When the event triggers it triggers with an argument (In this specific case of the definition of Tapped. When it does it passes this argument to all the event listeners.

When does that lambda function run?

Whenever the event is triggered and causes all the listeners to be called. One of them will be this lambda method.

I suggest have a look at: How to: Subscribe to and Unsubscribe from Events
and more in general about events

Also have a look at Delegates and Events on MSDN and += operator with Events

Body:
I have the following code:

recognizer = new GestureRecognizer();
recognizer.Tapped += (args) =>
{
    // Send an OnSelect message to the focused object and its ancestors.
    if (FocusedObject != null)
    {
        FocusedObject.SendMessageUpwards("OnSelect",
            SendMessageOptions.DontRequireReceiver);
    }
};

I am working in a project for Unity and I am not that experienced with the syntax of this operation:

recognizer.Tapped += (args) =>
{
    // Send an OnSelect message to the focused object and its ancestors.
    if (FocusedObject != null)
    {
        FocusedObject.SendMessageUpwards("OnSelect",
            SendMessageOptions.DontRequireReceiver);
    }

I understand that Tapped is the event listener for taps. However, I don't understand the following things:

1) Why are they using a += operator to add a lambda function. How can you add a lambda function like that? I've always used += on primitive types.

2) Where does "args" come from?

3) When does that lambda function run?


问:
Replacing letters at certain indices
I'm currently making a hangman program. It starts out and asks you for a letter, and then if you get it right, it replaces a dash at that word, with the letter.

For example:

If the word is jazz, and you choose an a, it would come out

```<code>-a--
</code>```

now when you guess a z, it's supposed to come out as

```<code>-azz
</code>```

but instead, it only prints the z at the first index that the letter z shows up.

```<code>-az-
</code>```

Here's my code so far:

```<code>secret_word = "jazz"
dashes = "----"

def get_guess():
    while True:
        print dashes
        guess = input("Guess: ")
        if len(guess) > 1:
            print "Your guess must have exactly one character!"
        elif guess.isupper():
            print "Your guess must be a lowercase letter!"
        elif guess.isdigit():
            print "Your guess must be a letter!"
        else:
            return guess
            break

def update_dashes(secret_word, dashes, guess):
    for i in range(len(secret_word)):
        if guess == secret_word[i]:
            #right here is where I change the dashes to letters.
            dashes = dashes[:i] + guess + dashes[i + 1:]
            return dashes

while True:
    user_guess = get_guess()
    dashes = update_dashes(secret_word, dashes, user_guess)
    if user_guess in secret_word:
        print "That letter is in the secret word!"
    else:
        print "That letter is not in the secret word!"
</code>```

答:
You have your indentation wrong in the update_dashes function. You want to loop through the entire length of the secret_word repeatedly replacing the characters and only when you have finished, return the dashes string.

```<code>def update_dashes(secret_word, dashes, guess):
    for i in range(len(secret_word)):
        if guess == secret_word[i]:
            #right here is where I change the dashes to letters.
            dashes = dashes[:i] + guess + dashes[i + 1:]
    return dashes
</code>```

and just a little test in the interpreter:

```<code>>>> update_dashes("bob", "---", "b")
'b-b'
</code>```

which looks like its working great! :)

Title: Replacing letters at certain indices

Body:
I'm currently making a hangman program. It starts out and asks you for a letter, and then if you get it right, it replaces a dash at that word, with the letter.

For example:

If the word is jazz, and you choose an a, it would come out

-a--

now when you guess a z, it's supposed to come out as

-azz

but instead, it only prints the z at the first index that the letter z shows up.

-az-

Here's my code so far:

secret_word = "jazz"
dashes = "----"

def get_guess():
    while True:
        print dashes
        guess = input("Guess: ")
        if len(guess) > 1:
            print "Your guess must have exactly one character!"
        elif guess.isupper():
            print "Your guess must be a lowercase letter!"
        elif guess.isdigit():
            print "Your guess must be a letter!"
        else:
            return guess
            break

def update_dashes(secret_word, dashes, guess):
    for i in range(len(secret_word)):
        if guess == secret_word[i]:
            #right here is where I change the dashes to letters.
            dashes = dashes[:i] + guess + dashes[i + 1:]
            return dashes

while True:
    user_guess = get_guess()
    dashes = update_dashes(secret_word, dashes, user_guess)
    if user_guess in secret_word:
        print "That letter is in the secret word!"
    else:
        print "That letter is not in the secret word!"

Body:
You have your indentation wrong in the update_dashes function. You want to loop through the entire length of the secret_word repeatedly replacing the characters and only when you have finished, return the dashes string.

def update_dashes(secret_word, dashes, guess):
    for i in range(len(secret_word)):
        if guess == secret_word[i]:
            #right here is where I change the dashes to letters.
            dashes = dashes[:i] + guess + dashes[i + 1:]
    return dashes

and just a little test in the interpreter:

>>> update_dashes("bob", "---", "b")
'b-b'

which looks like its working great! :)


问:
Better handling of Thread Context ClassLoader in OSGi
I've been using OSGi for a while now and I have various solutions to the problems I encountered. I wanted to revisit one of these and see if people had come up with different solutions.

One of the most common issues I have with OSGi (Equinox 3.4.2) is the frequent unavailability of the Thread's context ClassLoader. I know this is partly an Equinox problem, but I have encountered the issue with Felix as well. I encounter this mostly with 3rd party libraries that start their own Threads or ThreadPools. When these are started during Bundle or DS activation, they can end up without their ClassLoader. If the 3rd party library has guards against the context ClassLoader being missing, then no problem, but not everyone checks it. Later, if the said library needs to do dynamic classloading it might blow up.

The idiom I have been using for a while is the following (briefly):

```<code>ClassLoader tccl = Thread.currentThread().getContextClassLoader();
try {
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    /*
     * Start threads, or establish connections, here, now
     */
} finally {
    Thread.currentThread().setContextClassLoader(tccl);
}
</code>```

This idiom usually ends up in the Activator or the DS activate() method. There are some minor variations where I do check whether tccl is not null and I don't override the context classloader.

Now, I have a this bit of code plastered into various places where I know some 3rd party library might spawn a Thread and ruin my day. While it was manageable at first, I have ended up having this in many random places and it's bothering me.

Anybody else suffering from this issue, and what solutions have they come up with? I would also like to get an idea of whether this problem is solved in the new Equinox 3.5.x, and whether anyone has actually seen it work?

Regards.

答:
Great question, we've been doing the same work around (in Felix/Karaf/Servicemix4.2) and have been searching for a better solution.  Here is the response that I got back from the Felix team...

http://old.nabble.com/Can-the-thread-context-classloader-issue-be-solved-at-all--td28260809.html#a30704352

Essentially, they say that there isn't a better solution at the moment.

However, I do see that Equinox references some other options including "Buddy Policies" and using a "Context Finder" here...

http://wiki.eclipse.org/Context_Class_Loader_Enhancements

If anyone knows of other options or even a roadmap to resolve this in the future, please let us know...

ContentLicense: CC BY-SA 2.5

Body:
I've been using OSGi for a while now and I have various solutions to the problems I encountered. I wanted to revisit one of these and see if people had come up with different solutions.

One of the most common issues I have with OSGi (Equinox 3.4.2) is the frequent unavailability of the Thread's context ClassLoader. I know this is partly an Equinox problem, but I have encountered the issue with Felix as well. I encounter this mostly with 3rd party libraries that start their own Threads or ThreadPools. When these are started during Bundle or DS activation, they can end up without their ClassLoader. If the 3rd party library has guards against the context ClassLoader being missing, then no problem, but not everyone checks it. Later, if the said library needs to do dynamic classloading it might blow up.

The idiom I have been using for a while is the following (briefly):

ClassLoader tccl = Thread.currentThread().getContextClassLoader();
try {
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    /*
     * Start threads, or establish connections, here, now
     */
} finally {
    Thread.currentThread().setContextClassLoader(tccl);
}

This idiom usually ends up in the Activator or the DS activate() method. There are some minor variations where I do check whether tccl is not null and I don't override the context classloader.

Now, I have a this bit of code plastered into various places where I know some 3rd party library might spawn a Thread and ruin my day. While it was manageable at first, I have ended up having this in many random places and it's bothering me.

Anybody else suffering from this issue, and what solutions have they come up with? I would also like to get an idea of whether this problem is solved in the new Equinox 3.5.x, and whether anyone has actually seen it work?

Regards.


问:
git commit id placed into POM memory doesn't go into manifest
I'm trying to coerce my Maven build to produce a line like this in the manifest of the resulting jar file:

```<code>SCM-Revision: fdf7abe874a0a54f580aec96da366c168446378c
</code>```

such that the value is the git commit id.

So, I found this plugin, and I followed the instructions for setting it up.  The verbose output and the ant run output looks fine, but the resulting manifest file just has the raw property reference, not the substituted string.

This is what I have in the parent pom for my multiproject build:

```<code>        <plugin>
            <groupId>pl.project13.maven</groupId>
            <artifactId>git-commit-id-plugin</artifactId>
            <version>2.2.3</version>
            <executions>
                <execution>
                    <id>get-the-git-infos</id>
                    <goals>
                        <goal>revision</goal>
                    </goals>
                    <phase>validate</phase>
                </execution>
            </executions>
            <configuration>
                <verbose>true</verbose>
                <generateGitPropertiesFile>true</generateGitPropertiesFile>
                <failOnNoGitDirectory>true</failOnNoGitDirectory>
                <injectAllReactorProjects>true</injectAllReactorProjects>
                <dotGitDirectory>${project.basedir}/../../.git</dotGitDirectory>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <archive>
                    <manifestEntries>
                        <SCM-Revision>${git.commit.id}, ${gitCommit}</SCM-Revision>
                    </manifestEntries>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.8</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <configuration>
                        <target>
                            <echo>Git-Infos: ${git.commit.id}, ${gitCommit}</echo>
                        </target>
                    </configuration>
                    <goals>
                        <goal>run</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
</code>```

Because I was doing other experiments to get this to work, I also defined the following in an earlier "properties" section:

```<code>    <gitCommit>${git.commit.id}</gitCommit>
</code>```

When I run the build, I see this in the output, along with the verbose output from the plugin:

```<code>[INFO] --- maven-antrun-plugin:1.8:run (default) @ usl-shared ---
[INFO] Executing tasks

main:
     [echo] Git-Infos: fdf7abe874a0a54f580aec96da366c168446378c, fdf7abe874a0a54f580aec96da366c168446378c
[INFO] Executed tasks
</code>```

However, this is what I get in the manifest file in the jar:

```<code>SCM-Revision: ${git.commit.id}, ${git.commit.id}
</code>```

Somehow the property reference(s) in the jar plugin didn't substitute the property values.

Update:

I also note that the git.properties file was created in target/classes, but it's not in the jar file.  This implies that the file was created after the jar file was created, which implies that those properties were set after the jar file was created, making this behavior understandable.  This sounds like a problem with the "phase".  I'm using the recommended configuration for this, but it sure seems like that would be the problem.

Update:

I don't know if this is relevant, but note that the packaging type of our artifact projects is "bundle", not "jar".  We also use the maven-bundle-plugin.  I tried as a test to change the packaging to "jar", and that made the property substitution work.  It dropped all of our required osgi properties, however.

答:
As you mentioned in your update, your problem is regarding maven-bundle-plugin.

So you can get rid of the maven-jar-plugin and maven-antrun-plugin if you don't use them for anything than for the commit id stuff.

Presuming your maven-bundle-plugin looks something like this:

```<code>             <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${pom.groupId}.${pom.artifactId}</Bundle-SymbolicName>
                        <Bundle-Name>Service listener example</Bundle-Name>
                        <Bundle-Description>A bundle that displays messages at startup and when service events occur</Bundle-Description>
                        <Bundle-Vendor>Apache Felix</Bundle-Vendor>
                        <Bundle-Version>1.0.0</Bundle-Version>
                        <Bundle-Activator>tutorial.example1.Activator</Bundle-Activator>
                        <Import-Package>org.osgi.framework</Import-Package>
                        <SCM-Revision>${git.commit.id}, ${gitCommit}</SCM-Revision>
                    </instructions>
                </configuration>
            </plugin>
</code>```

You can just add your attribute (i.e.SCM-Revision) in your maven-bundle-plugin your attribute as a Instruction in the <configuration> section.

Body:
I'm trying to coerce my Maven build to produce a line like this in the manifest of the resulting jar file:

SCM-Revision: fdf7abe874a0a54f580aec96da366c168446378c

such that the value is the git commit id.

So, I found this plugin, and I followed the instructions for setting it up.  The verbose output and the ant run output looks fine, but the resulting manifest file just has the raw property reference, not the substituted string.

This is what I have in the parent pom for my multiproject build:

        <plugin>
            <groupId>pl.project13.maven</groupId>
            <artifactId>git-commit-id-plugin</artifactId>
            <version>2.2.3</version>
            <executions>
                <execution>
                    <id>get-the-git-infos</id>
                    <goals>
                        <goal>revision</goal>
                    </goals>
                    <phase>validate</phase>
                </execution>
            </executions>
            <configuration>
                <verbose>true</verbose>
                <generateGitPropertiesFile>true</generateGitPropertiesFile>
                <failOnNoGitDirectory>true</failOnNoGitDirectory>
                <injectAllReactorProjects>true</injectAllReactorProjects>
                <dotGitDirectory>${project.basedir}/../../.git</dotGitDirectory>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <archive>
                    <manifestEntries>
                        <SCM-Revision>${git.commit.id}, ${gitCommit}</SCM-Revision>
                    </manifestEntries>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.8</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <configuration>
                        <target>
                            <echo>Git-Infos: ${git.commit.id}, ${gitCommit}</echo>
                        </target>
                    </configuration>
                    <goals>
                        <goal>run</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

Because I was doing other experiments to get this to work, I also defined the following in an earlier "properties" section:

    <gitCommit>${git.commit.id}</gitCommit>

When I run the build, I see this in the output, along with the verbose output from the plugin:

[INFO] --- maven-antrun-plugin:1.8:run (default) @ usl-shared ---
[INFO] Executing tasks

main:
     [echo] Git-Infos: fdf7abe874a0a54f580aec96da366c168446378c, fdf7abe874a0a54f580aec96da366c168446378c
[INFO] Executed tasks

However, this is what I get in the manifest file in the jar:

SCM-Revision: ${git.commit.id}, ${git.commit.id}

Somehow the property reference(s) in the jar plugin didn't substitute the property values.

Update:

I also note that the git.properties file was created in target/classes, but it's not in the jar file.  This implies that the file was created after the jar file was created, which implies that those properties were set after the jar file was created, making this behavior understandable.  This sounds like a problem with the "phase".  I'm using the recommended configuration for this, but it sure seems like that would be the problem.

Update:

I don't know if this is relevant, but note that the packaging type of our artifact projects is "bundle", not "jar".  We also use the maven-bundle-plugin.  I tried as a test to change the packaging to "jar", and that made the property substitution work.  It dropped all of our required osgi properties, however.

Body:
As you mentioned in your update, your problem is regarding maven-bundle-plugin.

So you can get rid of the maven-jar-plugin and maven-antrun-plugin if you don't use them for anything than for the commit id stuff.

Presuming your maven-bundle-plugin looks something like this:

             <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${pom.groupId}.${pom.artifactId}</Bundle-SymbolicName>
                        <Bundle-Name>Service listener example</Bundle-Name>
                        <Bundle-Description>A bundle that displays messages at startup and when service events occur</Bundle-Description>
                        <Bundle-Vendor>Apache Felix</Bundle-Vendor>
                        <Bundle-Version>1.0.0</Bundle-Version>
                        <Bundle-Activator>tutorial.example1.Activator</Bundle-Activator>
                        <Import-Package>org.osgi.framework</Import-Package>
                        <SCM-Revision>${git.commit.id}, ${gitCommit}</SCM-Revision>
                    </instructions>
                </configuration>
            </plugin>

You can just add your attribute (i.e.SCM-Revision) in your maven-bundle-plugin your attribute as a Instruction in the <configuration> section.


问:
Why does maven 3.2 download same artifact multiple times from all repositories defined in pom
I have defined 2 repositories in pom.xml like below. One is public and other is thirdparty.

```<code><repositories>
   <repository>
        <id>public</id>
        <name>Nexus - Public Repositories</name>
        <layout>default</layout>
        <url>http://mavenrepo.aaa.net/nexus/content/groups/public</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>thirdparty</id>
        <name>Nexus - Third Party</name>
        <layout>default</layout>
        <url>http://mavenrepo.aaa.net/nexus/content/repositories/thirdparty</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>
</code>```

Say there is a dependency called grpId:artId:1.1.0 which I have defined in my pom. This dependency is present in both the repositories defined above- public and thirdparty

When I run mvn install I see different behaviours in the way maven downloads the grpId:artId:1.1.0 artifact based on the version of maven i am using.

Behaviours :-

1. Using Maven 3.1 and previous versions

a. Maven looks up the dependency grpId:artId:1.1.0 in 'public' repo

b. Maven finds the dependency and downloads it.

c. Maven does not look up the dependency grpId:artId:1.1.0 in

'thirdparty' repo as it is already downloaded from previous repository.

2. Using Maven 3.2

a. Maven looks up the dependency grpId:artId:1.1.0 in 'public' repo

b. Maven finds the dependency in 'public' repo and downloads it.

c. Maven again looks up the dependency grpId:artId:1.1.0 in
'thirdparty' repo even  though it is already downloaded from 'public' repository.

d. Maven finds the dependency in 'thirdparty' repo and downloads it
and overwrites the dependency downloaded from 'public' repo previously

I wonder why maven is behaving in an absurd manner for maven-3.2. It should stop looking further for the dependency which is already resolved and downloaded from one repository .

Is there a way to achieve it using maven 3.2 ?

答:
This was a bug identified and fixed by maven in version 3.2.5

https://issues.apache.org/jira/browse/MNG-5723

Body:
I have defined 2 repositories in pom.xml like below. One is public and other is thirdparty.

<repositories>
   <repository>
        <id>public</id>
        <name>Nexus - Public Repositories</name>
        <layout>default</layout>
        <url>http://mavenrepo.aaa.net/nexus/content/groups/public</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>thirdparty</id>
        <name>Nexus - Third Party</name>
        <layout>default</layout>
        <url>http://mavenrepo.aaa.net/nexus/content/repositories/thirdparty</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

Say there is a dependency called grpId:artId:1.1.0 which I have defined in my pom. This dependency is present in both the repositories defined above- public and thirdparty

When I run mvn install I see different behaviours in the way maven downloads the grpId:artId:1.1.0 artifact based on the version of maven i am using.

Behaviours :-

1. Using Maven 3.1 and previous versions

a. Maven looks up the dependency grpId:artId:1.1.0 in 'public' repo

b. Maven finds the dependency and downloads it.

c. Maven does not look up the dependency grpId:artId:1.1.0 in

'thirdparty' repo as it is already downloaded from previous repository.

2. Using Maven 3.2

a. Maven looks up the dependency grpId:artId:1.1.0 in 'public' repo

b. Maven finds the dependency in 'public' repo and downloads it.

c. Maven again looks up the dependency grpId:artId:1.1.0 in
'thirdparty' repo even  though it is already downloaded from 'public' repository.

d. Maven finds the dependency in 'thirdparty' repo and downloads it
and overwrites the dependency downloaded from 'public' repo previously

I wonder why maven is behaving in an absurd manner for maven-3.2. It should stop looking further for the dependency which is already resolved and downloaded from one repository .

Is there a way to achieve it using maven 3.2 ?


问:
How to catch error when app run or program carsh
Hi guys here I have one doubt how can I Catch error when user run app

However how can i get error

How to get error

How to display in Activity

```<code>    try {
    //code that may crash
} catch(Exception _e){
    //here do something when try detects error
    Log.e("try/catch error", _e.toString());

}
</code>```

答:
Java supports checked and unchecked exceptions.

You should use checked exceptions for all exceptional events that you can anticipate and that a well-written application should be able to handle. A checked exception extends the Exception class. A method that throws a checked exception or that calls a method that specifies a checked exception needs to either specify or handle it.

Unchecked exceptions extend the RuntimeException. You should use them for internal errors that you can’t anticipate and that, most often, the application can’t recover from. Methods can but don’t need to handle or specify an unchecked exception. Typical examples that throw unchecked exceptions are:

```<code>the missing initialization of a variable which results in a NullPointerException or
the improper use of an API that causes an IllegalArgumentException
</code>```

More on this subject could be found here

Body:
Hi guys here I have one doubt how can I Catch error when user run app

However how can i get error

How to get error

How to display in Activity

    try {
    //code that may crash
} catch(Exception _e){
    //here do something when try detects error
    Log.e("try/catch error", _e.toString());

}

Body:
Java supports checked and unchecked exceptions.

You should use checked exceptions for all exceptional events that you can anticipate and that a well-written application should be able to handle. A checked exception extends the Exception class. A method that throws a checked exception or that calls a method that specifies a checked exception needs to either specify or handle it.

Unchecked exceptions extend the RuntimeException. You should use them for internal errors that you can’t anticipate and that, most often, the application can’t recover from. Methods can but don’t need to handle or specify an unchecked exception. Typical examples that throw unchecked exceptions are:

the missing initialization of a variable which results in a NullPointerException or
the improper use of an API that causes an IllegalArgumentException

More on this subject could be found here


问:
How to prevent Jquery append line more than one time
my code is looking for any forms and add a new token ID line.
I need to prevent adding the new line,  if I have this line.

```<code><SCRIPT LANGUAGE = "JavaScript" >
          $(document).ready(function() {
                $("form").append('<input type="hidden" name="tokenF" id="tokenID" value="#session.tokenF">');<br>
            });
    </script>
</code>```

 Please, advise me:

 Thank you .

答:
You can search for any forms that don't already have the Token ID Line.

```<code>$("form").find(
    'form:not(:Contains("
            <input type="hidden" name="tokenF" id="tokenID" value="#session.tokenF">'
    ).append(
        '<input type="hidden" name="tokenF" id="tokenID" value="#session.tokenF">'
    );
</code>```

This finds form fields that do not contain the line you wish to add, then appends the line.

Body:
my code is looking for any forms and add a new token ID line.
I need to prevent adding the new line,  if I have this line.

 Please, advise me:

 Thank you .

Body:
You can search for any forms that don't already have the Token ID Line.

$("form").find(
    'form:not(:Contains("
            <input type="hidden" name="tokenF" id="tokenID" value="#session.tokenF">'
    ).append(
        '<input type="hidden" name="tokenF" id="tokenID" value="#session.tokenF">'
    );

This finds form fields that do not contain the line you wish to add, then appends the line.


问:
Html5 video command
Hallo i would like to make a videocomics for ipad and i tought to create a video in html5 that stops in some timeline point and play again if i press a button. It soulc be possible to do that? thanks a lot. </p>

答:
Have a look at the spec:

http://www.w3.org/TR/html5/video.html#playing-the-media-resource

Show's you what's possible with the DOM / Javascript :-)

Title: Html5 video command


问:
Python: how to count the occurrence of specific pattern with overlap in a list or string?
My problem is logically easy, but hard to implement for me. I have a list of numbers,(or you could say a string of numbers, it is not hard to transfer between strings and lists) I'd like to count the occurrence of some specific patterns with overlap. For example, the code is below:

```<code>A = [0, 1, 2 ,4, 5, 8, 4, 4, 5, 8, 2, 4, 4, 5, 5, 8, 9, 10, 3, 2]
</code>```

For "4,5,8" occurs, then I count a1 = 1, a2 = 1, a3 = 1. For "4,4,5,8" occurs, then I count a1 = 2, a2 = 1, a3 = 1. For "4,4,5,5,5,8,8,8" occurs, I count a1 = 2, a2 = 3, a3 = 3. That is to say, for a pattern, you count if the pattern at least include "4,5,8" in this order. "4,5,9" doesn't count. "4,4,4,5,5,2,8" doesn't count at all. For "4,5,4,5,8", a1 = 1, a2 = 1, a3 = 1.

Thank you all for your help.

答:
I tried to use

re.findall(r'26+8',test_string)

This will output the substring like "266666668", "268", "26668" in a nonoverlapping way. However, what if I want to search if there were a pattern shown below: "2(6+8+)+7" (this syntax doesn't work in "re", what I want essentially is a pattern like "266868688887", in which you could see there is back and forth movement between 6 and 8. Once you reach 7, the search is done. Has anyone a right idea to express the pattern is "re"? Thanks!

Body:
My problem is logically easy, but hard to implement for me. I have a list of numbers,(or you could say a string of numbers, it is not hard to transfer between strings and lists) I'd like to count the occurrence of some specific patterns with overlap. For example, the code is below:

A = [0, 1, 2 ,4, 5, 8, 4, 4, 5, 8, 2, 4, 4, 5, 5, 8, 9, 10, 3, 2]

For "4,5,8" occurs, then I count a1 = 1, a2 = 1, a3 = 1. For "4,4,5,8" occurs, then I count a1 = 2, a2 = 1, a3 = 1. For "4,4,5,5,5,8,8,8" occurs, I count a1 = 2, a2 = 3, a3 = 3. That is to say, for a pattern, you count if the pattern at least include "4,5,8" in this order. "4,5,9" doesn't count. "4,4,4,5,5,2,8" doesn't count at all. For "4,5,4,5,8", a1 = 1, a2 = 1, a3 = 1.

Thank you all for your help.


问:
Finding max value using reduce
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

```<code>{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])
</code>```

This is what I have so far:

```<code>(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)
</code>```

This produces the outcome:

```<code>{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}
</code>```

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

答:
You can use something like:

```<code>(into {} (map (fn [[k {:keys [city sales]}]] [k city])
                (reduce (fn [product-cities {:keys [product sales city]}]
                          (let [sales (Double/parseDouble (clojure.string/replace sales "," ""))
                                prev-sales (get-in product-cities [product :sales] 0)]
                            (if (> sales prev-sales)
                              (assoc product-cities product {:sales sales :city city})
                              product-cities)))
                        {}
                        table)))
</code>```

P.S. Although previous answer could be more readable...

Title: Finding max value using reduce

Body:
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])

This is what I have so far:

(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)

This produces the outcome:

{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

Body:
You can use something like:

(into {} (map (fn [[k {:keys [city sales]}]] [k city])
                (reduce (fn [product-cities {:keys [product sales city]}]
                          (let [sales (Double/parseDouble (clojure.string/replace sales "," ""))
                                prev-sales (get-in product-cities [product :sales] 0)]
                            (if (> sales prev-sales)
                              (assoc product-cities product {:sales sales :city city})
                              product-cities)))
                        {}
                        table)))

P.S. Although previous answer could be more readable...


问:
Why am I getting "Uncaught ReferenceError: React not defined"
I am getting Uncaught ReferenceError: React not defined, this is when I try to use the Chrome browser console to create var boldElement = React.createElement('b');. Why might this be happening?

答:
The most basic reason that this might be happening could be how the file structure is created inside of your html.  Check your syntax. It could be an issue where;

```<code><head>
  <meta charset="utf-8">
  <title>Basic Example</title>
  <script src="/vendor/react.js"></script>
  <script src="/vendor/react-dom.js"></script>
</head>
</code>```

However you need to place a period "." before your file path;

```<code><head>
  <meta charset="utf-8">
  <title>Basic Example</title>
  <script src="./vendor/react.js"></script>
  <script src="./vendor/react-dom.js"></script>
</head>
</code>```

Body:
The most basic reason that this might be happening could be how the file structure is created inside of your html.  Check your syntax. It could be an issue where;

<head>
  <meta charset="utf-8">
  <title>Basic Example</title>
  <script src="/vendor/react.js"></script>
  <script src="/vendor/react-dom.js"></script>
</head>

However you need to place a period "." before your file path;

<head>
  <meta charset="utf-8">
  <title>Basic Example</title>
  <script src="./vendor/react.js"></script>
  <script src="./vendor/react-dom.js"></script>
</head>


问:
React - Uncaught RangeError: Maximum call stack size exceeded
I'm beginner for React.js and trying to understand concept of props & state with multiple records.

I'm having two components -

UserData.jsx

UserDataResult.jsx

In UserData.jsx I used this.state for user records. This record I want to show through child component UserDataResult.jsx.

Don't know what I'm doing wrong, so that I'm getting error in console log.

Error is : Uncaught RangeError: Maximum call stack size exceeded

Code:

** UserData.jsx **

```<code>import React from "react";
import UserDataResult from "./UserDataResult.jsx";

class UserData extends React.Component{

    constructor (props){
        super(props);

        this.state = {
            users : [
                {
                    id : 1,
                    name : "Jack",
                    age : 32,
                    location : "USA",
                    skill : "Drummer",
                },
                {
                    id : 2,
                    name : "Andrew",
                    age : 35,
                    location : "USA",
                    skill : "Guitar player",
                },
            ]
        };

    }

    render(){
        return(
            <section>
                <h6> Headline </h6>
                <hr />

                <div>

                    {
                            this.state.users.map( (contact) => {

                                return <UserDataResult contact={contact} />

                            } )
                    }

                </div>
            </section>
        );
    }
}

export default UserData;
</code>```

** UserDataResult.jsx **

```<code>import React from "react";

class UserDataResult extends React.Component{
    render(){

        return(

            <section>
                <div>

                <p>
                    {this.props.contact.id}
                    {this.props.contact.name}
                    {this.props.contact.age}
                    {this.props.contact.location}
                    {this.props.contact.skill}
                </p>
                </div>

            </section>
        );
    }
}
export default UserDataResult;
</code>```

答:
Try this for your constructor:

You need to include props to allow React to properly pass the props down into the component. I can't recall the exact reason.

```<code>constructor(props) {                  // you need to include props
    super(props);                     // you need to include it here also
    this.state = {
        users = [
            {
                id : 1,
                name : "Jack",
                age : 32,
                location : "USA",
                skill : "Drummer"
            },
            {
                id : 2,
                name : "Andrew",
                age : 35,
                location : "USA",
                skill : "Guitar player"
            }
        ]
    };
}
</code>```

The above will give you access to this.state.users which will be an array.

Then, try this down in your component:

```<code><div>
    <UserDataResult checkResult={this.state.users} />
</div>
</code>```

Then, you can update it by pushing into the array.

Try to make something that allows you to call this:

```<code>const newUsersArray = this.state.users.push({
        id: 3
        name: 'Bob Ross'
        age: 25
        location: 'Cambodia'
        skill: 'Maximum'
    })

this.setState({ users: newUsersArray })
</code>```

You need to treat state as if it is immutable 24/7. Always replace it with an updated value.

React does all kinds of fancy comparisons behind the scenes and helps you optimize performance. Notice how I added the new user to the array and then just reassigned it.

This will prime you for the Redux world, in which we use reducers and directly manipulating state is 100% illegal.

Get in your mind now that doing this.state.push() or state.users.bob = 'ok' is bad. You want to do what I showed above, and the Bob example would be like:

```<code>return {
  ...state,
  bob: 'ok'
}
</code>```

What that does is creates a new object and "spreads" the existing state into it, so all of it as it is at that moment, then it simply adds bob: 'ok' as a property on that new object and since it occurs after/below, it takes precedence and overwrites the existing key called bob.

That's a bit more advanced, but you should know that reducers strive to be pure functions and that using React immutably is very important. Do some reading about it.

This stuff has bearing on where, when, and why components re-render. It is at the heart of React's blistering performance.

If you call this.setState() from inside the render function, or a lifecycle method, it can go into an infinite loop, because setState triggers a re-rendering of the component, and the re-rendering triggers setState again.

Body:
I'm beginner for React.js and trying to understand concept of props & state with multiple records.

I'm having two components -

UserData.jsx

UserDataResult.jsx

In UserData.jsx I used this.state for user records. This record I want to show through child component UserDataResult.jsx.

Don't know what I'm doing wrong, so that I'm getting error in console log.

Error is : Uncaught RangeError: Maximum call stack size exceeded

Code:

** UserData.jsx **

import React from "react";
import UserDataResult from "./UserDataResult.jsx";

class UserData extends React.Component{

    constructor (props){
        super(props);

        this.state = {
            users : [
                {
                    id : 1,
                    name : "Jack",
                    age : 32,
                    location : "USA",
                    skill : "Drummer",
                },
                {
                    id : 2,
                    name : "Andrew",
                    age : 35,
                    location : "USA",
                    skill : "Guitar player",
                },
            ]
        };

    }

    render(){
        return(

 Headline

                    {
                            this.state.users.map( (contact) => {

                                return <UserDataResult contact={contact} />

                            } )
                    }

        );
    }
}

export default UserData;

** UserDataResult.jsx **

import React from "react";

class UserDataResult extends React.Component{
    render(){

        return(

                    {this.props.contact.id}
                    {this.props.contact.name}
                    {this.props.contact.age}
                    {this.props.contact.location}
                    {this.props.contact.skill}

        );
    }
}
export default UserDataResult;

Body:
Try this for your constructor:

You need to include props to allow React to properly pass the props down into the component. I can't recall the exact reason.

constructor(props) {                  // you need to include props
    super(props);                     // you need to include it here also
    this.state = {
        users = [
            {
                id : 1,
                name : "Jack",
                age : 32,
                location : "USA",
                skill : "Drummer"
            },
            {
                id : 2,
                name : "Andrew",
                age : 35,
                location : "USA",
                skill : "Guitar player"
            }
        ]
    };
}

The above will give you access to this.state.users which will be an array.

Then, try this down in your component:

<div>
    <UserDataResult checkResult={this.state.users} />
</div>

Then, you can update it by pushing into the array.

Try to make something that allows you to call this:

const newUsersArray = this.state.users.push({
        id: 3
        name: 'Bob Ross'
        age: 25
        location: 'Cambodia'
        skill: 'Maximum'
    })

this.setState({ users: newUsersArray })

You need to treat state as if it is immutable 24/7. Always replace it with an updated value.

React does all kinds of fancy comparisons behind the scenes and helps you optimize performance. Notice how I added the new user to the array and then just reassigned it.

This will prime you for the Redux world, in which we use reducers and directly manipulating state is 100% illegal.

Get in your mind now that doing this.state.push() or state.users.bob = 'ok' is bad. You want to do what I showed above, and the Bob example would be like:

return {
  ...state,
  bob: 'ok'
}

What that does is creates a new object and "spreads" the existing state into it, so all of it as it is at that moment, then it simply adds bob: 'ok' as a property on that new object and since it occurs after/below, it takes precedence and overwrites the existing key called bob.

That's a bit more advanced, but you should know that reducers strive to be pure functions and that using React immutably is very important. Do some reading about it.

This stuff has bearing on where, when, and why components re-render. It is at the heart of React's blistering performance.

If you call this.setState() from inside the render function, or a lifecycle method, it can go into an infinite loop, because setState triggers a re-rendering of the component, and the re-rendering triggers setState again.


问:
Add form values dynamically
I have this JavaScript code to dynamically add values on a form as they're entered. However, I'm struggling a little with what I want to do.

I have 4 questions on a quiz, each with 4 answers.

I want to add the values for each of the 4 answer boxes per question. But I can't work out how to use this script more than once on a page. Can anyone advise please?

        <form name="form" >
            Enter a number:
            <input name="sum1" onChange="updatesum1()" />
            and another number:
            <input name="sum2" onChange="updatesum1()" />
            and another number:
            <input name="sum3" onChange="updatesum1()" />
            and another number:
            <input name="sum4" onChange="updatesum1()" />
            Their sum is:
            <input name="sum" readonly style="border:0px;">
        </form>

    ```

答:
This is not how I would have done it, but it changes the "sum" as you want it to in chrome.

If you are able to use jQuery I would head that route.

```<code>    <script type="text/javascript">
        $(document).ready(function () {

            $(".addInput").on("change", function () {//jQuery's on event handles all inputs

                updateSum();//call the function
            });

            function updateSum() {//This function could be made more generic.

               var sum1 = parseInt($("#sum1").val());
               var sum2 = parseInt($("#sum2").val());
               var sum3 = parseInt($("#sum3").val());
               var sum4 = parseInt($("#sum4").val());

               if(isNaN(sum1)){//make sure the input contains a parsable number.
                   sum1 = 0;
               }
               if(isNaN(sum2)){
                   sum2 = 0;
               }
               if(isNaN(sum3)){
                   sum3 = 0;
               }
               if(isNaN(sum4)){
                   sum4 = 0;
               }

               var sum = sum1 + sum2 + sum3 + sum4;//add everything up

                $("#sum").val(sum);//add it to te sum input
            }
        });

        //function updatesum1() {
        //    document.form.sum.value = (document.form.sum1.value - 0)
        //                            + (document.form.sum2.value - 0)
        //                            + (document.form.sum3.value - 0)
        //                            + (document.form.sum4.value - 0);
        //}
    </script>
    <title>Input Adding</title>
</head>
<body>
    <form name="form" >
        Enter a number:
        <input name="sum1" class="addInput" id="sum1" value/>
        and another number:
        <input name="sum2" class="addInput" id="sum2" value/>
        and another number:
        <input name="sum3" class="addInput" id="sum3" value/>
        and another number:
        <input name="sum4" class="addInput" id="sum4" value/>
        Their sum is:
        <input name="sum" id="sum" readonly style="border:0px;">
    </form>

</body>
</code>```

Hope this Helps

Title: Add form values dynamically

Body:
This is not how I would have done it, but it changes the "sum" as you want it to in chrome.

If you are able to use jQuery I would head that route.

    <script type="text/javascript">
        $(document).ready(function () {

            $(".addInput").on("change", function () {//jQuery's on event handles all inputs

                updateSum();//call the function
            });

            function updateSum() {//This function could be made more generic.

               var sum1 = parseInt($("#sum1").val());
               var sum2 = parseInt($("#sum2").val());
               var sum3 = parseInt($("#sum3").val());
               var sum4 = parseInt($("#sum4").val());

               if(isNaN(sum1)){//make sure the input contains a parsable number.
                   sum1 = 0;
               }
               if(isNaN(sum2)){
                   sum2 = 0;
               }
               if(isNaN(sum3)){
                   sum3 = 0;
               }
               if(isNaN(sum4)){
                   sum4 = 0;
               }

               var sum = sum1 + sum2 + sum3 + sum4;//add everything up

                $("#sum").val(sum);//add it to te sum input
            }
        });

        //function updatesum1() {
        //    document.form.sum.value = (document.form.sum1.value - 0)
        //                            + (document.form.sum2.value - 0)
        //                            + (document.form.sum3.value - 0)
        //                            + (document.form.sum4.value - 0);
        //}
    </script>
    <title>Input Adding</title>
</head>
<body>
    <form name="form" >
        Enter a number:
        <input name="sum1" class="addInput" id="sum1" value/>
        and another number:
        <input name="sum2" class="addInput" id="sum2" value/>
        and another number:
        <input name="sum3" class="addInput" id="sum3" value/>
        and another number:
        <input name="sum4" class="addInput" id="sum4" value/>
        Their sum is:
        <input name="sum" id="sum" readonly style="border:0px;">
    </form>

</body>

Hope this Helps


问:
Why do devices with 'ColorTemperature' trait in rooms receive commands for 'ColorSpectrum'?
To illustrate an example scenario that prompted this question, please consider the following:

A room, attic, that contains 3 devices: one light that supports both ColorSpectrum and ColorTemperature, one light that only supports ColorTemperature and one light that only supports ColorSpectrum (all 3 also support OnOff and Brightness, but this appears to be irrelevant).

"Set the attic to warm white" will result in two of the lights receiving a temperature value in Kelvin, whereas the third (which didn't support ColorTemperature) will receive an rgb/hsv color value approximating the correct hue of white.

Conversely: "Set the attic to red" will result in all 3 lights receiving an rgb/hsv color value (including the light that does not support the ColorSpectrum trait).

We are unsure how a light that supports only ColorTemperature is supposed to respond to an rgb/hsv value. This final scenario - after the light's failure to be able to execute the user's command - left us with 3 options to respond:

Lie and respond 'SUCCESS' for all 3 lights, "Ok, changing 3 lights to red."

Omit the third light from the response entirely, "Ok, changing 3 lights to red."

Respond with "notSupported" 'ERROR' for the third light, "Ok, changing 2 lights to red. That mode isn't available for the LIGHT_3."

Option 1 is clearly undesirable, incorrect feedback is worse than no feedback at all.

Option 2 is equivalent to 1, though it seems odd that Google Home should assume that a device omitted from a response was successfully processed.

Option 3 we deem unideal as well, as we expect the user may get bored of hearing that a certain light in their room is unable to change color when they might be perfectly aware of this fact. Our preference would go to a response of: "Ok, changing 2 lights to red." We feel that this communicates clearly that one light didn't change, without the potentially superfluous error message.

Our question, then, is how we might realize this?

Is the behavior listed above unintended (a bug)?

Is there some response that we are unaware of that can be used to communicate to Google Home that a device simply is not eligible for the provided execution?

Is the behavior listed above not experienced by others or the result of a mistake on our part?

Thank you for reading.

答:
I'm going to check about this scenario as it might be a bug in which devices get commands when they shouldn't.

Canonically, option three may be undesirable but is the right implementation. Trying to ignore the command will also create a bad user experience as they receive an incorrect reply.


问:
How do I remove the DocuSign watermark from a signed PDF?
I have implemented DocuSign in my application for signing the PDF but after making signature some details regarding DocuSign information is displaying in PDF in red color. Please find the Image. Can anyone suggest me how to hide this information from the PDF after making signature?

答: The watermark in the upper right corner cannot be removed and will be applied to all documents signed in DocuSign's Demo environment. If you would like to have documents signed without that watermark you will need to go live and being making calls in the Production environment.</p>


问:
(Cocoa error 3840.)" (Invalid value around character 0.) AFNetworking
I've been getting the following error when using the GET method to retrieve a file from a server:

```<code>Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x16e81ed0 {NSDebugDescription=Invalid value around character 0.}
</code>```

I've tried a number of different things and I believe it could be something to do with the JSON format on the file that I'm trying to get.

Here is the code I've been using:

```<code>_username = @"JonDoe";
NSDictionary *parameters = @{ @"username" : _username};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

[manager GET:@"http://.........."
  parameters:parameters
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         NSLog(@"JSON: %@", responseObject);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
     }];
</code>```

My POST method works fine. I just can't seem to fix this issue with the GET. Any ideas? Thank you.

答:
Hey guys this is what I found to be my issue: I was calling Alamofire via a function to Authenticate Users: I used the function "Login User" With the parameters that would be called from the "body"(email: String, password: String)  That would be passed

my errr was exactly:

optional(alamofire.aferror.responseserializationfailed(alamofire.aferror.responseserializationfailurereason.jsonserializationfailed(error domain=nscocoaerrordomain code=3840 "invalid value around character 0." userinfo={nsdebugdescription=invalid value around character 0

character 0 is the key here: meaning the the call for the "email" was not matching the parameters: See the code below

func loginUser(email: String, password: String, completed: @escaping downloadComplete) {
        let lowerCasedEmail = email.lowercased()

```<code>    let header = [
        "Content-Type" : "application/json; charset=utf-8"
    ]
    let body: [String: Any] = [
        "email": lowerCasedEmail,
        "password": password
    ]

    Alamofire.request(LOGIN_USER, method: .post, parameters: body, encoding: JSONEncoding.default, headers: header).responseJSON { (response) in
        if response.result.error == nil {

            if let data = response.result.value as? Dictionary<String, AnyObject> {
                if let email = data["user"] as? String {
                    self.userEmail = email
                    print(self.userEmail)
                }
                if let token = data["token"] as? String {
                    self.token_Key = token
                    print(self.token_Key)
                }
</code>```

"email" in function parameters must match the let "email" when parsing then it will work..I no longer got the error...And character 0 was the "email" in the "body" parameter for the Alamofire request:

Hope this helps

Body:
I've been getting the following error when using the GET method to retrieve a file from a server:

Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x16e81ed0 {NSDebugDescription=Invalid value around character 0.}

I've tried a number of different things and I believe it could be something to do with the JSON format on the file that I'm trying to get.

Here is the code I've been using:

_username = @"JonDoe";
NSDictionary *parameters = @{ @"username" : _username};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

[manager GET:@"http://.........."
  parameters:parameters
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         NSLog(@"JSON: %@", responseObject);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
     }];

My POST method works fine. I just can't seem to fix this issue with the GET. Any ideas? Thank you.

Body:
Hey guys this is what I found to be my issue: I was calling Alamofire via a function to Authenticate Users: I used the function "Login User" With the parameters that would be called from the "body"(email: String, password: String)  That would be passed

my errr was exactly:

optional(alamofire.aferror.responseserializationfailed(alamofire.aferror.responseserializationfailurereason.jsonserializationfailed(error domain=nscocoaerrordomain code=3840 "invalid value around character 0." userinfo={nsdebugdescription=invalid value around character 0

character 0 is the key here: meaning the the call for the "email" was not matching the parameters: See the code below

func loginUser(email: String, password: String, completed: @escaping downloadComplete) {
        let lowerCasedEmail = email.lowercased()

    let header = [
        "Content-Type" : "application/json; charset=utf-8"
    ]
    let body: [String: Any] = [
        "email": lowerCasedEmail,
        "password": password
    ]

    Alamofire.request(LOGIN_USER, method: .post, parameters: body, encoding: JSONEncoding.default, headers: header).responseJSON { (response) in
        if response.result.error == nil {

            if let data = response.result.value as? Dictionary<String, AnyObject> {
                if let email = data["user"] as? String {
                    self.userEmail = email
                    print(self.userEmail)
                }
                if let token = data["token"] as? String {
                    self.token_Key = token
                    print(self.token_Key)
                }

"email" in function parameters must match the let "email" when parsing then it will work..I no longer got the error...And character 0 was the "email" in the "body" parameter for the Alamofire request:

Hope this helps


问:
Self Referential Relationship in SQLAlchemy
I am trying to create a self referential relationship in SQLAlchemy.

I have a class 'Issue' that may have identical 'Issue' siblings that are exactly the same but have a different cover image attribute.

I would like each model to contain an attribute containing a list of its siblings but not itself if possible.

My issue model currently looks like this:

```<code>class Issue(db.Model):
    __tablename__ = 'issues'
    # IDs
    id = db.Column(db.Integer, primary_key=True)
    title_id = db.Column(db.Integer, db.ForeignKey('titles.id'))
    publisher_id = db.Column(db.Integer, db.ForeignKey('publishers.id'))
    parent_id = db.Column(db.Integer, db.ForeignKey('issues.id'))
    # Attributes
    product_id = db.Column(db.String(100))
    issue_number = db.Column(db.Float)
    .......
    # Relationships
    is_parent = db.Column(db.Boolean(), default=False)
    alternates = db.relationship('Issue',
                backref=db.backref('parent', remote_side=[id])
            )
</code>```

Each Issue has an 'is_parent' attribute that I set when it is determined that the issue is the 'base' issue. However, I still want all siblings to be able to access one another.

Currently, I am giving the 'parent' issue a relationship with all of its 'children'/'siblings'.

The problem occurs when I am interacting with an instance of a 'sibling'. I would like to directly access all of its relatives but I must go through the parent first.

Any help would be greatly appreciated!

EDIT: Basically, I would like to create a self-referential many-to-many relationship. Am I wrong in believing this is the correct direction to pursue?

答:
I know this is old, but the op could also just use a self referential relational scheme to find the children easily. Here is how that would work in your group.

```<code>class Issue(db.Model):
    __tablename__ = 'issues'
    # IDs
    id = db.Column(db.Integer, primary_key=True)
    title_id = db.Column(db.Integer, db.ForeignKey('titles.id'))
    publisher_id = db.Column(db.Integer, db.ForeignKey('publishers.id'))
    parent_id = db.Column(db.Integer, db.ForeignKey('issues.id'))
    # Attributes
    product_id = db.Column(db.String(100))
    issue_number = db.Column(db.Float)
    .......
    # Relationships
    #is_parent = db.Column(db.Boolean(), default=False)
    alternates = db.relationship('Issue',
                backref=db.backref('parent', remote_side=[id])
            )
    #This is what you need to add to make the database link it self
    parent_id=db.Column(db.Integer, db.ForeignKey('issues.id'))
    children=db.relationship('Issue', backref=db.backref('parent', remote_side=[id]))
</code>```

Calling children would send you all the children of the parent. Calling parent would give you the parent of the current group. If it returns None then you are looking at a root Issue.

Body:
I am trying to create a self referential relationship in SQLAlchemy.

I have a class 'Issue' that may have identical 'Issue' siblings that are exactly the same but have a different cover image attribute.

I would like each model to contain an attribute containing a list of its siblings but not itself if possible.

My issue model currently looks like this:

class Issue(db.Model):
    __tablename__ = 'issues'
    # IDs
    id = db.Column(db.Integer, primary_key=True)
    title_id = db.Column(db.Integer, db.ForeignKey('titles.id'))
    publisher_id = db.Column(db.Integer, db.ForeignKey('publishers.id'))
    parent_id = db.Column(db.Integer, db.ForeignKey('issues.id'))
    # Attributes
    product_id = db.Column(db.String(100))
    issue_number = db.Column(db.Float)
    .......
    # Relationships
    is_parent = db.Column(db.Boolean(), default=False)
    alternates = db.relationship('Issue',
                backref=db.backref('parent', remote_side=[id])
            )

Each Issue has an 'is_parent' attribute that I set when it is determined that the issue is the 'base' issue. However, I still want all siblings to be able to access one another.

Currently, I am giving the 'parent' issue a relationship with all of its 'children'/'siblings'.

The problem occurs when I am interacting with an instance of a 'sibling'. I would like to directly access all of its relatives but I must go through the parent first.

Any help would be greatly appreciated!

EDIT: Basically, I would like to create a self-referential many-to-many relationship. Am I wrong in believing this is the correct direction to pursue?

Body:
I know this is old, but the op could also just use a self referential relational scheme to find the children easily. Here is how that would work in your group.

class Issue(db.Model):
    __tablename__ = 'issues'
    # IDs
    id = db.Column(db.Integer, primary_key=True)
    title_id = db.Column(db.Integer, db.ForeignKey('titles.id'))
    publisher_id = db.Column(db.Integer, db.ForeignKey('publishers.id'))
    parent_id = db.Column(db.Integer, db.ForeignKey('issues.id'))
    # Attributes
    product_id = db.Column(db.String(100))
    issue_number = db.Column(db.Float)
    .......
    # Relationships
    #is_parent = db.Column(db.Boolean(), default=False)
    alternates = db.relationship('Issue',
                backref=db.backref('parent', remote_side=[id])
            )
    #This is what you need to add to make the database link it self
    parent_id=db.Column(db.Integer, db.ForeignKey('issues.id'))
    children=db.relationship('Issue', backref=db.backref('parent', remote_side=[id]))

Calling children would send you all the children of the parent. Calling parent would give you the parent of the current group. If it returns None then you are looking at a root Issue.


问:
MySQL query for maximum duplicate value(s)
```<code>| b_id |
+------+
|   10 |
|   10 |
|   20 |
|   30 |
|   40 |
|   40 |
|   70 |
|   40 |
|   10 |
</code>```

Very Similar to mysql query for maximum duplicate value I need the b_id(s) that have the most entries.

The posted solution

```<code>select b_id, count(b_id)
from books
group by b_id
order by count(b_id) desc
limit 1;
</code>```

doesn't work for me, as it only shows one of the b_ids that repeat the maximum number of time.
My required result here is

```<code>| b_id | reps |
+------+------+
|   10 |    3 |
|   40 |    3 |
</code>```

答:
Here you go, move your query to cross join part which gives you the max count value and then with same query match count of inner query with your main query to get b_id(s) who have same max count

```<code>select a.b_id,maxcountb
from books a
cross join (
    select  count(b_id) maxcountb
    from books
    group by b_id
    order by maxcountb desc
    limit 1
) b
group by a.b_id
having count(a.b_id) =maxcountb
</code>```

Demo

Another way to rewrite above for better understanding

```<code>select a.b_id,count(a.b_id) maxcounta
from books a
group by a.b_id
having maxcounta =(
  select  count(b_id) maxcountb
  from books
  group by b_id
  order by maxcountb desc
  limit 1
)
</code>```

Demo

Body:
| b_id |
+------+
|   10 |
|   10 |
|   20 |
|   30 |
|   40 |
|   40 |
|   70 |
|   40 |
|   10 |

Very Similar to mysql query for maximum duplicate value I need the b_id(s) that have the most entries.

The posted solution

select b_id, count(b_id)
from books
group by b_id
order by count(b_id) desc
limit 1;

doesn't work for me, as it only shows one of the b_ids that repeat the maximum number of time.
My required result here is

| b_id | reps |
+------+------+
|   10 |    3 |
|   40 |    3 |

Body:
Here you go, move your query to cross join part which gives you the max count value and then with same query match count of inner query with your main query to get b_id(s) who have same max count

select a.b_id,maxcountb
from books a
cross join (
    select  count(b_id) maxcountb
    from books
    group by b_id
    order by maxcountb desc
    limit 1
) b
group by a.b_id
having count(a.b_id) =maxcountb

Demo

Another way to rewrite above for better understanding

select a.b_id,count(a.b_id) maxcounta
from books a
group by a.b_id
having maxcounta =(
  select  count(b_id) maxcountb
  from books
  group by b_id
  order by maxcountb desc
  limit 1
)

Demo