问:
Lines are not copying in Odoo
The Python code is below.Just check the function which is in the initial class have any error .

employee.py

```<code>import time
import math
import os, base64
from tempfile import TemporaryFile
import random

from odoo.osv import expression
from odoo.tools.float_utils import float_round as round
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError, ValidationError
from odoo import api, fields, models, _
#==================================================
# Class : BiEmployee
# Description : Employee Main Class
#==================================================
class BiEmployee(models.Model):
    _name = "bi.employee"
    _description = "Employee Module"
    _rec_name = "name"
    name = fields.Char(string='Name', required=False )
    emp_name = fields.Char(string = 'Employee Name')
    age = fields.Char(string = 'Age')
    address = fields.Text(string = 'Address')
    ug_degree = fields.Selection([('bcom', 'B.Com'),('be', 'BE'),('btech', 'B.Tech'),], string = 'Degree', required=True )

    # ten_mark = fields.Float("10th Mark")
    # plustwo_mark = fields.Float("12th Mark")
    # deg_mark = fields.Float("Degree Mark")

    employee_ids = fields.One2many('bi.employee.line','employee_id',"employee")
    employee_copy_ids = fields.One2many('bi.employee.line.copy','employee_copy_id')
    employee_line_idss = fields.One2many('bi.employee.copy','employee_line_id')

    @api.multi
    def button_confirm(self):
        line_obj = self.env['bi.employee.line']
        for file in self:
            values = {}
            vals = {
                'emp_name_copy':file.emp_name,
                'age_copy':file.age,
                'address_copy':file.address,
                'ug_degree_line':file.ug_degree,
                'employee_copy_id':file.id,
                }
            # raise UserError(_(str(vals)))
        self.env['bi.employee.line.copy'].create(vals)
        for line in line_obj:
            values = {
                'ten_mark_copy':line.ten_mark,
                'plustwo_mark_copy':line.plustwo_mark,
                'deg_mark_copy':line.deg_mark,
                'employee_line_id':line.id
            }
            # raise UserError(_(str(values)))
        self.env['bi.employee.copy'].create(values)

#==================================================
# Class : BiEmployeeLine
# Description : Employee Line
#==================================================

class BiEmployeeLine(models.Model):
    _name = "bi.employee.line"
    _description = "Employee line"
    # _rec_name = "name"

    ten_mark = fields.Float(string = '10th Mark')
    plustwo_mark = fields.Float(string = '12th Mark')
    deg_mark = fields.Float(string = 'Degree Mark')

    employee_id = fields.Many2one('bi.employee',"Employee")
    employee_line_ids = fields.One2many('bi.employee.copy','employee_line_id')

    # @api.multi
    # def button_confirms(self):
    #   for file in self:
    #       values = {
    #           'ten_mark_copy':file.ten_mark,
    #           'plustwo_mark_copy':file.plustwo_mark,
    #           'deg_mark_copy':file.deg_mark,
    #           'employee_line_id':file.id
    #           }
    #   self.env['bi.employee.copy'].create(values)

#==================================================
# Class : BiEmployeeLineCopy
# Description : Employee Line Copy
#==================================================

class BiEmployeeLineCopy(models.Model):
    _name = "bi.employee.line.copy"
    _description = "Employee Line Copy"

    emp_name_copy = fields.Char(string = 'Employee Name')
    age_copy = fields.Char(string = 'Age')
    address_copy = fields.Char(string = 'Address')
    ug_degree_line = fields.Char(string='Degree')

    employee_line_copy_ids = fields.One2many('bi.employee.copy','employee_line_copy_id')
    employee_copy_id = fields.Many2one('bi.employee')

#==================================================
# Class : BiEmployeeCopy
# Description : Employee Copy
#==================================================

class BiEmployeeCopy(models.Model):
    _name = "bi.employee.copy"
    _description = "Employee Copy"

    ten_mark_copy = fields.Float(string = '10th Mark')
    plustwo_mark_copy = fields.Float(string = '12th Mark')
    deg_mark_copy = fields.Float(string = 'Degree Mark')
    employee_line_copy_id = fields.Many2one('bi.employee.line.copy')
    employee_line_id = fields.Many2one('bi.employee.line')
</code>```

The XML code is just below:
employee.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data>
       <menuitem name="Employee Details"
            id="bi_menu_employee_root"
            web_icon="bi_employee,static/description/icon.png"/>

        <menuitem
            id="bi_menu_employee_main"
            name="Details"
            parent="bi_employee.bi_menu_employee_root"
            sequence="0"/>

        <record id="bi_view_employee_tree" model="ir.ui.view">
            <field name="name">bi.employee.tree</field>
            <field name="model">bi.employee</field>
            <field name="arch" type="xml">
                <tree string="Employee">
                    <field name="emp_name"/>
                </tree>
            </field>
        </record>

        <record id="view_employee" model="ir.ui.view">
            <field name="name">bi.employee.form</field>
            <field name="model">bi.employee</field>
            <field name="arch" type="xml">
                <form string="Employee Details">
                    <header>
                        <button name = "button_confirm" string ="Confirm" class ="oe_highlight" type = "object"/>
                    </header>
                    <sheet>
                        <group>
                            <group>
                                <field name="emp_name"/>
                                <field name="ug_degree"/>
                            </group>
                            <group>
                                <field name="age"/>
                                <field name="address"/>
                            </group>
                        </group>
                    <notebook>
                    <page string="Academic Details">
                        <field name="employee_ids">
                            <tree string="Employee Information" editable="bottom">
                                <field name="ten_mark"/>
                                <field name="plustwo_mark"/>
                                <field name="deg_mark"/>
                            </tree>
                        </field>
                    </page>
                    </notebook>
                    </sheet>
                </form>
            </field>
        </record>

        <record id="bi_view_employee" model="ir.actions.act_window">
            <field name="name">Employee Management</field>
            <field name="res_model">bi.employee</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="domain">[]</field>
            <field name="context">{}</field>
            <field name="view_id" eval="False"/>
            <field name="help" type="html">
                <p class="oe_view_nocontent_create">
                </p>
            </field>
        </record>

        <menuitem
            id="bi_menu_employee_details"
            name="Employee Details"
            action = "bi_view_employee"
            parent="bi_employee.bi_menu_employee_main"
            sequence="1"/>

        <record id="bi_view_employee_line_copy_tree" model="ir.ui.view">
            <field name="name">bi.employee.line.copy.tree</field>
            <field name="model">bi.employee.line.copy</field>
            <field name="arch" type="xml">
                <tree string="Employee">
                    <field name="emp_name_copy"/>
                </tree>
            </field>
        </record>

        <record id="view_employee_line_copy_form" model="ir.ui.view">
            <field name="name">bi.employee.line.copy.form</field>
            <field name="model">bi.employee.line.copy</field>
            <field name="arch" type="xml">
                <form string="Employee Details Copy">

                    <sheet>
                        <group>
                            <group>
                                <field name="emp_name_copy"/>
                                <field name="ug_degree_line"/>
                            </group>
                            <group>
                                <field name="age_copy"/>
                                <field name="address_copy"/>
                            </group>
                        </group>
                    <notebook>
                    <page string="Academic Details">
                        <field name="employee_line_copy_ids">

                            <tree string="Employee Information" editable="bottom">
                                <field name="ten_mark_copy"/>
                                <field name="plustwo_mark_copy"/>
                                <field name="deg_mark_copy"/>
                            </tree>
                        </field>
                    </page>
                    </notebook>
                    </sheet>
                </form>
            </field>
        </record>

        <record id="bi_view_employee_line_copy" model="ir.actions.act_window">
            <field name="name">Employee Management</field>
            <field name="res_model">bi.employee.line.copy</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="domain">[]</field>
            <field name="context">{}</field>
            <field name="view_id" eval="False"/>
            <field name="help" type="html">
                <p class="oe_view_nocontent_create">
                </p>
            </field>
        </record>

        <menuitem
            id="bi_menu_employee_line_copy_details"
            name="Employee Details Copy"
            action = "bi_view_employee_line_copy"
            parent="bi_employee.bi_menu_employee_main"
            sequence="2"/>

    </data>
</odoo>
</code>```

I need to copy all the fields to another object including line when I click 'Confirm' button.But unfortunately the lines are not copying.Can anybody help ?

答:
In your code, you have been trying to create a line items using a null object line_obj = self.env['bi.employee.line'].

Change your values create loop like below:

```<code> for line in self.employee_ids:
        values = {
            'ten_mark_copy':line.ten_mark,
            'plustwo_mark_copy':line.plustwo_mark,
            'deg_mark_copy':line.deg_mark,
            'employee_line_id':line.id
        }
