问:
ODOO 10 many2many
I have a problem in ODOO 10 with a many2many relationship.
I have extended res.partner this way:

```<code>class ResPartner(models.Model):
    x_bagsdesign = fields.Many2many('product.product',string='Bags Design',relation='bags_design_manufactur')
</code>```

then I have extended also product.template model:

```<code>class product_template_fields(models.Model):
    _inherit = 'product.template'
    x_traders_stock = fields.Many2many(
    'res.partner', string='Traders with access to stock',relation='xtradstock_res_partner_rel')

    @api.multi
    def write(self, vals):

        record = super(product_template_fields, self).write(vals)
        for singletrader in self.x_traders_stock:
            singletrader.x_bagsdesign = [(4,self.id)]

        return record
</code>```

This way every time a new x_traders_stock is inserted in product.template, a new x_bags_design is also created in res.partner.

BUT.. when I save a new record in product.template I get an sql error:

```<code>bad query:  INSERT INTO bags_design_manufactur (res_partner_id, product_product_id)
                    (SELECT a, b FROM unnest(ARRAY[1]) AS a, unnest(ARRAY[7]) AS b)
                    EXCEPT (SELECT res_partner_id, product_product_id FROM bags_design_manufactur WHERE res_partner_id IN (1))
</code>```

I don't understand where the EXCEPT part of the sql query is coming from and how to prevent it. If anyone can help I would be grateful.. thanks!

答:
The error message is a bit different from expected, but I can fix some problems in your code. First of all you have to take into account that a product.product object is a variant of a product.template object, so you can have in a database many product.product objects pointing to the same product.template (e.g. a product.template is a T-shirt and a product.product is a T-shirt colour red size M). This means that you can't try to set the ID of a product.template in a field which is expecting the ID of a product.product, as you're doing here:

```<code>singletrader.x_bagsdesign = [(4,self.id)]
</code>```

Of course, that mistake will not give you the message error you are receiving, there must be something wrong in other part of your code (I guess related to bags_design_manufactur model).

However, to fix the problem I told you above, you should write this:

```<code>class product_template_fields(models.Model):
    _inherit = 'product.template'

    x_traders_stock = fields.Many2many(
        comodel_name='res.partner',
        string='Traders with access to stock',
        relation='xtradstock_res_partner_rel'
    )

    @api.multi
    def write(self, vals):
        result = super(product_template_fields, self).write(vals)
        for prod_templ in self:
            products = self.env['product.product'].search([
                ('product_tmpl_id', '=', prod_templ.id),
            ])
            for singletrader in prod_templ.x_traders_stock:
                singletrader.write({
                    'x_bagsdesign': [(4, product.id) for product in products],
                })
        return result
</code>```

EDIT

product.product inherits from product.template by delegation, this means that every field you create in product.template model is going to be available in product.product objects, so when you are creating the Many2many field x_traders_stock in product.template, you're creating it in product.product too, so you don't need to add records each time a x_trader is generated. Instead you should change your models:

```<code>class ResPartner(models.Model):
    x_bagsdesign_prod_templ = fields.Many2many(
        comodel_name='product.template',
        column1='partner_id',
        column2='product_tmpl_id',
        string='Bags Design',
        relation='xtradstock_res_partner_rel'
    )

class ProductTemplate(models.Model):
    _inherit = 'product.template'

    x_traders_stock = fields.Many2many(
        comodel_name='res.partner',
        column1='product_tmpl_id',
        column2='partner_id',
        string='Traders with access to stock',
        relation='xtradstock_res_partner_rel'
    )
</code>```

And then, if you want to access to the product.product objects a partner has, you can do it this way:

```<code>any_partner.x_bagsdesign_prod_templ.mapped('product_variant_ids')
</code>```

If you preferred it, you could even create a new related field in res.partner which brought the product.product objects a partner has.

Title: ODOO 10 many2many

Body:
I have a problem in ODOO 10 with a many2many relationship.
I have extended res.partner this way:

class ResPartner(models.Model):
    x_bagsdesign = fields.Many2many('product.product',string='Bags Design',relation='bags_design_manufactur')

then I have extended also product.template model:

class product_template_fields(models.Model):
    _inherit = 'product.template'
    x_traders_stock = fields.Many2many(
    'res.partner', string='Traders with access to stock',relation='xtradstock_res_partner_rel')

    @api.multi
    def write(self, vals):

        record = super(product_template_fields, self).write(vals)
        for singletrader in self.x_traders_stock:
            singletrader.x_bagsdesign = [(4,self.id)]

        return record

This way every time a new x_traders_stock is inserted in product.template, a new x_bags_design is also created in res.partner.

BUT.. when I save a new record in product.template I get an sql error:

bad query:  INSERT INTO bags_design_manufactur (res_partner_id, product_product_id)
                    (SELECT a, b FROM unnest(ARRAY[1]) AS a, unnest(ARRAY[7]) AS b)
                    EXCEPT (SELECT res_partner_id, product_product_id FROM bags_design_manufactur WHERE res_partner_id IN (1))

I don't understand where the EXCEPT part of the sql query is coming from and how to prevent it. If anyone can help I would be grateful.. thanks!

Body:
The error message is a bit different from expected, but I can fix some problems in your code. First of all you have to take into account that a product.product object is a variant of a product.template object, so you can have in a database many product.product objects pointing to the same product.template (e.g. a product.template is a T-shirt and a product.product is a T-shirt colour red size M). This means that you can't try to set the ID of a product.template in a field which is expecting the ID of a product.product, as you're doing here:

singletrader.x_bagsdesign = [(4,self.id)]

Of course, that mistake will not give you the message error you are receiving, there must be something wrong in other part of your code (I guess related to bags_design_manufactur model).

However, to fix the problem I told you above, you should write this:

class product_template_fields(models.Model):
    _inherit = 'product.template'

    x_traders_stock = fields.Many2many(
        comodel_name='res.partner',
        string='Traders with access to stock',
        relation='xtradstock_res_partner_rel'
    )

    @api.multi
    def write(self, vals):
        result = super(product_template_fields, self).write(vals)
        for prod_templ in self:
            products = self.env['product.product'].search([
                ('product_tmpl_id', '=', prod_templ.id),
            ])
            for singletrader in prod_templ.x_traders_stock:
                singletrader.write({
                    'x_bagsdesign': [(4, product.id) for product in products],
                })
        return result

EDIT

product.product inherits from product.template by delegation, this means that every field you create in product.template model is going to be available in product.product objects, so when you are creating the Many2many field x_traders_stock in product.template, you're creating it in product.product too, so you don't need to add records each time a x_trader is generated. Instead you should change your models:

class ResPartner(models.Model):
    x_bagsdesign_prod_templ = fields.Many2many(
        comodel_name='product.template',
        column1='partner_id',
        column2='product_tmpl_id',
        string='Bags Design',
        relation='xtradstock_res_partner_rel'
    )

class ProductTemplate(models.Model):
    _inherit = 'product.template'

    x_traders_stock = fields.Many2many(
        comodel_name='res.partner',
        column1='product_tmpl_id',
        column2='partner_id',
        string='Traders with access to stock',
        relation='xtradstock_res_partner_rel'
    )

And then, if you want to access to the product.product objects a partner has, you can do it this way:

any_partner.x_bagsdesign_prod_templ.mapped('product_variant_ids')

If you preferred it, you could even create a new related field in res.partner which brought the product.product objects a partner has.


来源: stackexchange

问:
Null array of buttons supposed to be set
I don't understand why in my code I get a :

null reference object

when i try to click on my buttons.

```<code>buttonMenuOption = findViewById(R.id.buttonOption);
Button[] buttonsOption = new Button[nbObjects];
buttonsOption[0] = findViewById(R.id.buttonOption0);
buttonsOption[1] = findViewById(R.id.buttonOption1);
buttonMenuOption.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        setContentView(R.layout.graph_option);
            for (int i = 0; i < nbObjects; i++) {
                final int j = i;
                    buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            //Do stuff
                          }
                    });
             }
     });
</code>```

To resume my code, there is an option button in my main activity, when I press it, it changes the layout then there are multiples buttons to activate a color picker.

Why is my buttonsOption[0] a null reference?

Update

```<code>buttonMenuOption = findViewById(R.id.buttonOption)
buttonMenuOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
     setContentView(R.layout.graph_option);
     Button[] buttonsOption = new Button[nbObjects];
        for (int i = 0; i < nbObjects; i++) {
            final int j = i;
            buttonsOption[0] = findViewById(R.id.buttonOption0);
            buttonsOption[1] = findViewById(R.id.buttonOption1);
            buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //Do stuff
                      }
                });
         }
 });
</code>```

答:
problem occurred from

```<code>buttonsOption[0] = findViewById(R.id.buttonOption0);
buttonsOption[1] = findViewById(R.id.buttonOption1);
</code>```

which are declared before related layout initialize.

so you may have to declare button reference after setContentView(R.layout.graph_option); like below

