问:
how to return two array list in JSON and view in data table rows using asp.net MVC?
RoleListand EmpListwe having two arraylist how to return two array list in JSON and how to view in data table rows.

I need to return return Json(EmpList,RoleList, JsonRequestBehavior.AllowGet);

```<code>[HttpPost]
        [MyExceptionHandler]
        public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();
            List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
            string sRptModuleIDs = string.Empty;
            foreach (ViewRoleModules emp in EmpList)
            {
                sRptModuleIDs += emp.ModuleID + ",";
            }
            if (sRptModuleIDs != "")
            {
                sRptModuleIDs = sRptModuleIDs.Remove(sRptModuleIDs.Length - 1, 1);
            }

            List<ViewRoleModules> RoleList;
            foreach (var rid in sRptModuleIDs.Split(','))
            {
                string RID = rid;
                RoleList = type.GetSiteRoleModulesViews(rid);
            }

            return Json(EmpList, JsonRequestBehavior.AllowGet);

        }
</code>```

Scripts:

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

            $("#DomainID").change(function () {

                var id = $(this).val();
                $("#example tbody tr").remove();

                $.ajax({

                    type: 'POST',

                    url: '@Url.Action("ViewModules")',
                    dataType: 'json',
                    data: { id: id },
                    success: function (data) {
                        var items = '';
                        $.each(data, function (i, item) {
                            $("#findValue").show();
                            var rows = "<tr>"
                            + "<td>" + i + "</td>"
                            + "<td>" + item.ModuleName + "</td>"
                            + "<td>" + item.Url + "</td>"
                            + "<td>" + item.RoleName + "</td>"
                            + "</tr>";
                            $('#example tbody').append(rows);
                        });

                    },
                    error: function (ex) {
                        var r = jQuery.parseJSON(response.responseText);
                        alert("Message: " + r.Message);
                        alert("StackTrace: " + r.StackTrace);
                        alert("ExceptionType: " + r.ExceptionType);
                    }
                });
                return false;
            })
        });
    </script>
</code>```

Cshtml:

```<code><table id="example" class="display table table-bordered" cellspacing="0" width="100%;">
                        <thead>
                            <tr>
                                <th>S#</th>
                                <th>Module Name</th>
                                <th>Url</th>
                                <th>Roles</th>
                                @*<th>Action</th>*@
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
</code>```

in my code return only one array list..

I need to display to array list

```<code>public List<ViewRoleModules> GetRoleModulesViews(int id)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> EmpList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_Modules_SelectDomainModules", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@DomainID", id);
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    EmpList.Add(

                        new ViewRoleModules
                        {
                            ModuleID = Convert.ToInt32(dr["ModuleID"]),
                            CompanyTypeID = Convert.ToInt32(dr["CompanyTypeID"]),
                            DomainID = Convert.ToInt32(dr["DomainID"]),
                            ParentModuleID = Convert.ToInt32(dr["ParentModuleID"]),
                            ModuleName = Convert.ToString(dr["ModuleName"]),
                            FolderName = Convert.ToString(dr["FolderName"] == DBNull.Value ? null : dr["FolderName"].ToString()),
                            Url = Convert.ToString(dr["Url"]),
                            TabOrder = Convert.ToInt32(dr["TabOrder"]),
                            Style = Convert.ToString(dr["Style"]),
                            Status = Convert.ToString(dr["Status"]),
                            IsTab = Convert.ToString(dr["IsTab"]),
                            ApprovalProcess = Convert.ToString(dr["ApprovalProcess"]),
                            CreatedBy = Convert.ToInt32(dr["CreatedBy"] == DBNull.Value ? null : dr["CreatedBy"].ToString()),
                            CreatedDate = Convert.ToDateTime(dr["CreatedDate"]),
                            ModifiedBy = Convert.ToInt32(dr["ModifiedBy"] == DBNull.Value ? null : dr["ModifiedBy"].ToString()),
                            ModifiedDate = Convert.ToDateTime(dr["ModifiedDate"] == DBNull.Value ? null : dr["ModifiedDate"].ToString())
                        }
                    );
                }

                return EmpList;
            }
        }

        public List<ViewRoleModules> GetSiteRoleModulesViews(string rid)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> RoleList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_SiteRoleModules_SelectOne", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@ModuleID", Convert.ToInt32(rid));
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    RoleList.Add(

                        new ViewRoleModules
                        {
                            RoleID = Convert.ToInt32(dr["RoleID"]),
                            RoleName = Convert.ToString(dr["RoleName"])

                        }
                    );
                }

                return RoleList;
            }
        }