</code>```

Hope it will help you.

Title: Lines are not copying in Odoo

Body:
The Python code is below.Just check the function which is in the initial class have any error .

employee.py

import time
import math
import os, base64
from tempfile import TemporaryFile
import random

from odoo.osv import expression
from odoo.tools.float_utils import float_round as round
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError, ValidationError
from odoo import api, fields, models, _
#==================================================
# Class : BiEmployee
# Description : Employee Main Class
#==================================================
class BiEmployee(models.Model):
    _name = "bi.employee"
    _description = "Employee Module"
    _rec_name = "name"
    name = fields.Char(string='Name', required=False )
    emp_name = fields.Char(string = 'Employee Name')
    age = fields.Char(string = 'Age')
    address = fields.Text(string = 'Address')
    ug_degree = fields.Selection([('bcom', 'B.Com'),('be', 'BE'),('btech', 'B.Tech'),], string = 'Degree', required=True )

    # ten_mark = fields.Float("10th Mark")
    # plustwo_mark = fields.Float("12th Mark")
    # deg_mark = fields.Float("Degree Mark")

    employee_ids = fields.One2many('bi.employee.line','employee_id',"employee")
    employee_copy_ids = fields.One2many('bi.employee.line.copy','employee_copy_id')
    employee_line_idss = fields.One2many('bi.employee.copy','employee_line_id')

    @api.multi
    def button_confirm(self):
        line_obj = self.env['bi.employee.line']
        for file in self:
            values = {}
            vals = {
                'emp_name_copy':file.emp_name,
                'age_copy':file.age,
                'address_copy':file.address,
                'ug_degree_line':file.ug_degree,
                'employee_copy_id':file.id,
                }
            # raise UserError(_(str(vals)))
        self.env['bi.employee.line.copy'].create(vals)
        for line in line_obj:
            values = {
                'ten_mark_copy':line.ten_mark,
                'plustwo_mark_copy':line.plustwo_mark,
                'deg_mark_copy':line.deg_mark,
                'employee_line_id':line.id
            }
            # raise UserError(_(str(values)))
        self.env['bi.employee.copy'].create(values)

#==================================================
# Class : BiEmployeeLine
# Description : Employee Line
#==================================================

class BiEmployeeLine(models.Model):
    _name = "bi.employee.line"
    _description = "Employee line"
    # _rec_name = "name"

    ten_mark = fields.Float(string = '10th Mark')
    plustwo_mark = fields.Float(string = '12th Mark')
    deg_mark = fields.Float(string = 'Degree Mark')

    employee_id = fields.Many2one('bi.employee',"Employee")
    employee_line_ids = fields.One2many('bi.employee.copy','employee_line_id')

    # @api.multi
    # def button_confirms(self):
    #   for file in self:
    #       values = {
    #           'ten_mark_copy':file.ten_mark,
    #           'plustwo_mark_copy':file.plustwo_mark,
    #           'deg_mark_copy':file.deg_mark,
    #           'employee_line_id':file.id
    #           }
    #   self.env['bi.employee.copy'].create(values)

#==================================================
# Class : BiEmployeeLineCopy
# Description : Employee Line Copy
#==================================================

class BiEmployeeLineCopy(models.Model):
    _name = "bi.employee.line.copy"
    _description = "Employee Line Copy"

    emp_name_copy = fields.Char(string = 'Employee Name')
    age_copy = fields.Char(string = 'Age')
    address_copy = fields.Char(string = 'Address')
    ug_degree_line = fields.Char(string='Degree')

    employee_line_copy_ids = fields.One2many('bi.employee.copy','employee_line_copy_id')
    employee_copy_id = fields.Many2one('bi.employee')

#==================================================
# Class : BiEmployeeCopy
# Description : Employee Copy
#==================================================

class BiEmployeeCopy(models.Model):
    _name = "bi.employee.copy"
    _description = "Employee Copy"

    ten_mark_copy = fields.Float(string = '10th Mark')
    plustwo_mark_copy = fields.Float(string = '12th Mark')
    deg_mark_copy = fields.Float(string = 'Degree Mark')
    employee_line_copy_id = fields.Many2one('bi.employee.line.copy')
    employee_line_id = fields.Many2one('bi.employee.line')

The XML code is just below:
employee.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data>
       <menuitem name="Employee Details"
            id="bi_menu_employee_root"
            web_icon="bi_employee,static/description/icon.png"/>

        <menuitem
            id="bi_menu_employee_main"
            name="Details"
            parent="bi_employee.bi_menu_employee_root"
            sequence="0"/>

        <record id="bi_view_employee_tree" model="ir.ui.view">
            <field name="name">bi.employee.tree</field>
            <field name="model">bi.employee</field>
            <field name="arch" type="xml">
                <tree string="Employee">
                    <field name="emp_name"/>
                </tree>
            </field>
        </record>

        <record id="view_employee" model="ir.ui.view">
            <field name="name">bi.employee.form</field>
            <field name="model">bi.employee</field>
            <field name="arch" type="xml">
                <form string="Employee Details">

                        <button name = "button_confirm" string ="Confirm" class ="oe_highlight" type = "object"/>

                    <sheet>
                        <group>
                            <group>
                                <field name="emp_name"/>
                                <field name="ug_degree"/>
                            </group>
                            <group>
                                <field name="age"/>
                                <field name="address"/>
                            </group>
                        </group>
                    <notebook>
                    <page string="Academic Details">
                        <field name="employee_ids">
                            <tree string="Employee Information" editable="bottom">
                                <field name="ten_mark"/>
                                <field name="plustwo_mark"/>
                                <field name="deg_mark"/>
                            </tree>
                        </field>
                    </page>
                    </notebook>
                    </sheet>
                </form>
            </field>
        </record>

        <record id="bi_view_employee" model="ir.actions.act_window">
            <field name="name">Employee Management</field>
            <field name="res_model">bi.employee</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="domain">[]</field>
            <field name="context">{}</field>
            <field name="view_id" eval="False"/>
            <field name="help" type="html">

            </field>
        </record>

        <menuitem
            id="bi_menu_employee_details"
            name="Employee Details"
            action = "bi_view_employee"
            parent="bi_employee.bi_menu_employee_main"
            sequence="1"/>

        <record id="bi_view_employee_line_copy_tree" model="ir.ui.view">
            <field name="name">bi.employee.line.copy.tree</field>
            <field name="model">bi.employee.line.copy</field>
            <field name="arch" type="xml">
                <tree string="Employee">
                    <field name="emp_name_copy"/>
                </tree>
            </field>
        </record>

        <record id="view_employee_line_copy_form" model="ir.ui.view">
            <field name="name">bi.employee.line.copy.form</field>
            <field name="model">bi.employee.line.copy</field>
            <field name="arch" type="xml">
                <form string="Employee Details Copy">

                    <sheet>
                        <group>
                            <group>
                                <field name="emp_name_copy"/>
                                <field name="ug_degree_line"/>
                            </group>
                            <group>
                                <field name="age_copy"/>
                                <field name="address_copy"/>
                            </group>
                        </group>
                    <notebook>
                    <page string="Academic Details">
                        <field name="employee_line_copy_ids">

                            <tree string="Employee Information" editable="bottom">
                                <field name="ten_mark_copy"/>
                                <field name="plustwo_mark_copy"/>
                                <field name="deg_mark_copy"/>
                            </tree>
                        </field>
                    </page>
                    </notebook>
                    </sheet>
                </form>
            </field>
        </record>

        <record id="bi_view_employee_line_copy" model="ir.actions.act_window">
            <field name="name">Employee Management</field>
            <field name="res_model">bi.employee.line.copy</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="domain">[]</field>
            <field name="context">{}</field>
            <field name="view_id" eval="False"/>
            <field name="help" type="html">

            </field>
        </record>

        <menuitem
            id="bi_menu_employee_line_copy_details"
            name="Employee Details Copy"
            action = "bi_view_employee_line_copy"
            parent="bi_employee.bi_menu_employee_main"
            sequence="2"/>

    </data>
</odoo>

I need to copy all the fields to another object including line when I click 'Confirm' button.But unfortunately the lines are not copying.Can anybody help ?

Body:
In your code, you have been trying to create a line items using a null object line_obj = self.env['bi.employee.line'].

Change your values create loop like below:

 for line in self.employee_ids:
        values = {
            'ten_mark_copy':line.ten_mark,
            'plustwo_mark_copy':line.plustwo_mark,
            'deg_mark_copy':line.deg_mark,
            'employee_line_id':line.id
        }

Hope it will help you.


来源: stackexchange

问:
MPAndroidChart line graph remove only top border android
I am using MPAndroidChart for line graph. I have some 5 points. Below is my code.

```<code> LineChart lineChart = (LineChart) findViewById(R.id.chart);
    lineChart.setDrawBorders(true);
    lineChart.getDescription().setEnabled(false);
    lineChart.fitScreen();
    lineChart.setPadding(0,0,0,0);
    lineChart.getLegend().setEnabled(false);
    lineChart.setDoubleTapToZoomEnabled(false);

    lineChart.getAxisLeft().setEnabled(false);
    lineChart.getAxisRight().setEnabled(true);
    lineChart.getAxisLeft().setStartAtZero(true);

    lineChart.getAxisRight().setDrawAxisLine(true);
    lineChart.getAxisRight().setDrawLabels(true);
    lineChart.getAxisRight().setDrawGridLines(false);

    lineChart.getXAxis().setEnabled(true);
    lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);

    lineChart.getXAxis().setDrawAxisLine(true);
    lineChart.getXAxis().setDrawGridLines(true);
    lineChart.setScaleMinima(3f, 0f);
    lineChart.setBackgroundColor(Color.TRANSPARENT); //set whatever color you prefer
    lineChart.setDrawGridBackground(false);
    lineChart.setTouchEnabled(true);
    lineChart.setDragEnabled(true);
    lineChart.setScaleEnabled(true);
    lineChart.setPinchZoom(false);
    Legend l = lineChart.getLegend();
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
    l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
    l.setDrawInside(true);
    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();

    ArrayList<Entry> values = new ArrayList<Entry>();
    values.add(new Entry(Float.parseFloat("1"), 5));
    values.add(new Entry(Float.parseFloat("2"), 2));
    values.add(new Entry(Float.parseFloat("3"), 6));
    values.add(new Entry(Float.parseFloat("4"), 8));
    values.add(new Entry(Float.parseFloat("5"), 2));

    LineDataSet d = new LineDataSet(values, "Actual kWh ");
    d.setMode(LineDataSet.Mode.CUBIC_BEZIER);
    d.setLineWidth(2.5f);
    d.setCircleRadius(3f);
    d.setCircleColorHole(Color.BLACK);
    d.setValueTextSize(10f);
    d.setValueTextColor(Color.WHITE);
    dataSets.add(d);
    LineData data = new LineData(dataSets);
    lineChart.setData(data);
    lineChart.invalidate();