```<code>    buttonMenuOption = findViewById(R.id.buttonOption);
 final Button[] buttonsOption = new Button[nbObjects];

buttonMenuOption.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        setContentView(R.layout.graph_option);
         buttonsOption[0] = findViewById(R.id.buttonOption0);//change here
         buttonsOption[1] = findViewById(R.id.buttonOption1);// change here
            for (int i = 0; i < nbObjects; i++) {
                final int j = i;
                    buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            //Do stuff
                          }
                    });
             }
     });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I don't understand why in my code I get a :

null reference object

when i try to click on my buttons.

buttonMenuOption = findViewById(R.id.buttonOption);
Button[] buttonsOption = new Button[nbObjects];
buttonsOption[0] = findViewById(R.id.buttonOption0);
buttonsOption[1] = findViewById(R.id.buttonOption1);
buttonMenuOption.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        setContentView(R.layout.graph_option);
            for (int i = 0; i < nbObjects; i++) {
                final int j = i;
                    buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            //Do stuff
                          }
                    });
             }
     });

To resume my code, there is an option button in my main activity, when I press it, it changes the layout then there are multiples buttons to activate a color picker.

Why is my buttonsOption[0] a null reference?

Update

buttonMenuOption = findViewById(R.id.buttonOption)
buttonMenuOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
     setContentView(R.layout.graph_option);
     Button[] buttonsOption = new Button[nbObjects];
        for (int i = 0; i < nbObjects; i++) {
            final int j = i;
            buttonsOption[0] = findViewById(R.id.buttonOption0);
            buttonsOption[1] = findViewById(R.id.buttonOption1);
            buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //Do stuff
                      }
                });
         }
 });

Body:
problem occurred from

buttonsOption[0] = findViewById(R.id.buttonOption0);
buttonsOption[1] = findViewById(R.id.buttonOption1);

which are declared before related layout initialize.

so you may have to declare button reference after setContentView(R.layout.graph_option); like below

    buttonMenuOption = findViewById(R.id.buttonOption);
 final Button[] buttonsOption = new Button[nbObjects];

buttonMenuOption.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        setContentView(R.layout.graph_option);
         buttonsOption[0] = findViewById(R.id.buttonOption0);//change here
         buttonsOption[1] = findViewById(R.id.buttonOption1);// change here
            for (int i = 0; i < nbObjects; i++) {
                final int j = i;
                    buttonsOption[i].setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            //Do stuff
                          }
                    });
             }
     });


问:
How to use std::foreach with parameters/modification
I've found myself writing

```<code>for(int i=0;i<myvec.size();i++)
   myvec[i]->DoWhatever(param);
</code>```

a lot, and I'd like to compress this into a foreach statement, but I'm not sure how to get param in there without going super-verbose. I've also got things like

```<code>for(int i=0;i<myvec.size();i++)
   if(myvec[i]->IsOK())
      myvec[i]->DoWhatever(param);
</code>```

and I'd like to rewrite that guy too. Any thoughts?

Oh, also, for various reasons, I don't want to use boost.

答:
My preferred solution is usually to write a functor to do what I need:

```<code>struct doWhatever {
  doWhatever(const Param& p) p(p) {}
  void operator(MyVec v&, Param p) {
    v.DoWhatever(param);
  }

private:
  Param p;
};
</code>```

And then the loop:

```<code>std::for_each(myvec.begin(), myvec.end(), doWhatever(param));
</code>```

Depending on how many variations of this you have, this might be a bit too verbose.
There are plenty of options for doing it inline though.
boost::lambda would let you construct the function you need at the call-site. boost::bind (or the standard library bind functions) would let you bind the parameter param to the function so you don't need to supply it as an argument every time.

boost::lambda is probably the most concise and flexible approach. I usually use the plain functor approach because the syntax is easier to remember. ;)

OwnerDisplayName: Jesse Beder

ContentLicense: CC BY-SA 2.5

Body:
I've found myself writing

for(int i=0;i<myvec.size();i++)
   myvec[i]->DoWhatever(param);

a lot, and I'd like to compress this into a foreach statement, but I'm not sure how to get param in there without going super-verbose. I've also got things like

for(int i=0;i<myvec.size();i++)
   if(myvec[i]->IsOK())
      myvec[i]->DoWhatever(param);

and I'd like to rewrite that guy too. Any thoughts?

Oh, also, for various reasons, I don't want to use boost.

Body:
My preferred solution is usually to write a functor to do what I need:

struct doWhatever {
  doWhatever(const Param& p) p(p) {}
  void operator(MyVec v&, Param p) {
    v.DoWhatever(param);
  }

private:
  Param p;
};

And then the loop:

std::for_each(myvec.begin(), myvec.end(), doWhatever(param));

Depending on how many variations of this you have, this might be a bit too verbose.
There are plenty of options for doing it inline though.
boost::lambda would let you construct the function you need at the call-site. boost::bind (or the standard library bind functions) would let you bind the parameter param to the function so you don't need to supply it as an argument every time.

boost::lambda is probably the most concise and flexible approach. I usually use the plain functor approach because the syntax is easier to remember. ;)

OwnerDisplayName: jalf


问:
Why does Map with a pointer to template functor as value_type not work?
Visual studio borks when I try to create a std::map with the value type being a pointer to template-functor. Am I doing something illegal here ?

```<code>// Functor prototype
template< class T, class evenT>
class FunctionHandler {};

// std::Map definition
template <class T, class evenT>
map<int, FunctionHandler<T, evenT>* > lookup;
</code>```

Can someone please tell me if this is an error (and why is this wrong) or is it just Visual studio ?

答:
The problem is that you cannot have a "variable template".  It doesn't make any sense.

You need to create a variable with a specific type (i.e. specific values for T and evenT), or do something like:

```<code>template <class T, class evenT>
class SomeClass
{
    map<int, FunctionHandler<T, evenT>* > lookup;
};
</code>```

Body:
Visual studio borks when I try to create a std::map with the value type being a pointer to template-functor. Am I doing something illegal here ?

// Functor prototype
template< class T, class evenT>
class FunctionHandler {};

// std::Map definition
template <class T, class evenT>
map<int, FunctionHandler<T, evenT>* > lookup;

Can someone please tell me if this is an error (and why is this wrong) or is it just Visual studio ?

Body:
The problem is that you cannot have a "variable template".  It doesn't make any sense.

You need to create a variable with a specific type (i.e. specific values for T and evenT), or do something like:

template <class T, class evenT>
class SomeClass
{
    map<int, FunctionHandler<T, evenT>* > lookup;
};


问:
How can I use special characters with json encode?
I am encoding some text with json:

```<code>  $json = array('result' => '',);
  $json['result'].='My name is Roger';
  echo json_encode($json);
</code>```

My output is My name is Roger.

But when I write

```<code>  $json = array('result' => '',);
  $json['result'].='test {#[^[*]+|€~!,<€¥<=?"{*\>Ö.ßäülenwj test ';
  echo json_encode($json);