</code>```

答:
You can easily combine the two with an anonymous type:

```<code>var data = new {EmpList = EmpList, RoleList = RoleList};
return Json(data, JsonRequestBehavior.AllowGet);
</code>```

And on the client side just use the property you need:

```<code>success: function (data) {
    // do something with role list
    $.each(data.RoleList, function (i, item) {

    ...
    // do something else with employee list
    $.each(data.EmpList, function (i, item) {
</code>```

Body:
RoleListand EmpListwe having two arraylist how to return two array list in JSON and how to view in data table rows.

I need to return return Json(EmpList,RoleList, JsonRequestBehavior.AllowGet);

[HttpPost]
        [MyExceptionHandler]
        public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();
            List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
            string sRptModuleIDs = string.Empty;
            foreach (ViewRoleModules emp in EmpList)
            {
                sRptModuleIDs += emp.ModuleID + ",";
            }
            if (sRptModuleIDs != "")
            {
                sRptModuleIDs = sRptModuleIDs.Remove(sRptModuleIDs.Length - 1, 1);
            }

            List<ViewRoleModules> RoleList;
            foreach (var rid in sRptModuleIDs.Split(','))
            {
                string RID = rid;
                RoleList = type.GetSiteRoleModulesViews(rid);
            }

            return Json(EmpList, JsonRequestBehavior.AllowGet);

        }

Scripts:

Cshtml:

                                S#
                                Module Name
                                Url
                                Roles
                                @*Action	*@

in my code return only one array list..

I need to display to array list

public List<ViewRoleModules> GetRoleModulesViews(int id)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> EmpList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_Modules_SelectDomainModules", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@DomainID", id);
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    EmpList.Add(

                        new ViewRoleModules
                        {
                            ModuleID = Convert.ToInt32(dr["ModuleID"]),
                            CompanyTypeID = Convert.ToInt32(dr["CompanyTypeID"]),
                            DomainID = Convert.ToInt32(dr["DomainID"]),
                            ParentModuleID = Convert.ToInt32(dr["ParentModuleID"]),
                            ModuleName = Convert.ToString(dr["ModuleName"]),
                            FolderName = Convert.ToString(dr["FolderName"] == DBNull.Value ? null : dr["FolderName"].ToString()),
                            Url = Convert.ToString(dr["Url"]),
                            TabOrder = Convert.ToInt32(dr["TabOrder"]),
                            Style = Convert.ToString(dr["Style"]),
                            Status = Convert.ToString(dr["Status"]),
                            IsTab = Convert.ToString(dr["IsTab"]),
                            ApprovalProcess = Convert.ToString(dr["ApprovalProcess"]),
                            CreatedBy = Convert.ToInt32(dr["CreatedBy"] == DBNull.Value ? null : dr["CreatedBy"].ToString()),
                            CreatedDate = Convert.ToDateTime(dr["CreatedDate"]),
                            ModifiedBy = Convert.ToInt32(dr["ModifiedBy"] == DBNull.Value ? null : dr["ModifiedBy"].ToString()),
                            ModifiedDate = Convert.ToDateTime(dr["ModifiedDate"] == DBNull.Value ? null : dr["ModifiedDate"].ToString())
                        }
                    );
                }

                return EmpList;
            }
        }

        public List<ViewRoleModules> GetSiteRoleModulesViews(string rid)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> RoleList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_SiteRoleModules_SelectOne", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@ModuleID", Convert.ToInt32(rid));
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    RoleList.Add(

                        new ViewRoleModules
                        {
                            RoleID = Convert.ToInt32(dr["RoleID"]),
                            RoleName = Convert.ToString(dr["RoleName"])

                        }
                    );
                }

                return RoleList;
            }
        }

Body:
You can easily combine the two with an anonymous type:

var data = new {EmpList = EmpList, RoleList = RoleList};
return Json(data, JsonRequestBehavior.AllowGet);

And on the client side just use the property you need:

success: function (data) {
    // do something with role list
    $.each(data.RoleList, function (i, item) {

    ...
    // do something else with employee list
    $.each(data.EmpList, function (i, item) {


来源: stackexchange

问:
Serialize json object with date - javascript
How to serialize json object with specific date format ?

json object

```<code>{"date": "/Date(-62135596800000)/"}
</code>```

to string

```<code>{"date": "Jan 01,1"}
</code>```

and i am using extjs as a core library

答:
the following code is not finished, but it should give you what you need to achieve your goal. If not, let me know :)

```<code>function rxFn(str,m1) {
    var d = new Date(parseInt(m1,10));
    return <whatever format you wish based on the date object>
}

function fixDateFormat(jsonObject) {
    for(var i in jsonObject) {
        switch(typeof jsonObject[i]) {
            case 'object':
                fixDateFormat(jsonObject);
                break;
            case 'string':
                jsonObject[i].replace(/Date\(([0-9]+)\)/,rxFn);
        }
    }
}
</code>```

The basic idea is to loop over the json object recursivly and fix all the date serializations you find.

ContentLicense: CC BY-SA 3.0

Body:
How to serialize json object with specific date format ?

json object

{"date": "/Date(-62135596800000)/"}

to string

{"date": "Jan 01,1"}

and i am using extjs as a core library

Body:
the following code is not finished, but it should give you what you need to achieve your goal. If not, let me know :)

function rxFn(str,m1) {
    var d = new Date(parseInt(m1,10));
    return <whatever format you wish based on the date object>
}

function fixDateFormat(jsonObject) {
    for(var i in jsonObject) {
        switch(typeof jsonObject[i]) {
            case 'object':
                fixDateFormat(jsonObject);
                break;
            case 'string':
                jsonObject[i].replace(/Date\(([0-9]+)\)/,rxFn);
        }
    }
}

The basic idea is to loop over the json object recursivly and fix all the date serializations you find.

ContentLicense: CC BY-SA 2.5


问:
Can i update wordpress version of my PHP5 customised wordpress site into latest wordpress version?
Can i update wordpress version of  my PHP5 customised wordpress site into latest wordpress version?  Now it is in 4.6 and i want to move it to 4.9.1. Any issues will be rised?</p>

答:
You can do it and mostly that will not cause any of issue. But before do WordPress update make sure you have to take backup for your databases once.
First of all take backup for database and make your full theme folder backup and store it as a zip , so if any issue will be raised then you directly unzip that as a theme and that will work fine.

If you have do your WordPress customization all in function.php file then your new WordPress will work perfect with your changes.

If your site have Woocomerce or other more useful plugin for front site then you should take backup for that also.

After WordPress update you may be find plugin update so do it one by one.


问:
How to get data and insert using id in php?
I make shopping site in php and I have one issue of product data.

```<code>First I make **product** datatabe below.

    CREATE TABLE IF NOT EXISTS `product` (
       `product_id` int(11) NOT NULL AUTO_INCREMENT,
       `product_sales_id` int(11) NOT NULL,
       `product_name` varchar(100) NOT NULL,
       `product_price` varchar(5000) NOT NULL,
       `image_name` varchar(300) NOT NULL,
       PRIMARY KEY (`product_id`)
    )

And Second table **product sales** below :

    CREATE TABLE IF NOT EXISTS `product_sales` (
       `product_sales_id` int(11) NOT NULL,
    )

Below page it admin site page when select product to insert in database and
show in product page.

Add_Product.php :

    <?php
        include_once('include/connection.php');
        include_once('include/function.php');
    ?>

    <?php
        if(isset($_POST['submit'])){
            $product_name = mysqli_real_escape_string($conn,$_POST['product_name']);
            $product_price = mysqli_real_escape_string($conn,$_POST['product_price']);
            $image_name = mysqli_real_escape_string($conn, basename( $_FILES["product_image"]["name"]));

            $target_dir = "upload/";
            $target_file = $target_dir . basename($_FILES["product_image"]["name"]);
            $uploadOk = 1;
            $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
            $filetype = $_FILES["product_image"]["type"];

            $image_upload = move_uploaded_file($_FILES["product_image"]["tmp_name"], $target_file);

            if($image_upload){
                mysqli_query($conn,"INSERT INTO product(product_name,product_price,image_name) VALUES ('".$product_name."','".$product_price."','".$image_name."')");
            }

        }
    ?>
</code>```

I make on more page product sell page but i do not know how to make this
    Above show I make table product_sales and his id store in product table
    how to add product_sales in database and show in page using id through.

答:
If you are working on shopping site, then you are missing something very important.

You need to make one temp table for shopping cart that will contain all products that user will add and when user will place order after reviewing the products then they will come in products_sales table after removing from temp table.

Also you need to give product_id in product_sales table but no need to give product_sales_id in products table as products never belong to any particular order forever.

Body:
I make shopping site in php and I have one issue of product data.

First I make **product** datatabe below.

    CREATE TABLE IF NOT EXISTS `product` (
       `product_id` int(11) NOT NULL AUTO_INCREMENT,
       `product_sales_id` int(11) NOT NULL,
       `product_name` varchar(100) NOT NULL,
       `product_price` varchar(5000) NOT NULL,
       `image_name` varchar(300) NOT NULL,
       PRIMARY KEY (`product_id`)
    )

And Second table **product sales** below :

    CREATE TABLE IF NOT EXISTS `product_sales` (
       `product_sales_id` int(11) NOT NULL,
    )

Below page it admin site page when select product to insert in database and
show in product page.

Add_Product.php :

    <?php
        include_once('include/connection.php');
        include_once('include/function.php');
    ?>

    <?php
        if(isset($_POST['submit'])){
            $product_name = mysqli_real_escape_string($conn,$_POST['product_name']);
            $product_price = mysqli_real_escape_string($conn,$_POST['product_price']);
            $image_name = mysqli_real_escape_string($conn, basename( $_FILES["product_image"]["name"]));

            $target_dir = "upload/";
            $target_file = $target_dir . basename($_FILES["product_image"]["name"]);
            $uploadOk = 1;
            $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
            $filetype = $_FILES["product_image"]["type"];

            $image_upload = move_uploaded_file($_FILES["product_image"]["tmp_name"], $target_file);

            if($image_upload){
                mysqli_query($conn,"INSERT INTO product(product_name,product_price,image_name) VALUES ('".$product_name."','".$product_price."','".$image_name."')");
            }

        }
    ?>

I make on more page product sell page but i do not know how to make this
    Above show I make table product_sales and his id store in product table
    how to add product_sales in database and show in page using id through.


问:
application.conf for Scala SBT Akka Actors
I was wondering.. where do you put the application.conf file that configures actors in a file? I'm trying to do what is being done here but SBT is not picking up on the file - I was under the impression that SBT will find the application.conf and automatically add it to my -classpath. I currently have application.conf in /project/application.conf

The error I'm getting is:

```<code>[ERROR] [04/11/2012 16:08:13.174] [HittingTimeSystem-akka.actor.default-dispatcher-2] [akka://HittingTimeSystem/user/master] error while creating actor
akka.config.ConfigurationException:router Actor[akka://HittingTimeSystem/user/master/workerRouter] needs external configuration from file (e.g. application.conf)
</code>```

Thanks!
-kstruct

答:
just update:</p>

```<code>//  val conffactory = ConfigFactory.load() //  from 'src/test/resources' if 'sbt test'
//  val conffactory = ConfigFactory.load() //  from 'src/main/resources' if 'sbt run'
    val conf = ConfigFactory.parseFile(new File("config/application.conf")).getConfig("my") // from '/config' where / - root of app
</code>```

Body:
I was wondering.. where do you put the application.conf file that configures actors in a file? I'm trying to do what is being done here but SBT is not picking up on the file - I was under the impression that SBT will find the application.conf and automatically add it to my -classpath. I currently have application.conf in /project/application.conf

The error I'm getting is:

[ERROR] [04/11/2012 16:08:13.174] [HittingTimeSystem-akka.actor.default-dispatcher-2] [akka://HittingTimeSystem/user/master] error while creating actor
akka.config.ConfigurationException:router Actor[akka://HittingTimeSystem/user/master/workerRouter] needs external configuration from file (e.g. application.conf)

Thanks!
-kstruct

Body:
just update:

//  val conffactory = ConfigFactory.load() //  from 'src/test/resources' if 'sbt test'
//  val conffactory = ConfigFactory.load() //  from 'src/main/resources' if 'sbt run'
    val conf = ConfigFactory.parseFile(new File("config/application.conf")).getConfig("my") // from '/config' where / - root of app


问:
Render list in ordered structure without unicode characters
I have a list that looks like this:

```<code>[(u'Element1', u'Description1', u'Status1), (u'newElement2', u'newDescription2', u'newStatus2), (u'nextElement3', u'nextDescription3', u'nextStatus3), (u'anotherElement4', u'anotherDescription4', u'anotherStatus4)]
</code>```

I have an ansible playbook that uses a jinja2 template to render the list to a text file. The template file looks like this:

```<code>{% for item in description | batch(3, ' ') %}
{% for el in item %}
{{ el }}
{% endfor %}
{% endfor %}
</code>```

But this returns the text file to look like this:

```<code>[u'Element1', u'Description1', u'Status1]
[u'newElement2', u'newDescription2', u'newStatus2]
[u'nextElement3', u'nextDescription3', u'nextStatus3]
[u'anotherElement4', u'anotherDescription4', u'anotherStatus4]
</code>```

What I want the report to look like is this:

```<code>Element1           Description1           Status1
newElement2        nextDescription2       newStatus2
nextElement3       nextDescription3       nextStatus3
anotherElement4    anotherDescription4    anotherDescription4
</code>```

Is there a way to remove the unicode characters and render the lists this way?

答:
You could try

```<code>{% for el in item %}
    {% for e in el %}
        {{ e }}
    {% endfor %}
{% endfor %}
</code>```

Or use html tables if you want to be able to change formatting

Body:
I have a list that looks like this:

[(u'Element1', u'Description1', u'Status1), (u'newElement2', u'newDescription2', u'newStatus2), (u'nextElement3', u'nextDescription3', u'nextStatus3), (u'anotherElement4', u'anotherDescription4', u'anotherStatus4)]

I have an ansible playbook that uses a jinja2 template to render the list to a text file. The template file looks like this:

{% for item in description | batch(3, ' ') %}
{% for el in item %}
{{ el }}
{% endfor %}
{% endfor %}

But this returns the text file to look like this:

[u'Element1', u'Description1', u'Status1]
[u'newElement2', u'newDescription2', u'newStatus2]
[u'nextElement3', u'nextDescription3', u'nextStatus3]
[u'anotherElement4', u'anotherDescription4', u'anotherStatus4]

What I want the report to look like is this:

Element1           Description1           Status1
newElement2        nextDescription2       newStatus2
nextElement3       nextDescription3       nextStatus3
anotherElement4    anotherDescription4    anotherDescription4

Is there a way to remove the unicode characters and render the lists this way?

Body:
You could try

{% for el in item %}
    {% for e in el %}
        {{ e }}
    {% endfor %}
{% endfor %}

Or use html tables if you want to be able to change formatting


问:
PHP Regex Extract Substring with Quotes and Brackets
I have the following String examples:

```<code>new myProduct('', 'bbc_609'),
new myProduct('', '35857'),
</code>```

I want to be able to extract just the codes in the second set of single quotes:  bbc_609 or 35857

What I have tried:

```<code>$str = "new myProduct('', 'bbc_609'),";
preg_match('/ new myProduct('', '  ' (.*?) ''),/', $str, $match);
echo $match[1];
</code>```

I am getting a parse error so I am assuming that I am not escaping the quotes or brackets properly?

Any help appreciated.

Cheers

答:
Try this:</p>

```<code>$str = "new myProduct('', 'bbc_609'),";
preg_match("/new myProduct\('', '(.*?)'\)/i", $str, $match);
echo $match[1];
</code>```

Body:
I have the following String examples:

new myProduct('', 'bbc_609'),
new myProduct('', '35857'),

I want to be able to extract just the codes in the second set of single quotes:  bbc_609 or 35857

What I have tried:

$str = "new myProduct('', 'bbc_609'),";
preg_match('/ new myProduct('', '  ' (.*?) ''),/', $str, $match);
echo $match[1];

I am getting a parse error so I am assuming that I am not escaping the quotes or brackets properly?

Any help appreciated.

Cheers

Body:
Try this:

$str = "new myProduct('', 'bbc_609'),";
preg_match("/new myProduct\('', '(.*?)'\)/i", $str, $match);
echo $match[1];


问:
How .fnDestroy(),columnFilter(); both will work..Is there any way to do it. Currently only .fnDestroy is working
How .fnDestroy(),columnFilter(); both will work..Is there any way to do it. Currently only .fnDestroy is working.

The code describing the issue with DataTable:

```<code>$(document).ready(function () {
    var exampleResponsiveHelper = undefined;

    var nomineeTableResponsiveHelper = undefined;
    var coverageTableResponsiveHelper = undefined;
    var agentInfoTableResponsiveHelper = undefined;
    var payoutTableResponsiveHelper = undefined;
    var payoutTable1ResponsiveHelper = undefined;
    var payoutTable2ResponsiveHelper = undefined;
    var payoutTable3ResponsiveHelper = undefined;
    var payoutTable4ResponsiveHelper = undefined;
    var payoutTable5ResponsiveHelper = undefined;

    var breakpointDefinition = {
        tablet: 1024,
        phone : 480
    };

    ///////////////////////////////////////////////////
    var tableElement = $('#example');

    tableElement.dataTable({
        autoWidth        : false,

        preDrawCallback: function () {
            // Initialize the responsive datatables helper once.
            if (!exampleResponsiveHelper) {
                exampleResponsiveHelper = new ResponsiveDatatablesHelper(tableElement, breakpointDefinition);
            }
        },
        rowCallback    : function (nRow) {
            exampleResponsiveHelper.createExpandIcon(nRow);
        },
        drawCallback   : function (oSettings) {
            exampleResponsiveHelper.respond();
        }
    }).fnDestroy(),columnFilter();
}
</code>```

答:
To chain the commands use .fnDestroy().columnFilter();

You used comma in your code.

Body:
How .fnDestroy(),columnFilter(); both will work..Is there any way to do it. Currently only .fnDestroy is working.

The code describing the issue with DataTable:

$(document).ready(function () {
    var exampleResponsiveHelper = undefined;

    var nomineeTableResponsiveHelper = undefined;
    var coverageTableResponsiveHelper = undefined;
    var agentInfoTableResponsiveHelper = undefined;
    var payoutTableResponsiveHelper = undefined;
    var payoutTable1ResponsiveHelper = undefined;
    var payoutTable2ResponsiveHelper = undefined;
    var payoutTable3ResponsiveHelper = undefined;
    var payoutTable4ResponsiveHelper = undefined;
    var payoutTable5ResponsiveHelper = undefined;

    var breakpointDefinition = {
        tablet: 1024,
        phone : 480
    };

    ///////////////////////////////////////////////////
    var tableElement = $('#example');

    tableElement.dataTable({
        autoWidth        : false,

        preDrawCallback: function () {
            // Initialize the responsive datatables helper once.
            if (!exampleResponsiveHelper) {
                exampleResponsiveHelper = new ResponsiveDatatablesHelper(tableElement, breakpointDefinition);
            }
        },
        rowCallback    : function (nRow) {
            exampleResponsiveHelper.createExpandIcon(nRow);
        },
        drawCallback   : function (oSettings) {
            exampleResponsiveHelper.respond();
        }
    }).fnDestroy(),columnFilter();
}


问:
calling delete rest api by jquery
I had called the GET REST API by following code :

```<code> $.getJSON('http://myapisite.com/user/1?callback=?', function(msg){
         console.log(msg);
      });
</code>```

But for calling  DELETE REST API through jquery
what i had tried is :

```<code>$.ajax({
  url: 'http://mysite.com/user/1?callback=?',
  type: 'DELETE',
      dataType: 'json',
         data: '',
  success: function(response) { console.log('PUT completed'+response); }
      });.
</code>```

and this api is not being called , I want to know how should i call the DELETE REST API .

Thanks

Title: calling delete rest api by jquery

Body:
I had called the GET REST API by following code :

 $.getJSON('http://myapisite.com/user/1?callback=?', function(msg){
         console.log(msg);
      });

But for calling  DELETE REST API through jquery
what i had tried is :

$.ajax({
  url: 'http://mysite.com/user/1?callback=?',
  type: 'DELETE',
      dataType: 'json',
         data: '',
  success: function(response) { console.log('PUT completed'+response); }
      });.

and this api is not being called , I want to know how should i call the DELETE REST API .

Thanks

Body:
You are trying to do a cross-domain request.  This means that you cannot use XMLHttpRequest (the basis of AJAX) because of the same-origin policy.  You are using a workaround called JSONP, which works by inserting <script> tags into your document.

Script tags will always fetch content via GET, so you can't do a DELETE, POST, PUT or suchlike with them.

The best workaround would be to have a script on your own server that proxies the DELETE request for you.


问:
Set Permission to delete file in OS X swift 3.0
I coded for osx application to remove file from directory path but I had received error as "couldn’t be removed because you don’t have permission to access it". So I want to set access permission code to remove that list of files. If any one have idea or solution please help me. The code as pasted below for reference :

```<code>if fileManager.fileExists(atPath: fullpath) == true {
                    print("File Available \(fullpath)")
                    do {
                        _ = try fileManager.removeItem(atPath: fullpath)
                    } catch let error as NSError{
                        print(error.localizedDescription)
                    }
                }
</code>```

In above code, I had found the exist file in directory but I got error that "couldn’t be removed because you don’t have permission to access it".

I want to get solution of access permission and remove file from directory. Thanks in advance.

答: If you want your app to be able to access files outside your own app, you need to turn App Sandbox off in your app target's capabilities.</p>

Body:
I coded for osx application to remove file from directory path but I had received error as "couldn’t be removed because you don’t have permission to access it". So I want to set access permission code to remove that list of files. If any one have idea or solution please help me. The code as pasted below for reference :

if fileManager.fileExists(atPath: fullpath) == true {
                    print("File Available \(fullpath)")
                    do {
                        _ = try fileManager.removeItem(atPath: fullpath)
                    } catch let error as NSError{
                        print(error.localizedDescription)
                    }
                }

In above code, I had found the exist file in directory but I got error that "couldn’t be removed because you don’t have permission to access it".

I want to get solution of access permission and remove file from directory. Thanks in advance.


问:
Compare key and values of one nested dictionary in other nested dictionary
I am trying to recursively compare below two python dictionaries:

```<code>expectededr = {'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'attempted': {'smpp': {'registeredDelivery': 0}, 'status': 'success', 'OATON': 1, 'OANPI': 1, 'DATON': 1, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404'}, 'customerID': 'customer01', 'productID': 'product'}

edr = {'Category': 'NO', 'Type': 'mt', 'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'protocolID': 'smpp', 'direction': 'attempted', 'attempted': {'status': 'success', 'OANPI': 1, 'DATON': 1, 't2': 1512549691602, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404', 'smpp': {'fragmented': False, 'sequenceID': 1, 'registeredDelivery': 0, 'messageID': '4e7b48ad-b39e-4e91-a7bb-2de463e4a6ee', 'srcPort': 39417, 'messageType': 4, 'Status': 0, 'ESMClass': 0, 'dstPort': 0, 'size': 0}, 'OATON': 1, 'PID': 0, 't1': 1512549691602}, 'customerID': 'customer01', 'productID': 'product'}
</code>```

I am trying to compare the in a way that find and compare the key and value of first dictionary in second and if matching then print PASS else print FAIL.

```<code>for key in expectededr:
   if expectededr[key] == edr[key]:
       print("PASS")
   else:
       print("FAIL")
</code>```

Output:

```<code>FAIL
PASS
PASS
PASS
</code>```

Above code is not able to compare all the keys and values as these are nested dictionaries.

As you can see below, if i print key and values above i see that its not going in sub dictionary and missing their keys:

```<code>for key in expectededr:
    if expectededr[key] == edr[key]:
        print(expectededr[key])
        print(edr[key])
</code>```

Output:

```<code>customer01
customer01
e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3
e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3
product
product
</code>```

Could someone help to update this code so that I can do the comparision in these nested dictionaries ?

答:
One way is to flatten the dictionaries and then compare if the keys match.

So Lets initialiaze your dicts first:

```<code>In [23]: expectededr = {'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'attempted': {'smpp': {'registeredDelivery': 0}, 'status': 'success', 'OATON': 1, 'OANP
    ...: I': 1, 'DATON': 1, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404'}, 'customerID': 'customer01', 'productID': 'product'}
    ...:
    ...: edr = {'Category': 'NO', 'Type': 'mt', 'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'protocolID': 'smpp', 'direction': 'attempted', 'attempted': {'
    ...: status': 'success', 'OANPI': 1, 'DATON': 1, 't2': 1512549691602, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404', 'smpp': {'fragmented': False, '
    ...: sequenceID': 1, 'registeredDelivery': 0, 'messageID': '4e7b48ad-b39e-4e91-a7bb-2de463e4a6ee', 'srcPort': 39417, 'messageType': 4, 'Status': 0, 'ESMCl
    ...: ass': 0, 'dstPort': 0, 'size': 0}, 'OATON': 1, 'PID': 0, 't1': 1512549691602}, 'customerID': 'customer01', 'productID': 'product'}
    ...:
</code>```

For flattening your dictionaries, we can use the approach suggested in Flatten nested Python dictionaries, compressing keys:

```<code>In [24]: import collections
    ...:
    ...: def flatten(d, parent_key='', sep='_'):
    ...:     items = []
    ...:     for k, v in d.items():
    ...:         new_key = parent_key + sep + k if parent_key else k
    ...:         if isinstance(v, collections.MutableMapping):
    ...:             items.extend(flatten(v, new_key, sep=sep).items())
    ...:         else:
    ...:             items.append((new_key, v))
    ...:     return dict(items)
    ...:
</code>```

And generated flattened dicts

```<code>In [25]: flat_expectededr = flatten(expectededr)

In [26]: flat_edr = flatten(edr)
</code>```

Now its a simple comparison:

```<code>In [27]: for key in flat_expectededr:
    ...:     if flat_edr.get(key) == flat_expectededr[key]:
    ...:         print "PASS"
    ...:     else:
    ...:         print "FAIL"
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
</code>```

Body:
I am trying to recursively compare below two python dictionaries:

expectededr = {'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'attempted': {'smpp': {'registeredDelivery': 0}, 'status': 'success', 'OATON': 1, 'OANPI': 1, 'DATON': 1, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404'}, 'customerID': 'customer01', 'productID': 'product'}

edr = {'Category': 'NO', 'Type': 'mt', 'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'protocolID': 'smpp', 'direction': 'attempted', 'attempted': {'status': 'success', 'OANPI': 1, 'DATON': 1, 't2': 1512549691602, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404', 'smpp': {'fragmented': False, 'sequenceID': 1, 'registeredDelivery': 0, 'messageID': '4e7b48ad-b39e-4e91-a7bb-2de463e4a6ee', 'srcPort': 39417, 'messageType': 4, 'Status': 0, 'ESMClass': 0, 'dstPort': 0, 'size': 0}, 'OATON': 1, 'PID': 0, 't1': 1512549691602}, 'customerID': 'customer01', 'productID': 'product'}

I am trying to compare the in a way that find and compare the key and value of first dictionary in second and if matching then print PASS else print FAIL.

for key in expectededr:
   if expectededr[key] == edr[key]:
       print("PASS")
   else:
       print("FAIL")

Output:

FAIL
PASS
PASS
PASS

Above code is not able to compare all the keys and values as these are nested dictionaries.

As you can see below, if i print key and values above i see that its not going in sub dictionary and missing their keys:

for key in expectededr:
    if expectededr[key] == edr[key]:
        print(expectededr[key])
        print(edr[key])

Output:

customer01
customer01
e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3
e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3
product
product

Could someone help to update this code so that I can do the comparision in these nested dictionaries ?

Body:
One way is to flatten the dictionaries and then compare if the keys match.

So Lets initialiaze your dicts first:

In [23]: expectededr = {'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'attempted': {'smpp': {'registeredDelivery': 0}, 'status': 'success', 'OATON': 1, 'OANP
    ...: I': 1, 'DATON': 1, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404'}, 'customerID': 'customer01', 'productID': 'product'}
    ...:
    ...: edr = {'Category': 'NO', 'Type': 'mt', 'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'protocolID': 'smpp', 'direction': 'attempted', 'attempted': {'
    ...: status': 'success', 'OANPI': 1, 'DATON': 1, 't2': 1512549691602, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404', 'smpp': {'fragmented': False, '
    ...: sequenceID': 1, 'registeredDelivery': 0, 'messageID': '4e7b48ad-b39e-4e91-a7bb-2de463e4a6ee', 'srcPort': 39417, 'messageType': 4, 'Status': 0, 'ESMCl
    ...: ass': 0, 'dstPort': 0, 'size': 0}, 'OATON': 1, 'PID': 0, 't1': 1512549691602}, 'customerID': 'customer01', 'productID': 'product'}
    ...:

For flattening your dictionaries, we can use the approach suggested in Flatten nested Python dictionaries, compressing keys:

In [24]: import collections
    ...:
    ...: def flatten(d, parent_key='', sep='_'):
    ...:     items = []
    ...:     for k, v in d.items():
    ...:         new_key = parent_key + sep + k if parent_key else k
    ...:         if isinstance(v, collections.MutableMapping):
    ...:             items.extend(flatten(v, new_key, sep=sep).items())
    ...:         else:
    ...:             items.append((new_key, v))
    ...:     return dict(items)
    ...:

And generated flattened dicts

In [25]: flat_expectededr = flatten(expectededr)

In [26]: flat_edr = flatten(edr)

Now its a simple comparison:

In [27]: for key in flat_expectededr:
    ...:     if flat_edr.get(key) == flat_expectededr[key]:
    ...:         print "PASS"
    ...:     else:
    ...:         print "FAIL"
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS
PASS


问:
join the SAS datases sideways, horizontal
I have a dataset as following

```<code>ID  A1  A2  A3
A   1.2 1.5 1
A   1.3 1.7 1.3
A   1.4 1.8 1.7
B   1.5 1.8 1.9
B  1.6 1.7 1.0
</code>```

and result I am looking for is

```<code>A   1.2 1.5 1 1.3 1.7 1.3 1.4 1.8 1.7
</code>```

I know that SAS variable names cannot be repeated but when I tried Proc SQL, with inner join it gives me more rows.

答:
A SAS datastep is the best option here.  Set up an array to read each value in turn, including across rows, storing them in a new array, then only output after the last ID is read.

The only problem is that you need to know the maximum number of values an ID can take, which will be nrows x ncols (not just the number of rows).  In your example the anser is 9, as ID A has 3 rows and 3 columns.  One solution is to set the number of elements in the new array to be higher than you think you'll need, it just means there will be some empty columns at the end of your dataset.  I've set the value to be 10 in my code below.

```<code>data have;
input ID $  A1  A2  A3;
datalines;
A   1.2 1.5 1
A   1.3 1.7 1.3
A   1.4 1.8 1.7
B   1.5 1.8 1.9
B  1.6 1.7 1.0
;
run;

data want;
set have;
by id;
retain newA1-newA10; /* keep values across rows */
array oldvars{*} A: ; /* array of existing variables */
array newvars{*} newA1-newA10; /* array of new variables */
if first.id then do; /* reset counter and array values when ID changes */
    counter=0;
    call missing(of newA1-newA10);
    end;
do i = 1 to dim(oldvars); /* loop through each value and store in new array */
    counter+1;
    newvars{counter} = oldvars{i};
end;
if last.id then output; /* only output after last ID is read */
drop A: counter i; /* drop unwanted variables */
run;
</code>```

Body:
I have a dataset as following

ID  A1  A2  A3
A   1.2 1.5 1
A   1.3 1.7 1.3
A   1.4 1.8 1.7
B   1.5 1.8 1.9
B  1.6 1.7 1.0

and result I am looking for is

A   1.2 1.5 1 1.3 1.7 1.3 1.4 1.8 1.7

I know that SAS variable names cannot be repeated but when I tried Proc SQL, with inner join it gives me more rows.

Body:
A SAS datastep is the best option here.  Set up an array to read each value in turn, including across rows, storing them in a new array, then only output after the last ID is read.

The only problem is that you need to know the maximum number of values an ID can take, which will be nrows x ncols (not just the number of rows).  In your example the anser is 9, as ID A has 3 rows and 3 columns.  One solution is to set the number of elements in the new array to be higher than you think you'll need, it just means there will be some empty columns at the end of your dataset.  I've set the value to be 10 in my code below.

data have;
input ID $  A1  A2  A3;
datalines;
A   1.2 1.5 1
A   1.3 1.7 1.3
A   1.4 1.8 1.7
B   1.5 1.8 1.9
B  1.6 1.7 1.0
;
run;

data want;
set have;
by id;
retain newA1-newA10; /* keep values across rows */
array oldvars{*} A: ; /* array of existing variables */
array newvars{*} newA1-newA10; /* array of new variables */
if first.id then do; /* reset counter and array values when ID changes */
    counter=0;
    call missing(of newA1-newA10);
    end;
do i = 1 to dim(oldvars); /* loop through each value and store in new array */
    counter+1;
    newvars{counter} = oldvars{i};
end;
if last.id then output; /* only output after last ID is read */
drop A: counter i; /* drop unwanted variables */
run;


问:
How to determine if restaurant is part of franchise?
I want to use the FourSquare api but I'm curious to know how or if I can figure out if a restaurant belongs to a franchise or not? Like all Starbucks/McDonalds will be part of their specific franchise ID.</p>

答:
Foursquare provides information whether the restaurant is part of a chain or not. However this information is available only if Owner of the Restaurant chain has registered their business i.e. created a page regarding Business on the Foursquare.

The venue Details API yeilds the the page field in API Response. This contains the restaurant chain information.

https://developer.foursquare.com/docs/api/venues/details

Below is snippet for Pizza Hut seattle Venue details.

```<code>            "page": {
            "pageInfo": {
                "description": "Follow Pizza Hut on Foursquare and check in to your local store to share your love for pizza with all of your friends!",
                "banner": "https://is1.4sqi.net/userpix/WPQD1CUUGRQ510FD.jpg",
                "links": {
                    "count": 1,
                    "items": [
                        {
                            "url": "http://order.pizzahut.com"
                        }
                    ]
                }
            },
            "user": {
                "id": "910282",
                "firstName": "Pizza Hut",
                "gender": "none",
                "photo": {
                    "prefix": "https://igx.4sqi.net/img/user/",
                    "suffix": "/910282-FGR40Q3CQH0CGF3N.png"
                },
                "type": "chain",
                "tips": {
                    "count": 3810
                },
                "lists": {
                    "groups": [
                        {
                            "type": "created",
                            "count": 2,
                            "items": []
                        }
                    ]
                },
                "homeCity": "Dallas, TX",
                "bio": "",
                "contact": {
                    "twitter": "pizzahut"
                }
            }
        }
</code>```

Check it contains type field which has value as chain

Body:
Foursquare provides information whether the restaurant is part of a chain or not. However this information is available only if Owner of the Restaurant chain has registered their business i.e. created a page regarding Business on the Foursquare.

The venue Details API yeilds the the page field in API Response. This contains the restaurant chain information.

https://developer.foursquare.com/docs/api/venues/details

Below is snippet for Pizza Hut seattle Venue details.

            "page": {
            "pageInfo": {
                "description": "Follow Pizza Hut on Foursquare and check in to your local store to share your love for pizza with all of your friends!",
                "banner": "https://is1.4sqi.net/userpix/WPQD1CUUGRQ510FD.jpg",
                "links": {
                    "count": 1,
                    "items": [
                        {
                            "url": "http://order.pizzahut.com"
                        }
                    ]
                }
            },
            "user": {
                "id": "910282",
                "firstName": "Pizza Hut",
                "gender": "none",
                "photo": {
                    "prefix": "https://igx.4sqi.net/img/user/",
                    "suffix": "/910282-FGR40Q3CQH0CGF3N.png"
                },
                "type": "chain",
                "tips": {
                    "count": 3810
                },
                "lists": {
                    "groups": [
                        {
                            "type": "created",
                            "count": 2,
                            "items": []
                        }
                    ]
                },
                "homeCity": "Dallas, TX",
                "bio": "",
                "contact": {
                    "twitter": "pizzahut"
                }
            }
        }

Check it contains type field which has value as chain


问:
how to remove first two words of a strings output
I want to remove the first two words that come up in my output string. this string is also within another string.

What I have:

```<code>for servers in `ls /data/field`
do
  string=`cat /data/field/$servers/time`
</code>```

This sends this text:

```<code>00:00 down server
</code>```

I would like to remove "00:00 down" so that it only displays "server".

I have tried using cut -d ' ' -f2- $string which ends up just removing directories that the command searches.

Any ideas?

答:
For the examples given, I prefer cut. But for the general problem expressed by the question, the answers above have minor short-comings. For instance, when you don't know how many spaces are between the words (cut), or whether they start with a space or not (cut,sed), or cannot be easily used in a pipeline (shell for-loop). Here's a perl example that is fast, efficient, and not too hard to remember:

```<code> | perl -pe 's/^\s*(\S+\s+){2}//'
</code>```

Perl's -p operates like sed's. That is, it gobbles input one line at a time, like -n, and after dong work, prints the line again. The -e starts the command-line-based script. The script is simply a one-line substitute s/// expression; substitute matching regular expressions on the left hand side with the string on the right-hand side. In this case, the right-hand side is empty, so we're just cutting out the expression found on the left-hand side.

The regular expression, particular to Perl (and all PLRE derivatives, like those in Python and Ruby and Javascript), uses \s to match whitespace, and \S to match non-whitespace. So the combination of \S+\s+ matches a word followed by its whitespace. We group that sub-expression together with (...) and then tell sed to match exactly 2 of those in a row with the {m,n} expression, where n is optional and m is 2. The leading \s* means trim leading whitespace.

Body:
I want to remove the first two words that come up in my output string. this string is also within another string.

What I have:

for servers in `ls /data/field`
do
  string=`cat /data/field/$servers/time`

This sends this text:

00:00 down server

I would like to remove "00:00 down" so that it only displays "server".

I have tried using cut -d ' ' -f2- $string which ends up just removing directories that the command searches.

Any ideas?

Body:
For the examples given, I prefer cut. But for the general problem expressed by the question, the answers above have minor short-comings. For instance, when you don't know how many spaces are between the words (cut), or whether they start with a space or not (cut,sed), or cannot be easily used in a pipeline (shell for-loop). Here's a perl example that is fast, efficient, and not too hard to remember:

 | perl -pe 's/^\s*(\S+\s+){2}//'

Perl's -p operates like sed's. That is, it gobbles input one line at a time, like -n, and after dong work, prints the line again. The -e starts the command-line-based script. The script is simply a one-line substitute s/// expression; substitute matching regular expressions on the left hand side with the string on the right-hand side. In this case, the right-hand side is empty, so we're just cutting out the expression found on the left-hand side.

The regular expression, particular to Perl (and all PLRE derivatives, like those in Python and Ruby and Javascript), uses \s to match whitespace, and \S to match non-whitespace. So the combination of \S+\s+ matches a word followed by its whitespace. We group that sub-expression together with (...) and then tell sed to match exactly 2 of those in a row with the {m,n} expression, where n is optional and m is 2. The leading \s* means trim leading whitespace.


问:
Firebase realtime database does not retrieving data in release apk [Android]
The data retrieved perfectly when run the app on the device or emulator, but it is not showing the images when generate release apk

I think the problem is due to proguard so I tried this answer
https://stackoverflow.com/a/26274623/4819445

But it is not working.

This is my proguard_rules.pro

```<code>-dontwarn org.w3c.dom.**
-dontwarn org.joda.time.**
-dontwarn org.shaded.apache.**
-dontwarn org.ietf.jgss.**
-dontwarn com.firebase.**
-dontnote com.firebase.client.core.GaePlatform

-keepattributes Signature
-keepattributes *Annotation*
-keepattributes InnerClasses,EnclosingMethod

-keep class com.images.backgrounds.** { *; }

-keep class com.firebase.** { *; }

-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }

-keep class com.firebase.** { *; }
-keep class org.apache.** { *; }
-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }
-dontwarn org.apache.**
-dontwarn org.w3c.dom.**
-dontwarn javax.annotation.**
#
-dontwarn java.awt.**
-dontwarn java.beans.Beans
-dontwarn javax.security.**
-keep class javamail.** {*;}
-keep class javax.mail.** {*;}
-keep class javax.activation.** {*;}
-keep class com.sun.mail.dsn.** {*;}
-keep class com.sun.mail.handlers.** {*;}
-keep class com.sun.mail.smtp.** {*;}
-keep class com.sun.mail.util.** {*;}
-keep class mailcap.** {*;}
-keep class mimetypes.** {*;}
-keep class myjava.awt.datatransfer.** {*;}
-keep class org.apache.harmony.awt.** {*;}
-keep class org.apache.harmony.misc.** {*;}
</code>```

Also, I add @Keep in the model class
And I make minifyEnabled = true in bulid gradle file:

```<code>release {
            useProguard true
            shrinkResources true
            minifyEnabled true
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
</code>```

But the images form POJO still not showing in APK

Please help me

答:
Most likely Proguard is hiding/stripping those classes in release mode, making it impossible for Firebase to serialize/deserialize them.
You can include the annotation "@Keep" so proguard will not delete any methods from this class.

e.g.:

```<code>...
@IgnoreExtraProperties
@Keep
public class Posto {
    public String uid;
    public String nome;
...
</code>```

Include this dependency in build.gradle :

```<code>compile 'com.android.support:support-annotations:25.2.0'
</code>```

Check this for more info: https://developer.android.com/studio/build/shrink-code.html

This answer is based on my own issue, reported and solved on Encapsulated getters refurn null from firebase database only in release. Works fine in debug mode

Body:
The data retrieved perfectly when run the app on the device or emulator, but it is not showing the images when generate release apk

I think the problem is due to proguard so I tried this answer
https://stackoverflow.com/a/26274623/4819445

But it is not working.

This is my proguard_rules.pro

-dontwarn org.w3c.dom.**
-dontwarn org.joda.time.**
-dontwarn org.shaded.apache.**
-dontwarn org.ietf.jgss.**
-dontwarn com.firebase.**
-dontnote com.firebase.client.core.GaePlatform

-keepattributes Signature
-keepattributes *Annotation*
-keepattributes InnerClasses,EnclosingMethod

-keep class com.images.backgrounds.** { *; }

-keep class com.firebase.** { *; }

-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }

-keep class com.firebase.** { *; }
-keep class org.apache.** { *; }
-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }
-dontwarn org.apache.**
-dontwarn org.w3c.dom.**
-dontwarn javax.annotation.**
#
-dontwarn java.awt.**
-dontwarn java.beans.Beans
-dontwarn javax.security.**
-keep class javamail.** {*;}
-keep class javax.mail.** {*;}
-keep class javax.activation.** {*;}
-keep class com.sun.mail.dsn.** {*;}
-keep class com.sun.mail.handlers.** {*;}
-keep class com.sun.mail.smtp.** {*;}
-keep class com.sun.mail.util.** {*;}
-keep class mailcap.** {*;}
-keep class mimetypes.** {*;}
-keep class myjava.awt.datatransfer.** {*;}
-keep class org.apache.harmony.awt.** {*;}
-keep class org.apache.harmony.misc.** {*;}

Also, I add @Keep in the model class
And I make minifyEnabled = true in bulid gradle file:

release {
            useProguard true
            shrinkResources true
            minifyEnabled true
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

But the images form POJO still not showing in APK

Please help me

Body:
Most likely Proguard is hiding/stripping those classes in release mode, making it impossible for Firebase to serialize/deserialize them.
You can include the annotation "@Keep" so proguard will not delete any methods from this class.

e.g.:

...
@IgnoreExtraProperties
@Keep
public class Posto {
    public String uid;
    public String nome;
...

Include this dependency in build.gradle :

compile 'com.android.support:support-annotations:25.2.0'

Check this for more info: https://developer.android.com/studio/build/shrink-code.html

This answer is based on my own issue, reported and solved on Encapsulated getters refurn null from firebase database only in release. Works fine in debug mode


问:
Authorization_code grant flow on Owin.Security.OAuth: returns invalid_grant
I am trying to setup my authentication using the authorization_code grant flow. I had it previously working with grant_type=password, so I kind of know how the stuff is supposed to work. But when using grant_type=authorization_code, I couldn't make it return anything other than invalid_grant

Here is my setup:

```<code>app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/auth/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(5),
    Provider = new SampleAuthProvider()
});

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
    AuthenticationType = "Bearer"
});
</code>```

SampleAuthProvider is the following class: https://gist.github.com/anonymous/8a0079b705423b406c00

Basically, it's just logging every step and validating it. I tried the request:

```<code>POST http://localhost:12345/auth/token
grant_type=authorization_code&code=xxxxxx&client_id=xxxxx&redirect_uri=https://xxxx.com/
Content-Type: application/x-www-form-urlencoded
</code>```

It's going through:

OnMatchEndpoint

OnValidateClientAuthentication

And that's all. I expected it to call OnValidateTokenRequest and OnGrantAuthorizationCodenext, but it just didn't. I have no idea why.

The xxxx's in the request aren't placeholders, I tried it like that. Maybe the middleware makes some checks on its own and rejects the request because of that? I tried variants of the redirect_uri with http, without any protocol, without trailing slash...

It also works properly with a custom grant_type. It  so if I too desperate, I guess I can use that to simulate authorization_code, but I'd rather not have to do that.

TL;DR

My OAuthAuthorizationServerProvider returns {"error":"invalid_grant"}after OnValidateClientAuthentication when using grant_type=authorization_code.

Why is it stopping there?

How can I make the whole damn thing work?

Thanks for your help!

Edit

As pointed out by RajeshKannan, I made a mistake in my configuration. I didn't provide an AuthorizationCodeProvider instance. However, that didn't completely solve the problem, since in my case, the code is not issued by the AuthorizationCodeProvider, and I can't just deserialize it. I anwered with the workaround I got working.

答:
I had the same error. Things I was missing:

Specify OAuthAuthorizationServerOptions.AuthorizationCodeProvider according to the documentation.

Specify the same client_id as a GET-parameter when making a request to the token endpoint as you did when you received the authorization_code.

Override OAuthAuthorizationServerProvider.ValidateClientAuthentication and in this method call context.TryGetFormCredentials. This sets the property context.ClientId to the value from the client_id GET-parameter. This property must be set, otherwise you'll get the invalid_grant error. Also, call context.Validated().

After doing all of the above, I could finally exchange the authorization_code to an access_token at the token endpoint.

Body:
I am trying to setup my authentication using the authorization_code grant flow. I had it previously working with grant_type=password, so I kind of know how the stuff is supposed to work. But when using grant_type=authorization_code, I couldn't make it return anything other than invalid_grant

Here is my setup:

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/auth/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(5),
    Provider = new SampleAuthProvider()
});

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
    AuthenticationType = "Bearer"
});

SampleAuthProvider is the following class: https://gist.github.com/anonymous/8a0079b705423b406c00

Basically, it's just logging every step and validating it. I tried the request:

POST http://localhost:12345/auth/token
grant_type=authorization_code&code=xxxxxx&client_id=xxxxx&redirect_uri=https://xxxx.com/
Content-Type: application/x-www-form-urlencoded

It's going through:

OnMatchEndpoint

OnValidateClientAuthentication

And that's all. I expected it to call OnValidateTokenRequest and OnGrantAuthorizationCodenext, but it just didn't. I have no idea why.

The xxxx's in the request aren't placeholders, I tried it like that. Maybe the middleware makes some checks on its own and rejects the request because of that? I tried variants of the redirect_uri with http, without any protocol, without trailing slash...

It also works properly with a custom grant_type. It  so if I too desperate, I guess I can use that to simulate authorization_code, but I'd rather not have to do that.

TL;DR

My OAuthAuthorizationServerProvider returns {"error":"invalid_grant"}after OnValidateClientAuthentication when using grant_type=authorization_code.

Why is it stopping there?

How can I make the whole damn thing work?

Thanks for your help!

Edit

As pointed out by RajeshKannan, I made a mistake in my configuration. I didn't provide an AuthorizationCodeProvider instance. However, that didn't completely solve the problem, since in my case, the code is not issued by the AuthorizationCodeProvider, and I can't just deserialize it. I anwered with the workaround I got working.


问:
How to do mp4 video compression
I am refer this link for the video compression..https://github.com/lalongooo/VideoCompressor when I compress .mkv file its works and gives smaller size  but when I compress .mp4 file it gives higher size than original size of video..I am not understand what changes i have to do for making this happen...this code uses the MediaCodec for the video compressor..and is it possible to do compression fast?</p>

答:
SOLVED

Simply put the condition before calling the compression function.
Check the selected video height and width using MediaMetaDataRetriever and set if condition.

```<code>public void compress() {

    Log.w("VideoMessage","eNTERED : "+inputPath);
    lMediaMetadataRetriever.setDataSource(inputPath);
    String lVideoWidth = lMediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
    Log.w("VideoMessage","VideoWidth: "+lVideoWidth);
    String lVideoHeight = lMediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
    Log.w("VideoMessage","VideoHeight: "+lVideoHeight);
    if(Integer.valueOf(lVideoWidth)<=640 || Integer.valueOf(lVideoHeight)<=360){
        Toast.makeText(this, "Video Already in compressed form", Toast.LENGTH_SHORT).show();
    }
    else{
        try2CreateCompressDir();
        outPath=Environment.getExternalStorageDirectory()
                + File.separator
                + APP_DIR
                + COMPRESSED_VIDEOS_DIR
                +"VIDEO_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date()) + ".mp4";

        new VideoCompressor.execute(inputPath,outPath);

    }
}
</code>```

Title: How to do mp4 video compression

Body:
SOLVED

Simply put the condition before calling the compression function.
Check the selected video height and width using MediaMetaDataRetriever and set if condition.

public void compress() {

    Log.w("VideoMessage","eNTERED : "+inputPath);
    lMediaMetadataRetriever.setDataSource(inputPath);
    String lVideoWidth = lMediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
    Log.w("VideoMessage","VideoWidth: "+lVideoWidth);
    String lVideoHeight = lMediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
    Log.w("VideoMessage","VideoHeight: "+lVideoHeight);
    if(Integer.valueOf(lVideoWidth)<=640 || Integer.valueOf(lVideoHeight)<=360){
        Toast.makeText(this, "Video Already in compressed form", Toast.LENGTH_SHORT).show();
    }
    else{
        try2CreateCompressDir();
        outPath=Environment.getExternalStorageDirectory()
                + File.separator
                + APP_DIR
                + COMPRESSED_VIDEOS_DIR
                +"VIDEO_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date()) + ".mp4";

        new VideoCompressor.execute(inputPath,outPath);

    }
}


问:
Does null conditional operator always break on first null ocurrence?
Having a C# background, I always use the ?. operator when acessing class properties (when using Entity Framework relationships).

For example, if I use this and the status class is null, it'll throw an exception since I'm trying to get a property out of a null object.

```<code>var order = DB.Order.Find(1);

var status = order.status.text;
</code>```

To fix this, I could do something like this:

```<code>var address = order.status?.text ?? "No status";
</code>```

The ?. operator will break on the first null and skip the rest of the acessings.

I came across the same situation in PHP and had to do something like this:

```<code>$order = Orders::find(1);
$status = $order->status->text;
</code>```

If the status is empty, it'll throw the same exception (trying to get property out of a null object).

But then I did this and it worked:

```<code>$status = $order->status->text ?? "No status";
</code>```

Apparently, PHP is skipping the ->text acessing if status is null.

I created a fiddle to check if this is not only in my environment, and surprisingly it worked just fine!

```<code><?php
$j = "Hello!";
echo $a->b->c->d->e ?? $a->b->c->d ?? $a->b->c ?? $a->b ?? $j;
</code>```

<< "Hello!"

Is this really the expected behavior of the ?? operator in PHP? Because I didnd't see this mentioned in the docs.

答:
After some research, I found out that the null-conditional operator (??) that was added in PHP 7 is basically a syntatic sugar for the isset() function as if it were used in a ternary call.

```<code>echo isset($a->b->c) ? $a->b->c : "Hello!";
</code>```

The documentation for the isset function shows a clear example of an attempt to access deep array values:

```<code><?php

$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));

// Checking deeper array values
var_dump(isset($a['pie']['a']));        // TRUE
var_dump(isset($a['pie']['b']));        // FALSE
var_dump(isset($a['cake']['a']['b']));  // FALSE

?>
</code>```

The isset() function doesn't throw an E_NOTICE when the variable is null, it just skips the rest of the acessing. Since the null coalesce operator basically uses isset() internally, it also won't throw an exception when trying to access a property on a null object.

Here is the link to the implementation suggestion, it contains a link to the merge request containing the source code of this operator.

Body:
Having a C# background, I always use the ?. operator when acessing class properties (when using Entity Framework relationships).

For example, if I use this and the status class is null, it'll throw an exception since I'm trying to get a property out of a null object.

var order = DB.Order.Find(1);

var status = order.status.text;

To fix this, I could do something like this:

var address = order.status?.text ?? "No status";

The ?. operator will break on the first null and skip the rest of the acessings.

I came across the same situation in PHP and had to do something like this:

$order = Orders::find(1);
$status = $order->status->text;

If the status is empty, it'll throw the same exception (trying to get property out of a null object).

But then I did this and it worked:

$status = $order->status->text ?? "No status";

Apparently, PHP is skipping the ->text acessing if status is null.

I created a fiddle to check if this is not only in my environment, and surprisingly it worked just fine!

<?php
$j = "Hello!";
echo $a->b->c->d->e ?? $a->b->c->d ?? $a->b->c ?? $a->b ?? $j;

<< "Hello!"

Is this really the expected behavior of the ?? operator in PHP? Because I didnd't see this mentioned in the docs.

Body:
After some research, I found out that the null-conditional operator (??) that was added in PHP 7 is basically a syntatic sugar for the isset() function as if it were used in a ternary call.

echo isset($a->b->c) ? $a->b->c : "Hello!";

The documentation for the isset function shows a clear example of an attempt to access deep array values:

<?php

$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));

// Checking deeper array values
var_dump(isset($a['pie']['a']));        // TRUE
var_dump(isset($a['pie']['b']));        // FALSE
var_dump(isset($a['cake']['a']['b']));  // FALSE

?>

The isset() function doesn't throw an E_NOTICE when the variable is null, it just skips the rest of the acessing. Since the null coalesce operator basically uses isset() internally, it also won't throw an exception when trying to access a property on a null object.

Here is the link to the implementation suggestion, it contains a link to the merge request containing the source code of this operator.


问:
Can't install Laravel
I can not install Laravel. I am using xampp. here's what I get when I try and install it</p>

答:
Laravel is designed to be installed into a fresh project directory. However, if for some reason you want to install Laravel into an existing non-empty directory, do the following.

In this example, we install Laravel into foo and then copy it into an existing project named bar

1) Create the new Laravel project:

```<code>$ laravel new foo
</code>```

You should now see your two projects:

```<code>$ ls
foo/      bar/
</code>```

2) Copy Laravel project files into bar/ and rerun Composer installation.

```<code>rsync -av --ignore-existing --exclude=vendor foo/ bar
cd bar/
composer install
</code>```

Beware that this will not overwrite any files in case of name conflicts. If you have an existing composer.json, you will need to manually composer require all the Laravel dependencies. Similarly, if you have an existing .gitignore file, then you should manually merge the two.

Title: Can't install Laravel

Body:
Laravel is designed to be installed into a fresh project directory. However, if for some reason you want to install Laravel into an existing non-empty directory, do the following.

In this example, we install Laravel into foo and then copy it into an existing project named bar

1) Create the new Laravel project:

$ laravel new foo

You should now see your two projects:

$ ls
foo/      bar/

2) Copy Laravel project files into bar/ and rerun Composer installation.

rsync -av --ignore-existing --exclude=vendor foo/ bar
cd bar/
composer install

Beware that this will not overwrite any files in case of name conflicts. If you have an existing composer.json, you will need to manually composer require all the Laravel dependencies. Similarly, if you have an existing .gitignore file, then you should manually merge the two.


问:
Header guards in C++ and C
At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:

add.h:

```<code>#include "mymath.h"
int add(int x, int y);
</code>```

subtract.h:

```<code>#include "mymath.h"
int subtract(int x, int y);
</code>```

main.cpp:

```<code>#include "add.h"
#include "subtract.h"
</code>```

In implementing the header guard, it is mentioned as follows:

```<code>#ifndef ADD_H
#define ADD_H

// your declarations here

#endif
</code>```

What could the declaration be here? And, should int main() come after #endif?

Is adding _H a convention or a must do thing?

Thanks.

答:
The result of preprocessing one implementation (".cpp") file is a translation unit (TU).

Headers can include other headers, so a header may be indirectly included multiple times within the same TU.  (Your mymath.h is an example of this.)

Definitions can only occur at most once per TU.  (Some definitions must also not be in multiple TUs; this case is slightly different and not discussed here.)

The problem include guards solve is preventing multiple definition errors when a given header is included more than once within one TU.

Include guards work by "wrapping" the contents of the header in such a way that the second and subsequent includes are no-ops.  The #ifndef/#define directives should be the first two lines of the file, and #endif should be the last.

Include guards are only used in headers.  Do not define your main function in a header: put it in an implementation file.

If you have a header that will define a type and declare a function, but also needs a header itself:

```<code>#include "other_header.h"

struct Example {};

void f();
</code>```

"Wrapping" it with include guards gives the complete contents of the file:

```<code>#ifndef UNIQUE_NAME_HERE
#define UNIQUE_NAME_HERE

#include "other_header.h"

struct Example {};

void f();

#endif
</code>```

The name used for the include guard must be unique, otherwise conflicting names will give confusing results.  These names are only simple macros, and there is nothing in the language which enforces a certain style.  However, project conventions usually impose requirements.  There are several different include guard naming styles you can find here on SO and elsewhere; this answer gives good criteria and a good overview.

ContentLicense: CC BY-SA 4.0

Title: Header guards in C++ and C

Body:
At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:

add.h:

#include "mymath.h"
int add(int x, int y);

subtract.h:

#include "mymath.h"
int subtract(int x, int y);

main.cpp:

#include "add.h"
#include "subtract.h"

In implementing the header guard, it is mentioned as follows:

#ifndef ADD_H
#define ADD_H

// your declarations here

#endif

What could the declaration be here? And, should int main() come after #endif?

Is adding _H a convention or a must do thing?

Thanks.

Body:
The result of preprocessing one implementation (".cpp") file is a translation unit (TU).

Headers can include other headers, so a header may be indirectly included multiple times within the same TU.  (Your mymath.h is an example of this.)

Definitions can only occur at most once per TU.  (Some definitions must also not be in multiple TUs; this case is slightly different and not discussed here.)

The problem include guards solve is preventing multiple definition errors when a given header is included more than once within one TU.

Include guards work by "wrapping" the contents of the header in such a way that the second and subsequent includes are no-ops.  The #ifndef/#define directives should be the first two lines of the file, and #endif should be the last.

Include guards are only used in headers.  Do not define your main function in a header: put it in an implementation file.

If you have a header that will define a type and declare a function, but also needs a header itself:

#include "other_header.h"

struct Example {};

void f();

"Wrapping" it with include guards gives the complete contents of the file:

#ifndef UNIQUE_NAME_HERE
#define UNIQUE_NAME_HERE

#include "other_header.h"

struct Example {};

void f();

#endif

The name used for the include guard must be unique, otherwise conflicting names will give confusing results.  These names are only simple macros, and there is nothing in the language which enforces a certain style.  However, project conventions usually impose requirements.  There are several different include guard naming styles you can find here on SO and elsewhere; this answer gives good criteria and a good overview.


问:
Convert a string to expression in java
I have a String for example:

```<code>String s= "(resultSet.get(\"PRIMARY_ROLE\")=='COO Business Management Team' && resultSet.get(\"DEPT_LEVEL\")=='5') ? 1:0";
</code>```

where resultSet is a map.

Is there a way I can convert it to expression so that I can evaluate its value.

Say:

```<code>int i=  (resultSet.get("PRIMARY_ROLE")=='COO Business Management Team' && resultSet.get("DEPT_LEVEL")=='5') ? 1:0 ;
</code>```

答:
If each of expressions is a syntactically correct JavaScript then you can use Oracle Nashorn engine shipped as part of JDK starting from Java 8 (previously it was Mozilla Rhino):</p>

```<code>public static void main(String[] args) throws ScriptException {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine se = sem.getEngineByExtension("js");

    String s= "(resultSet.get(\"PRIMARY_ROLE\")=='COO Business Management Team' && resultSet.get(\"DEPT_LEVEL\")=='5') ? 1:0";
    Bindings bindings = se.createBindings();
    bindings.put("resultSet",
            new HashMap<String, String>() {{
                put("PRIMARY_ROLE","COO Business Management Team");
                put("DEPT_LEVEL","5");
            }});

    Object result = se.eval(s, bindings);
    System.out.println("Expression evaluates to "+ result);
}
</code>```

Title: Convert a string to expression in java

Body:
I have a String for example:

String s= "(resultSet.get(\"PRIMARY_ROLE\")=='COO Business Management Team' && resultSet.get(\"DEPT_LEVEL\")=='5') ? 1:0";

where resultSet is a map.

Is there a way I can convert it to expression so that I can evaluate its value.

Say:

int i=  (resultSet.get("PRIMARY_ROLE")=='COO Business Management Team' && resultSet.get("DEPT_LEVEL")=='5') ? 1:0 ;

Body:
If each of expressions is a syntactically correct JavaScript then you can use Oracle Nashorn engine shipped as part of JDK starting from Java 8 (previously it was Mozilla Rhino):

public static void main(String[] args) throws ScriptException {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine se = sem.getEngineByExtension("js");

    String s= "(resultSet.get(\"PRIMARY_ROLE\")=='COO Business Management Team' && resultSet.get(\"DEPT_LEVEL\")=='5') ? 1:0";
    Bindings bindings = se.createBindings();
    bindings.put("resultSet",
            new HashMap<String, String>() {{
                put("PRIMARY_ROLE","COO Business Management Team");
                put("DEPT_LEVEL","5");
            }});

    Object result = se.eval(s, bindings);
    System.out.println("Expression evaluates to "+ result);
}


问:
How can I extract the week number from java.util.Date in scala
I already tried to use:
getWeek
getCalendarDate
and I don't want to use Calendar package (because I am using a specific software that don't allow me to use it)
Thanks in advance,</p>

答:
Here is the API documentation for JavaDoc - java.util.Date

You should be able to see that java.utils.Date has no method for getting week.

People generally use Calender for various requirements. In your case, you can use a DateFormat to format your Date object to a String then parse it to get the integer value.

```<code>import java.text.SimpleDateFormat
import java.util.Date

val date = new Date()

// if you want week in year
val formatter1 = new SimpleDateFormat("w")
val week1 = Integer.parseInt(formatter1.format(date))

// if you want week in month
val formatter2 = new SimpleDateFormat("W")
val week2 = Integer.parseInt(formatter2.format(date))
</code>```

Body:
Here is the API documentation for JavaDoc - java.util.Date

You should be able to see that java.utils.Date has no method for getting week.

People generally use Calender for various requirements. In your case, you can use a DateFormat to format your Date object to a String then parse it to get the integer value.

import java.text.SimpleDateFormat
import java.util.Date

val date = new Date()

// if you want week in year
val formatter1 = new SimpleDateFormat("w")
val week1 = Integer.parseInt(formatter1.format(date))

// if you want week in month
val formatter2 = new SimpleDateFormat("W")
val week2 = Integer.parseInt(formatter2.format(date))


问:
Rails Select boolean with NULL value
First the environment:

Rails 2.1.0, Ruby 1.8.7, Mysql 5.1.54, Ubuntu 11.04

I have a boolean field in my table which starts as NULL, but I can not find a good way to set it to NULL. (This field is basically a yes / no / unanswered field, which true / false / null seems about right for. The client specifically said he would like it to be able to remain null (unanswered).)

Here is my migration (specific names replaced):

```<code>class AddQuestionToClients < ActiveRecord::Migration
    def self.up
        add_column :clients, :question, :boolean
    end
    def self.down
        remove_column :clients, :question
    end
end
</code>```

My controller uses a basic

```<code>@client = Client.find(params[:id])
@client.update_attributes(params[:client])
</code>```

My view has a select (I think this is causing the problem, was never great with form helper selects):

```<code><%= f.select :question, [["Yes", true], ["No", false]], { :include_blank => true, :selected => @client.question } %>
</code>```

When selecting yes, true is passed; no, false is passed; blank, "" is passed.
But "" seems to automatically convert to false when updating the database.

To get around this, I'm doing this:

```<code>params[:client][:question] = (params[:client][:question] == "")? nil : params[:client][:question]
</code>```

But this can't be the right way to do it. What am I missing?

答:
This isn't mentioned in previous posts, but in Rails 5 this should work if you want to name the nil option

```<code><%= f.select :question, [["Yes", true], ["No", false]], { :include_blank => 'Name this whatever you want, it will be nil when submitted', :selected => @client.question } %>
</code>```

Tested this on my own project

Title: Rails Select boolean with NULL value

Body:
First the environment:

Rails 2.1.0, Ruby 1.8.7, Mysql 5.1.54, Ubuntu 11.04

I have a boolean field in my table which starts as NULL, but I can not find a good way to set it to NULL. (This field is basically a yes / no / unanswered field, which true / false / null seems about right for. The client specifically said he would like it to be able to remain null (unanswered).)

Here is my migration (specific names replaced):

class AddQuestionToClients < ActiveRecord::Migration
    def self.up
        add_column :clients, :question, :boolean
    end
    def self.down
        remove_column :clients, :question
    end
end

My controller uses a basic

@client = Client.find(params[:id])
@client.update_attributes(params[:client])

My view has a select (I think this is causing the problem, was never great with form helper selects):

<%= f.select :question, [["Yes", true], ["No", false]], { :include_blank => true, :selected => @client.question } %>

When selecting yes, true is passed; no, false is passed; blank, "" is passed.
But "" seems to automatically convert to false when updating the database.

To get around this, I'm doing this:

params[:client][:question] = (params[:client][:question] == "")? nil : params[:client][:question]

But this can't be the right way to do it. What am I missing?

Body:
This isn't mentioned in previous posts, but in Rails 5 this should work if you want to name the nil option

<%= f.select :question, [["Yes", true], ["No", false]], { :include_blank => 'Name this whatever you want, it will be nil when submitted', :selected => @client.question } %>

Tested this on my own project


问:
String manipulation in VB (.NET)
I'm looking for a way to split a string into separate strings.  The source string is in the format:

```<code>    Surname, First name (dd-mm-yyyy) (dd-mm-yyyy).doc
</code>```

so an example is...

```<code>    Smith, John (01-07-2017) (02-07-2027).doc
</code>```

All source strings follow this exact format.

I've been playing with stripping the file extension and counting back 12 characters to get the contents of the second parenthesis.  So I can return (dd-mm-yyyy) into a separate string but really I need to dissect all parts of the source string to their own strings and assign them to their own variables and without the spaces and parenthesis e.g.

```<code>strSurname variable will hold "Smith"
strFirstname variable will hold "John"
strDateofBirth variable will hold "01-07-2017"
strExpiryDate variable will hold "02-07-2027"
</code>```

Can anyone help me out? Thanks in advance.

答:
I'd use this approach using string methods:

```<code>Dim inputPath="    Smith, John (01-07-2017) (02-07-2027).doc"
Dim token = Path.GetFileNameWithoutExtension(inputPath.Trim())
Dim indexOfComma = token.IndexOf(","c)
Dim surName = token.Remove(indexOfComma).Trim()
Dim secondToken = token.Substring(indexOfComma).Trim(" "c, ","c)
Dim indexOfLeftparanthesis = secondToken.IndexOf("("c)
Dim firstName = secondToken.Remove(indexOfLeftparanthesis).Trim()
Dim dateBlocks = secondToken.Substring(indexOfLeftparanthesis).Trim().Split()
Dim dateofBirth = dateBlocks(0).Trim("("c,")"c)
Dim expiryDate = dateBlocks(1).Trim("("c,")"c)
</code>```

You should check if the indexOf... variables are >= 0 and dateBlocks.Length = 2.

Title: String manipulation in VB (.NET)

Body:
I'm looking for a way to split a string into separate strings.  The source string is in the format:

    Surname, First name (dd-mm-yyyy) (dd-mm-yyyy).doc

so an example is...

    Smith, John (01-07-2017) (02-07-2027).doc

All source strings follow this exact format.

I've been playing with stripping the file extension and counting back 12 characters to get the contents of the second parenthesis.  So I can return (dd-mm-yyyy) into a separate string but really I need to dissect all parts of the source string to their own strings and assign them to their own variables and without the spaces and parenthesis e.g.

strSurname variable will hold "Smith"
strFirstname variable will hold "John"
strDateofBirth variable will hold "01-07-2017"
strExpiryDate variable will hold "02-07-2027"

Can anyone help me out? Thanks in advance.

Body:
I'd use this approach using string methods:

Dim inputPath="    Smith, John (01-07-2017) (02-07-2027).doc"
Dim token = Path.GetFileNameWithoutExtension(inputPath.Trim())
Dim indexOfComma = token.IndexOf(","c)
Dim surName = token.Remove(indexOfComma).Trim()
Dim secondToken = token.Substring(indexOfComma).Trim(" "c, ","c)
Dim indexOfLeftparanthesis = secondToken.IndexOf("("c)
Dim firstName = secondToken.Remove(indexOfLeftparanthesis).Trim()
Dim dateBlocks = secondToken.Substring(indexOfLeftparanthesis).Trim().Split()
Dim dateofBirth = dateBlocks(0).Trim("("c,")"c)
Dim expiryDate = dateBlocks(1).Trim("("c,")"c)

You should check if the indexOf... variables are >= 0 and dateBlocks.Length = 2.


问:
Parameterising an import statement
I maintain a Python module that wraps and exposes the functionality of a DLL (also maintained by me).  The interfacing with the DLL uses ctypes.

This all works wonderfully thanks to the wonders of ctypes.  However, as I am by no means a Python expert, there are some parts of the Python that I feel are not idiomatic.

In particular I offer control of the DLL location to the user of the module. The DLL is loaded during the import of the module. I do this because I want to switch behaviour based on the capability of the DLL, and I need to load the DLL in order to query its behaviour.

By default, the DLL load relies of the DLL search path to locate the DLL. I would like to be able to allow the user to specify a full path to the DLL, should they wish to pick out a particular version.

At the moment I do this by using an environment variable but I recognise that this is a rather grotesque way to do it. What I'm looking for is a canonical or idiomatic Python way for the module importer to pass some information to the module which can be accessed at module import time.

答:
You should defer loading the DLL to the point where it's actually used for the first time, and offer an optional function initialize:

```<code>_initialized=False
def initialize(path=None):
  if _initialized:
    if path:
      raise ValueError, "initialize called after first use"
    return
  if path is None:
    path = default_path
  load_dll(path)
  determine_features()
</code>```

Then, call initialized() in all API you offer. This gives the user a chance to override it, but if they don't, it will continue to work as it does today (you can even preserve support for the environment variable).

If you are willing to change the API, use classes:

```<code>class DLLAPI:
  def __init__(self, path=None):
    ...
</code>```

Users would have to create a DLLAPI instance, and may or may not pass a DLL path. That should allow to even use different DLLs simultaneously.

Title: Parameterising an import statement

Body:
You should defer loading the DLL to the point where it's actually used for the first time, and offer an optional function initialize:

_initialized=False
def initialize(path=None):
  if _initialized:
    if path:
      raise ValueError, "initialize called after first use"
    return
  if path is None:
    path = default_path
  load_dll(path)
  determine_features()

Then, call initialized() in all API you offer. This gives the user a chance to override it, but if they don't, it will continue to work as it does today (you can even preserve support for the environment variable).

If you are willing to change the API, use classes:

class DLLAPI:
  def __init__(self, path=None):
    ...

Users would have to create a DLLAPI instance, and may or may not pass a DLL path. That should allow to even use different DLLs simultaneously.


问:
table keeps resizing not overflow
I'm trying to make my table overflow on the x axis instead of resizing once it gets past 900px browser width.

Here is my code:

```<code><div className='jobTableTop'>
<table className='jobsTable'>
  <tbody>
    <tr className='jobsTableHeader'>
      <td style={{"color": "lightgray"}}>BY</td>
      <td style={{"color": "lightgray"}}>JOB TITLE</td>
      <td style={{"color": "lightgray"}}>OPTION</td>
      <td style={{"color": "lightgray"}}>LOCATION</td>
      <td style={{"color": "lightgray"}}>WAGE</td>
      <td style={{"padding-top": "0px"}}></td>
    </tr>
    {this.props.dataToShow.map(function (item, index) {
      return (
        (index >= minItem && index <= maxItem) ?
          <tr key={item.id}>
            <td>{item.company}</td>
            <td>{item.title}</td>
            <td>{item.option}</td>
            <td>{item.location}</td>
            <td>{item.wage}</td>
            <td style={{"padding-top": "0px"}}>
              <a href={'/job-detail/' + item.id}>
                <Button className={classes.button} style={{"font-size": "20px"}} raised color="accent">
                  Apply
                </Button>
              </a>
            </td>
          </tr>
          :
          ''
        )})}
      </tbody>
    </table>
   </div>
</code>```

that is the jsx/html code

here is the css:

```<code>@media screen and (max-width: 900px){
    .jobsTable{
        overflow: hidden;
    }
}
.jobsTable tr {
border-bottom: 1px solid lightgray;
display: flex;
}
.jobsTable tr td {
    width: 16.6%;
    height: 40px;
    padding-top: 20px;
    font-size: 20px;
    vertical-align: middle;
    color: black;
}
</code>```

so when it goes under 900px i want it so that theres a scroll bar instead of the table going smaller no matter what i seem to do nothing makes it do this. Im trying to make it mobile compatible without making a separate version of the site.

edit changed:

all i changed was this.

```<code>.jobTableTop {
    width: 100%;
    overflow-x: scroll;
    overflow-y: hidden;
}
</code>```

i have to make the webpage around 750px instead of 900px. how would i achieve said goal.

答: I fixed said issue by upping the % to about 300% for 360px and worked it out from there for all the other size of screen</p>

Title: table keeps resizing not overflow

Body:
I'm trying to make my table overflow on the x axis instead of resizing once it gets past 900px browser width.

Here is my code:

      BY
      JOB TITLE
      OPTION
      LOCATION
      WAGE

    {this.props.dataToShow.map(function (item, index) {
      return (
        (index >= minItem && index <= maxItem) ?

            {item.company}
            {item.title}
            {item.option}
            {item.location}
            {item.wage}

                <Button className={classes.button} style={{"font-size": "20px"}} raised color="accent">
                  Apply
                </Button>

          :
          ''
        )})}

that is the jsx/html code

here is the css:

@media screen and (max-width: 900px){
    .jobsTable{
        overflow: hidden;
    }
}
.jobsTable tr {
border-bottom: 1px solid lightgray;
display: flex;
}
.jobsTable tr td {
    width: 16.6%;
    height: 40px;
    padding-top: 20px;
    font-size: 20px;
    vertical-align: middle;
    color: black;
}

so when it goes under 900px i want it so that theres a scroll bar instead of the table going smaller no matter what i seem to do nothing makes it do this. Im trying to make it mobile compatible without making a separate version of the site.

edit changed:

all i changed was this.

.jobTableTop {
    width: 100%;
    overflow-x: scroll;
    overflow-y: hidden;
}

i have to make the webpage around 750px instead of 900px. how would i achieve said goal.