</code>```

I am able to do most of the customization. My question is how to remove only the topborder ? Also in the X Axis I am getting decimal values like 1, 1.2, 1.3 and it goes on. I want the X Axis to have values like 1, 2, 3, 4 , 5. How can I do this ?

答:
Try this

This Display Vertical lines

```<code>LineChart lineChart = (LineChart) findViewById(R.id.chart1);
    lineChart.setDrawBorders(false);
    lineChart.getDescription().setEnabled(false);
    lineChart.fitScreen();
    lineChart.setPadding(0,0,0,0);
    lineChart.getLegend().setEnabled(false);
    lineChart.setDoubleTapToZoomEnabled(false);

    lineChart.getAxisLeft().setEnabled(true);
    lineChart.getAxisRight().setEnabled(true);
    lineChart.getAxisLeft().setStartAtZero(false);

    lineChart.getAxisRight().setDrawAxisLine(false);
    lineChart.getAxisRight().setDrawLabels(true);
    lineChart.getAxisRight().setDrawGridLines(false);

    lineChart.getXAxis().setEnabled(true);
    lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
    lineChart.getAxisLeft().setDrawGridLines(false);
    lineChart.getAxisRight().setDrawGridLines(false);
    lineChart.getXAxis().setDrawAxisLine(true);
    lineChart.getXAxis().setDrawGridLines(true);
    lineChart.setScaleMinima(3f, 0f);
    lineChart.setBackgroundColor(Color.TRANSPARENT); //set whatever color you prefer
    lineChart.setDrawGridBackground(false);
    lineChart.setTouchEnabled(false);
    lineChart.setDragEnabled(false);
    lineChart.setScaleEnabled(false);
    lineChart.setPinchZoom(false);
    Legend l = lineChart.getLegend();
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
    l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
    l.setDrawInside(true);
    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();

    ArrayList<Entry> values = new ArrayList<Entry>();
    values.add(new Entry(Float.parseFloat("1"), 5));
    values.add(new Entry(Float.parseFloat("2"), 2));
    values.add(new Entry(Float.parseFloat("3"), 6));
    values.add(new Entry(Float.parseFloat("4"), 8));
    values.add(new Entry(Float.parseFloat("5"), 2));

    LineDataSet d = new LineDataSet(values, "Actual kWh ");
    d.setMode(LineDataSet.Mode.CUBIC_BEZIER);
    d.setLineWidth(2.5f);
    d.setCircleRadius(3f);
    d.setCircleColorHole(Color.BLACK);
    d.setValueTextSize(10f);
    d.setValueTextColor(Color.WHITE);
    dataSets.add(d);
    LineData data = new LineData(dataSets);
    lineChart.setData(data);
    lineChart.invalidate();
</code>```

If You don't need any grid lines

use

```<code>lineChart.getAxisLeft().setDrawGridLines(false);
        lineChart.getAxisRight().setDrawGridLines(false);
        lineChart.getXAxis().setDrawAxisLine(true);
        lineChart.getXAxis().setDrawGridLines(true);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using MPAndroidChart for line graph. I have some 5 points. Below is my code.

 LineChart lineChart = (LineChart) findViewById(R.id.chart);
    lineChart.setDrawBorders(true);
    lineChart.getDescription().setEnabled(false);
    lineChart.fitScreen();
    lineChart.setPadding(0,0,0,0);
    lineChart.getLegend().setEnabled(false);
    lineChart.setDoubleTapToZoomEnabled(false);

    lineChart.getAxisLeft().setEnabled(false);
    lineChart.getAxisRight().setEnabled(true);
    lineChart.getAxisLeft().setStartAtZero(true);

    lineChart.getAxisRight().setDrawAxisLine(true);
    lineChart.getAxisRight().setDrawLabels(true);
    lineChart.getAxisRight().setDrawGridLines(false);

    lineChart.getXAxis().setEnabled(true);
    lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);

    lineChart.getXAxis().setDrawAxisLine(true);
    lineChart.getXAxis().setDrawGridLines(true);
    lineChart.setScaleMinima(3f, 0f);
    lineChart.setBackgroundColor(Color.TRANSPARENT); //set whatever color you prefer
    lineChart.setDrawGridBackground(false);
    lineChart.setTouchEnabled(true);
    lineChart.setDragEnabled(true);
    lineChart.setScaleEnabled(true);
    lineChart.setPinchZoom(false);
    Legend l = lineChart.getLegend();
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
    l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
    l.setDrawInside(true);
    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();

    ArrayList<Entry> values = new ArrayList<Entry>();
    values.add(new Entry(Float.parseFloat("1"), 5));
    values.add(new Entry(Float.parseFloat("2"), 2));
    values.add(new Entry(Float.parseFloat("3"), 6));
    values.add(new Entry(Float.parseFloat("4"), 8));
    values.add(new Entry(Float.parseFloat("5"), 2));

    LineDataSet d = new LineDataSet(values, "Actual kWh ");
    d.setMode(LineDataSet.Mode.CUBIC_BEZIER);
    d.setLineWidth(2.5f);
    d.setCircleRadius(3f);
    d.setCircleColorHole(Color.BLACK);
    d.setValueTextSize(10f);
    d.setValueTextColor(Color.WHITE);
    dataSets.add(d);
    LineData data = new LineData(dataSets);
    lineChart.setData(data);
    lineChart.invalidate();

I am able to do most of the customization. My question is how to remove only the topborder ? Also in the X Axis I am getting decimal values like 1, 1.2, 1.3 and it goes on. I want the X Axis to have values like 1, 2, 3, 4 , 5. How can I do this ?

Body:
Try this

This Display Vertical lines

LineChart lineChart = (LineChart) findViewById(R.id.chart1);
    lineChart.setDrawBorders(false);
    lineChart.getDescription().setEnabled(false);
    lineChart.fitScreen();
    lineChart.setPadding(0,0,0,0);
    lineChart.getLegend().setEnabled(false);
    lineChart.setDoubleTapToZoomEnabled(false);

    lineChart.getAxisLeft().setEnabled(true);
    lineChart.getAxisRight().setEnabled(true);
    lineChart.getAxisLeft().setStartAtZero(false);

    lineChart.getAxisRight().setDrawAxisLine(false);
    lineChart.getAxisRight().setDrawLabels(true);
    lineChart.getAxisRight().setDrawGridLines(false);

    lineChart.getXAxis().setEnabled(true);
    lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
    lineChart.getAxisLeft().setDrawGridLines(false);
    lineChart.getAxisRight().setDrawGridLines(false);
    lineChart.getXAxis().setDrawAxisLine(true);
    lineChart.getXAxis().setDrawGridLines(true);
    lineChart.setScaleMinima(3f, 0f);
    lineChart.setBackgroundColor(Color.TRANSPARENT); //set whatever color you prefer
    lineChart.setDrawGridBackground(false);
    lineChart.setTouchEnabled(false);
    lineChart.setDragEnabled(false);
    lineChart.setScaleEnabled(false);
    lineChart.setPinchZoom(false);
    Legend l = lineChart.getLegend();
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
    l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
    l.setDrawInside(true);
    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();

    ArrayList<Entry> values = new ArrayList<Entry>();
    values.add(new Entry(Float.parseFloat("1"), 5));
    values.add(new Entry(Float.parseFloat("2"), 2));
    values.add(new Entry(Float.parseFloat("3"), 6));
    values.add(new Entry(Float.parseFloat("4"), 8));
    values.add(new Entry(Float.parseFloat("5"), 2));

    LineDataSet d = new LineDataSet(values, "Actual kWh ");
    d.setMode(LineDataSet.Mode.CUBIC_BEZIER);
    d.setLineWidth(2.5f);
    d.setCircleRadius(3f);
    d.setCircleColorHole(Color.BLACK);
    d.setValueTextSize(10f);
    d.setValueTextColor(Color.WHITE);
    dataSets.add(d);
    LineData data = new LineData(dataSets);
    lineChart.setData(data);
    lineChart.invalidate();

If You don't need any grid lines

use

lineChart.getAxisLeft().setDrawGridLines(false);
        lineChart.getAxisRight().setDrawGridLines(false);
        lineChart.getXAxis().setDrawAxisLine(true);
        lineChart.getXAxis().setDrawGridLines(true);


问:
Why does TimeSpan.FromSeconds(double) round to milliseconds?
TimeSpan.FromSeconds takes a double, and can represent values down to 100 nanoseconds, however this method inexplicably rounds the time to whole milliseconds.

Given that I've just spent half an hour to pinpoint this (documented!) behaviour, knowing why this might be the case would make it easier to put up with the wasted time.

Can anyone suggest why this seemingly counter-productive behaviour is implemented?

```<code>TimeSpan.FromSeconds(0.12345678).TotalSeconds
    // 0.123
TimeSpan.FromTicks((long)(TimeSpan.TicksPerSecond * 0.12345678)).TotalSeconds
    // 0.1234567
</code>```

答:
Imagine you're the developer responsible for designing the TimeSpan type. You've got all the basic functionality in place; it all seems to be working great. Then one day some beta tester comes along and shows you this code:

```<code>double x = 100000000000000;
double y = 0.5;
TimeSpan t1 = TimeSpan.FromMilliseconds(x + y);
TimeSpan t2 = TimeSpan.FromMilliseconds(x) + TimeSpan.FromMilliseconds(y);
Console.WriteLine(t1 == t2);
</code>```

