答:
table != null should work.

Here's an example:

```<code>using System;
using System.Data;

public class Program
{
    public static void Main()
    {
        DataTable table = null;

        Test(table);

        table = new DataTable();

        Test(table);
    }

    public static void Test(DataTable table)
    {
        if(table == null)
        {
            Console.WriteLine("table is null");
            return;
        }

        if(table.IsInitialized == false)
        {
            Console.WriteLine("table is not initalised.");
            return;
        }

        Console.WriteLine("table row count: " + table.Rows.Count);
    }
}
</code>```

Output:

```<code>table is null
table row count: 0
</code>```

https://dotnetfiddle.net/0s2Jp8

Title: How to determine if DataTable is null, not initialized

Body:
I have a method that does some work on a DataTable e.g.

private void MyMethod(DataTable table)
{
    if(table.Rows.Count > 0)
    {
       //  do some work
    }
 }

However, if the method receives a null datatable from the application it serves I get an 'Object reference not set to an instance of an object' error.

I have also tried . . .

if(table.IsInitialized) { }

and

if(table != null) {  }

but I get the same error message.

How do I test to see if the incoming datatable is instantiated and not null please?

The DataTable is coming from a cast of a datagrid in a WinForms app i.e.

DataTable table = (DataTable)datagridview.DataSource;

So the issue arises if the original datagridview is empty.

Body:
table != null should work.

Here's an example:

using System;
using System.Data;

public class Program
{
    public static void Main()
    {
        DataTable table = null;

        Test(table);

        table = new DataTable();

        Test(table);
    }

    public static void Test(DataTable table)
    {
        if(table == null)
        {
            Console.WriteLine("table is null");
            return;
        }

        if(table.IsInitialized == false)
        {
            Console.WriteLine("table is not initalised.");
            return;
        }

        Console.WriteLine("table row count: " + table.Rows.Count);
    }
}

Output:

table is null
table row count: 0

https://dotnetfiddle.net/0s2Jp8


来源: stackexchange

问:
Cannot read property 'force' of undefined (Simple D3 Network graph)
I am new to D3 and Javascript but have typically had luck with just copying the basic D3 scripts and getting my data into the proper format for the visualization to work. I have tried several of the D3 Network graphs and have gotten the same error for all of them when I inspect the page.

Uncaught TypeError: Cannot read property 'force' of undefined.

If you look at the script here: http://bl.ocks.org/jose187/4733747
I just copied it completely along with the respective .json file and am getting the above error. It seems to think that d3.layout.force() is an "anonymous function". Any ideas what is going on? Or how to fix it? Thank you!

答: OK, since I'm already here and I had the same problem, my solution was to downgrade to //d3js.org/d3.v3.js</p>

ContentLicense: CC BY-SA 3.0


问:
How do you compile the Hello World program for Java?
I am at step 6 in the process of installing JDK onto windows using instructions from  this website .

When I attempt to “Set the Current Drive to the drive where you saved your source file Hello.java” by typing “c:”, nothing happens (the instructions indicate that something like C:\xxx> should appear).

I have saved the hello world file in the C: directory as indicated in the previous step (step 5).

I am trying to start learning Java and any help would be appreciated.

答: Make a directory (example  C:\myjava) then save your Hello.java file inside the myjava folder. Open your command prompt and type cd c:\myjava. Then type javac Hello.java to compile your code.</p>


问:
Request.IsAjaxRequest() alternative in MVC6
I am trying to run this example Rendering Partial Views using ajax, but i got the following compilation error:

'HttpRequest' does not contain a definition for 'IsAjaxRequest' and no extension method 'IsAjaxRequest' accepting a first argument of type 'HttpRequest' could be found.

```<code>    public ActionResult ItemsList(string ID)
    {
        Item item = Service.GetItemById(ID);

        if (Request.IsAjaxRequest())
        {
            return PartialView("viewPath", item);
        }
        else
        {
            return View("viewPath", item);
        }
    }
</code>```

答:
Check the user agent, as this:</p>

```<code>var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";
</code>```

Body:
I am trying to run this example Rendering Partial Views using ajax, but i got the following compilation error:

'HttpRequest' does not contain a definition for 'IsAjaxRequest' and no extension method 'IsAjaxRequest' accepting a first argument of type 'HttpRequest' could be found.

    public ActionResult ItemsList(string ID)
    {
        Item item = Service.GetItemById(ID);

        if (Request.IsAjaxRequest())
        {
            return PartialView("viewPath", item);
        }
        else
        {
            return View("viewPath", item);
        }
    }

Body:
Check the user agent, as this:

var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";


问:
Error: E0708 : E0708: Invalid transition
Using this tutorial i created workflow for hive script but gives me error when i run below command:

```<code> oozie job -oozie http://xxx.xx.xx.xx:11000/oozie -config  /home/ec2-user/ankit/oozie_job1/job.properties -submit
</code>```

Error which i get is this :

Error: E0708 : E0708: Invalid transition, node [Oozie_test] transition [Tester]

My workflow code is below:

```<code><workflow-app name="Tester" xmlns="uri:oozie:workflow:0.1">
<start to="Oozie_test"/>
<action name="Oozie_test">
<hive xmlns="uri:oozie:hive-action:0.2">
 <job-tracker>xxx.xx.xx.xx:8021</job-tracker>
 <name-node>xxx.xx.11.xx:8020</name-node>
 <configuration>
    <property>
         <name>oozie.hive.defaults</name>
         <value>/home/ec2-user/ankit/oozie_job1/hive-default.xml</value>
    </property>
 </configuration>
 <script>hive_job1.hql</script>
</hive>
<ok to="Tester"/>
<error to="fail"/>
</action>
<end name="end"/>
</workflow-app>
</code>```

As this being my first oozie workflow,i am not able to get where exactly i am going wrong or what i have missed.

I tried to  search the solution for this on internet but couldn't find any luck.

Please let me know how to solve this error and what other info is required from my side.

答: Confirm if you have copied your workflow.xml to hdfs. You need not copy job.properties to hdfs but have to copy all the other files and libraries to hdfs</p>

Body:
Using this tutorial i created workflow for hive script but gives me error when i run below command:

 oozie job -oozie http://xxx.xx.xx.xx:11000/oozie -config  /home/ec2-user/ankit/oozie_job1/job.properties -submit

Error which i get is this :

Error: E0708 : E0708: Invalid transition, node [Oozie_test] transition [Tester]

My workflow code is below:

<workflow-app name="Tester" xmlns="uri:oozie:workflow:0.1">
<start to="Oozie_test"/>
<action name="Oozie_test">
<hive xmlns="uri:oozie:hive-action:0.2">
 <job-tracker>xxx.xx.xx.xx:8021</job-tracker>
 <name-node>xxx.xx.11.xx:8020</name-node>
 <configuration>
    <property>
         <name>oozie.hive.defaults</name>
         <value>/home/ec2-user/ankit/oozie_job1/hive-default.xml</value>
    </property>
 </configuration>

</hive>
<ok to="Tester"/>
<error to="fail"/>
</action>
<end name="end"/>
</workflow-app>

As this being my first oozie workflow,i am not able to get where exactly i am going wrong or what i have missed.

I tried to  search the solution for this on internet but couldn't find any luck.

Please let me know how to solve this error and what other info is required from my side.


问:
Magento 1.9 create new Hello World module

 Hello, guys!

I really hope someone will help me with this.

I trying to make new module in magento 1.9.3.2, which show "Hello world!" from phtml file. I  created that step by step by this rules. Module is created, but when I open module (127.0.0.1/magento/helloworld) in browser, nothing appear, just empty this template.
opened module in browser - screenshot

Here is steps by what i guided:

1. Module declaration:
     Create new xml file in  app/etc/modules/M4U_HelloWorld.xml

    <?xml version="1.0"?>
                 <config>
                       <modules>
                          <M4U_HelloWorld>
                               <active>true</active>
                               <codePool>local</codePool>
                          </M4U_HelloWorld>
                       </modules>
                 </config>

Module configuration

    2.1. Create controller class in app/code/local/M4U/HelloWorld/controllers/IndexController.php

class M4U_HelloWorld_IndexController extends  Mage_Core_Controller_Front_Action
                    {
                      public function indexAction()
                      {
                         $this->loadLayout(array('default'));
                         $this->renderLayout();
                      }
                    }

2.2. Create Block class in app/code/local/M4U/HelloWorld/Block/HelloWorld.php

```<code>class M4U_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
                  {
                       // necessary methods
                  }
</code>```

2.3. Create configuration xml in app/code/local/M4U/HelloWorld/etc/config.xml

```<code><?xml version="1.0"?>
<config>
<global>
    <modules>
            <m4u_helloworld>
                    <version>0.1.0</version>
            </m4u_helloworld>
    </modules>
<blocks>
        <helloworld>
            <rewrite>
     <helloworld>M4U_HelloWorld_Block_HelloWorld</helloworld>
    </rewrite>
        </helloworld>
 </blocks>
    </global>
   <frontend>
            <routers>
                    <helloworld>
                            <use>standard</use>
                            <args>
                                  <module>M4U_HelloWorld</module>
                                  <frontName>helloworld</frontName>
                            </args>
                    </helloworld>
            </routers>
    <layout>
        <updates>
            <helloworld>
                  <file>helloworld.xml</file>
            </helloworld>
        </updates>
        </layout>
    </frontend>
</code>```

Define frontend template

3.1. Define page layout in app/design/frontend/default/default/layout/helloworld.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <helloworld_index_index>
        <reference name="root">
            <action method="setTemplate">                  <template>page/1column.phtml</template></action>
        </reference>
        <reference name="content">
            <block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"/>
        </reference>
    </helloworld_index_index>
</layout>

Create template file in   app/design/frontend/default/default/template/helloworld/helloworld.phtml

答:
As Per Inchoo Article :

We will start by creating a simple “Hello world” module. However, you
  will soon see that simple takes a new meaning with Magento. Creating a
  bare bone module requires at least two files in Magento. For your
  module to work you need /app/etc/modules/MyCompany_MyModule.xml,
  app/code/local/MyCompany/MyModule/etc/config.xml. But, barebone module
  will not give you a “Hello developer” -So, we need to add few more
  files to the game.