</code>```

Then I do not get any output.

I also tested to work with htmlspecialchars but without success.

答:
maybe your file is ISO-8859-1/15 encoded. json_encode only works with utf8 charset.

In your test scenario you can convert the whole file to utf8 and I think you will get the right response.

Otherwise you need to convert your string to utf8 using utf8_encode("iso_string");

Hope this helps.

Grtngs
Dustin

Body:
I am encoding some text with json:

  $json = array('result' => '',);
  $json['result'].='My name is Roger';
  echo json_encode($json);

My output is My name is Roger.

But when I write

  $json = array('result' => '',);
  $json['result'].='test {#[^[*]+|€~!,<€¥<=?"{*\>Ö.ßäülenwj test ';
  echo json_encode($json);

Then I do not get any output.

I also tested to work with htmlspecialchars but without success.


问:
How to extract last X digits from fixed Y digit number using RegEx?
How to extract last X digits from fixed Y digit number using RegEx?

input : 1234567890123456

((?=\d{16}$)\d{10}|)  gives 1234567890

But

((?=\d{16}$)\d{10}$|) does not give 7890123456

basically, I want last 10 digits if it is compulsory 16 digit no else nothing.

答:
How to extract last X digits from fixed Y digit number using RegEx?

.{X}$

where X is number of digits you want to extract


问:
Can we create react native app without "create-react-native-app" cli?
Do we always need this "create-react-native-app" utility or we can set up manually? I wanted to know if there is any other way to setup for working with react-native.</p>

答:
Yes, you can.

```<code>$ npm install -g react-native-cli
$ react-native init AwesomeProject
$ cd AwesomeProject
$ react-native run-ios/android
</code>```

Explanation:

$ npm install -g react-native-cli installs a global npm package from Facebook to create a native project.

$ react-native init AwesomeProject will create a blank app with the data structure.

$react-native run-ios/android will compile your application and install on your device.

Body:
Yes, you can.

$ npm install -g react-native-cli
$ react-native init AwesomeProject
$ cd AwesomeProject
$ react-native run-ios/android

Explanation:

$ npm install -g react-native-cli installs a global npm package from Facebook to create a native project.

$ react-native init AwesomeProject will create a blank app with the data structure.

$react-native run-ios/android will compile your application and install on your device.


问:
How to save a Button drawable when rotating screen
I just read this: Saving Android Activity state using Save Instance State

this: Android - Open resource from @drawable String

My situation is: I have a Button background set when pressing it to be green with

```<code>button.setBackgroundResource(R.drawable.greenbutton);
</code>```

How can I store this information with onSaveInstanceState and onRestoreInstanceState?

I tried: How to maintain a button style and click state after screen rotation? and worked but maybe there is something better than a three-nested-if-conditionals procedure? I mean I have to do this for 4+ Button and I think it a lot of work for just a simple cause :)

Thank you

EDIT: this is the code so far

```<code>package com.example.android.testbutton;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.change);
    }

    Button button;
    Boolean click;

    public void changeColor(View view) {
        click = true;
        button.setBackgroundResource(R.drawable.greenbutton);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {

        // Save UI state changes to the savedInstanceState.
        // This bundle will be passed to onCreate if the process is
        // killed and restarted.

        savedInstanceState.putBoolean("buttonClicked", click);
        // etc.

        super.onSaveInstanceState(savedInstanceState);
    }

//onRestoreInstanceState

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);

        // Restore UI state from the savedInstanceState.
        // This bundle has also been passed to onCreate.

        Boolean firstAnswer = savedInstanceState.getBoolean("buttonClicked");
        {
            if (savedInstanceState != null) {
                if (savedInstanceState.containsKey("buttonClicked")) {
                    if (savedInstanceState.getBoolean("buttonClicked"))
                        button.setBackgroundResource(R.drawable.greenbutton);

                    //some codes to make the button becomes clicked.
                }
            }
        }
    }
}
</code>```

答:
You have a few options:

You can set specific flags in AndroidManifest file:

<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>

It does not work by default because , when you change the orientation onCreate will be called again and it redraws your view. But If you set these flags and you are using a different layout for landscape mode, by adding these parameters the layout for landscape mode will not be called, because onCreate will not be called second time.

You can save int resources by:

int colorFirst = answerOne.getHighlightColor();
savedInstanceState.putInt("key", colorFirst);

Body:
I just read this: Saving Android Activity state using Save Instance State

this: Android - Open resource from @drawable String

My situation is: I have a Button background set when pressing it to be green with

button.setBackgroundResource(R.drawable.greenbutton);

How can I store this information with onSaveInstanceState and onRestoreInstanceState?

I tried: How to maintain a button style and click state after screen rotation? and worked but maybe there is something better than a three-nested-if-conditionals procedure? I mean I have to do this for 4+ Button and I think it a lot of work for just a simple cause :)

Thank you

EDIT: this is the code so far

package com.example.android.testbutton;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.change);
    }

    Button button;
    Boolean click;

    public void changeColor(View view) {
        click = true;
        button.setBackgroundResource(R.drawable.greenbutton);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {

        // Save UI state changes to the savedInstanceState.
        // This bundle will be passed to onCreate if the process is
        // killed and restarted.

        savedInstanceState.putBoolean("buttonClicked", click);
        // etc.

        super.onSaveInstanceState(savedInstanceState);
    }

//onRestoreInstanceState

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);

        // Restore UI state from the savedInstanceState.
        // This bundle has also been passed to onCreate.

        Boolean firstAnswer = savedInstanceState.getBoolean("buttonClicked");
        {
            if (savedInstanceState != null) {
                if (savedInstanceState.containsKey("buttonClicked")) {
                    if (savedInstanceState.getBoolean("buttonClicked"))
                        button.setBackgroundResource(R.drawable.greenbutton);

                    //some codes to make the button becomes clicked.
                }
            }
        }
    }
}


问:
TS:2304 cannot find Jasmine definitions in WebStorm 2017.3 with Angular CLI
Angular by default has included @types/jasmine.  Moreover, the types are include in the tsconfig.spec.ts

```<code>{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "module": "commonjs",
    "target": "es5",
    "baseUrl": "",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "test.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}
</code>```

W/O the definitions I can still click into the definition files which is weird:

My describe will only work if I reference the path directly which is bad practice:

```<code>///<reference path="../../../node_modules/@types/jasmine/index.d.ts"/>
// Now works!

describe('Service: Auth', () => {

});
</code>```

Question: Any idea why my types for Jasmine are not being visually referenced in WebStorm?

答: WebStorm does not support tsconfig.spec.json. All the TypeScript options should be described in the file named tsconfig.json. Please follow this related issue for updates: https://youtrack.jetbrains.com/issue/WEB-28091

Body:
Angular by default has included @types/jasmine.  Moreover, the types are include in the tsconfig.spec.ts

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "module": "commonjs",
    "target": "es5",
    "baseUrl": "",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "test.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}

W/O the definitions I can still click into the definition files which is weird:

My describe will only work if I reference the path directly which is bad practice:

///<reference path="../../../node_modules/@types/jasmine/index.d.ts"/>
// Now works!

describe('Service: Auth', () => {

});

Question: Any idea why my types for Jasmine are not being visually referenced in WebStorm?


问:
I am unable to access the webelement without using the find_elements
```<code>paymentNumber = driver.find_elements_by_xpath('.//*[@id="search"]')
paymentNumber.send_keys(check_number)
</code>```

but as it returns a list I am unable to send values to the textbox. Already tried with find_element_by_xpath(''), it just crashes by raising exception:raise exception_class(message, screen, stacktrace):cant locate the webelement

Error:   File

line 53, in downloadFile
      paymentNumber.send_keys(check_number) AttributeError: ("'list' object has no attribute 'send_keys'", u'occurred at index 0')

答:
Given that you use the same Xpath expression it is hard to believe that

```<code>find_element_by_xpath
</code>```

behaves differently than

```<code>find_elements_by_xpath
</code>```

Most probably, the Xpath expression is wrong and no element is found. With find_elements_by_xpath an empty list is retrieved so calling anything on the first element won't work.

Change your Xpath expression, so that it matches the element you want to work with. Add some logging or check the size of the list of elements prior to using it.

Body:
paymentNumber = driver.find_elements_by_xpath('.//*[@id="search"]')
paymentNumber.send_keys(check_number)

but as it returns a list I am unable to send values to the textbox. Already tried with find_element_by_xpath(''), it just crashes by raising exception:raise exception_class(message, screen, stacktrace):cant locate the webelement

Error:   File

line 53, in downloadFile
      paymentNumber.send_keys(check_number) AttributeError: ("'list' object has no attribute 'send_keys'", u'occurred at index 0')

Body:
Given that you use the same Xpath expression it is hard to believe that

find_element_by_xpath

behaves differently than

find_elements_by_xpath

Most probably, the Xpath expression is wrong and no element is found. With find_elements_by_xpath an empty list is retrieved so calling anything on the first element won't work.

Change your Xpath expression, so that it matches the element you want to work with. Add some logging or check the size of the list of elements prior to using it.


问:
Angular routing error and right way to do it?
I've been learning angular to use with my ruby on rails application and am having some problems with the routing

this is my app.routing file:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

//Layouts
import { FullLayoutComponent } from './layouts/full-layout.component';

export const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full', },

  {
    path: '', component: FullLayoutComponent, data: { title: 'Página Inicial' },
    children:
    [{ path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule' },
    { path: 'organizations', loadChildren: './organizations/organizations.module#OrganizationsModule' },
    ]
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
    export class AppRoutingModule { }
</code>```

this is the organizations.module file:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

//Routing
import { OrganizationsRoutingModule } from './organizations-routing.module';

@NgModule({
  imports: [
    OrganizationsRoutingModule
  ],
  declarations: []
})
export class OrganizationsModule{ }
</code>```

and this is the organizations-routing.module file:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { OrganizationsComponent } from './organizations.component';
import { OrganizationFormComponent } from './organization-form/organization-form.component';
import { CommonModule } from '@angular/common';
 import { FormsModule } from '@angular/forms';

const routes: Routes = [
  {
    path: '', pathMatch: 'full', component: OrganizationsComponent,
    data: { title: 'Organizações' },
    children: [

      {
        path: 'new', component: OrganizationFormComponent,
        data: { title: 'Cadastrar nova Organização' }
      },
      {
        path: ':id', component: OrganizationFormComponent,
        data: { title: 'Mostrar Organização' }
      },
      {
        path: ':id/edit', component: OrganizationFormComponent,
        data: { title: 'Editar Organização' }
      },
    ]
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes), CommonModule, FormsModule],
  exports: [RouterModule],
  declarations:[OrganizationsComponent, OrganizationFormComponent]
})
export class OrganizationsRoutingModule { }
</code>```

doing it this way, the /organizations path works, but /organizations/new don't, I get this error on the console:

Other way that I tried is to put everything on app.routing, resulting in something like this:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

//Layouts
import { FullLayoutComponent } from './layouts/full-layout.component';
import { OrganizationsComponent } from './organizations/organizations.component';
import { OrganizationFormComponent } from './organizations/organization-form/organization-form.component';

export const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full', },

  {
    path: '', component: FullLayoutComponent, data: { title: 'Página Inicial' },
    children:
    [{ path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule' },
      {
        path: 'organizations', pathMatch: 'full', component: OrganizationsComponent,
        data: { title: 'Organizações' },
      },
      {
        path: 'organizations/new', component: OrganizationFormComponent,
        data: { title: 'Cadastrar nova Organização' }
      },
      {
        path: 'organizations/:id', component: OrganizationFormComponent,
        data: { title: 'Mostrar Organização' }
      },
      {
        path: 'organizations/:id/edit', component: OrganizationFormComponent,
        data: { title: 'Editar Organização' }
      },
    ]
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

this works, but as far as I have seen, it isn't the best way to do it.

How should I build my routes?

thanks!

答:
You have a lot of mistakes on your logic

First of all, Why would you redirect '' to 'dashboard' and then have 'dashboard' be a child of '' ??

Also you should never use pathMatch: 'full' when the path: '' has children

You should do the following in my opinion:

app-routing.module.ts

```<code>export const routes: Routes = [
  {
    path: '', component: FullLayoutComponent, data: { title: 'Página Inicial' },
    children: [
        { path: '', redirectTo: 'dashboard' },
        { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule' },
        { path: 'organizations', redirectTo: '/organizations' },
      ]
    },
];
</code>```

organizations-routing.module

```<code>const routes: Routes = [
  {
    path: 'organizations', component: OrganizationsComponent,
    data: { title: 'Organizações' },
    children: [
      {
        path: 'new', component: OrganizationFormComponent,
        data: { title: 'Cadastrar nova Organização' }
      },
      {
        path: ':id', component: OrganizationFormComponent,
        data: { title: 'Mostrar Organização' }
      },
      {
        path: ':id/edit', component: OrganizationFormComponent,
        data: { title: 'Editar Organização' }
      },
    ]
  },
];
</code>```

Body:
I've been learning angular to use with my ruby on rails application and am having some problems with the routing

this is my app.routing file:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

//Layouts
import { FullLayoutComponent } from './layouts/full-layout.component';

export const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full', },

  {
    path: '', component: FullLayoutComponent, data: { title: 'Página Inicial' },
    children:
    [{ path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule' },
    { path: 'organizations', loadChildren: './organizations/organizations.module#OrganizationsModule' },
    ]
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
    export class AppRoutingModule { }

this is the organizations.module file:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

//Routing
import { OrganizationsRoutingModule } from './organizations-routing.module';

@NgModule({
  imports: [
    OrganizationsRoutingModule
  ],
  declarations: []
})
export class OrganizationsModule{ }

and this is the organizations-routing.module file:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { OrganizationsComponent } from './organizations.component';
import { OrganizationFormComponent } from './organization-form/organization-form.component';
import { CommonModule } from '@angular/common';
 import { FormsModule } from '@angular/forms';

const routes: Routes = [
  {
    path: '', pathMatch: 'full', component: OrganizationsComponent,
    data: { title: 'Organizações' },
    children: [

      {
        path: 'new', component: OrganizationFormComponent,
        data: { title: 'Cadastrar nova Organização' }
      },
      {
        path: ':id', component: OrganizationFormComponent,
        data: { title: 'Mostrar Organização' }
      },
      {
        path: ':id/edit', component: OrganizationFormComponent,
        data: { title: 'Editar Organização' }
      },
    ]
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes), CommonModule, FormsModule],
  exports: [RouterModule],
  declarations:[OrganizationsComponent, OrganizationFormComponent]
})
export class OrganizationsRoutingModule { }

doing it this way, the /organizations path works, but /organizations/new don't, I get this error on the console:

Other way that I tried is to put everything on app.routing, resulting in something like this:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

//Layouts
import { FullLayoutComponent } from './layouts/full-layout.component';
import { OrganizationsComponent } from './organizations/organizations.component';
import { OrganizationFormComponent } from './organizations/organization-form/organization-form.component';

export const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full', },

  {
    path: '', component: FullLayoutComponent, data: { title: 'Página Inicial' },
    children:
    [{ path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule' },
      {
        path: 'organizations', pathMatch: 'full', component: OrganizationsComponent,
        data: { title: 'Organizações' },
      },
      {
        path: 'organizations/new', component: OrganizationFormComponent,
        data: { title: 'Cadastrar nova Organização' }
      },
      {
        path: 'organizations/:id', component: OrganizationFormComponent,
        data: { title: 'Mostrar Organização' }
      },
      {
        path: 'organizations/:id/edit', component: OrganizationFormComponent,
        data: { title: 'Editar Organização' }
      },
    ]
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

this works, but as far as I have seen, it isn't the best way to do it.

How should I build my routes?

thanks!

Body:
You have a lot of mistakes on your logic

First of all, Why would you redirect '' to 'dashboard' and then have 'dashboard' be a child of '' ??

Also you should never use pathMatch: 'full' when the path: '' has children

You should do the following in my opinion:

app-routing.module.ts

export const routes: Routes = [
  {
    path: '', component: FullLayoutComponent, data: { title: 'Página Inicial' },
    children: [
        { path: '', redirectTo: 'dashboard' },
        { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule' },
        { path: 'organizations', redirectTo: '/organizations' },
      ]
    },
];

organizations-routing.module

const routes: Routes = [
  {
    path: 'organizations', component: OrganizationsComponent,
    data: { title: 'Organizações' },
    children: [
      {
        path: 'new', component: OrganizationFormComponent,
        data: { title: 'Cadastrar nova Organização' }
      },
      {
        path: ':id', component: OrganizationFormComponent,
        data: { title: 'Mostrar Organização' }
      },
      {
        path: ':id/edit', component: OrganizationFormComponent,
        data: { title: 'Editar Organização' }
      },
    ]
  },
];


问:
WPF Toolkit (February 2010 release) Chart with Column Series empty when ItemsSource has only one item
I'm having an annoying problem: I have a simple Chart with one ColumnSeries and two axis (a LinearAxis for the dependent value and a DateTimeAxis for the independent one).
My ColumnSeries' ItemsSource is bound to a Collection of instances of DataPoint (simple class with only 3 properties: Date, IndependentValue and DependentValue).
The Chart displays the columns correctly if the Collection has 2 or more items in it; but if it only has one, it won't show any column.

Any ideas on what's going on?

Here's the XAML (with both standard and WPF Toolkit's namespaces omitted for brevity):

```<code><Window x:Class="Demo.MainWindow" (...) xmlns:local="clr-namespace:Demo">
  <Grid>
    <Grid.Resources>
      <local:DataPointCollection x:Key="DataPointCollection" />
    </Grid.Resources>
    <ct:Chart Title="Demo">
      <ct:ColumnSeries Title="A"
                       ItemsSource="{StaticResource DataPointCollection}"
                       IndependentValueBinding="{Binding Date}"
                       DependentValueBinding="{Binding DependentValue}" />
      <ct:Chart.Axes>
        <ct:LinearAxis Orientation="Y"
                       ShowGridLines="True"
                       Title="Dependent Title" />
        <ct:DateTimeAxis Orientation=X"
                         ShowGridLines="True"
                         Interval="1"
                         IntervalType="Days" />
      </ct:Chart.Axes>
    </ct:Chart>
  </Grid>
</Window>
</code>```

The DataPointCollection class:

```<code>using System;

namespace Demo
{
  using System.Collections.ObjectModel;

  public class DataPointCollection: Collection<DataPoint>
  {
    public DataPointCollection()
    {
      Add(new DataPoint { Date = DateTime.Now.Date, DependentValue = 5 });
      // Comment next line to see an empty chart:
      Add(new DataPoint { Date = DateTime.Now.Date.AddDays(1), DependentValue = 6 });
    }
  }
}
</code>```

And the DataPoint class:

```<code>using System;

namespace Demo
{
  public class DataPoint
  {
    public DateTime Date { get; set; }
    public double DependentValue { get; set; }
  }
}
</code>```

The project is a regular WPF Application (WPF 4).

Thanks in advance.

答:
Glancing at the source code for ColumnSeries shows that the column width is related to the range of the data, which in your case is zero.  Unless you want to fix bugs in the toolkit, the only workaround I can suggest is to surround your single point with dummy points to make it look like only one column is being shown:

```<code>        var now = DateTime.Now;
        Add(new DataPoint { Date = now, DependentValue = 5 });
        Add(new DataPoint { Date = now + TimeSpan.FromDays(1), DependentValue = 0 });
        Add(new DataPoint { Date = now - TimeSpan.FromDays(1), DependentValue = 0 });
</code>```

Body:
I'm having an annoying problem: I have a simple Chart with one ColumnSeries and two axis (a LinearAxis for the dependent value and a DateTimeAxis for the independent one).
My ColumnSeries' ItemsSource is bound to a Collection of instances of DataPoint (simple class with only 3 properties: Date, IndependentValue and DependentValue).
The Chart displays the columns correctly if the Collection has 2 or more items in it; but if it only has one, it won't show any column.

Any ideas on what's going on?

Here's the XAML (with both standard and WPF Toolkit's namespaces omitted for brevity):

<Window x:Class="Demo.MainWindow" (...) xmlns:local="clr-namespace:Demo">
  <Grid>
    <Grid.Resources>
      <local:DataPointCollection x:Key="DataPointCollection" />
    </Grid.Resources>
    <ct:Chart Title="Demo">
      <ct:ColumnSeries Title="A"
                       ItemsSource="{StaticResource DataPointCollection}"
                       IndependentValueBinding="{Binding Date}"
                       DependentValueBinding="{Binding DependentValue}" />
      <ct:Chart.Axes>
        <ct:LinearAxis Orientation="Y"
                       ShowGridLines="True"
                       Title="Dependent Title" />
        <ct:DateTimeAxis Orientation=X"
                         ShowGridLines="True"
                         Interval="1"
                         IntervalType="Days" />
      </ct:Chart.Axes>
    </ct:Chart>
  </Grid>
</Window>

The DataPointCollection class:

using System;

namespace Demo
{
  using System.Collections.ObjectModel;

  public class DataPointCollection: Collection<DataPoint>
  {
    public DataPointCollection()
    {
      Add(new DataPoint { Date = DateTime.Now.Date, DependentValue = 5 });
      // Comment next line to see an empty chart:
      Add(new DataPoint { Date = DateTime.Now.Date.AddDays(1), DependentValue = 6 });
    }
  }
}

And the DataPoint class:

using System;

namespace Demo
{
  public class DataPoint
  {
    public DateTime Date { get; set; }
    public double DependentValue { get; set; }
  }
}

The project is a regular WPF Application (WPF 4).

Thanks in advance.

Body:
Glancing at the source code for ColumnSeries shows that the column width is related to the range of the data, which in your case is zero.  Unless you want to fix bugs in the toolkit, the only workaround I can suggest is to surround your single point with dummy points to make it look like only one column is being shown:

        var now = DateTime.Now;
        Add(new DataPoint { Date = now, DependentValue = 5 });
        Add(new DataPoint { Date = now + TimeSpan.FromDays(1), DependentValue = 0 });
        Add(new DataPoint { Date = now - TimeSpan.FromDays(1), DependentValue = 0 });


问:
Nativescript inner StackLayout
Hello everyone I'm trying to make inner StackLayouts but the second one comes to top of first one so that I can't see the second StackLayout  should I handle with css  if it is how or is there an other way

Here is my code

```<code><StackLayout orientation="horizontal">
    <StackLayout width="500">
         <GridLayout columns="50, *" rows="*" width="500" height="50"
         verticalAlignment="top">
               <Label text="Name" row="0" col="0" backgroundColor="red">
               </Label>
               <Label text="Fol" row="0" col="1" class="alignRight"
               backgroundColor="blue"></Label>
         </GridLayout>
    </StackLayout>

      <StackLayout orientation="horizontal" width="500" height="180">
           <Image src="http://lorempixel.com/400/200" width="500" left="10"
           top="30">
           </Image>
      </StackLayout>
</StackLayout>
</code>```

Thank you

答:
At first I would delete the widths to see how the page is displayed. 500 is a very big value. Only large tablets can support that.
As an example at first I would try this :

```<code><GridLayout columns="auto, auto">
    <GridLayout col="0" columns="50, *" rows="*" verticalAlignment="top">
          <Label text="Name" row="0" col="0" backgroundColor="red">
          </Label>
          <Label text="Fol" row="0" col="1" class="alignRight"
               backgroundColor="blue"></Label>
    </GridLayout>
    <Image col="1" src="http://lorempixel.com/400/200" left="10" op="30">
    </Image>
</GridLayout>
</code>```

After you see the two parts align horizontally you can start tweaking the widths

Title: Nativescript inner StackLayout

Body:
Hello everyone I'm trying to make inner StackLayouts but the second one comes to top of first one so that I can't see the second StackLayout  should I handle with css  if it is how or is there an other way

Here is my code

<StackLayout orientation="horizontal">
    <StackLayout width="500">
         <GridLayout columns="50, *" rows="*" width="500" height="50"
         verticalAlignment="top">

         </GridLayout>
    </StackLayout>

      <StackLayout orientation="horizontal" width="500" height="180">
           <Image src="http://lorempixel.com/400/200" width="500" left="10"
           top="30">
           </Image>
      </StackLayout>
</StackLayout>

Thank you

Body:
At first I would delete the widths to see how the page is displayed. 500 is a very big value. Only large tablets can support that.
As an example at first I would try this :

<GridLayout columns="auto, auto">
    <GridLayout col="0" columns="50, *" rows="*" verticalAlignment="top">
          <Label text="Name" row="0" col="0" backgroundColor="red">
          </Label>
          <Label text="Fol" row="0" col="1" class="alignRight"
               backgroundColor="blue"></Label>
    </GridLayout>
    <Image col="1" src="http://lorempixel.com/400/200" left="10" op="30">
    </Image>
</GridLayout>

After you see the two parts align horizontally you can start tweaking the widths


问:
WiFi getScanResults returns an empty list if GPS is off. (Android 6.0.1)
i tried to explain the problem in this gif

basically, this test app receives an "RSSI_CHANGED" intent and displays the scan results on the screen.

scan results are always empty unless GPS is enabled.

I guess my question is why?

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions

I have "ACCESS_COARSE_LOCATION" granted

答:
You must declare ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION. A location permission is required because Bluetooth scans can be used to gather information about the location of the user.

This information may come from the user's own devices

So you must give that permission and on the GPS for Bluetooth devices.


问:
PlasticSCM - Icon 'unknown' not present in theme
I'm using CentOS Linux release 7.4.1708, Gnome 3.22.2 and I've installed PlasticSCM 6.0.16.1792.

I created a new repository and everything worked fine until I use the Workspace explorer or the  Pending changes tabs (only when changes exists). Plastic shows several error pop-ups with the message:

Icon 'unknown' not present in theme

I've checked the logs in ${HOME}/.plastic4/gtkplastic.log.txt:

```<code>2017-12-04 16:43:15,252 (null) user at (null) ERROR ExceptionHandler - [HandleUnhandledGLibException] Unexpected error: Icon 'unknown' not present in theme.
</code>```

I tried to change the icon theme from Adawait to Gnome using the Gnome Tweak Tool with no success.

Is there anything that I should configure to fix this problem?

Thank you.

答:
I'm using pretty much the same setup and works for me. I installed from the latest iso at https://www.centos.org/download/:

Centos 7.4.1708:

```<code>> cat /etc/*elease
CentOS Linux release 7.4.1708 (Core)
</code>```

gnome 3.22.2:

```<code>> cat /usr/share/gnome/gnome-version.xml
<?xml version="1.0" encoding="UTF-8"?>
<gnome-version>
 <platform>3</platform>
 <minor>22</minor>
 <micro>2</micro>
 <distributor>GNOME.Org</distributor>
 <date>2017-08-06</date>
</code>```

Plastic version 6.0.16.1820 (Latest available as I write)

```<code>cm version
6.0.16.1820
</code>```

This is what I have in the theme directory:

```<code>> ls -l -R /opt/plasticscm5/theme/*
http://txt.do/dqve8
</code>```

Can you try changing your OS icon set?

Body:
I'm using CentOS Linux release 7.4.1708, Gnome 3.22.2 and I've installed PlasticSCM 6.0.16.1792.

I created a new repository and everything worked fine until I use the Workspace explorer or the  Pending changes tabs (only when changes exists). Plastic shows several error pop-ups with the message:

Icon 'unknown' not present in theme

I've checked the logs in ${HOME}/.plastic4/gtkplastic.log.txt:

2017-12-04 16:43:15,252 (null) user at (null) ERROR ExceptionHandler - [HandleUnhandledGLibException] Unexpected error: Icon 'unknown' not present in theme.

I tried to change the icon theme from Adawait to Gnome using the Gnome Tweak Tool with no success.

Is there anything that I should configure to fix this problem?

Thank you.

Body:
I'm using pretty much the same setup and works for me. I installed from the latest iso at https://www.centos.org/download/:

Centos 7.4.1708:

> cat /etc/*elease
CentOS Linux release 7.4.1708 (Core)

gnome 3.22.2:

> cat /usr/share/gnome/gnome-version.xml
<?xml version="1.0" encoding="UTF-8"?>
<gnome-version>
 <platform>3</platform>
 <minor>22</minor>
 <micro>2</micro>
 <distributor>GNOME.Org</distributor>
 <date>2017-08-06</date>

Plastic version 6.0.16.1820 (Latest available as I write)

cm version
6.0.16.1820

This is what I have in the theme directory:

> ls -l -R /opt/plasticscm5/theme/*
http://txt.do/dqve8

Can you try changing your OS icon set?


问:
JIRA REST API -- Create Project HTTP 400 error
I have downloaded latest version of Jira (https://www.atlassian.com/software/jira/download) and have set it up on my laptop. I am trying to use the REST api for creating a project and running into issues , I am using java for making the call.

the JSON I am sending is -- {\"key\":\"VSPRJ\",\"name\":\"FROMVSPROJ\",\"projectTypeKey\":\"software\",\"description\":\"VSPROJDESC\",\"lead\":\"ADMIN\",\"assigneeType\":\"PROJECT_LEAD\"}

Java code snippet I am using is below

```<code>private static ResponseEntity WriteProjectIssueInformation2Jira()
{
    httpHeaders = createHeadersWithAuthentication();

    String createProjJSON = createCreateProjectJSON("INEMP2", "EMPMGMT", "com.atlassian.jira-core-project-templates:jira-core-project-management","business","ADMIN","PROJECT_LEAD","10000","0","http://atlassian.com","10324","0","0","projfromcode");

    String url = JIRA_URL + "/rest/api/2/project";

    System.out.println(url);
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<String> requestEntity = new HttpEntity<String>(createProjJSON, httpHeaders);

    return restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
}
</code>```

I am getting 400 not matter what I change w.r.t to the JSON I am sending , I have tried the project GET api's and it returns back data. Both the sample java program and JIRA is running in my local laptop.

Not sure if there is any permissions required , please help

答: The issue was with the lead attribute in the json, i created a user gave necessary permission and gave this userid as value for lead attribute and it started working</p>

Body:
I have downloaded latest version of Jira (https://www.atlassian.com/software/jira/download) and have set it up on my laptop. I am trying to use the REST api for creating a project and running into issues , I am using java for making the call.

the JSON I am sending is -- {\"key\":\"VSPRJ\",\"name\":\"FROMVSPROJ\",\"projectTypeKey\":\"software\",\"description\":\"VSPROJDESC\",\"lead\":\"ADMIN\",\"assigneeType\":\"PROJECT_LEAD\"}

Java code snippet I am using is below

private static ResponseEntity WriteProjectIssueInformation2Jira()
{
    httpHeaders = createHeadersWithAuthentication();

    String createProjJSON = createCreateProjectJSON("INEMP2", "EMPMGMT", "com.atlassian.jira-core-project-templates:jira-core-project-management","business","ADMIN","PROJECT_LEAD","10000","0","http://atlassian.com","10324","0","0","projfromcode");

    String url = JIRA_URL + "/rest/api/2/project";

    System.out.println(url);
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<String> requestEntity = new HttpEntity<String>(createProjJSON, httpHeaders);

    return restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
}

I am getting 400 not matter what I change w.r.t to the JSON I am sending , I have tried the project GET api's and it returns back data. Both the sample java program and JIRA is running in my local laptop.

Not sure if there is any permissions required , please help


问:
pybind11: how to package c++ and python code into a single package?
I am trying to package together an existing Python code and a new C++ 11 code using CMake and pybind 11. I think I am missing something simple to add into CMake scripts, but can't find it anywhere: pybind11 examples have only C++ code and none of Python, other online resources are rather convoluted and not up-to-date -- so I just can't figure out how to package functions in both languages together and make them available via Python's import my_package down the line... as an example, I have cloned the cmake_example from pybind11 and added a mult function into cmake_example/mult.py

```<code>def mult(a, b):
    return a * b
</code>```

how would I make it visible along with add and subtract to pass the test below?

```<code>import cmake_example as m

assert m.__version__ == '0.0.1'
assert m.add(1, 2) == 3
assert m.subtract(1, 2) == -1
assert m.mult(2, 2) == 4
</code>```

currently, this test fails..

Thanks!

答:
The simplest solution has nothing to do with pybind11 as such. What authors usually do when they want to combine pure Python and C/Cython/other native extensions in the same package, is the following.

You create two modules.

mymodule is a public interface, a pure Python module

_mymodule is a private implementation, a complied module

Then in mymodule you import necessary symbols from _mymoudle (and fallback to pure Python version if necessary).

Here's example from yarl package:

quoting.py

```<code>try:
    from ._quoting import _quote, _unquote
    quote = _quote
    unquote = _unquote
except ImportError:  # pragma: no cover
    quote = _py_quote
    unquote = _py_unquote
</code>```

_quoting.pyx

Update

Here follows the script. For the sake of reproducibility I'm doing it against original cmake_example.

```<code>git clone --recursive https://github.com/pybind/cmake_example.git
# at the time of writing https://github.com/pybind/cmake_example/commit/8818f493
cd cmake_example
</code>```

Now create pure Python modules (inside cmake_example/cmake_example).

cmake_example/__init__.py

```<code>"""Root module of your package"""
</code>```

cmake_example/math.py

```<code>def mul(a, b):
    """Pure Python-only function"""
    return a * b

def add(a, b):
    """Fallback function"""
    return a + b

try:
    from ._math import add
except ImportError:
    pass
</code>```

Now let's modify existing files to turn cmake_example module into cmake_example._math.

src/main.cpp (subtract removed for brevity)

```<code>#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

namespace py = pybind11;

PYBIND11_MODULE(_math, m) {
    m.doc() = R"pbdoc(
        Pybind11 example plugin
        -----------------------

        .. currentmodule:: _math

        .. autosummary::
           :toctree: _generate

           add
    )pbdoc";

    m.def("add", &add, R"pbdoc(
        Add two numbers

        Some other explanation about the add function.
    )pbdoc");

#ifdef VERSION_INFO
    m.attr("__version__") = VERSION_INFO;
#else
    m.attr("__version__") = "dev";
#endif
}
</code>```

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 2.8.12)
project(cmake_example)

add_subdirectory(pybind11)
pybind11_add_module(_math src/main.cpp)
</code>```

setup.py

```<code># the above stays intact

from subprocess import CalledProcessError

kwargs = dict(
    name='cmake_example',
    version='0.0.1',
    author='Dean Moldovan',
    author_email='dean0x7d@gmail.com',
    description='A test project using pybind11 and CMake',
    long_description='',
    ext_modules=[CMakeExtension('cmake_example._math')],
    cmdclass=dict(build_ext=CMakeBuild),
    zip_safe=False,
    packages=['cmake_example']
)

# likely there are more exceptions, take a look at yarl example
try:
    setup(**kwargs)
except CalledProcessError:
    print('Failed to build extension!')
    del kwargs['ext_modules']
    setup(**kwargs)
</code>```

Now we can build it.

```<code>python setup.py bdist_wheel
</code>```

In my case it produces dist/cmake_example-0.0.1-cp27-cp27mu-linux_x86_64.whl (if C++ compilation fails it's cmake_example-0.0.1-py2-none-any.whl). Here is what it contents (unzip -l ...):

```<code>Archive:  cmake_example-0.0.1-cp27-cp27mu-linux_x86_64.whl
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  2017-12-05 21:42   cmake_example/__init__.py
    81088  2017-12-05 21:43   cmake_example/_math.so
      223  2017-12-05 21:46   cmake_example/math.py
       10  2017-12-05 21:48   cmake_example-0.0.1.dist-info/DESCRIPTION.rst
      343  2017-12-05 21:48   cmake_example-0.0.1.dist-info/metadata.json
       14  2017-12-05 21:48   cmake_example-0.0.1.dist-info/top_level.txt
      105  2017-12-05 21:48   cmake_example-0.0.1.dist-info/WHEEL
      226  2017-12-05 21:48   cmake_example-0.0.1.dist-info/METADATA
      766  2017-12-05 21:48   cmake_example-0.0.1.dist-info/RECORD
---------                     -------
    82775                     9 files
</code>```

Body:
I am trying to package together an existing Python code and a new C++ 11 code using CMake and pybind 11. I think I am missing something simple to add into CMake scripts, but can't find it anywhere: pybind11 examples have only C++ code and none of Python, other online resources are rather convoluted and not up-to-date -- so I just can't figure out how to package functions in both languages together and make them available via Python's import my_package down the line... as an example, I have cloned the cmake_example from pybind11 and added a mult function into cmake_example/mult.py

def mult(a, b):
    return a * b

how would I make it visible along with add and subtract to pass the test below?

import cmake_example as m

assert m.__version__ == '0.0.1'
assert m.add(1, 2) == 3
assert m.subtract(1, 2) == -1
assert m.mult(2, 2) == 4

currently, this test fails..

Thanks!

Body:
The simplest solution has nothing to do with pybind11 as such. What authors usually do when they want to combine pure Python and C/Cython/other native extensions in the same package, is the following.

You create two modules.

mymodule is a public interface, a pure Python module

_mymodule is a private implementation, a complied module

Then in mymodule you import necessary symbols from _mymoudle (and fallback to pure Python version if necessary).

Here's example from yarl package:

quoting.py

try:
    from ._quoting import _quote, _unquote
    quote = _quote
    unquote = _unquote
except ImportError:  # pragma: no cover
    quote = _py_quote
    unquote = _py_unquote

_quoting.pyx

Update

Here follows the script. For the sake of reproducibility I'm doing it against original cmake_example.

git clone --recursive https://github.com/pybind/cmake_example.git
# at the time of writing https://github.com/pybind/cmake_example/commit/8818f493
cd cmake_example

Now create pure Python modules (inside cmake_example/cmake_example).

cmake_example/__init__.py

"""Root module of your package"""

cmake_example/math.py

def mul(a, b):
    """Pure Python-only function"""
    return a * b

def add(a, b):
    """Fallback function"""
    return a + b

try:
    from ._math import add
except ImportError:
    pass

Now let's modify existing files to turn cmake_example module into cmake_example._math.

src/main.cpp (subtract removed for brevity)

#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

namespace py = pybind11;

PYBIND11_MODULE(_math, m) {
    m.doc() = R"pbdoc(
        Pybind11 example plugin
        -----------------------

        .. currentmodule:: _math

        .. autosummary::
           :toctree: _generate

           add
    )pbdoc";

    m.def("add", &add, R"pbdoc(
        Add two numbers

        Some other explanation about the add function.
    )pbdoc");

#ifdef VERSION_INFO
    m.attr("__version__") = VERSION_INFO;
#else
    m.attr("__version__") = "dev";
#endif
}

CMakeLists.txt

cmake_minimum_required(VERSION 2.8.12)
project(cmake_example)

add_subdirectory(pybind11)
pybind11_add_module(_math src/main.cpp)

setup.py

# the above stays intact

from subprocess import CalledProcessError

kwargs = dict(
    name='cmake_example',
    version='0.0.1',
    author='Dean Moldovan',
    author_email='dean0x7d@gmail.com',
    description='A test project using pybind11 and CMake',
    long_description='',
    ext_modules=[CMakeExtension('cmake_example._math')],
    cmdclass=dict(build_ext=CMakeBuild),
    zip_safe=False,
    packages=['cmake_example']
)

# likely there are more exceptions, take a look at yarl example
try:
    setup(**kwargs)
except CalledProcessError:
    print('Failed to build extension!')
    del kwargs['ext_modules']
    setup(**kwargs)

Now we can build it.

python setup.py bdist_wheel

In my case it produces dist/cmake_example-0.0.1-cp27-cp27mu-linux_x86_64.whl (if C++ compilation fails it's cmake_example-0.0.1-py2-none-any.whl). Here is what it contents (unzip -l ...):

Archive:  cmake_example-0.0.1-cp27-cp27mu-linux_x86_64.whl
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  2017-12-05 21:42   cmake_example/__init__.py
    81088  2017-12-05 21:43   cmake_example/_math.so
      223  2017-12-05 21:46   cmake_example/math.py
       10  2017-12-05 21:48   cmake_example-0.0.1.dist-info/DESCRIPTION.rst
      343  2017-12-05 21:48   cmake_example-0.0.1.dist-info/metadata.json
       14  2017-12-05 21:48   cmake_example-0.0.1.dist-info/top_level.txt
      105  2017-12-05 21:48   cmake_example-0.0.1.dist-info/WHEEL
      226  2017-12-05 21:48   cmake_example-0.0.1.dist-info/METADATA
      766  2017-12-05 21:48   cmake_example-0.0.1.dist-info/RECORD
---------                     -------
    82775                     9 files


问:
Sum outputs from atoi
I am trying to learn C++14 (with a "modern"/non-C style). I am trying to sum the digits in a string, for the digits that are equal to the next digit (or the first digit, if at the end of the string). I solved it in Python, but in C++14, I get unexpected output.

main.cpp:

```<code>#include <iostream>
#include <stdlib.h>

using namespace std;

using sum_t =  uint64_t; // int; // unsigned long long;

// sum_digits sums the digits in the given std::string and returns an integer of type sum_t
sum_t sum_digits(std::string digits) {
    sum_t total = 0;
    for (const auto &digit : digits) {
        total += atoi(new char(digit));
        cout << "sum this far: " << total << endl;
    }
    return total;
}

// return the last char
// returns ' ' if given an empty string
char last(std::string digits) {
    auto dl = digits.length();
    if (dl < 1) {
        return ' ';
    }
    return digits.at(dl - 1);
}

// sum_equal_digits returns a sum of the digits that are equal to the next one
sum_t sum_equal_digits(std::string digits) {
    auto equal_digits = ""s; // a list of equal digits, as std::string
    auto prev_digit = last(digits); // start with the last digit, since the digit list is supposed to be circular
    for (const auto &digit : digits) {
        if (digit == prev_digit) {
            equal_digits += digit;
        }
        prev_digit = digit;
    }
    return sum_digits(equal_digits);
}

void equal(sum_t a, sum_t b) {
    if (a == b) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
        exit(EXIT_FAILURE);
    }
}

int main() {
    equal(sum_equal_digits("1122"s), 3);
    equal(sum_equal_digits("1111"s), 4);
    equal(sum_equal_digits("1234"s), 0);
    equal(sum_equal_digits("91212129"s), 9);
    equal(sum_equal_digits("823936645345581272695677318513459491834641129844393742672553544439126314399846773234845535593355348931499496184839582118817689171948635864427852215325421433717458975771369522138766248225963242168658975326354785415252974294317138511141826226866364555761117178764543435899886711426319675443679829181257496966219435831621565519667989898725836639626681645821714861443141893427672384716732765884844772433374798185955741311116365899659833634237938878181367317218635539667357364295754744829595842962773524584225427969467467611641591834876769829719248136613147351298534885563144114336211961674392912181735773851634298227454157885241769156811787611897349965331474217223461176896643242975397227859696554492996937235423272549348349528559432214521551656971136859972232854126262349381254424597348874447736545722261957871275935756764184378994167427983811716675476257858556464755677478725146588747147857375293675711575747132471727933773512571368467386151966568598964631331428869762151853634362356935751298121849281442128796517663482391226174256395515166361514442624944181255952124524815268864131969151433888721213595267927325759562132732586252438456569556992685896517565257787464673718221817783929691626876446423134331749327322367571432532857235214364221471769481667118117729326429556357572421333798517168997863151927281418238491791975399357393494751913155219862399959646993428921878798119215675548847845477994836744929918954159722827194721564121532315459611433157384994543332773796862165243183378464731546787498174844781781139571984272235872866886275879944921329959736315296733981313643956576956851762149275521949177991988236529475373595217665112434727744235789852852765675189342753695377219374791548554786671473733124951946779531847479755363363288448281622183736545494372344785112312749694167483996738384351293899149136857728545977442763489799693492319549773328626918874718387697878235744154491677922317518952687439655962477734559232755624943644966227973617788182213621899579391324399386146423427262874437992579573858589183571854577861459758534348533553925167947139351819511798829977371215856637215221838924612644785498936263849489519896548811254628976642391428413984281758771868781714266261781359762798"), 1144);
    return 0;
}
</code>```

The last two lines of the output are:

```<code>sum this far: 18446744073627459815
NO
</code>```

But I was expecting:

```<code>sum this far: 1144
YES
</code>```

I compiled the program with:

```<code>g++ -O2 -std=c++14 -Wfatal-errors -pedantic -Wall main.cpp -o main
</code>```

I also tried using sum_t = int; and using sum_t = uint64_t;.

How can the program be corrected?

答:
In addtion to Mr1Penguin's answer, which is right for atoi; one could avoid the whole atoi hastle with

```<code>sum_t sum_digits(std::string digits) {
    sum_t total = 0;
    for (const auto &digit : digits)
        total += digit - '0'
    return total;
}
</code>```

but it won't have quite the same protection against non numeric characters.

Title: Sum outputs from atoi

Body:
I am trying to learn C++14 (with a "modern"/non-C style). I am trying to sum the digits in a string, for the digits that are equal to the next digit (or the first digit, if at the end of the string). I solved it in Python, but in C++14, I get unexpected output.

main.cpp:

#include <iostream>
#include <stdlib.h>

using namespace std;

using sum_t =  uint64_t; // int; // unsigned long long;

// sum_digits sums the digits in the given std::string and returns an integer of type sum_t
sum_t sum_digits(std::string digits) {
    sum_t total = 0;
    for (const auto &digit : digits) {
        total += atoi(new char(digit));
        cout << "sum this far: " << total << endl;
    }
    return total;
}

// return the last char
// returns ' ' if given an empty string
char last(std::string digits) {
    auto dl = digits.length();
    if (dl < 1) {
        return ' ';
    }
    return digits.at(dl - 1);
}

// sum_equal_digits returns a sum of the digits that are equal to the next one
sum_t sum_equal_digits(std::string digits) {
    auto equal_digits = ""s; // a list of equal digits, as std::string
    auto prev_digit = last(digits); // start with the last digit, since the digit list is supposed to be circular
    for (const auto &digit : digits) {
        if (digit == prev_digit) {
            equal_digits += digit;
        }
        prev_digit = digit;
    }
    return sum_digits(equal_digits);
}

void equal(sum_t a, sum_t b) {
    if (a == b) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
        exit(EXIT_FAILURE);
    }
}

int main() {
    equal(sum_equal_digits("1122"s), 3);
    equal(sum_equal_digits("1111"s), 4);
    equal(sum_equal_digits("1234"s), 0);
    equal(sum_equal_digits("91212129"s), 9);
    equal(sum_equal_digits("823936645345581272695677318513459491834641129844393742672553544439126314399846773234845535593355348931499496184839582118817689171948635864427852215325421433717458975771369522138766248225963242168658975326354785415252974294317138511141826226866364555761117178764543435899886711426319675443679829181257496966219435831621565519667989898725836639626681645821714861443141893427672384716732765884844772433374798185955741311116365899659833634237938878181367317218635539667357364295754744829595842962773524584225427969467467611641591834876769829719248136613147351298534885563144114336211961674392912181735773851634298227454157885241769156811787611897349965331474217223461176896643242975397227859696554492996937235423272549348349528559432214521551656971136859972232854126262349381254424597348874447736545722261957871275935756764184378994167427983811716675476257858556464755677478725146588747147857375293675711575747132471727933773512571368467386151966568598964631331428869762151853634362356935751298121849281442128796517663482391226174256395515166361514442624944181255952124524815268864131969151433888721213595267927325759562132732586252438456569556992685896517565257787464673718221817783929691626876446423134331749327322367571432532857235214364221471769481667118117729326429556357572421333798517168997863151927281418238491791975399357393494751913155219862399959646993428921878798119215675548847845477994836744929918954159722827194721564121532315459611433157384994543332773796862165243183378464731546787498174844781781139571984272235872866886275879944921329959736315296733981313643956576956851762149275521949177991988236529475373595217665112434727744235789852852765675189342753695377219374791548554786671473733124951946779531847479755363363288448281622183736545494372344785112312749694167483996738384351293899149136857728545977442763489799693492319549773328626918874718387697878235744154491677922317518952687439655962477734559232755624943644966227973617788182213621899579391324399386146423427262874437992579573858589183571854577861459758534348533553925167947139351819511798829977371215856637215221838924612644785498936263849489519896548811254628976642391428413984281758771868781714266261781359762798"), 1144);
    return 0;
}

The last two lines of the output are:

sum this far: 18446744073627459815
NO

But I was expecting:

sum this far: 1144
YES

I compiled the program with:

g++ -O2 -std=c++14 -Wfatal-errors -pedantic -Wall main.cpp -o main

I also tried using sum_t = int; and using sum_t = uint64_t;.

How can the program be corrected?

Body:
In addtion to Mr1Penguin's answer, which is right for atoi; one could avoid the whole atoi hastle with

sum_t sum_digits(std::string digits) {
    sum_t total = 0;
    for (const auto &digit : digits)
        total += digit - '0'
    return total;
}

but it won't have quite the same protection against non numeric characters.


问:
Same image getting uploaded for all the options
I have a dynamic website. I want to accept the details of different items including their image. The js is working but only for one item. The moment I add another item and I try to upload a different pic, either it does not open the dialog or it will take the same image for all the items. For single item, the code is working fine.
This is my fiddle.

```<code>$(".file-upload").on('change', function(){
    readURL(this);
});
$(".upload-button").on('click', function() {
    $(".file-upload").click();
});
$("#additem").click( function () {
    $(".grid").append('<div class="cell" style="overflow: hidden; visibility:;"><form><fieldset style="color:white;"><legend>Item Details</legend><img class="profile-pic" src="" /><div class="upload-button" style="cursor:pointer;">Upload Image</div></br><input class="file-upload" type="file" accept="image/*"/></br><p><input type="text" placeholder="Item name"/></br><p><input type="text" placeholder="Item category"/></br><p><input type="number" placeholder="Number of items"/></br><p><input id="itemsubmit" type="submit" class="btn" value="Add Item"/></br></fieldset></form></div>');
});
</code>```

I feel that my js is working for only one item. If somebody can tell me where am I going wrong. Thanks in advance.

答:
It seems to be you are dynamically adding some new controls to the form on button click.

So the newly created elements doesn't have an event listener that is the issue.

Try to change your code like this.

```<code>  $("body").on('change', '.file-upload', function() {
    /* Your code goes here. */
  });

  $("body").on('click', '.upload-button', function() {
    $(this).parent().find('.file-upload').click();
  });
</code>```

Check this fiddle

Body:
I have a dynamic website. I want to accept the details of different items including their image. The js is working but only for one item. The moment I add another item and I try to upload a different pic, either it does not open the dialog or it will take the same image for all the items. For single item, the code is working fine.
This is my fiddle.

$(".file-upload").on('change', function(){
    readURL(this);
});
$(".upload-button").on('click', function() {
    $(".file-upload").click();
});
$("#additem").click( function () {
    $(".grid").append('
<form><fieldset style="color:white;"><legend>Item Details</legend>
Upload Image

<input class="file-upload" type="file" accept="image/*"/>

<input type="text" placeholder="Item name"/>

<input type="text" placeholder="Item category"/>

<input type="number" placeholder="Number of items"/>

<input id="itemsubmit" type="submit" class="btn" value="Add Item"/>
</fieldset></form>
');
});

I feel that my js is working for only one item. If somebody can tell me where am I going wrong. Thanks in advance.

Body:
It seems to be you are dynamically adding some new controls to the form on button click.

So the newly created elements doesn't have an event listener that is the issue.

Try to change your code like this.

  $("body").on('change', '.file-upload', function() {
    /* Your code goes here. */
  });

  $("body").on('click', '.upload-button', function() {
    $(this).parent().find('.file-upload').click();
  });

Check this fiddle


问:
Google Chrome theme color for href links hover
I'm creating a theme for Chrome, but when I set "tab_text" in manifest.json, the bottom URL status bar is the same color. I searched for a solution in the documentation, but I didn't find an attribute that tints the bottom bar. It affects that bar (as seen on picture) and the download list too. Is there a way to customize the bottom URL status bar?

```<code>"colors" : {
    "tab_text" : [150,150,150]
}
</code>```

<img src="https://i.stack.imgur.com/01CXL.jpg" alt="The "tab_text" affects the bottom bar">

答:
I just had a look at the source file for this (linked from the Chrome theme page on Google code). There currently is no way of setting the status bar text independently.

The background color of the status bar is always the same as that of the toolbar.

ContentLicense: CC BY-SA 4.0

Body:
I'm creating a theme for Chrome, but when I set "tab_text" in manifest.json, the bottom URL status bar is the same color. I searched for a solution in the documentation, but I didn't find an attribute that tints the bottom bar. It affects that bar (as seen on picture) and the download list too. Is there a way to customize the bottom URL status bar?

"colors" : {
    "tab_text" : [150,150,150]
}

<img src="https://i.stack.imgur.com/01CXL.jpg" alt="The "tab_text" affects the bottom bar">


问:
How to put a text and a string inside array
I've create this code

```<code> $S_Jenis = $_POST['JenisTrx'];
 $S_Keterangan = $_POST['KeteranganTrx'];
 $S_Jumlah = $_POST['JumlahTrx'];
</code>```

and I call it here

```<code>$msg = array
      (
    'body'  => $S_Keterangan Rp$S_Jumlah,
    'title' => Kas $S_Jenis,
            'icon'  => 'myicon',
            'sound' => 'mySound'
      );
</code>```

but it's an error if I put "Kas" inside title and 2 String inside body, anyone know how to fix this?

答:
Assuming you want to concatenate these strings:

```<code>$msg = array(
  'body'  => $S_Keterangan . ' Rp' . $S_Jumlah,
  'title' => 'Kas' . $S_Jenis,
  'icon'  => 'myicon',
  'sound' => 'mySound'
);
</code>```

To read about string concatenation in PHP, see: http://php.net/manual/en/language.operators.string.php

Body:
I've create this code

 $S_Jenis = $_POST['JenisTrx'];
 $S_Keterangan = $_POST['KeteranganTrx'];
 $S_Jumlah = $_POST['JumlahTrx'];

and I call it here

$msg = array
      (
    'body'  => $S_Keterangan Rp$S_Jumlah,
    'title' => Kas $S_Jenis,
            'icon'  => 'myicon',
            'sound' => 'mySound'
      );

but it's an error if I put "Kas" inside title and 2 String inside body, anyone know how to fix this?

Body:
Assuming you want to concatenate these strings:

$msg = array(
  'body'  => $S_Keterangan . ' Rp' . $S_Jumlah,
  'title' => 'Kas' . $S_Jenis,
  'icon'  => 'myicon',
  'sound' => 'mySound'
);

To read about string concatenation in PHP, see: http://php.net/manual/en/language.operators.string.php


问:
Java Configuration vs Component Scan Annotations
Java configuration allows us to manage bean creation within a configuration file. Annotated @Component, @Service classes used with component scanning does the same. However, I'm concerned about using these two mechanisms at the same time.

Should Java configuration and annotated component scans be avoided in the same project? I ask because the result is unclear in the following scenario:

```<code>@Configuration
public class MyConfig {
    @Bean
    public Foo foo() {
        return new Foo(500);
    }
}

...

@Component
public class Foo {
    private int value;

    public Foo() {
    }
    public Foo(int value) {
        this.value = value;
    }
}

...

public class Consumer {
    @Autowired
    Foo foo;

    ...
}
</code>```

So, in the above situation, will the Consumer get a Foo instance with a 500 value or 0 value? I've tested locally and it appears that the Java configured Foo (with value 500) is created consistently. However, I'm concerned that my testing isn't thorough enough to be conclusive.

What is the real answer? Using both Java config and component scanning on @Component beans of the same type seems like a bad thing.

答:
It is perfectly valid to have Java configuration and annotated component scans in the same project because they server different purposes.

@Component (@Service,@Repository etc) are used to auto-detect and auto-configure beans.

@Bean annotation is used to explicitly declare a single bean, instead of letting Spring do it automatically.

You can do the following with @Bean. But, this is not possible with @Component

```<code>@Bean
public MyService myService(boolean someCondition) {
    if(someCondition) {
      return new MyServiceImpl1();
    }else{
        return new MyServiceImpl2();
    }
}
</code>```

Haven't really faced a situation where both Java config and component scanning on the bean of the same type were required.

As per the spring documentation,

To declare a bean, simply annotate a method with the @Bean annotation.
  When JavaConfig encounters such a method, it will execute that method
  and register the return value as a bean within a BeanFactory. By
  default, the bean name will be the same as the method name

So, As per this, it is returning the correct Foo (with value 500).

Body:
Java configuration allows us to manage bean creation within a configuration file. Annotated @Component, @Service classes used with component scanning does the same. However, I'm concerned about using these two mechanisms at the same time.

Should Java configuration and annotated component scans be avoided in the same project? I ask because the result is unclear in the following scenario:

@Configuration
public class MyConfig {
    @Bean
    public Foo foo() {
        return new Foo(500);
    }
}

...

@Component
public class Foo {
    private int value;

    public Foo() {
    }
    public Foo(int value) {
        this.value = value;
    }
}

...

public class Consumer {
    @Autowired
    Foo foo;

    ...
}

So, in the above situation, will the Consumer get a Foo instance with a 500 value or 0 value? I've tested locally and it appears that the Java configured Foo (with value 500) is created consistently. However, I'm concerned that my testing isn't thorough enough to be conclusive.

What is the real answer? Using both Java config and component scanning on @Component beans of the same type seems like a bad thing.

Body:
It is perfectly valid to have Java configuration and annotated component scans in the same project because they server different purposes.

@Component (@Service,@Repository etc) are used to auto-detect and auto-configure beans.

@Bean annotation is used to explicitly declare a single bean, instead of letting Spring do it automatically.

You can do the following with @Bean. But, this is not possible with @Component

@Bean
public MyService myService(boolean someCondition) {
    if(someCondition) {
      return new MyServiceImpl1();
    }else{
        return new MyServiceImpl2();
    }
}

Haven't really faced a situation where both Java config and component scanning on the bean of the same type were required.

As per the spring documentation,

To declare a bean, simply annotate a method with the @Bean annotation.
  When JavaConfig encounters such a method, it will execute that method
  and register the return value as a bean within a BeanFactory. By
  default, the bean name will be the same as the method name

So, As per this, it is returning the correct Foo (with value 500).