Why does that output False? the tester asks you. Even though you understand why this happened (the loss of precision in adding together x and y), you have to admit it does seem a bit strange from a client perspective. Then he throws this one at you:

```<code>x = 10.0;
y = 0.5;
t1 = TimeSpan.FromMilliseconds(x + y);
t2 = TimeSpan.FromMilliseconds(x) + TimeSpan.FromMilliseconds(y);
Console.WriteLine(t1 == t2);
</code>```

That one outputs True! The tester is understandably skeptical.

At this point you have a decision to make. Either you can allow an arithmetic operation between TimeSpan values that have been constructed from double values to yield a result whose precision exceeds the accuracy of the double type itself—e.g., 100000000000000.5 (16 significant figures)—or you can, you know, not allow that.

So you decide, you know what, I'll just make it so that any method that uses a double to construct a TimeSpan will be rounded to the nearest millisecond. That way, it is explicitly documented that converting from a double to a TimeSpan is a lossy operation, absolving me in cases where a client sees weird behavior like this after converting from double to TimeSpan and hoping for an accurate result.

I'm not necessarily arguing that this is the "right" decision here; clearly, this approach causes some confusion on its own. I'm just saying that a decision needed to be made one way or the other, and this is what was apparently decided.

ContentLicense: CC BY-SA 2.5

Body:
TimeSpan.FromSeconds takes a double, and can represent values down to 100 nanoseconds, however this method inexplicably rounds the time to whole milliseconds.

Given that I've just spent half an hour to pinpoint this (documented!) behaviour, knowing why this might be the case would make it easier to put up with the wasted time.

Can anyone suggest why this seemingly counter-productive behaviour is implemented?

TimeSpan.FromSeconds(0.12345678).TotalSeconds
    // 0.123
TimeSpan.FromTicks((long)(TimeSpan.TicksPerSecond * 0.12345678)).TotalSeconds
    // 0.1234567

Body:
Imagine you're the developer responsible for designing the TimeSpan type. You've got all the basic functionality in place; it all seems to be working great. Then one day some beta tester comes along and shows you this code:

double x = 100000000000000;
double y = 0.5;
TimeSpan t1 = TimeSpan.FromMilliseconds(x + y);
TimeSpan t2 = TimeSpan.FromMilliseconds(x) + TimeSpan.FromMilliseconds(y);
Console.WriteLine(t1 == t2);

Why does that output False? the tester asks you. Even though you understand why this happened (the loss of precision in adding together x and y), you have to admit it does seem a bit strange from a client perspective. Then he throws this one at you:

x = 10.0;
y = 0.5;
t1 = TimeSpan.FromMilliseconds(x + y);
t2 = TimeSpan.FromMilliseconds(x) + TimeSpan.FromMilliseconds(y);
Console.WriteLine(t1 == t2);

That one outputs True! The tester is understandably skeptical.

At this point you have a decision to make. Either you can allow an arithmetic operation between TimeSpan values that have been constructed from double values to yield a result whose precision exceeds the accuracy of the double type itself—e.g., 100000000000000.5 (16 significant figures)—or you can, you know, not allow that.

So you decide, you know what, I'll just make it so that any method that uses a double to construct a TimeSpan will be rounded to the nearest millisecond. That way, it is explicitly documented that converting from a double to a TimeSpan is a lossy operation, absolving me in cases where a client sees weird behavior like this after converting from double to TimeSpan and hoping for an accurate result.

I'm not necessarily arguing that this is the "right" decision here; clearly, this approach causes some confusion on its own. I'm just saying that a decision needed to be made one way or the other, and this is what was apparently decided.


问:
How to sort comma separated values in bash?
I have some numbers like

7, 15, 6, 2, -9

I want to sort it like this in bash(from command line or either a script file)

-9, 2, 6, 7, 15

How can I do this? I am unable to get this using sort command.

答:
With perl

```<code>$ s='7, 15, 6, 2, -9'
$ echo "$s" | perl -F',\h*' -lane 'print join ", ", sort {$a <=> $b} @F'
-9, 2, 6, 7, 15
$ echo "$s" | perl -F',\h*' -lane 'print join ", ", sort {$b <=> $a} @F'
15, 7, 6, 2, -9
</code>```

-F',\h*' use , and optional space/tab as field separator

see https://perldoc.perl.org/perlrun.html#Command-Switches for explanation of command line options

sort {$a <=> $b} @F sort the array numerically, in ascending order... use sort {$b <=> $a} @F' for descending order

join ", " tells how to join the array elements before passing on to print

Body:
With perl

$ s='7, 15, 6, 2, -9'
$ echo "$s" | perl -F',\h*' -lane 'print join ", ", sort {$a <=> $b} @F'
-9, 2, 6, 7, 15
$ echo "$s" | perl -F',\h*' -lane 'print join ", ", sort {$b <=> $a} @F'
15, 7, 6, 2, -9

-F',\h*' use , and optional space/tab as field separator

see https://perldoc.perl.org/perlrun.html#Command-Switches for explanation of command line options

sort {$a <=> $b} @F sort the array numerically, in ascending order... use sort {$b <=> $a} @F' for descending order

join ", " tells how to join the array elements before passing on to print


问:
How to count number of ObjectId occurrences in an array of ObjectIds' and attach the result to each document that is being returned?
I have a Tag schema:

```<code>const TagSchema = new Schema({
  label: {type: String, unique: true, minlength: 2},
  updatedAt: {type: Date, default: null},
  createdAt: {type: Date, default: new Date(), required: true},
  createdBy: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', default: null}
});

const Tag = mongoose.model('Tag', TagSchema);
</code>```

Then I have a Page schema:

```<code>const PageSchema = new Schema({
  tags: {type: [{type: mongoose.Schema.Types.ObjectId, ref: 'Tag'}], default: [], maxlength: 5}
});

const Page = mongoose.model('Page', PageSchema);
</code>```

As you can see it contains a Tag reference in its tags array.

Now what I need to do is when I fetch all tags via /tags, I also need to count the number of times each tag is used in all Pages.

So if a Tag is used 2times across all Pages, it should set an .occurrences property on the returned tag. For example this would be a response from /tags:

```<code>[
 {_id: '192398dsf7asdsdds8f7d', label: 'tag 1', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 2},
 {_id: '19239asdasd8dsf7ds8f7d', label: 'tag 2', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 1},
 {_id: '192398dsf7zxccxads8f7d', label: 'tag 1', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 5},
]
</code>```

I would have imagined that I could achieve this pretty easily in a mongoose pre('find') hook like this:

```<code>TagSchema.pre('find', function() {

  Page.count({tags: this._id}, (err, total) => {
    this.occurrences = total;
  });
});
</code>```

However, there are two problems here:

Page.count throws an error saying it's not a function, which I don't understand why because I use it somewhere else perfectly fine. And Page has been imported properly. Suggesting that you can't use count in a hook or something similar.

this is not the Tag document.

So I guess that the way I am going about this is completely wrong.

Since I am a novice in MongoDB maybe someone can provide me with a better, working, solution to my problem?

答:
```<code>db.Page.aggregate([
{
  $unwind:"$tags"
},
{
  $group:{
    _id:"$tags",
    occurrences:{$sum:1}
  }
},
{
  $lookup:{ //get data for each tag
    from:"tags",
    localField:"_id",
    foreignField:"_id",
    as:"tagsData"
  }
},
{
$project:{
  tagData:{$arrayElemAt: [ "$tagsData", 0 ]},
  occurrences:1
}
}
{
  $addFields:{
    "tagData._id":"$_id",
    "tagData.occurrences":"$occurrences"
  }
},
{
   $replaceRoot: { newRoot: "$tagData" }
}
])
</code>```

Body:
I have a Tag schema:

const TagSchema = new Schema({
  label: {type: String, unique: true, minlength: 2},
  updatedAt: {type: Date, default: null},
  createdAt: {type: Date, default: new Date(), required: true},
  createdBy: {type: mongoose.Schema.Types.ObjectId, ref: 'Account', default: null}
});

const Tag = mongoose.model('Tag', TagSchema);

Then I have a Page schema:

const PageSchema = new Schema({
  tags: {type: [{type: mongoose.Schema.Types.ObjectId, ref: 'Tag'}], default: [], maxlength: 5}
});

const Page = mongoose.model('Page', PageSchema);

As you can see it contains a Tag reference in its tags array.

Now what I need to do is when I fetch all tags via /tags, I also need to count the number of times each tag is used in all Pages.

So if a Tag is used 2times across all Pages, it should set an .occurrences property on the returned tag. For example this would be a response from /tags:

[
 {_id: '192398dsf7asdsdds8f7d', label: 'tag 1', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 2},
 {_id: '19239asdasd8dsf7ds8f7d', label: 'tag 2', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 1},
 {_id: '192398dsf7zxccxads8f7d', label: 'tag 1', updatedAt: '20170102', createdAt: '20170101', createdBy: '01238198dsad8s7d78ad7', occurrences: 5},
]

I would have imagined that I could achieve this pretty easily in a mongoose pre('find') hook like this:

TagSchema.pre('find', function() {

  Page.count({tags: this._id}, (err, total) => {
    this.occurrences = total;
  });
});

However, there are two problems here:

Page.count throws an error saying it's not a function, which I don't understand why because I use it somewhere else perfectly fine. And Page has been imported properly. Suggesting that you can't use count in a hook or something similar.

this is not the Tag document.

So I guess that the way I am going about this is completely wrong.