file 1: /app/etc/modules/Inchoo_HelloDeveloper.xml

```<code><?xml version="1.0"?>
<config>
    <modules>
        <Inchoo_HelloDeveloper>
            <active>true</active>
            <codePool>local</codePool>
        </Inchoo_HelloDeveloper>
    </modules>
</config>
</code>```

file 2: app/code/local/Inchoo/HelloDeveloper/etc/config.xml

```<code><?xml version="1.0"?>
<config>
    <modules>
        <Inchoo_HelloDeveloper>
            <version>0.1.0</version>
        </Inchoo_HelloDeveloper>
    </modules>
    <frontend>
        <routers>
            <Inchoo_HelloDeveloper_SomeFreeRouterName1>
                <use>standard</use>
                <args>
                    <module>Inchoo_HelloDeveloper</module>
                    <frontName>inchoo-hellodeveloper</frontName>
                </args>
            </Inchoo_HelloDeveloper_SomeFreeRouterName1>
        </routers>
    </frontend>
</config>
</code>```

file 3:
  app/code/local/Inchoo/HelloDeveloper/controllers/IndexController.php

```<code><?php

class Inchoo_HelloDeveloper_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        echo 'Hello developer...';
    }

    public function sayHelloAction()
    {
        echo 'Hello one more time...';
    }
}
?>
</code>```

Altough extremely simple, file 3 shows us one important thing: Naming
  connvention. Note the name of the class. Your moudle classes should
  keep names in form of MyCompany_MyModule_FileName, or in case of block
  and modules: MyCompany_MyModule_Block_FileName or
  MyCompany_MyModule_Module_FileName.

Body:
 Hello, guys!

I really hope someone will help me with this.

I trying to make new module in magento 1.9.3.2, which show "Hello world!" from phtml file. I  created that step by step by this rules. Module is created, but when I open module (127.0.0.1/magento/helloworld) in browser, nothing appear, just empty this template.
opened module in browser - screenshot

Here is steps by what i guided:

1. Module declaration:
     Create new xml file in  app/etc/modules/M4U_HelloWorld.xml

    <?xml version="1.0"?>
                 <config>
                       <modules>
                          <M4U_HelloWorld>
                               <active>true</active>
                               <codePool>local</codePool>
                          </M4U_HelloWorld>
                       </modules>
                 </config>

Module configuration

    2.1. Create controller class in app/code/local/M4U/HelloWorld/controllers/IndexController.php

class M4U_HelloWorld_IndexController extends  Mage_Core_Controller_Front_Action
                    {
                      public function indexAction()
                      {
                         $this->loadLayout(array('default'));
                         $this->renderLayout();
                      }
                    }

2.2. Create Block class in app/code/local/M4U/HelloWorld/Block/HelloWorld.php

class M4U_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
                  {
                       // necessary methods
                  }

2.3. Create configuration xml in app/code/local/M4U/HelloWorld/etc/config.xml

<?xml version="1.0"?>
<config>
<global>
    <modules>
            <m4u_helloworld>
                    <version>0.1.0</version>
            </m4u_helloworld>
    </modules>
<blocks>
        <helloworld>
            <rewrite>
     <helloworld>M4U_HelloWorld_Block_HelloWorld</helloworld>
    </rewrite>
        </helloworld>
 </blocks>
    </global>
   <frontend>
            <routers>
                    <helloworld>
                            <use>standard</use>
                            <args>
                                  <module>M4U_HelloWorld</module>
                                  <frontName>helloworld</frontName>
                            </args>
                    </helloworld>
            </routers>
    <layout>
        <updates>
            <helloworld>
                  <file>helloworld.xml</file>
            </helloworld>
        </updates>
        </layout>
    </frontend>

Define frontend template

3.1. Define page layout in app/design/frontend/default/default/layout/helloworld.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <helloworld_index_index>
        <reference name="root">
            <action method="setTemplate">                  <template>page/1column.phtml</template></action>
        </reference>
        <reference name="content">
            <block type="helloworld/helloworld" name="hello" template="helloworld/helloworld.phtml"/>
        </reference>
    </helloworld_index_index>
</layout>

Create template file in   app/design/frontend/default/default/template/helloworld/helloworld.phtml

Body:
As Per Inchoo Article :

We will start by creating a simple “Hello world” module. However, you
  will soon see that simple takes a new meaning with Magento. Creating a
  bare bone module requires at least two files in Magento. For your
  module to work you need /app/etc/modules/MyCompany_MyModule.xml,
  app/code/local/MyCompany/MyModule/etc/config.xml. But, barebone module
  will not give you a “Hello developer” -So, we need to add few more
  files to the game.

file 1: /app/etc/modules/Inchoo_HelloDeveloper.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Inchoo_HelloDeveloper>
            <active>true</active>
            <codePool>local</codePool>
        </Inchoo_HelloDeveloper>
    </modules>
</config>

file 2: app/code/local/Inchoo/HelloDeveloper/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Inchoo_HelloDeveloper>
            <version>0.1.0</version>
        </Inchoo_HelloDeveloper>
    </modules>
    <frontend>
        <routers>
            <Inchoo_HelloDeveloper_SomeFreeRouterName1>
                <use>standard</use>
                <args>
                    <module>Inchoo_HelloDeveloper</module>
                    <frontName>inchoo-hellodeveloper</frontName>
                </args>
            </Inchoo_HelloDeveloper_SomeFreeRouterName1>
        </routers>
    </frontend>
</config>

file 3:
  app/code/local/Inchoo/HelloDeveloper/controllers/IndexController.php

<?php

class Inchoo_HelloDeveloper_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        echo 'Hello developer...';
    }

    public function sayHelloAction()
    {
        echo 'Hello one more time...';
    }
}
?>

Altough extremely simple, file 3 shows us one important thing: Naming
  connvention. Note the name of the class. Your moudle classes should
  keep names in form of MyCompany_MyModule_FileName, or in case of block
  and modules: MyCompany_MyModule_Block_FileName or
  MyCompany_MyModule_Module_FileName.


问:
How to find public ip address without using third party website in ruby on rails?
How do I get a public IP address in Rails using request.env [] or gem or plugin or something else, but without using an external website, I have find my local ip address but can't able to find public ip address without using external website. I tried Socket gem also but that also not working for me. So please suggest for the solution?</p>

答:
As long as you're connecting to your local server, you're local to Rails and have a local IP-address, and the reason lies in TCP/IP. If you need to know your external IP-address, you can make a call to APIs that provide your IP-address in any simple format, for example https://api.ipify.org?format=json:

```<code>{"ip":"123.123.123.123"}
</code>```