Since I am a novice in MongoDB maybe someone can provide me with a better, working, solution to my problem?


问:
Return a list of similar authors
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

```<code>authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}
</code>```

And the function I came up with is this:

```<code>def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]
</code>```

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

```<code>get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
</code>```

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

答:
I would not include parameter author in the output if that's one of the elements in a list value. You could use list comprehension:

```<code>def get_similar(author_list, author):
    # Lists of similar authors
    similar = [author_list[auth] for auth in author_list[author] if auth in author_list]

    # Merge the lists and sort the authors. Do not include parameter author
    return sorted(auth for sub in similar for auth in sub if auth != author)

authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}

>>> get_similar(authors, 'Harlan Ellison')
['Chris Moore', 'Douglas Adams', 'Jeff Vandemeer', 'Kurt Vonnegut', 'Neil Stephenson', 'Terry Pratchett', 'Terry Pratchett', 'Tom Robbins']

>>> get_similar(authors, 'Ray Bradbury')  # There's 'Ray Bradbury' in the values of 'Isaac Asimov'
['Arthur Clarke', 'Douglas Adams', 'Kurt Vonnegut', 'Kurt Vonnegut', 'Neil Stephenson', 'Neil Stephenson', 'Richard Morgan', 'Stephen Baxter']
</code>```

Title: Return a list of similar authors

Body:
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}

And the function I came up with is this:

def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

Body:
I would not include parameter author in the output if that's one of the elements in a list value. You could use list comprehension:

def get_similar(author_list, author):
    # Lists of similar authors
    similar = [author_list[auth] for auth in author_list[author] if auth in author_list]

    # Merge the lists and sort the authors. Do not include parameter author
    return sorted(auth for sub in similar for auth in sub if auth != author)

authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}

>>> get_similar(authors, 'Harlan Ellison')
['Chris Moore', 'Douglas Adams', 'Jeff Vandemeer', 'Kurt Vonnegut', 'Neil Stephenson', 'Terry Pratchett', 'Terry Pratchett', 'Tom Robbins']

>>> get_similar(authors, 'Ray Bradbury')  # There's 'Ray Bradbury' in the values of 'Isaac Asimov'
['Arthur Clarke', 'Douglas Adams', 'Kurt Vonnegut', 'Kurt Vonnegut', 'Neil Stephenson', 'Neil Stephenson', 'Richard Morgan', 'Stephen Baxter']


问:
Type Inheritance Issue
I don't really know how to explain the problem I have. Below is an example of a few objects I have.

Lets say I have classes

```<code>public class Foo{}
public class FooBar extends Foo{}
</code>```

All of that is fine, however if I take a list and say I want it to be full of Foo objects, I cannot provide it a FooBar object. Why is this?

Example:

```<code>List<Foo> fooList = Arrays.asList(new FooBar());
</code>```

If FooBar extends Foo, why cant it be cast back to Foo?

答:
Arrays.asList(new FooBar()) returns a List<FooBar>, which cannot be assigned to a List<Foo>.  If it could be assigned to that, then you could create a List<FooBar>, assign it to a List<Foo>, and then add Foo to a list that must contain FooBar, which is clearly an error.

Instead, you need:

```<code>List<Foo> fooList = new ArrayList<>();
fooList.add(new FooBar());
</code>```

Title: Type Inheritance Issue

Body:
I don't really know how to explain the problem I have. Below is an example of a few objects I have.

Lets say I have classes

public class Foo{}
public class FooBar extends Foo{}

All of that is fine, however if I take a list and say I want it to be full of Foo objects, I cannot provide it a FooBar object. Why is this?

Example:

List<Foo> fooList = Arrays.asList(new FooBar());

If FooBar extends Foo, why cant it be cast back to Foo?

Body:
Arrays.asList(new FooBar()) returns a List<FooBar>, which cannot be assigned to a List<Foo>.  If it could be assigned to that, then you could create a List<FooBar>, assign it to a List<Foo>, and then add Foo to a list that must contain FooBar, which is clearly an error.

Instead, you need:

List<Foo> fooList = new ArrayList<>();
fooList.add(new FooBar());


问:
Remove ionic android platform
I am trying to remove android platform from my ionic project using 'ionic platform remove android' but it showing the error, Platform "android" not recognised as a core cordova platform. What i do?

答:
What version of ionic are you using?

if you're using the latest version,

try ionic cordova platform remove android

Title: Remove ionic android platform


问:
Pass Complex Model in Post Method of Asp.net MVC
In my Razor View, I have candidate details along with other Degrees etc. I have to append row of Candidate's degree. I have taken Degree View as a partial view. Which will be added by candidate according to the number of degree he has. I need to pass detail of degree along with other details of Candidate to controller. I have attached my UI and details here:-

Here is my Model

```<code> public class Candidate:BaseEntity
{
    public Candidate()
    {

        CandidateDegreeMap = new HashSet<CandidateDegreeMap>();
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNo { get; set; }
    public string Email { get; set; }
    public string Status { get; set; }
    public string Gender { get; set; }
    public DateTime Dob { get; set; }
    public DateTime DateCreated { get; set; }
    public int CreatedBy { get; set; }
    public DateTime? DateModified { get; set; }
    public int? ModifiedBy { get; set; }
    public bool IsDeleted { get; set; }

    public ICollection<CandidateDegreeMap> CandidateDegreeMap { get; set; }

}
</code>```

I need to pass candidate details with their multiple Education.
Here I am Adding my controller

```<code>[HttpPost]
    public async Task<IActionResult> AddEdit([FromBody]CandidateModel model,
string returnUrl = null)
    {
        return await Task.Run(()=>View("AddCandidate",model));
    }
</code>```

My View is below

```<code>/*Dashboard Page Ends*/
</code>```

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AddCandidate - CVManagement</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href=/css/select2.min.css />
    <link rel="stylesheet" href=/css/style.css />
    <link rel="stylesheet" href=/css/responsive.css />

                         <mp>John Doe</mp> arrow_drop_down

                     Dashboard

                     Candidates

    Dashboard
    Openings
    Add Candidate

Candidate Details

<form method="post" class="col s12 m12 l12 xl12" action="/Candidate/AddEdit">

Personal

                <input id="first_name" type="text" name="FirstName" value="">
                First Name

                <input id="last_name" type="text" name="LastName" value="">
                Last Name

                <input id="Dob" class="cv-date-picker" type="text" data-val="true" data-val-required="The Dob field is required." name="Dob" value="">
                Date of Birth

                <input id="Gender" type="text" disabled="disabled" name="Gender" value="">
                Gender

                <input id="phone_number" type="text" name="PhoneNo" value="">
                Phone Number

                <input id="email" type="email" name="Email" value="">
                Email

Education

        <input type="text" id="DegreeName" name="DegreeName" value="">
        Degree

        <input type="text" id="InstituteName" name="InstituteName" value="">
        Institute

        <input class="cv-date-picker" type="text" id="YearOfPassing" name="YearOfPassing" value="">
        Year Of Passing

            + Add more

Proffessional

                <input id="tot_exp" type="text">
                Total Experience

                <input id="rel_exp" type="text">
                Relevant Experience

             Add Wrok Experience

                    <input type="checkbox" class="filled-in" id="currentJob_1" />
                    Current Job

                    <input id="employer_1" type="text">
                    Employer

                    <input id="job_role_1" type="text">
                    Job Role

                    <select id="it_skills_1" class="material-select">
                        <option value="1">Option 1</option>
                        <option value="2">Option 2</option>
                        <option value="3">Option 3</option>
                    </select>
                    IT Skills

                        <input type="text" placeholder="Start" class="cv-date-picker">

                        <input type="text" placeholder="End" class="cv-date-picker">

                    Date Range

                    <input id="current_ctc_1" type="text">
                    Current CTC

                    <input id="expected_ctc_1" type="text">
                    Expected CTC

            clear

                    <input type="checkbox" class="filled-in" id="currentJob_2" />
                    Current Job

                    <input id="employer_2" type="text">
                    Employer

                    <input id="job_role_2" type="text">
                    Job Role

                    <select id="it_skills_2" class="material-select">
                        <option value="1">Option 1</option>
                        <option value="2">Option 2</option>
                        <option value="3">Option 3</option>
                    </select>
                    IT Skills

                        <input type="text" placeholder="Start" class="cv-date-picker">

                        <input type="text" placeholder="End" class="cv-date-picker">

                    Date Range

                    <input id="current_ctc_2" type="text">
                    Current CTC

                    <input id="expected_ctc_2" type="text">
                    Expected CTC

            clear

                <select id="capability" class="material-select">
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Capability

Recruiter Comment

                Good
                Bad Communication

                <textarea id="textarea1" class="materialize-textarea"></textarea>
                Comment

Hiring Manager Comment

                Good
                Bad Communication

                <textarea id="textarea1" class="materialize-textarea"></textarea>
                Comment

                <select class="material-select">
                    <option value="" disabled selected>Choose your option</option>
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Capability

                <select class="material-select">
                    <option value="" disabled selected>Choose your option</option>
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Opening

                <button class="btn btn-cre-opn waves-effect active">Save</button>
                <button class="btn btn-cre-opn waves-effect">Cancel</button>

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8K7NtNmNf5lJsh806e0aRPmUONXIh2RLjJ1oH6KtOEdcIrE95C_Obn7dzp3LNYv2Eof0VGrWukRpqxXnYDAJGverd0YJjhOSXeUEJZFmHpAnjwlJMAoTnrYn2ILawiFAHDDU6_ujcJ-blB1IsoYXRzk" /></form>

© 2017 - Azilen Technology Pvt. Ltd

```

Moreover Please find Image also

答:
I think this is what you want i guess

First create a a model class name CandidateModel, which has candidate model and list of education details of candidates.

```<code>public class CandidateModel {

  public CandidateModel(){
    this.CandidateEducationDetails = new HashSet<CandidateEducationDetails >();
    this.Candidate = new Candidate();
  }

 public Candidate Candidate { get; set;}
 public  List<CandidateEducationDetails> CandidateEducationDetails { get; set;}

}
</code>```

Now in controller set education details object and candidate object  to new instance of candidate model and pass the model to the view. You should use this CandidateModel class in view also

ContentLicense: CC BY-SA 4.0

Body:
In my Razor View, I have candidate details along with other Degrees etc. I have to append row of Candidate's degree. I have taken Degree View as a partial view. Which will be added by candidate according to the number of degree he has. I need to pass detail of degree along with other details of Candidate to controller. I have attached my UI and details here:-

Here is my Model

 public class Candidate:BaseEntity
{
    public Candidate()
    {

        CandidateDegreeMap = new HashSet<CandidateDegreeMap>();
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNo { get; set; }
    public string Email { get; set; }
    public string Status { get; set; }
    public string Gender { get; set; }
    public DateTime Dob { get; set; }
    public DateTime DateCreated { get; set; }
    public int CreatedBy { get; set; }
    public DateTime? DateModified { get; set; }
    public int? ModifiedBy { get; set; }
    public bool IsDeleted { get; set; }

    public ICollection<CandidateDegreeMap> CandidateDegreeMap { get; set; }

}

I need to pass candidate details with their multiple Education.
Here I am Adding my controller

[HttpPost]
    public async Task<IActionResult> AddEdit([FromBody]CandidateModel model,
string returnUrl = null)
    {
        return await Task.Run(()=>View("AddCandidate",model));
    }

My View is below

/*Dashboard Page Ends*/

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AddCandidate - CVManagement</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href=/css/select2.min.css />
    <link rel="stylesheet" href=/css/style.css />
    <link rel="stylesheet" href=/css/responsive.css />

                         <mp>John Doe</mp> arrow_drop_down

                     Dashboard

                     Candidates

    Dashboard
    Openings
    Add Candidate

Candidate Details

<form method="post" class="col s12 m12 l12 xl12" action="/Candidate/AddEdit">

Personal

                <input id="first_name" type="text" name="FirstName" value="">
                First Name

                <input id="last_name" type="text" name="LastName" value="">
                Last Name

                <input id="Dob" class="cv-date-picker" type="text" data-val="true" data-val-required="The Dob field is required." name="Dob" value="">
                Date of Birth

                <input id="Gender" type="text" disabled="disabled" name="Gender" value="">
                Gender

                <input id="phone_number" type="text" name="PhoneNo" value="">
                Phone Number

                <input id="email" type="email" name="Email" value="">
                Email

Education

        <input type="text" id="DegreeName" name="DegreeName" value="">
        Degree

        <input type="text" id="InstituteName" name="InstituteName" value="">
        Institute

        <input class="cv-date-picker" type="text" id="YearOfPassing" name="YearOfPassing" value="">
        Year Of Passing

            + Add more

Proffessional

                <input id="tot_exp" type="text">
                Total Experience

                <input id="rel_exp" type="text">
                Relevant Experience

             Add Wrok Experience

                    <input type="checkbox" class="filled-in" id="currentJob_1" />
                    Current Job

                    <input id="employer_1" type="text">
                    Employer

                    <input id="job_role_1" type="text">
                    Job Role

                    <select id="it_skills_1" class="material-select">
                        <option value="1">Option 1</option>
                        <option value="2">Option 2</option>
                        <option value="3">Option 3</option>
                    </select>
                    IT Skills

                        <input type="text" placeholder="Start" class="cv-date-picker">

                        <input type="text" placeholder="End" class="cv-date-picker">

                    Date Range

                    <input id="current_ctc_1" type="text">
                    Current CTC

                    <input id="expected_ctc_1" type="text">
                    Expected CTC

            clear

                    <input type="checkbox" class="filled-in" id="currentJob_2" />
                    Current Job

                    <input id="employer_2" type="text">
                    Employer

                    <input id="job_role_2" type="text">
                    Job Role

                    <select id="it_skills_2" class="material-select">
                        <option value="1">Option 1</option>
                        <option value="2">Option 2</option>
                        <option value="3">Option 3</option>
                    </select>
                    IT Skills

                        <input type="text" placeholder="Start" class="cv-date-picker">

                        <input type="text" placeholder="End" class="cv-date-picker">

                    Date Range

                    <input id="current_ctc_2" type="text">
                    Current CTC

                    <input id="expected_ctc_2" type="text">
                    Expected CTC

            clear

                <select id="capability" class="material-select">
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Capability

Recruiter Comment

                Good
                Bad Communication

                <textarea id="textarea1" class="materialize-textarea"></textarea>
                Comment

Hiring Manager Comment

                Good
                Bad Communication

                <textarea id="textarea1" class="materialize-textarea"></textarea>
                Comment

                <select class="material-select">
                    <option value="" disabled selected>Choose your option</option>
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Capability

                <select class="material-select">
                    <option value="" disabled selected>Choose your option</option>
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Opening

                <button class="btn btn-cre-opn waves-effect active">Save</button>
                <button class="btn btn-cre-opn waves-effect">Cancel</button>

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8K7NtNmNf5lJsh806e0aRPmUONXIh2RLjJ1oH6KtOEdcIrE95C_Obn7dzp3LNYv2Eof0VGrWukRpqxXnYDAJGverd0YJjhOSXeUEJZFmHpAnjwlJMAoTnrYn2ILawiFAHDDU6_ujcJ-blB1IsoYXRzk" /></form>

© 2017 - Azilen Technology Pvt. Ltd

Moreover Please find Image also

Body:
I think this is what you want i guess

First create a a model class name CandidateModel, which has candidate model and list of education details of candidates.

public class CandidateModel {

  public CandidateModel(){
    this.CandidateEducationDetails = new HashSet<CandidateEducationDetails >();
    this.Candidate = new Candidate();
  }

 public Candidate Candidate { get; set;}
 public  List<CandidateEducationDetails> CandidateEducationDetails { get; set;}

}

Now in controller set education details object and candidate object  to new instance of candidate model and pass the model to the view. You should use this CandidateModel class in view also


问:
Simple command Appending Excel Data to MS Access. "Data type mismatch in criteria expression"
I keep getting this error:

Run-time error '3464': Data type mismatch in criteria expression

I know this is a common error to get, but in my case none of the questions in the forum seems applicable.

This is my code, and I have checked several times that the field names are the same in Excel and Access. Could it be that one of my fields in the Access table is a check box? I'm using True/False as values in Excel for that field.

```<code>Private Sub cmdImportMaintJobs_Click()

  xlsMaintFile = OpenFileDialog(CurrentProject.Path & "\", "*.xls?", "MS Excel sheet", "*.xls; *.xlsx", "Select Excel file with Maintenance Jobs data")

  If Len(xlsMaintFile) > 0 Then
    CurrentDb.Execute "INSERT INTO tblMaintJob SELECT * FROM [Maint Jobs$A1:I50000] IN '" & xlsMaintFile & _
      "' [Excel 5.0;HDR=YES;IMEX=1] WHERE MoldID <> 0 "
    MsgBox "All done!", vbInformation, "Information"

  End If

End Sub
</code>```

答: I would highly recommend to import the data from Excel into temporary table first, all fields should be text. Then you'll be able to copy imported data to working table with explicit conversion and validation. Otherwise you'll run into similar problems with other data files</p>

Body:
I keep getting this error:

Run-time error '3464': Data type mismatch in criteria expression

I know this is a common error to get, but in my case none of the questions in the forum seems applicable.

This is my code, and I have checked several times that the field names are the same in Excel and Access. Could it be that one of my fields in the Access table is a check box? I'm using True/False as values in Excel for that field.

Private Sub cmdImportMaintJobs_Click()

  xlsMaintFile = OpenFileDialog(CurrentProject.Path & "\", "*.xls?", "MS Excel sheet", "*.xls; *.xlsx", "Select Excel file with Maintenance Jobs data")

  If Len(xlsMaintFile) > 0 Then
    CurrentDb.Execute "INSERT INTO tblMaintJob SELECT * FROM [Maint Jobs$A1:I50000] IN '" & xlsMaintFile & _
      "' [Excel 5.0;HDR=YES;IMEX=1] WHERE MoldID <> 0 "
    MsgBox "All done!", vbInformation, "Information"

  End If

End Sub


问:
The driver executable does not exist: C:\geckodriver.exe issue in Eclipse IDE
Please help me with this issue that is recurring every time I run my code.
I have extracted Geckodriver files in C Drive but when I run my code, the error that comes up is 'Exception in thread "main" java.lang.IllegalStateException: The driver executable does not exist: C:\geckodriver.exe'.

My code is given below:

```<code> package Basics;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Browserinvocation {
public static void main(String[] args) {
    // TODO Auto-generated method stub

System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

WebDriver driver = new FirefoxDriver();//FirefoxDriver class is used to implement methods present in Webdriver-Invocation of browser
driver.get("https://www.amazon.in/");// Get method to hit the url in browser

}

}
</code>```

Error in console :

Exception in thread "main" java.lang.IllegalStateException: The driver
  executable does not exist: C:\geckodriver.exe     at
  com.google.common.base.Preconditions.checkState(Preconditions.java:534)
    at
  org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:136)
    at
  org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:131)
    at
  org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
    at
  org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:141)
    at
  org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:339)
    at
  org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:158)
    at
  org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:120)
    at
  org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:98)
    at Basics.Browserinvocation.main(Browserinvocation.java:13)

答:
Your code is running at my side, might be you are not extracting the gecko driver.

Change the path and try it once, it should worked

Please let me know selenium jars version and your firefox browser version

```<code>System.setProperty("webdriver.gecko.driver", "C:/Users/sankalp.gupta/Desktop/JAVASEL/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("https://www.amazon.in");
System.out.println(driver.getCurrentUrl());
driver.close();
</code>```

Body:
Please help me with this issue that is recurring every time I run my code.
I have extracted Geckodriver files in C Drive but when I run my code, the error that comes up is 'Exception in thread "main" java.lang.IllegalStateException: The driver executable does not exist: C:\geckodriver.exe'.

My code is given below:

 package Basics;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Browserinvocation {
public static void main(String[] args) {
    // TODO Auto-generated method stub

System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

WebDriver driver = new FirefoxDriver();//FirefoxDriver class is used to implement methods present in Webdriver-Invocation of browser
driver.get("https://www.amazon.in/");// Get method to hit the url in browser

}

}

Error in console :

Exception in thread "main" java.lang.IllegalStateException: The driver
  executable does not exist: C:\geckodriver.exe     at
  com.google.common.base.Preconditions.checkState(Preconditions.java:534)
    at
  org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:136)
    at
  org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:131)
    at
  org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
    at
  org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:141)
    at
  org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:339)
    at
  org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:158)
    at
  org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:120)
    at
  org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:98)
    at Basics.Browserinvocation.main(Browserinvocation.java:13)

Body:
Your code is running at my side, might be you are not extracting the gecko driver.

Change the path and try it once, it should worked

Please let me know selenium jars version and your firefox browser version

System.setProperty("webdriver.gecko.driver", "C:/Users/sankalp.gupta/Desktop/JAVASEL/geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("https://www.amazon.in");
System.out.println(driver.getCurrentUrl());
driver.close();


问:
how to Parse values from Array?this is my sample array code?
```<code>Array
(
    [Action] => Array
        (
            [0] => Array
                (
                    [@attributes] => Array
                        (
                            [Name] => OfferActivationByOfferID
                            [Version] => 1.0
                            [ImagePath] => ./resources
                        )
                )
            [1] => Array
                (
                    [@attributes] => Array
                        (
                            [Name] => Ranjith
                            [Version] => 1.0
                            [ImagePath] => ./resources
                        )
                )
        )
)
</code>```

in this array i need [Name] attribute Value for Every Action tag.please do help.

sample output;

1.OfferActivationByOfferID

2.Ranjith

答:
```<code>$data = //Your full array
$names = array();
// then loop through the array
foreach($data['Action'] as $key=> $value){
    $names[] = $value['@attributes']['Name'];
}
</code>```

So $names will have all the names of the original array.

Body:
Array
(
    [Action] => Array
        (
            [0] => Array
                (
                    [@attributes] => Array
                        (
                            [Name] => OfferActivationByOfferID
                            [Version] => 1.0
                            [ImagePath] => ./resources
                        )
                )
            [1] => Array
                (
                    [@attributes] => Array
                        (
                            [Name] => Ranjith
                            [Version] => 1.0
                            [ImagePath] => ./resources
                        )
                )
        )
)

in this array i need [Name] attribute Value for Every Action tag.please do help.

sample output;

1.OfferActivationByOfferID

2.Ranjith

Body:
$data = //Your full array
$names = array();
// then loop through the array
foreach($data['Action'] as $key=> $value){
    $names[] = $value['@attributes']['Name'];
}

So $names will have all the names of the original array.


问:
Silverlight: Bing Map Control in OOB possible?
I'm playing with the Bing Map control for Silverlight and an out-of-browser (OOB) app. I get the "map loaded in unsupported uri scheme" error because the control does not like to be hosted on the file system and wants a WebApplication instead (http://). Here's a more detailed explanation I found to this:
http://conceptdev.blogspot.com/2009/03/silverlight-virtualearth-map-control.html

Is there a workaround to this when running a OOB app?

Thanks

答:
It's messy but it could work:

Write a WinForms program that contains a WebBrowser control

Embed a lightweight web server running on localhost into the program

Serve your Silverlight application via a web page to the browser

That's a lot of work to make it look like you don't have a browswer and it's still not OOB.


问:
How to get the size of Documents & data present in application?
I am adding some data in my application like class room information(class name, number of students in that class and classroom images) using core data. After addition of many record of class information I want to know how much document data size(in KB or MB) present in my app. So is it possible to get the size of documents & data as we can see from phone setting storage? If possible then how? </p>

答:
You can use following method to determine the file properties

```<code>NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:<File Path> error:&error];

NSNumber *fileSize = [fileAttributes objectForKey:NSFileSize];
double tempSize = (double)([fileSize unsignedLongLongValue]/(1000.0*1000.0));
</code>```

This will give you file size in MB

Body:
You can use following method to determine the file properties

NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:<File Path> error:&error];

NSNumber *fileSize = [fileAttributes objectForKey:NSFileSize];
double tempSize = (double)([fileSize unsignedLongLongValue]/(1000.0*1000.0));

This will give you file size in MB


问:
filtering in an ng-repeat from JSON response
I've got a question about filtering within a ng-repeat. But this isn't a simple question since I'm not really having a problem that needs a solution. In this case, I'm looking for the best possible answer that doesn't require a lot of code but still does the trick as to how I want it to. It will become more clear in my description.

a short introduction:

So I'm currently working on a shopping application. The shopping application has a connection with an existing PrestaShop webshop through the web service API. A rest API for PrestaShop. So after creating a customer section, products section, and a cart system, I would like to be able to update the "stock amount" of each product within the application. Many people would tell me: Well that's easy, just create a form with ng-repeat response data from the database and the possibility of updating the stock on let's say a button ng-click event.

Well I've done that but now the tricky part, and to explain I will provide some less important examples to make it more clear of what I'm asking:

The prestashop database

The prestashop database is a database that exists of over 250 tables. Among those tables are various connections through id's and attribute id's. Some simple examples are:

The customer table has an id_address row which connects to the address table. Within this table, all the 'customersaddress info is placed. So far, let's say updating a customer I've created a combination of update thecustomertable with thecustomer_idbut also update theaddresstable where theaddress_idis equal to theid_addressfrom the selectedcustomerwithin thecustomer` table.

Products also have some linked tables. Think about prices, taxes, sizes, and colors. The id_product_attribute is an attribute_id that could correspond to a color or size.

As explained above the prestashop database structure is very detailed which confines to using various filters for showing the wanted data.

Using the webservice

So for using the webservice I'm using a combination of angularJS, javascript, php, and JSON. The JSON is the actual data. by using $http.get(url, options) I'm able to get the data from the database. Then for showing the data I'm using response. A example is shown below:

```<code>$http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
    $scope.customers = response.data.customers.customer
});
</code>```

using $scope.customers = response.data.customers.customer gives me the option to show the customer data by using, for example, a ng-repeat as in the example below

    $http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
        $scope.customers = response.data.customers.customer
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="row listrow" ng-repeat="customer in customers | orderBy: customer.id">
        <div class="col-lg-8">
            <p class="customer" ng-bind="customer.id + ' ' + customer.firstname + ' ' + customer.lastname">
      </p>
        </div>
</div></code>```

In this case, the response would be empty since there is no database connection. To create a full example for testing here is some JSON data you could use from the customers table.

```<code>{"customers":{"customer":[{"id":"1","id_default_group":"0","id_lang":"0","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-30 09:27:03","secure_key":{},"deleted":"0","passwd":"$2y$10$eZvPTD9bkxwSfWN7qovrmee\/Den2TqZ5a6YjcGC\/lha3oU59MCjOO","lastname":"TestStefans","firstname":"John","email":"pub@prestashop.com","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:31","date_upd":"2017-10-27 15:56:54","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}},{"id":"2","id_default_group":"0","id_lang":"1","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-27 15:56:55","secure_key":{},"deleted":"0","passwd":"$2y$10$C8M6TIuzmZjP9kh06Hai8.XyuNG9WcSi9L34oXqAuidsJkoYog4WW","lastname":"Demoers","firstname":"Demoers","email":"demo@sdwebdesign.nl","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:33","date_upd":"2017-10-27 15:56:55","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}}]}}
</code>```

So with this information here is my question:

While working on the application the following data is given within the stock_availables table.

So while using the $http.get() and the response functions I was able to create a form for updating the stock. But now take a look at the id_product_attribute. This row corresponds to a product_attribute. In this case a size or color. Now I would like to filter these results. In this case by using for example ng-if="id_product_attribute == 0" I'm able to filter in a way that only all with this id_attribute are shown. But I would like to show all of them. So also with id="1", id="2", etc. But there is where I'm wondering, is there a way to do this in a sufficient way that wouldn't require a ng-if for each id? Since there are around 50 different id_attribute's which each corresponds to a color or size. So is there a function that could get each different id and filter that in a sufficient way than using many ng-if clauses. Look at the following full code as an example.

myApp.controller('ProductsController', function($scope, $http){

    $http.get('config/get/getProducts.php', {cache: true}).then(function(response){
        $scope.products = response.data.products.product
    });
    // Stock check + view
    $http.get('config/get/getStock.php', {cache: true}).then(function (response) {
        $scope.stock_availables = response.data.stock_availables.stock_available
    });

// Update Stock
    $scope.updateStock = function(stock_available) {

        var stock_id = stock_available.id;
        var product_id = stock_available.id_product;
        var stock_quantity = stock_available.quantity;

        console.log(stock_id + product_id + stock_quantity);

        // Post to the database //

    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="row listrow">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <ng-form name="stock">
                <div ng-repeat="stock_available in stock_availables">
                    <div class="row full-width padding-tb-15" ng-if="stock_available.id_product == product.id  && stock_available.id_product_attribute == 0" ng-repeat="product in products">
                        <div class="col-lg-12 form-stock-group hidden">
                            <input title="id" type="text" name="stockId" class="form-control" aria-describedby="" ng-value="stock_available.id">
                        </div>
                        <div class="col-lg-4">
                            <h5 ng-bind="product.name.language"></h5>
                        </div>
                        <div class="col-lg-3">
                            <h5 ng-bind="product.ean13"></h5>
                        </div>
                        <div class="col-lg-2">
                            <h5 ng-bind="product.reference"></h5>
                        </div>
                        <div ng-if="stock_available.id_product == product.id && stock_available.id_product_attribute == 0" ng-repeat="stock_available in stock_availables" class="col-lg-1 text-center">
                            <input title="stock_id" type="text" name="stock_id" class="form-control hidden" aria-describedby=""  ng-model="stock_available.id" ng-value="stock_available.id">
                            <input title="stock_id_product" type="text" name="stock_id_product" class="form-control hidden" aria-describedby="" ng-model="stock_available.id_product" ng-value="stock_available.id_product">
                            <h5 title="quantity" name="stockQuantity" aria-describedby="" ng-model="stock_available.quantity" ng-bind="stock_available.quantity"></h5>
                        </div>
                        <div ng-if="stock_available.id_product == product.id && stock_available.id_product_attribute == 0" ng-repeat="stock_available in stock_availables" class="col-lg-1 text-center">
                            <input title="updateStockAmount" class="form-control form-control-stock" type="number">
                        </div>
                        <div class="col-lg-1 text-center">

                                <i class="fa fa-print" aria-hidden="true"></i>

                        </div>
                    </div>
                </div>
            </ng-form>
        </div>
    </div></code>```