Or just get page contents (https://api.ipify.org).

If you need this only in development environment, you could use it only for Rails.env.development?

Body:
As long as you're connecting to your local server, you're local to Rails and have a local IP-address, and the reason lies in TCP/IP. If you need to know your external IP-address, you can make a call to APIs that provide your IP-address in any simple format, for example https://api.ipify.org?format=json:

{"ip":"123.123.123.123"}

Or just get page contents (https://api.ipify.org).

If you need this only in development environment, you could use it only for Rails.env.development?


问:
Convert list of dict to csv in python
I have used inheritance for employee details and I'm trying to write it as a csv. My output is in the form of list of dicts and when I'm trying to write it as csv, its not getting printed.
Here are my codes:

```<code>import csv
class Employee(object):
    def main(self,name,idno,position,salary):

        self.name=name
        self.idno=idno
        self.position=position
        self.salary=salary

class Employees(Employee):
    def main (self,name,idno,position,salary,age):
        Employee.main(self,name,idno,position,salary)
        self.age=age

    def input(self):

        e1=[]

        n=int(raw_input("Enter the number of employees:"))
        for i in range(n):
            self.name=raw_input("Name:")
            self.idno=raw_input("Idno:")
            self.position=raw_input("Position:")
            self.salary=int(raw_input("Salary:"))
            e2={"Name":self.name,"Idno":self.idno,"Position":self.position, "Salary":self.salary}
            e1.append(e2)
            print e1
</code>```

both list of dict to dict or dict of dict conversion doesnt works and writing to csv doesnt works. Can anyone help me out??

My output should look like this:

```<code>Name  Idno  Position  Salary
Abc    101   Trainee  12000
Def    102   Trainee  12000
</code>```

答:
use csv module of python.

```<code>data_list = [{...},{...}...]

keys = data_list[0].keys()
with open('test.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(data_list)
</code>```

Title: Convert list of dict to csv in python

Body:
I have used inheritance for employee details and I'm trying to write it as a csv. My output is in the form of list of dicts and when I'm trying to write it as csv, its not getting printed.
Here are my codes:

import csv
class Employee(object):
    def main(self,name,idno,position,salary):

        self.name=name
        self.idno=idno
        self.position=position
        self.salary=salary

class Employees(Employee):
    def main (self,name,idno,position,salary,age):
        Employee.main(self,name,idno,position,salary)
        self.age=age

    def input(self):

        e1=[]

        n=int(raw_input("Enter the number of employees:"))
        for i in range(n):
            self.name=raw_input("Name:")
            self.idno=raw_input("Idno:")
            self.position=raw_input("Position:")
            self.salary=int(raw_input("Salary:"))
            e2={"Name":self.name,"Idno":self.idno,"Position":self.position, "Salary":self.salary}
            e1.append(e2)
            print e1

both list of dict to dict or dict of dict conversion doesnt works and writing to csv doesnt works. Can anyone help me out??

My output should look like this:

Name  Idno  Position  Salary
Abc    101   Trainee  12000
Def    102   Trainee  12000

Body:
use csv module of python.

data_list = [{...},{...}...]

keys = data_list[0].keys()
with open('test.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(data_list)


问:
How to process a YAML stream in Python
I have a command line app the continuously outputs YAML data in the form:

```
- col0: datum0
  col1: datum1
  col2: datum2
- col0: datum0
  col1: datum1
  col2: datum2
...
```

It does this for all of eternity. I would like to write a Python script that continuously reads each of these records.

The PyYAML library seems best at taking fully loaded strings and interpreting those as a complete YAML document. Is there a way to put PyYAML into a "streaming" mode?

Or is my only option to chunk the data myself and feed it bit by bit into PyYAML?

答:
Here is what I've ended up using since there does not seem to be a built-in method for accomplishing what I want. This function should be generic enough that it can read in a stream of YAML and return top-level objects as they are encountered.

```<code>def streamInYAML(stream):
    y = stream.readline()
    cont = 1
    while cont:
        l = stream.readline()
        if len(l) == 0:
            cont = 0
        else:
            if l.startswith(' '):
                y = y + l
            else:
                yield yaml.load(y)
                y = l
</code>```

Can anyone do better?

OwnerDisplayName: Frank Krueger

ContentLicense: CC BY-SA 2.5

Title: How to process a YAML stream in Python

Body:
I have a command line app the continuously outputs YAML data in the form:

- col0: datum0
  col1: datum1
  col2: datum2
- col0: datum0
  col1: datum1
  col2: datum2
...

It does this for all of eternity. I would like to write a Python script that continuously reads each of these records.

The PyYAML library seems best at taking fully loaded strings and interpreting those as a complete YAML document. Is there a way to put PyYAML into a "streaming" mode?

Or is my only option to chunk the data myself and feed it bit by bit into PyYAML?

Body:
Here is what I've ended up using since there does not seem to be a built-in method for accomplishing what I want. This function should be generic enough that it can read in a stream of YAML and return top-level objects as they are encountered.

def streamInYAML(stream):
    y = stream.readline()
    cont = 1
    while cont:
        l = stream.readline()
        if len(l) == 0:
            cont = 0
        else:
            if l.startswith(' '):
                y = y + l
            else:
                yield yaml.load(y)
                y = l

Can anyone do better?

LastEditorDisplayName: Frank Krueger


问:
Watch/monitor background job for certain keyword
In a bash script, I'd like to watch/monitor a background process/job in the following way:

Run a command (in my case, nodeJS) in the background

Monitor its output, but do not display it

As soon as the output contains the word "Error" or the job exits/stops:

display the last output (i.e. the full error message)

exit the script

How do I do that?

答:
You can do it with strace:

In the simplest case strace runs the specified command until it  exits.
       It  intercepts  and  records  the  system  calls  which are called by a
       process and the signals which are received by a process.  The  name  of
       each  system  call,  its  arguments and its return value are printed on
       standard error or to the file specified with the -o option.

Such as:

```<code>strace -o /path/to/file.txt process_to_monitor
</code>```

Then you can use tail to extract the last part of the file (the last 10 lines by default).

```<code>tail /path/to/file.txt -n100
</code>```

In case you want to copy the last 100 hundred lines.

And then you grep whichever string you want from it.

Body:
You can do it with strace:

In the simplest case strace runs the specified command until it  exits.
       It  intercepts  and  records  the  system  calls  which are called by a
       process and the signals which are received by a process.  The  name  of
       each  system  call,  its  arguments and its return value are printed on
       standard error or to the file specified with the -o option.

Such as:

strace -o /path/to/file.txt process_to_monitor

Then you can use tail to extract the last part of the file (the last 10 lines by default).

tail /path/to/file.txt -n100

In case you want to copy the last 100 hundred lines.

And then you grep whichever string you want from it.


问:
How to retrieve arraylist from firebase database in recyclerview in android studio?
I want to populate my recyclerview from the data stored on firebase database.I tried searching net but most the examples have simple json tree structure and my Json db has following format:

and my android code is as follows:

ModelClass.java

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

import java.util.ArrayList;

public class ModelClass {

    private ArrayList<CategoryList> categoryList;

    public ModelClass(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    public ArrayList<CategoryList> getCategoryList() {
        return categoryList;
    }

    public void setCategoryList(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    public  static class CategoryList{
        public int Category_id;
        public String Category_name;
        public ArrayList<String>Emails;
        public ArrayList<String>Epabx;
        public ArrayList<String>Category_Fax;
        public ArrayList<Persons> persons;

        public CategoryList(int category_id, String category_name, ArrayList<String> emails,
                            ArrayList<String> epabx, ArrayList<String> category_Fax, ArrayList<Persons> persons) {
            Category_id = category_id;
            Category_name = category_name;
            Emails = emails;
            Epabx = epabx;
            Category_Fax = category_Fax;
            this.persons = persons;
        }

        public int getCategory_id() {
            return Category_id;
        }

        public void setCategory_id(int category_id) {
            Category_id = category_id;
        }

        public String getCategory_name() {
            return Category_name;
        }

        public void setCategory_name(String category_name) {
            Category_name = category_name;
        }

        public ArrayList<String> getEmails() {
            return Emails;
        }

        public void setEmails(ArrayList<String> emails) {
            Emails = emails;
        }

        public ArrayList<String> getEpabx() {
            return Epabx;
        }

        public void setEpabx(ArrayList<String> epabx) {
            Epabx = epabx;
        }

        public ArrayList<String> getCategory_Fax() {
            return Category_Fax;
        }

        public void setCategory_Fax(ArrayList<String> category_Fax) {
            Category_Fax = category_Fax;
        }

        public ArrayList<Persons> getPersons() {
            return persons;
        }

        public void setPersons(ArrayList<Persons> persons) {
            this.persons = persons;
        }
    }

    public static class Persons{
        private int Person_ID;
        private String Name;
        private String Designation;
        private String Office_Phone;
        private String Residence_Phone;
        private String VOIP;
        private String Address;
        private ArrayList<String>Fax;
        private String Ext;

        public Persons(int person_ID, String name, String designation, String office_Phone,
                       String residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext) {
            Person_ID = person_ID;
            Name = name;
            Designation = designation;
            Office_Phone = office_Phone;
            Residence_Phone = residence_Phone;
            this.VOIP = VOIP;
            Address = address;
            Fax = fax;
            Ext = ext;
        }

        public int getPerson_ID() {
            return Person_ID;
        }

        public void setPerson_ID(int person_ID) {
            Person_ID = person_ID;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getDesignation() {
            return Designation;
        }

        public void setDesignation(String designation) {
            Designation = designation;
        }

        public String getOffice_Phone() {
            return Office_Phone;
        }

        public void setOffice_Phone(String office_Phone) {
            Office_Phone = office_Phone;
        }

        public String getResidence_Phone() {
            return Residence_Phone;
        }

        public void setResidence_Phone(String residence_Phone) {
            Residence_Phone = residence_Phone;
        }

        public String getVOIP() {
            return VOIP;
        }

        public void setVOIP(String VOIP) {
            this.VOIP = VOIP;
        }

        public String getAddress() {
            return Address;
        }

        public void setAddress(String address) {
            Address = address;
        }

        public ArrayList<String> getFax() {
            return Fax;
        }

        public void setFax(ArrayList<String> fax) {
            Fax = fax;
        }

        public String getExt() {
            return Ext;
        }

        public void setExt(String ext) {
            Ext = ext;
        }
    }
}
</code>```

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_card_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.android.directory.MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/toolbar">
    </include>

    <EditText android:id="@+id/inputSearchMain"
        android:layout_below="@id/tool_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/edit_text_search"
        android:hint="@string/searchtext_hint"
        android:padding="5dp"
        android:textColor="#233343"
        android:inputType="textVisiblePassword"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginLeft="5dp"
        android:drawableRight="@drawable/search"/>

    <android.support.v7.widget.RecyclerView
        android:layout_below="@id/inputSearchMain"
        android:id="@+id/recyclerView_Main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>
</code>```

cardview_row_main.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/cardView_mainActivity"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="2dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="10dp">

            <ImageView
                android:id="@+id/govt_logo_Main"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/logo"
                android:layout_centerVertical="true"/>
            <TextView
                android:id="@+id/category_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:textSize="14sp"
                android:textColor="#233343"
                android:layout_centerInParent="true"/>
            <ImageView
                android:id="@+id/nextMain"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:src="@drawable/next"
                android:background="#1DE9B6"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"/>

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</RelativeLayout>
</code>```

MainActivity.java

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

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    DatabaseReference databaseCategory;
    private ArrayList<ModelClass.CategoryList> mcategoryset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        databaseCategory= FirebaseDatabase.getInstance().getReference().child("Category");
        recyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerAdapter<ModelClass,CategoryViewHolder>firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<ModelClass, CategoryViewHolder>(
                ModelClass.class, R.layout.cardview_row_main,CategoryViewHolder.class,databaseCategory
        ) {
            @Override
            protected void populateViewHolder(CategoryViewHolder viewHolder, ModelClass model, int position) {
                viewHolder.category_name.setText(model.getCategoryList().get);
            }
        };
        recyclerView.setAdapter(firebaseRecyclerAdapter);
    }
}
</code>```

How should i retrieve "Category_name" from the firebase database in this activity?

答:
Use this

Define the arraylist locally.

```<code>ArrayList<ModelClass > md = new ArrayList<>();
</code>```

Then call this

```<code>    mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                //Getting the data from snapshot
                 md= postSnapshot.getValue(ModelClass .class);

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

After that pass your arraylist into recycler adapter.

Body:
I want to populate my recyclerview from the data stored on firebase database.I tried searching net but most the examples have simple json tree structure and my Json db has following format:

and my android code is as follows:

ModelClass.java

package com.example.android.directory;

import java.util.ArrayList;

public class ModelClass {

    private ArrayList<CategoryList> categoryList;

    public ModelClass(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    public ArrayList<CategoryList> getCategoryList() {
        return categoryList;
    }

    public void setCategoryList(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    public  static class CategoryList{
        public int Category_id;
        public String Category_name;
        public ArrayList<String>Emails;
        public ArrayList<String>Epabx;
        public ArrayList<String>Category_Fax;
        public ArrayList<Persons> persons;

        public CategoryList(int category_id, String category_name, ArrayList<String> emails,
                            ArrayList<String> epabx, ArrayList<String> category_Fax, ArrayList<Persons> persons) {
            Category_id = category_id;
            Category_name = category_name;
            Emails = emails;
            Epabx = epabx;
            Category_Fax = category_Fax;
            this.persons = persons;
        }

        public int getCategory_id() {
            return Category_id;
        }

        public void setCategory_id(int category_id) {
            Category_id = category_id;
        }

        public String getCategory_name() {
            return Category_name;
        }

        public void setCategory_name(String category_name) {
            Category_name = category_name;
        }

        public ArrayList<String> getEmails() {
            return Emails;
        }

        public void setEmails(ArrayList<String> emails) {
            Emails = emails;
        }

        public ArrayList<String> getEpabx() {
            return Epabx;
        }

        public void setEpabx(ArrayList<String> epabx) {
            Epabx = epabx;
        }

        public ArrayList<String> getCategory_Fax() {
            return Category_Fax;
        }

        public void setCategory_Fax(ArrayList<String> category_Fax) {
            Category_Fax = category_Fax;
        }

        public ArrayList<Persons> getPersons() {
            return persons;
        }

        public void setPersons(ArrayList<Persons> persons) {
            this.persons = persons;
        }
    }

    public static class Persons{
        private int Person_ID;
        private String Name;
        private String Designation;
        private String Office_Phone;
        private String Residence_Phone;
        private String VOIP;
        private String Address;
        private ArrayList<String>Fax;
        private String Ext;

        public Persons(int person_ID, String name, String designation, String office_Phone,
                       String residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext) {
            Person_ID = person_ID;
            Name = name;
            Designation = designation;
            Office_Phone = office_Phone;
            Residence_Phone = residence_Phone;
            this.VOIP = VOIP;
            Address = address;
            Fax = fax;
            Ext = ext;
        }

        public int getPerson_ID() {
            return Person_ID;
        }

        public void setPerson_ID(int person_ID) {
            Person_ID = person_ID;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getDesignation() {
            return Designation;
        }

        public void setDesignation(String designation) {
            Designation = designation;
        }

        public String getOffice_Phone() {
            return Office_Phone;
        }

        public void setOffice_Phone(String office_Phone) {
            Office_Phone = office_Phone;
        }

        public String getResidence_Phone() {
            return Residence_Phone;
        }

        public void setResidence_Phone(String residence_Phone) {
            Residence_Phone = residence_Phone;
        }

        public String getVOIP() {
            return VOIP;
        }

        public void setVOIP(String VOIP) {
            this.VOIP = VOIP;
        }

        public String getAddress() {
            return Address;
        }

        public void setAddress(String address) {
            Address = address;
        }

        public ArrayList<String> getFax() {
            return Fax;
        }

        public void setFax(ArrayList<String> fax) {
            Fax = fax;
        }

        public String getExt() {
            return Ext;
        }

        public void setExt(String ext) {
            Ext = ext;
        }
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_card_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.android.directory.MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/toolbar">
    </include>

    <EditText android:id="@+id/inputSearchMain"
        android:layout_below="@id/tool_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/edit_text_search"
        android:hint="@string/searchtext_hint"
        android:padding="5dp"
        android:textColor="#233343"
        android:inputType="textVisiblePassword"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginLeft="5dp"
        android:drawableRight="@drawable/search"/>

    <android.support.v7.widget.RecyclerView
        android:layout_below="@id/inputSearchMain"
        android:id="@+id/recyclerView_Main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

cardview_row_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/cardView_mainActivity"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="2dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="10dp">

            <ImageView
                android:id="@+id/govt_logo_Main"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/logo"
                android:layout_centerVertical="true"/>
            <TextView
                android:id="@+id/category_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:textSize="14sp"
                android:textColor="#233343"
                android:layout_centerInParent="true"/>
            <ImageView
                android:id="@+id/nextMain"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:src="@drawable/next"
                android:background="#1DE9B6"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"/>

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</RelativeLayout>

MainActivity.java

package com.example.android.directory;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    DatabaseReference databaseCategory;
    private ArrayList<ModelClass.CategoryList> mcategoryset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        databaseCategory= FirebaseDatabase.getInstance().getReference().child("Category");
        recyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerAdapter<ModelClass,CategoryViewHolder>firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<ModelClass, CategoryViewHolder>(
                ModelClass.class, R.layout.cardview_row_main,CategoryViewHolder.class,databaseCategory
        ) {
            @Override
            protected void populateViewHolder(CategoryViewHolder viewHolder, ModelClass model, int position) {
                viewHolder.category_name.setText(model.getCategoryList().get);
            }
        };
        recyclerView.setAdapter(firebaseRecyclerAdapter);
    }
}

How should i retrieve "Category_name" from the firebase database in this activity?

Body:
Use this

Define the arraylist locally.

ArrayList<ModelClass > md = new ArrayList<>();

Then call this

    mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                //Getting the data from snapshot
                 md= postSnapshot.getValue(ModelClass .class);

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

After that pass your arraylist into recycler adapter.

ContentLicense: CC BY-SA 4.0


问:
Retrieve privileges using security role rather than using system user
Here is my code:

```<code>RetrievePrincipalAccessRequest request = new RetrievePrincipalAccessRequest();
request.Principal = new EntityReference("systemuser", new Guid("GUID of system user record."));
// record for which we want to check the access
request.Target = new EntityReference("account", new Guid("GUID of account record."));
try
{
    RetrievePrincipalAccessResponse responce = (RetrievePrincipalAccessResponse)organisationservice.Execute(request);
}
catch (Exception ex)
{
    Console.WriteLine("error" + ex.Message.ToString());
}
</code>```

It take out "can access| can edit| can read" privilege for system user and a
security principal can be either user or team but not a security role, therefore is there any C# code which can retrieve privileges using a security role.

I have Dynamic CRM Online instance.

Thanks :-)

答:
I have found one another solution:</p>

```<code>QueryExpression query = new QueryExpression
{
    EntityName = "role"
};

//Get all Security Roles
EntityCollection Securityroles = organisationservice.RetrieveMultiple(query);
//Get all Privileges
RetrievePrivilegeSetRequest requestp = new RetrievePrivilegeSetRequest();
RetrievePrivilegeSetResponse responsep = (RetrievePrivilegeSetResponse)organisationservice.Execute(requestp);
foreach (Entity securityrole in Securityroles.Entities)
{

    //Get record from RolePrivilege Mapping
    RetrieveRolePrivilegesRoleRequest req = new RetrieveRolePrivilegesRoleRequest();
    req.RoleId = new Guid(securityrole.Id.ToString());
    RetrieveRolePrivilegesRoleResponse response = (RetrieveRolePrivilegesRoleResponse)organisationservice.Execute(req);

    foreach (RolePrivilege priv in response.RolePrivileges)
    {
        var privile = responsep.EntityCollection.Entities.Where(a => a.Id == priv.PrivilegeId).ToArray();
    }
}
</code>```

Body:
Here is my code:

RetrievePrincipalAccessRequest request = new RetrievePrincipalAccessRequest();
request.Principal = new EntityReference("systemuser", new Guid("GUID of system user record."));
// record for which we want to check the access
request.Target = new EntityReference("account", new Guid("GUID of account record."));
try
{
    RetrievePrincipalAccessResponse responce = (RetrievePrincipalAccessResponse)organisationservice.Execute(request);
}
catch (Exception ex)
{
    Console.WriteLine("error" + ex.Message.ToString());
}

It take out "can access| can edit| can read" privilege for system user and a
security principal can be either user or team but not a security role, therefore is there any C# code which can retrieve privileges using a security role.

I have Dynamic CRM Online instance.

Thanks :-)

Body:
I have found one another solution:

QueryExpression query = new QueryExpression
{
    EntityName = "role"
};

//Get all Security Roles
EntityCollection Securityroles = organisationservice.RetrieveMultiple(query);
//Get all Privileges
RetrievePrivilegeSetRequest requestp = new RetrievePrivilegeSetRequest();
RetrievePrivilegeSetResponse responsep = (RetrievePrivilegeSetResponse)organisationservice.Execute(requestp);
foreach (Entity securityrole in Securityroles.Entities)
{

    //Get record from RolePrivilege Mapping
    RetrieveRolePrivilegesRoleRequest req = new RetrieveRolePrivilegesRoleRequest();
    req.RoleId = new Guid(securityrole.Id.ToString());
    RetrieveRolePrivilegesRoleResponse response = (RetrieveRolePrivilegesRoleResponse)organisationservice.Execute(req);

    foreach (RolePrivilege priv in response.RolePrivileges)
    {
        var privile = responsep.EntityCollection.Entities.Where(a => a.Id == priv.PrivilegeId).ToArray();
    }
}


答:
faster and shorter - no*, but you can make it more flexible and elegant

```<code>function find_range($n, $ranges) {
    foreach($ranges as $key => $range)
        if($n >= $range[0] && $n <= $range[1])
            return $key;
    return false;
}

$ages = array(
    'baby'   => array(0, 1),
    'child'  => array(2, 13),
    'teen'   => array(14, 19),
    'adult'  => array(20, 59),
    'senior' => array(60, 100)
);

var_dump(find_range(20, $ages));
</code>```

(* assuming ranges are arbitrary. If we know more about ranges, for example, that they are sorted, or always intersect, or follow some formula, we can find a better algorithm).

Title: Faster way to check if integer is in any of ranges?

Body:
I wonder if there is another way to shorten this ? Here is the example im looking for to do same thing just shorter.

if($c <= 100){
    echo 'A';
}elseif($c <= 200 && $c > 100){
    echo 'B';
}elseif($c <= 300 && $c > 200){
    echo 'C';
}elseif($c <= 400 && $c > 300){
    echo 'D';
}elseif($c <= 500 && $c > 400){
    echo 'E';
}elseif($c <= 600 && $c > 500){
    echo 'F';
}elseif($c <= 700 && $c > 600){
    echo 'Z';
}elseif($c <= 800 && $c > 700){
    echo 'H';
}elseif($c <= 900 && $c > 800){
    echo 'I';
}elseif($c < 1000 && $c > 900){
    echo 'K';
}elseif($c <= 1100 && $c > 1000){
    echo 'L';
}elseif($c <= 1200 && $c > 1100){
    echo 'M';
}elseif($c < 1300 && $c > 1200){
    echo 'N';
}elseif($c <= 1400 && $c > 1300){
    echo 'O';
}elseif($c <= 1500 && $c > 1400){
    echo 'P';
}elseif($c <= 1600 && $c > 1500){
    echo 'Q';
}elseif($c <= 1700 && $c > 1600){
    echo 'R';
}elseif($c <= 1800 && $c > 1700){
    echo 'S';
}elseif($c <= 1900 && $c > 1800){
    echo 'T';
}elseif($c <= 2000 && $c > 1900){
    echo 'V';
}elseif($c <= 2100 && $c > 2000){
    echo 'X';
}else{
    echo 'AA';
}

Body:
faster and shorter - no*, but you can make it more flexible and elegant

function find_range($n, $ranges) {
    foreach($ranges as $key => $range)
        if($n >= $range[0] && $n <= $range[1])
            return $key;
    return false;
}

$ages = array(
    'baby'   => array(0, 1),
    'child'  => array(2, 13),
    'teen'   => array(14, 19),
    'adult'  => array(20, 59),
    'senior' => array(60, 100)
);

var_dump(find_range(20, $ages));

(* assuming ranges are arbitrary. If we know more about ranges, for example, that they are sorted, or always intersect, or follow some formula, we can find a better algorithm).


问:
How to extract multiple array & insert data to database
How to extract below array & insert 3 data & 2 query

Extract this array & give me 2 row & 3 columns

```<code>Array
(
    [name] => Array
        (
            [0] => AAAAA
            [1] => BBBBB
        )

    [number] => Array
        (
            [0] => 7878787878
            [1] => 9898989898
        )

    [email] => Array
        (
            [0] => a@gmail.com
            [1] => b@gmail.com
        )

)
</code>```

We need Below query by foreach loop

```<code>INSERT INTO `contact_person` SET customer_id='131',cp_name='AAAAA',cp_phone='7878787878',cp_email='a@gmail.com

INSERT INTO `contact_person` SET customer_id='131',cp_name='BBBBB',cp_phone='9898989898',cp_email='b@gmail.com'
</code>```

答:
Make customer_id in your database an autonumber so that it will automatically generate a customer_id on insert.

Also all fields are some text field in db

```<code>$arr = Array
(
    'name' => Array
        (
            "AAAAA", "BBBBB"
        ),

    'number' => Array
        (
             "7878787878", "9898989898"
        ),

    'email' => Array
        (
            "a@gmail.com", "b@gmail.com"
        )
);
$count = count($arr['name']);
$sql = "";
if ($count > 0) {
    $sql = "INSERT INTO `contact_person` (cp_name, cp_phone, cp_email) VALUES ";
    for ($i=0; $i < $count; $i++) {
        $sql .= ($i+1==$count) ? "('".$arr['name'][$i]."', '".$arr['number'][$i]."', '".$arr['email'][$i]."'')" : "('".$arr['name'][$i]."', '".$arr['number'][$i]."', '".$arr['email'][$i]."''), ";
    }
}

echo ($sql);
</code>```

Body:
How to extract below array & insert 3 data & 2 query

Extract this array & give me 2 row & 3 columns

Array
(
    [name] => Array
        (
            [0] => AAAAA
            [1] => BBBBB
        )

    [number] => Array
        (
            [0] => 7878787878
            [1] => 9898989898
        )

    [email] => Array
        (
            [0] => a@gmail.com
            [1] => b@gmail.com
        )

)

We need Below query by foreach loop

INSERT INTO `contact_person` SET customer_id='131',cp_name='AAAAA',cp_phone='7878787878',cp_email='a@gmail.com

INSERT INTO `contact_person` SET customer_id='131',cp_name='BBBBB',cp_phone='9898989898',cp_email='b@gmail.com'

Body:
Make customer_id in your database an autonumber so that it will automatically generate a customer_id on insert.

Also all fields are some text field in db

$arr = Array
(
    'name' => Array
        (
            "AAAAA", "BBBBB"
        ),

    'number' => Array
        (
             "7878787878", "9898989898"
        ),

    'email' => Array
        (
            "a@gmail.com", "b@gmail.com"
        )
);
$count = count($arr['name']);
$sql = "";
if ($count > 0) {
    $sql = "INSERT INTO `contact_person` (cp_name, cp_phone, cp_email) VALUES ";
    for ($i=0; $i < $count; $i++) {
        $sql .= ($i+1==$count) ? "('".$arr['name'][$i]."', '".$arr['number'][$i]."', '".$arr['email'][$i]."'')" : "('".$arr['name'][$i]."', '".$arr['number'][$i]."', '".$arr['email'][$i]."''), ";
    }
}

echo ($sql);


问:
Complex query Laravel
Hi I have a complex queries

```<code>SELECT distinct libelle_adresse from adresse
where id_adresse in (select id_adresse from zone_adresse
where fk_zone in (select id_zone from zone
where id_arrondissement in (select id_arrondissement from arrondissement
where libelle_arrondissement="'.$_GET['arrondis'].'")))
</code>```

I've used $arrondis = $request->input('arrondis');to get the "arrondis" parameter from URL and pass it to my Controller.

This my attempt

```<code>    $term = $request->term;

    $arrondis = $request->input('arrondis');

    $query1 = DB::table('arrondissement')
    ->select('id_arrondissement')
    ->where('libelle_arrondissement','=',$arrondis)
    ->get();

    $query2 = DB::table('zone');
    ->select('id_zone')
    ->where('id_arrondissement','=',$query1)
    ->get();

    $query3 = DB::table('zone_adresse');
    ->select('id_adresse')
    ->where('fk_zone','=',$query2)
    ->get();

    $queries = DB::table('adresse');
    ->where('id_adresse','=',$query3)
    ->where('libelle_adresse','like','%'.$term.'%')
    ->take(3)->get();
    foreach ($queries as $query)
    {
        $results[] = ['id' => $query->id_adresse, 'value' => $query->libelle_adresse];
    }
    return response()->json($results);
</code>```

I know that I get the error when I pass the "query(1/2/3) variable" in "where" but I couldn't find any solution

Any help would be appreciated. Thanks

答:
Let try this

```<code>DB::table("adresse")
    ->whereIn("id_adresse", DB::table("zone_adresse")
       ->whereIn("fk_zone", DB::table("zone")
         ->whereIn("id_arrondissement", DB::table("arrondissement")
           ->where("libelle_arrondissement","=", $_GET['arrondis'])
           ->pluck("id_arrondissement")->toArray()
        )
         ->pluck("id_zone")->toArray()
    )->pluck("id_adresse")->toArray())
    ->distinct()
    ->select("libelle_adresse as value, id_adresse as id")
    ->where('libelle_adresse', 'like', '%'.$term.'%')
    ->get();
</code>```

This will help you put all your query into one. But this looks ugly(will solve the problem though). The best i would recommend is to use Eloquent

Title: Complex query Laravel

Body:
Hi I have a complex queries

SELECT distinct libelle_adresse from adresse
where id_adresse in (select id_adresse from zone_adresse
where fk_zone in (select id_zone from zone
where id_arrondissement in (select id_arrondissement from arrondissement
where libelle_arrondissement="'.$_GET['arrondis'].'")))

I've used $arrondis = $request->input('arrondis');to get the "arrondis" parameter from URL and pass it to my Controller.

This my attempt

    $term = $request->term;

    $arrondis = $request->input('arrondis');

    $query1 = DB::table('arrondissement')
    ->select('id_arrondissement')
    ->where('libelle_arrondissement','=',$arrondis)
    ->get();

    $query2 = DB::table('zone');
    ->select('id_zone')
    ->where('id_arrondissement','=',$query1)
    ->get();

    $query3 = DB::table('zone_adresse');
    ->select('id_adresse')
    ->where('fk_zone','=',$query2)
    ->get();

    $queries = DB::table('adresse');
    ->where('id_adresse','=',$query3)
    ->where('libelle_adresse','like','%'.$term.'%')
    ->take(3)->get();
    foreach ($queries as $query)
    {
        $results[] = ['id' => $query->id_adresse, 'value' => $query->libelle_adresse];
    }
    return response()->json($results);

I know that I get the error when I pass the "query(1/2/3) variable" in "where" but I couldn't find any solution

Any help would be appreciated. Thanks

Body:
Let try this

DB::table("adresse")
    ->whereIn("id_adresse", DB::table("zone_adresse")
       ->whereIn("fk_zone", DB::table("zone")
         ->whereIn("id_arrondissement", DB::table("arrondissement")
           ->where("libelle_arrondissement","=", $_GET['arrondis'])
           ->pluck("id_arrondissement")->toArray()
        )
         ->pluck("id_zone")->toArray()
    )->pluck("id_adresse")->toArray())
    ->distinct()
    ->select("libelle_adresse as value, id_adresse as id")
    ->where('libelle_adresse', 'like', '%'.$term.'%')
    ->get();

This will help you put all your query into one. But this looks ugly(will solve the problem though). The best i would recommend is to use Eloquent


问:
Python How to display both String and Integer value from Entrytext tkinter
I Want to display both string and Integer value after entering into the EntryText widget.

I am using below Code and able to display Integer value but not String:

```<code> global Input
 Input = int(entrytext1.get())
 print Input
</code>```

If I enter 'q' in entrytext1 get below error:

```<code> ValueError: invalid literal for int() with base 10: 'q'
</code>```

If I use below code, it will get below error:

```<code>global Input
Input = (entrytext1.get())
print Input

 No_SED_MENU_Items = len(SED_MENU_Items)
 print No_SED_MENU_Items
 if (not((Input > 0 ) and (Input <= No_SED_MENU_Items))):
  print('\nInvalid option')
 else:
  SMI = SED_MENU_Items[Input-1]['ID']
  SED_item_select = hex(SMI)[2:].zfill(4)
  FirstByte = SED_item_select[0:2]
  SecByte = SED_item_select[2:4]
  request = '22'+ ' '+FirstByte+' '+SecByte
  print (request)
</code>```

Error:

```<code>UnboundLocalError: local variable 'request' referenced before assignment
</code>```

How Can I fix that, If I type Integer, it should print my request and If I type String, if should only print

答:
You could change Input to accept inputs without casting them immediately, but then cast them later on depending on what you want to do with them. This is how you would do that.

```<code>Input = (entrytext1.get()) #Remove the integer casting

print (str(Input)) #Converts 'Input' to a string
print (int(Input)) #Converts 'Input' to an integer
</code>```

The problem with this is that Input is expecting any data type because there is no validation. By removing the data type and casting it later on, you allow anything to be entered. This can cause problems as Python will return a ValueError if you try to, for example, convert 'q' to an integer.

To get past this, you can use try-except blocks. Judging from a comment on the OP, this solution is better suited for you, as it allows both integer and string inputs, but only casts if it is possible, removing the chance of an error. I have implemented this in an example function below.

```<code>def CastIfPossible():
    Input = (entrytext1.get())

    try: #Try converting the input to an integer
        cast_test = int(Input)
        return cast_test #Returns if it is possible

    except ValueError: #If it is not possible
        print ("That was a string, not an integer. Casting is not possible.")
        return Input #Return the original input as a string

if __name__ == "__main__":
    cast_value = CastIfPossible()
    print (cast_value) #Prints both int and str inputs
</code>```

This allows anything to be entered by the user, converts it to an integer if possible, and if not, leaves it as a string.

Body:
I Want to display both string and Integer value after entering into the EntryText widget.

I am using below Code and able to display Integer value but not String:

 global Input
 Input = int(entrytext1.get())
 print Input

If I enter 'q' in entrytext1 get below error:

 ValueError: invalid literal for int() with base 10: 'q'

If I use below code, it will get below error:

global Input
Input = (entrytext1.get())
print Input

 No_SED_MENU_Items = len(SED_MENU_Items)
 print No_SED_MENU_Items
 if (not((Input > 0 ) and (Input <= No_SED_MENU_Items))):
  print('\nInvalid option')
 else:
  SMI = SED_MENU_Items[Input-1]['ID']
  SED_item_select = hex(SMI)[2:].zfill(4)
  FirstByte = SED_item_select[0:2]
  SecByte = SED_item_select[2:4]
  request = '22'+ ' '+FirstByte+' '+SecByte
  print (request)

Error:

UnboundLocalError: local variable 'request' referenced before assignment

How Can I fix that, If I type Integer, it should print my request and If I type String, if should only print

Body:
You could change Input to accept inputs without casting them immediately, but then cast them later on depending on what you want to do with them. This is how you would do that.

Input = (entrytext1.get()) #Remove the integer casting

print (str(Input)) #Converts 'Input' to a string
print (int(Input)) #Converts 'Input' to an integer

The problem with this is that Input is expecting any data type because there is no validation. By removing the data type and casting it later on, you allow anything to be entered. This can cause problems as Python will return a ValueError if you try to, for example, convert 'q' to an integer.

To get past this, you can use try-except blocks. Judging from a comment on the OP, this solution is better suited for you, as it allows both integer and string inputs, but only casts if it is possible, removing the chance of an error. I have implemented this in an example function below.

def CastIfPossible():
    Input = (entrytext1.get())

    try: #Try converting the input to an integer
        cast_test = int(Input)
        return cast_test #Returns if it is possible

    except ValueError: #If it is not possible
        print ("That was a string, not an integer. Casting is not possible.")
        return Input #Return the original input as a string

if __name__ == "__main__":
    cast_value = CastIfPossible()
    print (cast_value) #Prints both int and str inputs

This allows anything to be entered by the user, converts it to an integer if possible, and if not, leaves it as a string.


问:
How to determine if DataTable is null, not initialized
I have a method that does some work on a DataTable e.g.

```<code>private void MyMethod(DataTable table)
{
    if(table.Rows.Count > 0)
    {
       //  do some work
    }
 }
</code>```

However, if the method receives a null datatable from the application it serves I get an 'Object reference not set to an instance of an object' error.

I have also tried . . .

```<code>if(table.IsInitialized) { }
</code>```

and

```<code>if(table != null) {  }
</code>```

but I get the same error message.

How do I test to see if the incoming datatable is instantiated and not null please?

The DataTable is coming from a cast of a datagrid in a WinForms app i.e.

```<code>DataTable table = (DataTable)datagridview.DataSource;
</code>```

So the issue arises if the original datagridview is empty.

答:
How do I test to see if the incoming datatable is instantiated and not
  null please?

Technically, this should work and if the code below does not detect whether table is instantiated or not then there is another problem aside from the one at hand.

```<code>if(table != null && table.Rows != null && table.Rows.Count > 0)
</code>```

Body:
I have a method that does some work on a DataTable e.g.

private void MyMethod(DataTable table)
{
    if(table.Rows.Count > 0)
    {
       //  do some work
    }
 }

However, if the method receives a null datatable from the application it serves I get an 'Object reference not set to an instance of an object' error.

I have also tried . . .

if(table.IsInitialized) { }

and

if(table != null) {  }

but I get the same error message.

How do I test to see if the incoming datatable is instantiated and not null please?

The DataTable is coming from a cast of a datagrid in a WinForms app i.e.

DataTable table = (DataTable)datagridview.DataSource;

So the issue arises if the original datagridview is empty.

Body:
How do I test to see if the incoming datatable is instantiated and not
  null please?

Technically, this should work and if the code below does not detect whether table is instantiated or not then there is another problem aside from the one at hand.

if(table != null && table.Rows != null && table.Rows.Count > 0)


问:
Regex, string after 2 space
I would like to take the string after the 2 first space

Example :
  I have the string : "JUN 15 ME 10Y CDN BND"
  I would like to have "ME 10Y CDN BND"

The length of the string before the 2 space is variable off course.

Thanks a lot

答:
The regex you are looking for is

```<code>\s\S*\s(.*)
</code>```

Explanation:

\s = Find first space

\S = Find word after space

\s = Find second space

(.*) = Grab everything after the space

Your result will be returned in the first capture group - (.*)

Ps. You might be able to get away with a lookbehind - (?<=\s\S*\s).* - which returns only the portion you are interested in and avoids having to get the capture group, but not all regex engines support this, as the lookbehind, as you mentioned, is of variable width.

Title: Regex, string after 2 space

Body:
The regex you are looking for is

\s\S*\s(.*)

Explanation:

\s = Find first space

\S = Find word after space

\s = Find second space

(.*) = Grab everything after the space

Your result will be returned in the first capture group - (.*)

Ps. You might be able to get away with a lookbehind - (?<=\s\S*\s).* - which returns only the portion you are interested in and avoids having to get the capture group, but not all regex engines support this, as the lookbehind, as you mentioned, is of variable width.


问:
Bash script not handling input arguments passed
I'm running:

```<code>python Parser.py "Bot Pick Nut"
</code>```

In linux command line via MobaXterm. This works as intended, it returns True.
The issue I face is when run via the shell script it returns false? Can anyone advice why my shell is not giving the result to my python script correctly?

The Script:

```<code>#!/bin/sh
python Parser.py argv[0]
</code>```

The command:

```<code> ./Shell.sh "Bot Pick Nut"
</code>```

答:
The bash positional parameters start from $0 with $1 being the first argument for the script, subsequently numbered from $2..$n with $0 being the name of the script itself.

```<code>#!/bin/sh
python Parser.py "$1"
</code>```

A simple tabulation of the arguments in bash,

```<code>$0              the first positional parameter, equivalent to argv[0] in C, see the first argument
$FUNCNAME       the function name (attention: inside a function, $0 is still the $0 of the shell, not the function name)
$1 … $9        the argument list elements from 1 to 9
${10} … ${N}   the argument list elements beyond 9 (note the parameter expansion syntax!)
$*              all positional parameters except $0, see mass usage
$@              all positional parameters except $0, see mass usage
$#              the number of arguments, not counting $0
</code>```

Body:
I'm running:

python Parser.py "Bot Pick Nut"

In linux command line via MobaXterm. This works as intended, it returns True.
The issue I face is when run via the shell script it returns false? Can anyone advice why my shell is not giving the result to my python script correctly?

The Script:

#!/bin/sh
python Parser.py argv[0]

The command:

 ./Shell.sh "Bot Pick Nut"

Body:
The bash positional parameters start from $0 with $1 being the first argument for the script, subsequently numbered from $2..$n with $0 being the name of the script itself.

#!/bin/sh
python Parser.py "$1"

A simple tabulation of the arguments in bash,

$0              the first positional parameter, equivalent to argv[0] in C, see the first argument
$FUNCNAME       the function name (attention: inside a function, $0 is still the $0 of the shell, not the function name)
$1 … $9        the argument list elements from 1 to 9
${10} … ${N}   the argument list elements beyond 9 (note the parameter expansion syntax!)
$*              all positional parameters except $0, see mass usage
$@              all positional parameters except $0, see mass usage
$#              the number of arguments, not counting $0


问:
Turn on Flash as Light on Blackberry
I am new to BlackBerry application development and trying to make a simple application to turn my flash light on as a torch.  I know there are several applications that do this already, but I would like to try do it on my own.

I have installed eclipse and all the necesary add on to get my development environment running.  I have also successfully create the stock standard hello world application.

I am however struggling to find out how to do this.  I have been reading through the API documentation and started playing with FlashControl, VideoControl and SnapshotControl.

These however don't seem to expose methods to do this.

I know through the video camera I am able to go to options and turn the flash light on and this is exactly what i'm trying to mimic.

The code i have used so far which seems to just set the camera flash to force on is:

```<code>Player p = javax.microedition.media.Manager.createPlayer("capture://video");
p.realize();
p.start();

FlashControl flashControl = (FlashControl) p.getControl("javax.microedition.amms.control.camera.FlashControl");
flashControl.setMode(FlashControl.FORCE);
</code>```

答:
Try something like this

```<code>LED.setState(LED.STATE_ON);     // for LED
Backlight.enable(true);         // for Screen
this.setMode(FlashControl.ON);  // for flash light.
</code>```

or else import this package

```<code>package lsphone.flash.microfireps;
</code>```

Title: Turn on Flash as Light on Blackberry

Body:
I am new to BlackBerry application development and trying to make a simple application to turn my flash light on as a torch.  I know there are several applications that do this already, but I would like to try do it on my own.

I have installed eclipse and all the necesary add on to get my development environment running.  I have also successfully create the stock standard hello world application.

I am however struggling to find out how to do this.  I have been reading through the API documentation and started playing with FlashControl, VideoControl and SnapshotControl.

These however don't seem to expose methods to do this.

I know through the video camera I am able to go to options and turn the flash light on and this is exactly what i'm trying to mimic.

The code i have used so far which seems to just set the camera flash to force on is:

Player p = javax.microedition.media.Manager.createPlayer("capture://video");
p.realize();
p.start();

FlashControl flashControl = (FlashControl) p.getControl("javax.microedition.amms.control.camera.FlashControl");
flashControl.setMode(FlashControl.FORCE);

Body:
Try something like this

LED.setState(LED.STATE_ON);     // for LED
Backlight.enable(true);         // for Screen
this.setMode(FlashControl.ON);  // for flash light.

or else import this package

package lsphone.flash.microfireps;


问:
SQL GROUP BY explanation
So I have been playing around with SQL for a while now, and i can't seem to get the group by function down. For example, I have been using the w3schools online database with SQL, and experimenting with it.
One problem I can't seem to crack is to update the prices of products from the same supplier, and that their sum is some number.

Here is the link to the database: https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

So what I came up with was this:

```<code>    UPDATE Products
    SET Price=Price*100
    WHERE 47=(SELECT SUM(p.Price) FROM Products p GROUP BY p.SupplierID)
</code>```

It seems to update the whole database. I expected it only to update the prices of the products that belong to the first supplier, as the sum of their prices is 47. I guess I'm making some rookie mistake, but I just can't seem to get it right.

Edit:
My expected result would be that all rows from table Products who have supplierID=1 would update the price(Although it's not that I'm just aiming at the 1st supplier, but any supplier who's products prices sum up to 47), but what happens is that all the prices get updated, regardless of the supplier or the sum of their prices. But when I change the number from 47, nothing seems to happen.

答:
The group by clause aggregates the rows in your table, keeping one row for each combination of values available in the columns you specify.

In your example you have a table with product, supplier and price; if you group by supplier, the resulting dataset will have one row for each value in the supplier column.

What happens to the other columns depends on what you specify in your select clause. You can ignore or aggregate them.

```<code>select  supplier, sum(price)
from    Products
group by supplier
</code>```

This will return the sum of the price column for each  distinct supplier, while the product will be ignored.

On these aggregated rows the filtering is done with having clause, because the where only works on the original (not aggregated) rows.

Going on with the example above, selecting the supplier whose products prices have a sum of 47 would require

```<code>select  supplier, sum(price)
from    Products
group by supplier
having  sum(price) = 47
</code>```

Hope this helps

Title: SQL GROUP BY explanation

Body:
So I have been playing around with SQL for a while now, and i can't seem to get the group by function down. For example, I have been using the w3schools online database with SQL, and experimenting with it.
One problem I can't seem to crack is to update the prices of products from the same supplier, and that their sum is some number.

Here is the link to the database: https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

So what I came up with was this:

    UPDATE Products
    SET Price=Price*100
    WHERE 47=(SELECT SUM(p.Price) FROM Products p GROUP BY p.SupplierID)

It seems to update the whole database. I expected it only to update the prices of the products that belong to the first supplier, as the sum of their prices is 47. I guess I'm making some rookie mistake, but I just can't seem to get it right.

Edit:
My expected result would be that all rows from table Products who have supplierID=1 would update the price(Although it's not that I'm just aiming at the 1st supplier, but any supplier who's products prices sum up to 47), but what happens is that all the prices get updated, regardless of the supplier or the sum of their prices. But when I change the number from 47, nothing seems to happen.

Body:
The group by clause aggregates the rows in your table, keeping one row for each combination of values available in the columns you specify.

In your example you have a table with product, supplier and price; if you group by supplier, the resulting dataset will have one row for each value in the supplier column.

What happens to the other columns depends on what you specify in your select clause. You can ignore or aggregate them.

select  supplier, sum(price)
from    Products
group by supplier

This will return the sum of the price column for each  distinct supplier, while the product will be ignored.

On these aggregated rows the filtering is done with having clause, because the where only works on the original (not aggregated) rows.

Going on with the example above, selecting the supplier whose products prices have a sum of 47 would require

select  supplier, sum(price)
from    Products
group by supplier
having  sum(price) = 47

Hope this helps


问:
Spring Autowiring - if object name needs to be same as beanId always?
I have defined bean in spring configuration something like -

```<code><bean id="xyz" class="com.foo.Test">
</code>```

and the class where I am using the bean is

```<code>package com.bar;
import com.foo.Test;

Class Demo {
      @Autowired
      Test xyz;

      //Do operations of Test using abc now

}
</code>```

what I am asking I tried below and it worked fine.

```<code>package com.bar;
import com.foo.Test;

Class Demo {
     @Autowired
     Test abc;

     //Do operations of Test using abc now

}
</code>```

So if keeping the bean id same as object name doesn't matter ?

Thanks.

答:
If you autowire a bean and the spring context defines exactly one bean which is assignment compatible with the type you wire the bean to (in your case Test) then spring does not require any additional information.

If the spring context does define more than one bean which is assignment compatible with the type you wire the bean to you have to add the annotation @Qualifier and specify the identifier like this:

```<code>@Autowired
@Qualifier("xyz")
Test abc;
</code>```

Spring Framework Reference Documentation:

@Autowired

@Qualifier

Body:
I have defined bean in spring configuration something like -

<bean id="xyz" class="com.foo.Test">

and the class where I am using the bean is

package com.bar;
import com.foo.Test;

Class Demo {
      @Autowired
      Test xyz;

      //Do operations of Test using abc now

}

what I am asking I tried below and it worked fine.

package com.bar;
import com.foo.Test;

Class Demo {
     @Autowired
     Test abc;

     //Do operations of Test using abc now

}

So if keeping the bean id same as object name doesn't matter ?

Thanks.

Body:
If you autowire a bean and the spring context defines exactly one bean which is assignment compatible with the type you wire the bean to (in your case Test) then spring does not require any additional information.

If the spring context does define more than one bean which is assignment compatible with the type you wire the bean to you have to add the annotation @Qualifier and specify the identifier like this:

@Autowired
@Qualifier("xyz")
Test abc;

Spring Framework Reference Documentation:

@Autowired

@Qualifier


问:
How to fix my: TypeError: 'int' object does not support item assignment
New to python and I keep getting this error when I try running my code. This is the code I'm trying to run

```<code>table=[0]*3
column=0
n=0
with open('matrix.txt','r') as f:
    numbers=f.read()
    numbers=[int(x) for x in numbers.split()]
    for i in range(3):
        table[column]=[0]*3
        for j in range(3):
            table[i][j]=numbers[n]
            n+=1
    column+=1
print(table)
</code>```

I want to make a 3x3 table of the contents in my file. the file contents are;

```<code>2 3 4 1 2 6 9 8 9
</code>```

I keep getting the error message when I run it. Any ideas on how to fix it?

答: You are incrementing the column outside of the outer for loop. Moreover, it is misspelled.</p>

Body:
New to python and I keep getting this error when I try running my code. This is the code I'm trying to run

table=[0]*3
column=0
n=0
with open('matrix.txt','r') as f:
    numbers=f.read()
    numbers=[int(x) for x in numbers.split()]
    for i in range(3):
        table[column]=[0]*3
        for j in range(3):
            table[i][j]=numbers[n]
            n+=1
    column+=1
print(table)

I want to make a 3x3 table of the contents in my file. the file contents are;

2 3 4 1 2 6 9 8 9

I keep getting the error message when I run it. Any ideas on how to fix it?


问:
How to make the method isEmpty() true so that I can end up reading data from InputStream?
I read Algorithm Forth Edition today and try to understand how Dijkstra's two-stack Algorithm for Expression Evaluation work, so I wrote the my implementation code to Intellij IDEA, which is almost same with the code on the book, but I found that the program always paused and waited me continue to input string, and never prints the result.

The problem seems have nothing with the algorithm itself, but is related to the method StdOut.isEmpty(). it seems always give me a false value no matter the Standard InputStream is empty or not, and let me continue to type in data when the InputStream is empty, thus I put it in "while(!StdOut.isEmpty())", so the proceed are blocked. I do not know how to let it return a true value, and let the code run correctly.

and this is the code I wrote:

```<code>import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdIn;
/**
 * Created by Stepten.Wong on 2016/8/15 0015.
 */
public class DoubleStackEE
{
public static void main(String[] args)
{
    Stack<String> ops = new Stack<String>();
    Stack<Double> vals = new Stack<Double>();
    String s;
    while(!StdIn.isEmpty())
    {
        s = StdIn.readString();
        if(s.equals("("));
        else if(s.equals("+"))      ops.push(s);
        else if(s.equals("-"))      ops.push(s);
        else if(s.equals("*"))      ops.push(s);
        else if(s.equals("/"))      ops.push(s);
        else if(s.equals("^"))      ops.push(s);
        else if(s.equals("sqrt"))   ops.push(s);
        else if (s.equals('\n')) break;
        else if(s.equals(")")) {
            double val = 0;
            String op = ops.pop();
            if(op.equals("+"))           val = vals.pop() + vals.pop();
            else if(op.equals("-"))      val = vals.pop() - vals.pop();
            else if(op.equals("*"))      val = vals.pop() * vals.pop();
            else if(op.equals("/"))      val = vals.pop() / vals.pop();
            else if(op.equals("**"))     val = Math.pow(vals.pop(),                     vals.pop());
            else if(op.equals("sqrt"))   val = Math.sqrt(vals.pop());
            vals.push(val);
        }
        else vals.push(Double.parseDouble(s));
    }
    StdOut.println(vals.pop());
}
</code>```

}

here is the implement code of isEmpty() and readString() from their lib algs4.jar:

```<code>/**
 * Returns true if standard input is empty (except possibly for whitespace).
 * Use this method to know whether the next call to {@link #readString()},
 * {@link #readDouble()}, etc will succeed.
 *
 * @return <tt>true</tt> if standard input is empty (except possibly
 *         for whitespace); <tt>false</tt> otherwise
 */
public static boolean isEmpty() {
    return !scanner.hasNext();
}

 /**
 * Reads the next token  and returns the <tt>String</tt>.
 *
 * @return the next <tt>String</tt>
 * @throws NoSuchElementException if standard input is empty
 */
public static String readString() {
    return scanner.next();
}
</code>```

答: The key in here is to press ctrl+z followed by pressing Enter which is the signal to the stdIn that console has reached its EOF(end of file) and now it can return true to break the looping.

Body:
I read Algorithm Forth Edition today and try to understand how Dijkstra's two-stack Algorithm for Expression Evaluation work, so I wrote the my implementation code to Intellij IDEA, which is almost same with the code on the book, but I found that the program always paused and waited me continue to input string, and never prints the result.

The problem seems have nothing with the algorithm itself, but is related to the method StdOut.isEmpty(). it seems always give me a false value no matter the Standard InputStream is empty or not, and let me continue to type in data when the InputStream is empty, thus I put it in "while(!StdOut.isEmpty())", so the proceed are blocked. I do not know how to let it return a true value, and let the code run correctly.

and this is the code I wrote:

import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdIn;
/**
 * Created by Stepten.Wong on 2016/8/15 0015.
 */
public class DoubleStackEE
{
public static void main(String[] args)
{
    Stack<String> ops = new Stack<String>();
    Stack<Double> vals = new Stack<Double>();
    String s;
    while(!StdIn.isEmpty())
    {
        s = StdIn.readString();
        if(s.equals("("));
        else if(s.equals("+"))      ops.push(s);
        else if(s.equals("-"))      ops.push(s);
        else if(s.equals("*"))      ops.push(s);
        else if(s.equals("/"))      ops.push(s);
        else if(s.equals("^"))      ops.push(s);
        else if(s.equals("sqrt"))   ops.push(s);
        else if (s.equals('\n')) break;
        else if(s.equals(")")) {
            double val = 0;
            String op = ops.pop();
            if(op.equals("+"))           val = vals.pop() + vals.pop();
            else if(op.equals("-"))      val = vals.pop() - vals.pop();
            else if(op.equals("*"))      val = vals.pop() * vals.pop();
            else if(op.equals("/"))      val = vals.pop() / vals.pop();
            else if(op.equals("**"))     val = Math.pow(vals.pop(),                     vals.pop());
            else if(op.equals("sqrt"))   val = Math.sqrt(vals.pop());
            vals.push(val);
        }
        else vals.push(Double.parseDouble(s));
    }
    StdOut.println(vals.pop());
}

}

here is the implement code of isEmpty() and readString() from their lib algs4.jar:

/**
 * Returns true if standard input is empty (except possibly for whitespace).
 * Use this method to know whether the next call to {@link #readString()},
 * {@link #readDouble()}, etc will succeed.
 *
 * @return <tt>true</tt> if standard input is empty (except possibly
 *         for whitespace); <tt>false</tt> otherwise
 */
public static boolean isEmpty() {
    return !scanner.hasNext();
}

 /**
 * Reads the next token  and returns the <tt>String</tt>.
 *
 * @return the next <tt>String</tt>
 * @throws NoSuchElementException if standard input is empty
 */
public static String readString() {
    return scanner.next();
}


问:
How to convert an html webpage to a picture
How to convert an html webpage to a picture  like google preview.

Is there a Java library permitting this?

Is there a command-line argument to call browsers to make them convert a web page into a picture .png for instance?

答: See here. It shows that iText and FlyingSaucer (xhtmlrenderer) have such options.</p>


问:
Printing json in Laravel templates
I'm having trouble in moving Eloquent data to Laravel templates as JSON. The problematic data is user inputted text which has linebreaks, all kinds of special characters, quotes, hyphens, MS Word xml garbage tags, you name it.

When I print it to the template as

```<code><script>App.data = JSON.parse('{{data}}')</script>
</code>```

I get all kinds of JSON parsing errors. Usually from linebreaks, but also from special characters and so on. I'm now getting rid of them by ugly hacks, like

```<code>$data->body = str_replace("\n", "\\n", addslashes($data->body))
</code>```

But there has to be a more elegant solution. Using the regular json_encode() leaves linebreaks etc in the JSON that end up as errors.

I'm using Laravel 5.3 with TwigBridge, so I'm using Twig templates instead of Blade.

Title: Printing json in Laravel templates

Body:
I'm having trouble in moving Eloquent data to Laravel templates as JSON. The problematic data is user inputted text which has linebreaks, all kinds of special characters, quotes, hyphens, MS Word xml garbage tags, you name it.

When I print it to the template as

I get all kinds of JSON parsing errors. Usually from linebreaks, but also from special characters and so on. I'm now getting rid of them by ugly hacks, like

$data->body = str_replace("\n", "\\n", addslashes($data->body))

But there has to be a more elegant solution. Using the regular json_encode() leaves linebreaks etc in the JSON that end up as errors.

I'm using Laravel 5.3 with TwigBridge, so I'm using Twig templates instead of Blade.

Body:
Don't json_encode, just pass the PHP object straight through to your view. Then do:

<script>App.data = {!! $data !!}</script>


问:
C# correct and efficient conversion of double to decimal
What is the most efficient (and strictly correct) way to convert from a double to a decimal rounded to n places of precision?

I am using decimal.Round((decimal)d, n, MidpointRounding.AwayFromZero) but it occurs to me that I am rounding twice here- once duing the cast (decimal)d and once via Round().

Is there a way to directly round a double to a decimal to n places?  I suppose I can round trip it via strings but that seems ugly and expensive.

5/12/2017: i added an issue to corefx github here https://github.com/dotnet/corefx/issues/19706

答:
If your double happens to have 15 significant digits, then System.Convert.ToDecimal(d) does the trick:

```<code>Console.WriteLine(Convert.ToDecimal(123456789012345500.12D));  // Displays 123456789012346000
Console.WriteLine(Convert.ToDecimal(123456789012346500.12D));  // Displays 123456789012346000

Console.WriteLine(Convert.ToDecimal(10030.12345678905D));      // Displays 10030.123456789
Console.WriteLine(Convert.ToDecimal(10030.12345678915D));      // Displays 10030.1234567892
</code>```

Therefore, you can achieve the desired rounding without string conversion or Decimal.Round(), by first adding a suitable power of 10 (to create leading digits and reduce the number of decimals in the result) or subtracting the most significant digits (to increase the number of decimals), then invoking Convert.ToDecimal(d) (thereby rounding your modified Double at the 15th significant digit), and finally subtracting or adding the leading digits again from the Decimal number.

I really think your way is better.

Body:
If your double happens to have 15 significant digits, then System.Convert.ToDecimal(d) does the trick:

Console.WriteLine(Convert.ToDecimal(123456789012345500.12D));  // Displays 123456789012346000
Console.WriteLine(Convert.ToDecimal(123456789012346500.12D));  // Displays 123456789012346000

Console.WriteLine(Convert.ToDecimal(10030.12345678905D));      // Displays 10030.123456789
Console.WriteLine(Convert.ToDecimal(10030.12345678915D));      // Displays 10030.1234567892

Therefore, you can achieve the desired rounding without string conversion or Decimal.Round(), by first adding a suitable power of 10 (to create leading digits and reduce the number of decimals in the result) or subtracting the most significant digits (to increase the number of decimals), then invoking Convert.ToDecimal(d) (thereby rounding your modified Double at the 15th significant digit), and finally subtracting or adding the leading digits again from the Decimal number.

I really think your way is better.


问:
Auto-increment not created
domain class

```<code>package testgrails12

class Teams {
    Integer id
    String name
    static mapping = {
        table 'teams'
        version false
        name column: 'name', sqlType: 'VARCHAR(200)'
        id generator: 'increment',
                params: [table:'teams', column: 'idteam', sqlType: 'INT(10)', updateable: false, insertable: false]
        /*id column: 'idteam', sqlType: 'INT(11)', updateable: false, insertable: false,
                generator: 'increment'*/
    }
    static constraints = {
        name nullable: true
    }
}
</code>```

This class creates a table

I need to create a table with a field id auto incremental. Help me whith mapping.

答:
If you are using annotation then below code snippet might help you:</p>

```<code>@Id @GeneratedValue(strategy=GenerationType.AUTO)
OR
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) // both are the same thing
    @Column(name = "Id", unique = true, nullable = false)
    public Long getId() {
        return this.Id;
    }

    public void setId(Long Id) {
        this.Id = Id;
    }
</code>```

Title: Auto-increment not created

Body:
domain class

package testgrails12

class Teams {
    Integer id
    String name
    static mapping = {
        table 'teams'
        version false
        name column: 'name', sqlType: 'VARCHAR(200)'
        id generator: 'increment',
                params: [table:'teams', column: 'idteam', sqlType: 'INT(10)', updateable: false, insertable: false]
        /*id column: 'idteam', sqlType: 'INT(11)', updateable: false, insertable: false,
                generator: 'increment'*/
    }
    static constraints = {
        name nullable: true
    }
}

This class creates a table

I need to create a table with a field id auto incremental. Help me whith mapping.

Body:
If you are using annotation then below code snippet might help you:

@Id @GeneratedValue(strategy=GenerationType.AUTO)
OR
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) // both are the same thing
    @Column(name = "Id", unique = true, nullable = false)
    public Long getId() {
        return this.Id;
    }

    public void setId(Long Id) {
        this.Id = Id;
    }