I trying to create the following view:

Product-id 1: then all sizes, colors, etc.

Product-id 2: then all sizes, colors, etc.

Yes it is possible with writing 50 different ng-if statements but I'm asking if there is a better, easier and more sufficient way to do this?

A simple build of the dummy code can be found here

As always,

Thanks in advance!

答:
Have you considered using the database and letting the DB generate a specific query for this screen, which groups all the products together in a single row?.

so you currently have a bunch of "repeated" product IDs (since the query returns detailed information for color and size), but need to operate on the single record.

You can do that in the backend using a GROUP BY SQL query statement.

If the endpoint is being used by more programs, simply make your endpoint to be "only for this screen" and apply the necessary changes.

If changing the SQL on the backend is too complex (or politically inviable), you can always group_by using javascript:

https://www.consolelog.io/group-by-in-javascript

group_by takes as input a dataset and a column (i.e.).

given a dataset like:

```<code>c1 c2 c3
1  10 10
1  11 10
3  12 20

// this operation:
groups = group_by(dataset, "c1")

//returns this:

groups:

group 1 (2 elements)
    c2  c3
    10  10
    11  10
group 3 (1 element)
    c2  c3
    12  10
</code>```

this means you could feed the grouped dataset back into the grid program, so it can show groups as groups and items as items, by iterating first over the groups and later over the items.

There are many ways to implement group_by, like these:

What is the most efficient method to groupby on a javascript array of objects?

HTH

Body:
I've got a question about filtering within a ng-repeat. But this isn't a simple question since I'm not really having a problem that needs a solution. In this case, I'm looking for the best possible answer that doesn't require a lot of code but still does the trick as to how I want it to. It will become more clear in my description.

a short introduction:

So I'm currently working on a shopping application. The shopping application has a connection with an existing PrestaShop webshop through the web service API. A rest API for PrestaShop. So after creating a customer section, products section, and a cart system, I would like to be able to update the "stock amount" of each product within the application. Many people would tell me: Well that's easy, just create a form with ng-repeat response data from the database and the possibility of updating the stock on let's say a button ng-click event.

Well I've done that but now the tricky part, and to explain I will provide some less important examples to make it more clear of what I'm asking:

The prestashop database

The prestashop database is a database that exists of over 250 tables. Among those tables are various connections through id's and attribute id's. Some simple examples are:

The customer table has an id_address row which connects to the address table. Within this table, all the 'customersaddress info is placed. So far, let's say updating a customer I've created a combination of update thecustomertable with thecustomer_idbut also update theaddresstable where theaddress_idis equal to theid_addressfrom the selectedcustomerwithin thecustomer` table.

Products also have some linked tables. Think about prices, taxes, sizes, and colors. The id_product_attribute is an attribute_id that could correspond to a color or size.

As explained above the prestashop database structure is very detailed which confines to using various filters for showing the wanted data.

Using the webservice

So for using the webservice I'm using a combination of angularJS, javascript, php, and JSON. The JSON is the actual data. by using $http.get(url, options) I'm able to get the data from the database. Then for showing the data I'm using response. A example is shown below:

$http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
    $scope.customers = response.data.customers.customer
});

using $scope.customers = response.data.customers.customer gives me the option to show the customer data by using, for example, a ng-repeat as in the example below

    $http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
        $scope.customers = response.data.customers.customer
    });

In this case, the response would be empty since there is no database connection. To create a full example for testing here is some JSON data you could use from the customers table.

{"customers":{"customer":[{"id":"1","id_default_group":"0","id_lang":"0","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-30 09:27:03","secure_key":{},"deleted":"0","passwd":"$2y$10$eZvPTD9bkxwSfWN7qovrmee\/Den2TqZ5a6YjcGC\/lha3oU59MCjOO","lastname":"TestStefans","firstname":"John","email":"pub@prestashop.com","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:31","date_upd":"2017-10-27 15:56:54","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}},{"id":"2","id_default_group":"0","id_lang":"1","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-27 15:56:55","secure_key":{},"deleted":"0","passwd":"$2y$10$C8M6TIuzmZjP9kh06Hai8.XyuNG9WcSi9L34oXqAuidsJkoYog4WW","lastname":"Demoers","firstname":"Demoers","email":"demo@sdwebdesign.nl","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:33","date_upd":"2017-10-27 15:56:55","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}}]}}

So with this information here is my question:

While working on the application the following data is given within the stock_availables table.

So while using the $http.get() and the response functions I was able to create a form for updating the stock. But now take a look at the id_product_attribute. This row corresponds to a product_attribute. In this case a size or color. Now I would like to filter these results. In this case by using for example ng-if="id_product_attribute == 0" I'm able to filter in a way that only all with this id_attribute are shown. But I would like to show all of them. So also with id="1", id="2", etc. But there is where I'm wondering, is there a way to do this in a sufficient way that wouldn't require a ng-if for each id? Since there are around 50 different id_attribute's which each corresponds to a color or size. So is there a function that could get each different id and filter that in a sufficient way than using many ng-if clauses. Look at the following full code as an example.

myApp.controller('ProductsController', function($scope, $http){

    $http.get('config/get/getProducts.php', {cache: true}).then(function(response){
        $scope.products = response.data.products.product
    });
    // Stock check + view
    $http.get('config/get/getStock.php', {cache: true}).then(function (response) {
        $scope.stock_availables = response.data.stock_availables.stock_available
    });

// Update Stock
    $scope.updateStock = function(stock_available) {

        var stock_id = stock_available.id;
        var product_id = stock_available.id_product;
        var stock_quantity = stock_available.quantity;

        console.log(stock_id + product_id + stock_quantity);

        // Post to the database //

    };
});

            <ng-form name="stock">

                            <input title="id" type="text" name="stockId" class="form-control" aria-describedby="" ng-value="stock_available.id">

                            <input title="stock_id" type="text" name="stock_id" class="form-control hidden" aria-describedby=""  ng-model="stock_available.id" ng-value="stock_available.id">
                            <input title="stock_id_product" type="text" name="stock_id_product" class="form-control hidden" aria-describedby="" ng-model="stock_available.id_product" ng-value="stock_available.id_product">

                            <input title="updateStockAmount" class="form-control form-control-stock" type="number">

            </ng-form>

I trying to create the following view:

Product-id 1: then all sizes, colors, etc.

Product-id 2: then all sizes, colors, etc.

Yes it is possible with writing 50 different ng-if statements but I'm asking if there is a better, easier and more sufficient way to do this?

A simple build of the dummy code can be found here

As always,

Thanks in advance!

Body:
Have you considered using the database and letting the DB generate a specific query for this screen, which groups all the products together in a single row?.

so you currently have a bunch of "repeated" product IDs (since the query returns detailed information for color and size), but need to operate on the single record.

You can do that in the backend using a GROUP BY SQL query statement.

If the endpoint is being used by more programs, simply make your endpoint to be "only for this screen" and apply the necessary changes.

If changing the SQL on the backend is too complex (or politically inviable), you can always group_by using javascript:

https://www.consolelog.io/group-by-in-javascript

group_by takes as input a dataset and a column (i.e.).

given a dataset like:

c1 c2 c3
1  10 10
1  11 10
3  12 20

// this operation:
groups = group_by(dataset, "c1")

//returns this:

groups:

group 1 (2 elements)
    c2  c3
    10  10
    11  10
group 3 (1 element)
    c2  c3
    12  10

this means you could feed the grouped dataset back into the grid program, so it can show groups as groups and items as items, by iterating first over the groups and later over the items.

There are many ways to implement group_by, like these:

What is the most efficient method to groupby on a javascript array of objects?

HTH