问:
Fatal error: Call to a member function get() on null in Zend Framework 2
I am getting null when using $sm=$this->getServiceLocator() as a result $sm->get("XXXXXXXXXXX") throwing a Fatal error: Call to a member function get() on null.

What i am doing is that, while receiving user data in controller i am calling another controller validatorController inside my requested controller which is signupController and in validatorController i am using $sm=$this->getServiceLocator() which gives the above error

Here is my work

Error comes when i use $check=$this->_getUserTable()->isUnique($email); in ValidatorController.php but not in SignupController.php

Module.php

```<code><?php
namespace User;

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\ResultSet\ResultSet;
use User\Controller\ValidatorController;
use User\Model\User;
use User\Model\UserTable;

class Module {
    public function getConfig() {
        return include __DIR__."/config/module.config.php";
    }

    public function getAutoloaderConfig() {
        return array(
            "Zend\loader\StandardAutoloader"=>array(
               "namespaces"=>array(
                   __NAMESPACE__=>__DIR__."/src/".__NAMESPACE__
               )
            )
        );
    }

    public function getServiceConfig() {
        return array(
            "factories"=>array(
                'User\ValidatorController' => function ($sm) {
                    $validatorController = new ValidatorController();
                    return $validatorController;
                },
                "User\Model\UserTable"=>function($sm) {
                    $tableGateway=$sm->get("UserTableGateway");
                    $table=new UserTable($tableGateway);
                    return $table;
                },
                "UserTableGateway"=>function($sm) {
                    $dbAdapter=$sm->get("Zend\Db\Adapter\Adapter");
                    $resultSetPrototype=new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new User());
                    return new TableGateway("users",$dbAdapter,null,$resultSetPrototype);
                }
            )
        );
    }
}
</code>```

module.config.php

```<code><?php

return array(
    "controllers"=>array(
        "invokables"=>array(
            "User\Controller\User"=>"User\Controller\UserController",
            'User\Controller\Signup' => 'User\Controller\SignupController',
            'User\Controller\Validator' => 'User\Controller\ValidatorController'
        )
    ),
    // The following section is new and should be added to your file
    "router"=>array(
        "routes"=>array(
            "user"=>array(
                "type"=>"segment",
                "options"=>array(
                    "route" => "/user[/:action][/:id]",
                    "constraints" => array(
                        "id" => "[0-9]+",
                    ),
                    "defaults"=>array(
                        "controller"=>"User\Controller\User"
                    )
                )
            ),
            'signup' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/signup',
                    'defaults' => array(
                        'controller' => 'User\Controller\Signup',
                    )
                )
            ),
        )
    ),
    'view_manager' => array(//Add this config
        'strategies' => array(
            'ViewJsonStrategy',
        ),
    ),
);
</code>```

SignupController.php

```<code><?php
namespace User\Controller;

use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;

class SignupController extends AbstractRestfulController{
    private $_userTable;

    public function create($data) {

        /*
         * The above error is not coming here
         * $check=$this->_getUserTable()->isUnique($data['email']);
         *
         * But inside the below controller
         */

        // Calling a validatorContoller
        $validator=$this->getServiceLocator()->get('User\ValidatorController');
        $response=$validator->validateEmail($data['email']);

        return new JsonModel($response);
    }

    public function _getUserTable() {
        if(!$this->_userTable) {
            $sm=$this->getServiceLocator();
            $this->_userTable=$sm->get("User\Model\UserTable");
        }
        return $this->_userTable;
    }
}
</code>```

ValidatorController.php

```<code><?php
namespace User\Controller;

use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\Validator\EmailAddress;

class ValidatorController extends AbstractRestfulController {
    private $_userTable;

    public function validateEmail($email) {
        $validator = new EmailAddress();
        if($validator->isValid($email)) {

            // check if it is a unique entry in user table

            //  ***(THE SOURCE OF ERROR IS HERE)***
            $check=$this->_getUserTable()->isUnique($email);
            return $check;
        }
    }

    public function _getUserTable() {
        if(!$this->_userTable) {
            $sm=$this->getServiceLocator();
            $this->_userTable=$sm->get("User\Model\UserTable");
        }
        return $this->_userTable;
    }
}
</code>```

NOTE

Error comes when i use $check=$this->_getUserTable()->isUnique($email); in ValidatorController.php but not in SignupController.php

Thankyou

答:
getServiceLocator() is deprecated in ZendFramework 2. You must inject _userTable in your ValidatorController from your Module.php like this :

```<code>class Module {
...
public function getServiceConfig() {
    return array(
        "factories"=>array(
            'User\ValidatorController' => function ($sm) {
                $userTable = $sm->get("User\Model\UserTable");
                $validatorController = new ValidatorController();
                $validatorController->setUserTable($userTable);
                return $validatorController;
            },
...
}
</code>```

Then add a setUserTable() method in your ValidController and modify the getUserTable() method :

```<code>class ValidController {
    public function setUserTable($suerTable) {
        $this->_suerTable = $userTable
    }
    public function _getUserTable() {
        return $this->_userTable;
    }
}
</code>```

Body:
I am getting null when using $sm=$this->getServiceLocator() as a result $sm->get("XXXXXXXXXXX") throwing a Fatal error: Call to a member function get() on null.

What i am doing is that, while receiving user data in controller i am calling another controller validatorController inside my requested controller which is signupController and in validatorController i am using $sm=$this->getServiceLocator() which gives the above error

Here is my work

Error comes when i use $check=$this->_getUserTable()->isUnique($email); in ValidatorController.php but not in SignupController.php

Module.php

<?php
namespace User;

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\ResultSet\ResultSet;
use User\Controller\ValidatorController;
use User\Model\User;
use User\Model\UserTable;

class Module {
    public function getConfig() {
        return include __DIR__."/config/module.config.php";
    }

    public function getAutoloaderConfig() {
        return array(
            "Zend\loader\StandardAutoloader"=>array(
               "namespaces"=>array(
                   __NAMESPACE__=>__DIR__."/src/".__NAMESPACE__
               )
            )
        );
    }

    public function getServiceConfig() {
        return array(
            "factories"=>array(
                'User\ValidatorController' => function ($sm) {
                    $validatorController = new ValidatorController();
                    return $validatorController;
                },
                "User\Model\UserTable"=>function($sm) {
                    $tableGateway=$sm->get("UserTableGateway");
                    $table=new UserTable($tableGateway);
                    return $table;
                },
                "UserTableGateway"=>function($sm) {
                    $dbAdapter=$sm->get("Zend\Db\Adapter\Adapter");
                    $resultSetPrototype=new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new User());
                    return new TableGateway("users",$dbAdapter,null,$resultSetPrototype);
                }
            )
        );
    }
}

module.config.php

<?php

return array(
    "controllers"=>array(
        "invokables"=>array(
            "User\Controller\User"=>"User\Controller\UserController",
            'User\Controller\Signup' => 'User\Controller\SignupController',
            'User\Controller\Validator' => 'User\Controller\ValidatorController'
        )
    ),
    // The following section is new and should be added to your file
    "router"=>array(
        "routes"=>array(
            "user"=>array(
                "type"=>"segment",
                "options"=>array(
                    "route" => "/user[/:action][/:id]",
                    "constraints" => array(
                        "id" => "[0-9]+",
                    ),
                    "defaults"=>array(
                        "controller"=>"User\Controller\User"
                    )
                )
            ),
            'signup' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/signup',
                    'defaults' => array(
                        'controller' => 'User\Controller\Signup',
                    )
                )
            ),
        )
    ),
    'view_manager' => array(//Add this config
        'strategies' => array(
            'ViewJsonStrategy',
        ),
    ),
);

SignupController.php

<?php
namespace User\Controller;

use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;

class SignupController extends AbstractRestfulController{
    private $_userTable;

    public function create($data) {

        /*
         * The above error is not coming here
         * $check=$this->_getUserTable()->isUnique($data['email']);
         *
         * But inside the below controller
         */

        // Calling a validatorContoller
        $validator=$this->getServiceLocator()->get('User\ValidatorController');
        $response=$validator->validateEmail($data['email']);

        return new JsonModel($response);
    }

    public function _getUserTable() {
        if(!$this->_userTable) {
            $sm=$this->getServiceLocator();
            $this->_userTable=$sm->get("User\Model\UserTable");
        }
        return $this->_userTable;
    }
}

ValidatorController.php

<?php
namespace User\Controller;

use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\Validator\EmailAddress;

class ValidatorController extends AbstractRestfulController {
    private $_userTable;

    public function validateEmail($email) {
        $validator = new EmailAddress();
        if($validator->isValid($email)) {

            // check if it is a unique entry in user table

            //  ***(THE SOURCE OF ERROR IS HERE)***
            $check=$this->_getUserTable()->isUnique($email);
            return $check;
        }
    }

    public function _getUserTable() {
        if(!$this->_userTable) {
            $sm=$this->getServiceLocator();
            $this->_userTable=$sm->get("User\Model\UserTable");
        }
        return $this->_userTable;
    }
}

NOTE

Error comes when i use $check=$this->_getUserTable()->isUnique($email); in ValidatorController.php but not in SignupController.php

Thankyou

Body:
getServiceLocator() is deprecated in ZendFramework 2. You must inject _userTable in your ValidatorController from your Module.php like this :

class Module {
...
public function getServiceConfig() {
    return array(
        "factories"=>array(
            'User\ValidatorController' => function ($sm) {
                $userTable = $sm->get("User\Model\UserTable");
                $validatorController = new ValidatorController();
                $validatorController->setUserTable($userTable);
                return $validatorController;
            },
...
}

Then add a setUserTable() method in your ValidController and modify the getUserTable() method :

class ValidController {
    public function setUserTable($suerTable) {
        $this->_suerTable = $userTable
    }
    public function _getUserTable() {
        return $this->_userTable;
    }
}


来源: stackexchange

问:
Time complexity of binary search in a slightly unbalanced binary tree
The best case running time for binary search is O(log(n)), if the binary tree is balanced. The worst case would be, if the binary tree is so unbalanced, that it basically represents a linked list. In that case the running time of a binary search would be O(n).

However, what if the tree is only slightly unbalanced, as is teh case for this tree:

Best case would still be O(log n) if I am not mistaken. But what would be the worst case?

答:
In a sorted array of n values, the run-time of binary search for a value, is
O(log n), in the worst case.
 In the best case, the element you are searching for, is in the exact middle, and it can finish up in constant-time.
 In the average case too, the run-time is O(log n).

ContentLicense: CC BY-SA 3.0


问:
Unable to caste a control type to 'System.Web.UI.Webcontrols.Lable type
I have this generic function

```<code>T AddControl<T>() where T : WebControl, new() {
T ctrl = new T();
if (ctrl is Label)  {((Label)ctrl).Text = "FirstName :";}
return ctrl; }
</code>```

I get the error: "Cannot convert Type 'T' to 'System.Web.UI.Webcontrols.Lable'"
What would be the proper way of casting.
Thanks in advance.
BB

答:
You can use as instead:

```<code>T AddControl<T>() where T : WebControl, new() {
    T ctrl = new T();
    Label label = ctrl as Label;
    if (label != null)
    {
        label.Text = "FirstName :";
    }
    return ctrl;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this generic function

T AddControl<T>() where T : WebControl, new() {
T ctrl = new T();
if (ctrl is Label)  {((Label)ctrl).Text = "FirstName :";}
return ctrl; }

I get the error: "Cannot convert Type 'T' to 'System.Web.UI.Webcontrols.Lable'"
What would be the proper way of casting.
Thanks in advance.
BB

Body:
You can use as instead:

T AddControl<T>() where T : WebControl, new() {
    T ctrl = new T();
    Label label = ctrl as Label;
    if (label != null)
    {
        label.Text = "FirstName :";
    }
    return ctrl;
}


问:
Pandas Pyplot Multiple Markers, same line
I have a df:

```<code>time    c_1    c_2   c_3
 t1      v1    NaN    t1
 t2      v2    NaN    NaN
 t3      v3    t3     NaN
 t4      v4    NaN    NaN
 t5      v5    t5     NaN
 t6      v6    NaN    t6
</code>```

How do you:

Use matplotlib.pyplot to plot a line (t1, c_1)

And marks every corresponding point in (c_2) on the line in a particular style (say, green)

And also mark every point in (c_3) on the same line in another style (say, blue)

Then draw a dotted line to connect the markers (t1, t3), t3, t6) and (t5, t6)

I broke the questions down into points so that it is easier to read, but essentially I'm very new to pyplot, and I can't find a way to style 2 different markers in the same syntax. I'm also not very sure how to manipulate the markers, if that even possible..

What is the 'usual' way to accomplish this?

答:
Assume you have this dataframe:

```<code>        c_1  c_2  c_3  time
0  0.548814  NaN  1.0     1
1  0.715189  NaN  NaN     2
2  0.602763  3.0  NaN     3
3  0.544883  NaN  NaN     4
4  0.423655  5.0  NaN     5
5  0.645894  NaN  6.0     6
</code>```

If the following plot is what you're after

it can be produced with the following code:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

time = np.arange(1,7)
c_1 = np.random.rand(6)
c_2 = time*np.array([np.nan, np.nan, 1, np.nan, 1, np.nan])
c_3 = time*np.array([1, np.nan, np.nan, np.nan, np.nan, 1])

df = pd.DataFrame({"time":time, "c_1":c_1,"c_2":c_2,"c_3":c_3 })

ax = df.plot("time", "c_1")
ax.plot(df["c_2"], df["c_1"], marker="s", color="limegreen",  linestyle="")
ax.plot(df["c_3"], df["c_1"], marker="o", color="crimson", linestyle="")

# to be able to draw a line with coordinates
# from two different columns, we need to join them
df2 = df[["c_1","c_2"]].dropna()
df3 = df[["c_1","c_3"]].dropna().rename(columns = {'c_3':'c_2'}, inplace = False)
df4 = pd.concat([df2, df3]).sort_values(by=["c_2"])

ax.plot(df4["c_2"], df4["c_1"], color="burlywood",  linestyle=":", lw=2.5)

ax.set_xlim(0,7)
plt.show()
</code>```

Body:
I have a df:

time    c_1    c_2   c_3
 t1      v1    NaN    t1
 t2      v2    NaN    NaN
 t3      v3    t3     NaN
 t4      v4    NaN    NaN
 t5      v5    t5     NaN
 t6      v6    NaN    t6

How do you:

Use matplotlib.pyplot to plot a line (t1, c_1)

And marks every corresponding point in (c_2) on the line in a particular style (say, green)

And also mark every point in (c_3) on the same line in another style (say, blue)

Then draw a dotted line to connect the markers (t1, t3), t3, t6) and (t5, t6)

I broke the questions down into points so that it is easier to read, but essentially I'm very new to pyplot, and I can't find a way to style 2 different markers in the same syntax. I'm also not very sure how to manipulate the markers, if that even possible..

What is the 'usual' way to accomplish this?

Body:
Assume you have this dataframe:

        c_1  c_2  c_3  time
0  0.548814  NaN  1.0     1
1  0.715189  NaN  NaN     2
2  0.602763  3.0  NaN     3
3  0.544883  NaN  NaN     4
4  0.423655  5.0  NaN     5
5  0.645894  NaN  6.0     6

If the following plot is what you're after

it can be produced with the following code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

time = np.arange(1,7)
c_1 = np.random.rand(6)
c_2 = time*np.array([np.nan, np.nan, 1, np.nan, 1, np.nan])
c_3 = time*np.array([1, np.nan, np.nan, np.nan, np.nan, 1])

df = pd.DataFrame({"time":time, "c_1":c_1,"c_2":c_2,"c_3":c_3 })

ax = df.plot("time", "c_1")
ax.plot(df["c_2"], df["c_1"], marker="s", color="limegreen",  linestyle="")
ax.plot(df["c_3"], df["c_1"], marker="o", color="crimson", linestyle="")

# to be able to draw a line with coordinates
# from two different columns, we need to join them
df2 = df[["c_1","c_2"]].dropna()
df3 = df[["c_1","c_3"]].dropna().rename(columns = {'c_3':'c_2'}, inplace = False)
df4 = pd.concat([df2, df3]).sort_values(by=["c_2"])

ax.plot(df4["c_2"], df4["c_1"], color="burlywood",  linestyle=":", lw=2.5)

ax.set_xlim(0,7)
plt.show()


问:
Spring Boot + IntelliJ + Embedded Database = Headache
Either I'm missing some core concept buried deep within some documentation (Spring, Spring Boot, H2, HSQLDB, Derby, IntelliJ) or I've been staring at this for too long.

I have a Spring Boot project going. Tried using and initializing an H2 DB at first, tried connecting to it in IntelliJ only to realize that I might not be able to easily browse the db without giving up my firstborn child (Connect to H2 database using IntelliJ database client).

So I moved to DerbyDB. Same thing - db root folder is created in my app, I connect to it in IntelliJ but my tables, that were just created from starting the app are not available to browse.

I even tried SQLite, but support for SQLite is not as good and certain update functions were not available, but I could atleast find my tables in IntelliJ browser!

I just want a simple single file embedded DB that I can use, browse, and play with easily. Any suggestions?!

When I run the application, I see that the schema is exported:

```<code>2015-07-19 09:37:45.836  INFO 98608 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
Hibernate: drop table user_roles if exists
Hibernate: drop table users if exists
Hibernate: create table user_roles (id bigint generated by default as identity, role_name varchar(255), version bigint, user_id bigint, primary key (id))
Hibernate: create table users (id bigint generated by default as identity, email varchar(255), password varchar(255), username varchar(255), version bigint, primary key (id))
Hibernate: alter table user_roles add constraint FK_g1uebn6mqk9qiaw45vnacmyo2 foreign key (user_id) references users
2015-07-19 09:37:45.849  INFO 98608 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete
</code>```

In IntelliJ, nothing (using a remote source of jdbc:h2:./test;AUTO_SERVER=TRUE as per heenenee suggestion):

I see some votes to close because its unclear what I'm asking:

How do I develop applications using H2, HSQLDB, or Derby databases and connect to them with IntelliJ?

答:
I had similar problem. It was due to the default create-drop ddl strategy of the hibernate.
With this strategy after the application shutdown hibernate destroys the schema at the end of the session, that's why IntelliJ don't show anything. Change ddl strategy to the create and hibernate will create the schema and destroy previous data on the next application startup.

Here is an example of my configuration:

application.yml

```<code>spring:
  datasource.url: jdbc:h2:./db/testDb
  jpa.hibernate.ddl-auto: create
</code>```

IntelliJ database properties

Result

Body:
Either I'm missing some core concept buried deep within some documentation (Spring, Spring Boot, H2, HSQLDB, Derby, IntelliJ) or I've been staring at this for too long.

I have a Spring Boot project going. Tried using and initializing an H2 DB at first, tried connecting to it in IntelliJ only to realize that I might not be able to easily browse the db without giving up my firstborn child (Connect to H2 database using IntelliJ database client).

So I moved to DerbyDB. Same thing - db root folder is created in my app, I connect to it in IntelliJ but my tables, that were just created from starting the app are not available to browse.

I even tried SQLite, but support for SQLite is not as good and certain update functions were not available, but I could atleast find my tables in IntelliJ browser!

I just want a simple single file embedded DB that I can use, browse, and play with easily. Any suggestions?!

When I run the application, I see that the schema is exported:

2015-07-19 09:37:45.836  INFO 98608 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
Hibernate: drop table user_roles if exists
Hibernate: drop table users if exists
Hibernate: create table user_roles (id bigint generated by default as identity, role_name varchar(255), version bigint, user_id bigint, primary key (id))
Hibernate: create table users (id bigint generated by default as identity, email varchar(255), password varchar(255), username varchar(255), version bigint, primary key (id))
Hibernate: alter table user_roles add constraint FK_g1uebn6mqk9qiaw45vnacmyo2 foreign key (user_id) references users
2015-07-19 09:37:45.849  INFO 98608 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete

In IntelliJ, nothing (using a remote source of jdbc:h2:./test;AUTO_SERVER=TRUE as per heenenee suggestion):

I see some votes to close because its unclear what I'm asking:

How do I develop applications using H2, HSQLDB, or Derby databases and connect to them with IntelliJ?

Body:
I had similar problem. It was due to the default create-drop ddl strategy of the hibernate.
With this strategy after the application shutdown hibernate destroys the schema at the end of the session, that's why IntelliJ don't show anything. Change ddl strategy to the create and hibernate will create the schema and destroy previous data on the next application startup.

Here is an example of my configuration:

application.yml

spring:
  datasource.url: jdbc:h2:./db/testDb
  jpa.hibernate.ddl-auto: create

IntelliJ database properties

Result


问:
Call Activity's method on notification
I have an Activity with 2 buttons. A play and a pause button.
When this activity gets in the background, which means when the onStop() method has bean called, this creates a permanent notification that is only destroyed when the activity is resumed.
The notification does provide the play and pause buttons too. How do I call the activity's play() and pause() methods when the notification's buttons are clicked?
I really have no clue on how to address that issue.
I'm using a RemoteViews to construct a custom layout. And I know you can call
setOnClickPendingIntent() to bind an Intent to a view.

big thanks.

答: Instead of calling activity methods, you can use a service to initialize a media player instance and play or pause by passing intent extras. This way you would have more and easier control over the player. </p>

Title: Call Activity's method on notification


问:
How the rails find the controller from routes?
I am learning rails. I would like to check the convention here,

say, if I have a comment resource, will the rails always to find action in the comments_controller, no matter the rource is independent or nested in another resource?

A:

```<code>resources :comments
</code>```

B:

```<code>resources :blogs do
    resources :comments
end
</code>```

答: Yes, it will always use CommentsController. But using nested resources you will also have the blog_id set in params. You can read more on here, with detailed description and examples: http://guides.rubyonrails.org/routing.html#nested-resources

Body:
I am learning rails. I would like to check the convention here,

say, if I have a comment resource, will the rails always to find action in the comments_controller, no matter the rource is independent or nested in another resource?

A:

resources :comments

B:

resources :blogs do
    resources :comments
end


问:
Generate 2D bar code (e.g. QR Code, Data Matrix, PDF417) on iPhone and Android
I need a library to generate a 2D bar code on iPhone and Android (and preferably WM7 and possibly j2me too) - the idea is to transfer information to another device with a corresponding scanner (decoder). What are the good options?

ZXing is an option, in particular for the reading/decoding aspect, but I want to generate them on these devices.

答: Best option should be ZXing's library. I'm not sure about the Windows Phone 7 support tho.</p>


问:
WebRequest.GetRequestStream() Immediately sending Request Body
I am trying to send xml data to a web server through a POST request. I need to send request in chunks in order to track progress.

I have realised that when I set:

```<code>webRequest.SendChunked = true
</code>```

an empty request body is sent to the server when GetRequestStream() is called. However, when SendChunked is false and GetRequestStream() is called, no request is sent to the server until I am done writing to the stream and closed it or called GetResponse.

The following is that part of my code:

```<code>HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.Accept = "application/xml";
webRequest.AllowWriteStreamBuffering = false;
webRequest.SendChunked = true;

// get the bytes.
byte[] xmlBytes = Encoding.UTF8.GetBytes(this.reqStrTpl);
// webRequest.ContentLength = xmlBytes.Length;

Stream requestStream = webRequest.GetRequestStream();
</code>```

From the code as SendChunked is set to true, an empty request body is sent to the server at this call:

```<code>Stream requestStream = webRequest.GetRequestStream();
</code>```

even before I write into the stream. However, if SendChunked = false and I set the ContentLength, no request body is sent until I have written into the stream and called GetResponse.

I want to know what I am doing wrong with sending in chunks causing an empty body to be sent when GetRequestStream() is called whiles I have not even written into the stream. Thanks in advance.

答:
OK I found the solution. Just to help those who may be having similar problems:

The problem was that I was using PHP as CGI/FastCGI which is not able to handle chunked transfer properly. This is reported as a bug here: https://bugs.php.net/bug.php?id=60826. I don't know if there is a fix yet.

The solution is to use PHP as apache handler. I did that and now when WebRequest.GetRequestStream() is called, I get the chance to write the body in chunks and it works perfectly. I captured the network packets and I could confirm that the request body was sent in chunks as I write them in the stream.

Another important thing to note is that the Transfer-Encoding: chunked specification indicates that the data must be preceded by the data length in hexadecimal value followed by \r\n. For example:

```<code>D\r\nDaniel Oppong\r\n0\r\n\r\n
</code>```

where D is a hexadecimal value for the data length which is 13.

When writing the data bytes do not write these yourself as it will automatically be done by the Request Object. I was initially writing them myself and realised that they are also written in data received on the server. I then thought of writing the data only and by observing the network packets, these characters were already written as part of the data before being sent. Data received on the server was complete as expected.

I hope this will help others who will be having similar problems.

Body:
I am trying to send xml data to a web server through a POST request. I need to send request in chunks in order to track progress.

I have realised that when I set:

webRequest.SendChunked = true

an empty request body is sent to the server when GetRequestStream() is called. However, when SendChunked is false and GetRequestStream() is called, no request is sent to the server until I am done writing to the stream and closed it or called GetResponse.

The following is that part of my code:

HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.Accept = "application/xml";
webRequest.AllowWriteStreamBuffering = false;
webRequest.SendChunked = true;

// get the bytes.
byte[] xmlBytes = Encoding.UTF8.GetBytes(this.reqStrTpl);
// webRequest.ContentLength = xmlBytes.Length;

Stream requestStream = webRequest.GetRequestStream();

From the code as SendChunked is set to true, an empty request body is sent to the server at this call:

Stream requestStream = webRequest.GetRequestStream();

even before I write into the stream. However, if SendChunked = false and I set the ContentLength, no request body is sent until I have written into the stream and called GetResponse.

I want to know what I am doing wrong with sending in chunks causing an empty body to be sent when GetRequestStream() is called whiles I have not even written into the stream. Thanks in advance.

Body:
OK I found the solution. Just to help those who may be having similar problems:

The problem was that I was using PHP as CGI/FastCGI which is not able to handle chunked transfer properly. This is reported as a bug here: https://bugs.php.net/bug.php?id=60826. I don't know if there is a fix yet.

The solution is to use PHP as apache handler. I did that and now when WebRequest.GetRequestStream() is called, I get the chance to write the body in chunks and it works perfectly. I captured the network packets and I could confirm that the request body was sent in chunks as I write them in the stream.

Another important thing to note is that the Transfer-Encoding: chunked specification indicates that the data must be preceded by the data length in hexadecimal value followed by \r\n. For example:

D\r\nDaniel Oppong\r\n0\r\n\r\n

where D is a hexadecimal value for the data length which is 13.

When writing the data bytes do not write these yourself as it will automatically be done by the Request Object. I was initially writing them myself and realised that they are also written in data received on the server. I then thought of writing the data only and by observing the network packets, these characters were already written as part of the data before being sent. Data received on the server was complete as expected.

I hope this will help others who will be having similar problems.


问:
Function not working on resize
What I am trying to achieve is:

A button is added either before or after a menu item, depending on browser size.  This works fine on load.

On resize, check for buttons in the 'wrong' place, remove them and add them in the right place.  This is not working.

```<code>var masthead         = $('#masthead');
var dropdownToggle   = $('<button />', {'class': 'dropdown-toggle','aria-expanded': false})
var width            = $(window).innerWidth();

function addDropdowns() {
    if (width > 991) {
        $('.menu-item-has-children > a').after(dropdownToggle);  // On desktop, add the dropdown after the link
    } else {
        $(dropdownToggle).insertBefore('.menu-item-has-children > a'); // On mobile, add the dropdown before the link
    }
    }
addDropdowns();

var dropdownDesktop  = masthead.find('.menu-item-has-children > a + button');
var dropdownMobile   = masthead.find('.menu-item-has-children > button + a');
var dropdownToggles  = masthead.find('button.dropdown-toggle');

var resizeTimer;

$(window).on('resize', function(e) {

clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {

if (width > 991) {                              // if desktop ...

        if (dropdownMobile.length != 0) {       // do mobile dropdowns exist
            dropdownToggles.remove();           // if they do, remove them
        } else {
            if (dropdownDesktop.length != 0) {  // do desktop dropdowns exist
                return;                         // if they do, do nothing
            } else {
                addDropdowns();                 // if they do not, add them
            }
        }

    } else {                                    // if mobile ...

        if (dropdownDesktop.length != 0) {      // do desktop dropdowns exist
           dropdownToggles.remove();            // if they do, remove them
        } else {
           if (dropdownMobile.length != 0) {    // do mobile dropdowns exist
            return;                             // if they do, do nothing
                } else {
                 addDropdowns();                // if they do not, add them
                }
        }
    }
  }, 250);
});
</code>```

Outside of this function, (dropdownMobile.length != 0) and (dropdownDesktop.length != 0) evaluate correctly and (dropdownToggles.remove(); works too.  I am very new to JQuery and Javascript, and have been searching for an answer all weekend.  Any pointers gratefully received.

答:
Your problem is width is defined on pageload and not on resize.

```<code>var width            = $(window).innerWidth();
</code>```

Define width in resize function:

```<code>$(window).on('resize', function(e) {
    var resizeWidth = window.innerWidth;

    if(resizeWidth < 991) {
       // Do something

    }
}
</code>```

What I would also suggest use Throttling or Debounce on 'resize' because it is quite a heavy task for the browser to do this check without Debounce or Throttle.

"Debounce limits the rate at which a function can fire. A quick example:  you have a resize listener on the window which does some element dimension calculations and (possibly)  repositions a few elements.  That isn't a heavy task in itself but being repeatedly fired after numerous resizes will really slow your site down. "

Title: Function not working on resize

Body:
What I am trying to achieve is:

A button is added either before or after a menu item, depending on browser size.  This works fine on load.

On resize, check for buttons in the 'wrong' place, remove them and add them in the right place.  This is not working.

var masthead         = $('#masthead');
var dropdownToggle   = $('<button />', {'class': 'dropdown-toggle','aria-expanded': false})
var width            = $(window).innerWidth();

function addDropdowns() {
    if (width > 991) {
        $('.menu-item-has-children > a').after(dropdownToggle);  // On desktop, add the dropdown after the link
    } else {
        $(dropdownToggle).insertBefore('.menu-item-has-children > a'); // On mobile, add the dropdown before the link
    }
    }
addDropdowns();

var dropdownDesktop  = masthead.find('.menu-item-has-children > a + button');
var dropdownMobile   = masthead.find('.menu-item-has-children > button + a');
var dropdownToggles  = masthead.find('button.dropdown-toggle');

var resizeTimer;

$(window).on('resize', function(e) {

clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {

if (width > 991) {                              // if desktop ...

        if (dropdownMobile.length != 0) {       // do mobile dropdowns exist
            dropdownToggles.remove();           // if they do, remove them
        } else {
            if (dropdownDesktop.length != 0) {  // do desktop dropdowns exist
                return;                         // if they do, do nothing
            } else {
                addDropdowns();                 // if they do not, add them
            }
        }

    } else {                                    // if mobile ...

        if (dropdownDesktop.length != 0) {      // do desktop dropdowns exist
           dropdownToggles.remove();            // if they do, remove them
        } else {
           if (dropdownMobile.length != 0) {    // do mobile dropdowns exist
            return;                             // if they do, do nothing
                } else {
                 addDropdowns();                // if they do not, add them
                }
        }
    }
  }, 250);
});

Outside of this function, (dropdownMobile.length != 0) and (dropdownDesktop.length != 0) evaluate correctly and (dropdownToggles.remove(); works too.  I am very new to JQuery and Javascript, and have been searching for an answer all weekend.  Any pointers gratefully received.

Body:
Your problem is width is defined on pageload and not on resize.

var width            = $(window).innerWidth();

Define width in resize function:

$(window).on('resize', function(e) {
    var resizeWidth = window.innerWidth;

    if(resizeWidth < 991) {
       // Do something

    }
}

What I would also suggest use Throttling or Debounce on 'resize' because it is quite a heavy task for the browser to do this check without Debounce or Throttle.

"Debounce limits the rate at which a function can fire. A quick example:  you have a resize listener on the window which does some element dimension calculations and (possibly)  repositions a few elements.  That isn't a heavy task in itself but being repeatedly fired after numerous resizes will really slow your site down. "


问:
How to generate equal amount of different strings
I have this now:

```<code>var generateIcons = function(playtime, players) {
var count = playtime / 2;
icons = [];
for (var i = 1; i <= count; i++) {
    if (i % 8 === 0 && players === 8) {
        icons.push("cyan");
    }
    else if (i % 7 === 0 && players >= 7) {
        icons.push("violet");
    }
    else if (i % 6 === 0 && players >= 6) {
        icons.push("orange");
    }
    else if (i % 5 === 0 && players >= 5) {
        icons.push("black");
    }
    else if (i % 4 === 0 && players >= 4) {
        icons.push("gold");
    }
    else if (i % 3 === 0 && players >= 3) {
        icons.push("red");
    }
    else if (i % 2 === 0 && players >= 2) {
        icons.push("blue");
    }
    else {
        icons.push("green");
    }
}
};
</code>```

The problem is that, I get much more green than blue for example with: generateIcons(60,4);
How to get ~equal amount of green, blue, red, gold?

答:
So, if I understand your problem correctly, this should work:

var generateIcons = function(playtime, players) {
    var count = playtime / 2;
    icons = [];
    colors = ["cyan", "violet", "orange", "black", "gold", "red", "blue", "green"];
    for (var i = 0; i < count; i++) {
     icons.push(colors[i % players]);
    }
    return icons;
};

console.log(generateIcons(60, 4));```

Body:
I have this now:

var generateIcons = function(playtime, players) {
var count = playtime / 2;
icons = [];
for (var i = 1; i <= count; i++) {
    if (i % 8 === 0 && players === 8) {
        icons.push("cyan");
    }
    else if (i % 7 === 0 && players >= 7) {
        icons.push("violet");
    }
    else if (i % 6 === 0 && players >= 6) {
        icons.push("orange");
    }
    else if (i % 5 === 0 && players >= 5) {
        icons.push("black");
    }
    else if (i % 4 === 0 && players >= 4) {
        icons.push("gold");
    }
    else if (i % 3 === 0 && players >= 3) {
        icons.push("red");
    }
    else if (i % 2 === 0 && players >= 2) {
        icons.push("blue");
    }
    else {
        icons.push("green");
    }
}
};

The problem is that, I get much more green than blue for example with: generateIcons(60,4);
How to get ~equal amount of green, blue, red, gold?


问:
invalid operands of types 'double' and 'double' to binary 'operator%'
while solving a question on hackerearth i got this error , i tried to find solution but everywhere this error occurs when 2 different datatypes are used as operands but in my case both the operands  of sama data type, here is my full code</p>

```<code>#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    int arr[1000];
    int n;
    cin>>n;
    double ans=1;
    for(int i =0; i<n ;i++)
    {
        cin >> arr[i];
        ans=(ans*arr[i])%(pow(10,9)+7);
    }
    cout << ans;
    return 0;

}
</code>```

答:
Module operator (i.e. operator%) is not defined for floating points, but for integers only.

As you declared ans as a double, your expression ans*arr[i] evaluates as a double. Changing it to int ans will have the erroneous statement to compile (actually returning the integer modulo).

Body:
while solving a question on hackerearth i got this error , i tried to find solution but everywhere this error occurs when 2 different datatypes are used as operands but in my case both the operands  of sama data type, here is my full code

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    int arr[1000];
    int n;
    cin>>n;
    double ans=1;
    for(int i =0; i<n ;i++)
    {
        cin >> arr[i];
        ans=(ans*arr[i])%(pow(10,9)+7);
    }
    cout << ans;
    return 0;

}


问:
Convert SAS code to Pandas equivalent for groupby.first() and retain function
I have SAS code i need to convert into python pandas.

```<code>   data df1;
   set df;
       by id;
       retain flag_final;
       if first.id then do;
          if flag eq 0 then flag_final=flag;
          else flag_final=.;
       end;
       else do;
          flag_final=flag_final;
   run;
</code>```

I tried something like this in pandas but its not working i mean am not able to put if else condition into my merge clause. If some one has better idea how to get it done it would be very helpful

```<code>  df_temp=df[['id','flag']]
  df1= df.merge(df_temp.groupby('id').first().reset_index(), on='id').rename(
columns={'flag_x':'flag', 'flag_y':'flag_final'})
</code>```

Note: Even i am not able to understand obove SAS code. So can not put any example input and output dataset. If some knows SAS well can help me to understand it then might be possible i can convert it into pandas. Or you have some approach please suggest.

Edit: Adding input and output dataset:

Input Dataframe:

```<code>  import pandas as pd
  import numpy as np

 df = pd.DataFrame({'id': [1,1,2,1,2,2,3,3,4,3,3,4,4,4], 'flag': [np.nan,0,1,'p','q',0,"",2,0,'r',np.nan,0,1,np.nan]})
 df=df.sort_values('id')

  id      flag

  1         NaN
  1         0
  1         p
  2         1
  2         q
  2         0
  3         ""
  3         2
  3         r
  3         NaN
  4         0
  4         0
  4         1
  4        NaN
</code>```

Output dataset:

```<code>  id      flag     flag_final

  1         NaN     .
  1         0       .
  1         p       .
  2         1       .
  2         q       .
  2         0       .
  3         ""      .
  3         2       .
  3         r       .
  3         NaN     .
  4         0       0
  4         0       0
  4         1       0
  4        NaN      0
</code>```

I tried like this but its not working:

```<code>df=df.sort_values('id')
df.loc[:,'flag_final']=df
df['flag_final']=np.where(df['id'].first,np.where(df['flag'].iloc[0]==0,df['flag'],'.'),np.nan)
</code>```

答:
Here You go:

```<code>dfy = pd.DataFrame({'id': [1,1,2,1,2,2,3,3,4,3,3,4,4,4], 'flag': [np.nan,0,1,'p','q',0,"",2,0,'r',np.nan,0,1,np.nan]})
dfy["flag_final"] = np.nan
def func1(group):
    if group.flag.values[0] == 0:
        group.flag_final.values[0] = "0"
    else:
        group.flag_final.values[0] = "1"
    return group

dfy.sort_values('id', inplace=True)
dfy = dfy.groupby(['id']).apply(func1).fillna(method='ffill')
dfy["flag_final"] = dfy["flag_final"].map({0:0, 1:"." })
</code>```

I am trying to figure out how to add an empty object column with NaN Values so that I can eliminate the last line by just changing the "1" in function func1 to "."

Body:
I have SAS code i need to convert into python pandas.

   data df1;
   set df;
       by id;
       retain flag_final;
       if first.id then do;
          if flag eq 0 then flag_final=flag;
          else flag_final=.;
       end;
       else do;
          flag_final=flag_final;
   run;

I tried something like this in pandas but its not working i mean am not able to put if else condition into my merge clause. If some one has better idea how to get it done it would be very helpful

  df_temp=df[['id','flag']]
  df1= df.merge(df_temp.groupby('id').first().reset_index(), on='id').rename(
columns={'flag_x':'flag', 'flag_y':'flag_final'})

Note: Even i am not able to understand obove SAS code. So can not put any example input and output dataset. If some knows SAS well can help me to understand it then might be possible i can convert it into pandas. Or you have some approach please suggest.

Edit: Adding input and output dataset:

Input Dataframe:

  import pandas as pd
  import numpy as np

 df = pd.DataFrame({'id': [1,1,2,1,2,2,3,3,4,3,3,4,4,4], 'flag': [np.nan,0,1,'p','q',0,"",2,0,'r',np.nan,0,1,np.nan]})
 df=df.sort_values('id')

  id      flag

  1         NaN
  1         0
  1         p
  2         1
  2         q
  2         0
  3         ""
  3         2
  3         r
  3         NaN
  4         0
  4         0
  4         1
  4        NaN

Output dataset:

  id      flag     flag_final

  1         NaN     .
  1         0       .
  1         p       .
  2         1       .
  2         q       .
  2         0       .
  3         ""      .
  3         2       .
  3         r       .
  3         NaN     .
  4         0       0
  4         0       0
  4         1       0
  4        NaN      0

I tried like this but its not working:

df=df.sort_values('id')
df.loc[:,'flag_final']=df
df['flag_final']=np.where(df['id'].first,np.where(df['flag'].iloc[0]==0,df['flag'],'.'),np.nan)

Body:
Here You go:

dfy = pd.DataFrame({'id': [1,1,2,1,2,2,3,3,4,3,3,4,4,4], 'flag': [np.nan,0,1,'p','q',0,"",2,0,'r',np.nan,0,1,np.nan]})
dfy["flag_final"] = np.nan
def func1(group):
    if group.flag.values[0] == 0:
        group.flag_final.values[0] = "0"
    else:
        group.flag_final.values[0] = "1"
    return group

dfy.sort_values('id', inplace=True)
dfy = dfy.groupby(['id']).apply(func1).fillna(method='ffill')
dfy["flag_final"] = dfy["flag_final"].map({0:0, 1:"." })

I am trying to figure out how to add an empty object column with NaN Values so that I can eliminate the last line by just changing the "1" in function func1 to "."


问:
how to auto increment a number everytime when a button is clicked on other page using javascript
I have a form created using HTML and CSS, this form is not for submitting any data in fact it's only for printing purposes.

This form has an input field at top left corner to put a unique 6 digit number to uniquely identify each form.

On the homepage, there is a button link to that form page and I want to increment that serial no which is by default 000000 every time a link button to this form page is clicked.

index.html:

```<code><a href="pages/form-1.html"></a>
</code>```

form-1.html:

```<code><input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
</code>```

答:
You have two solution:

Using cookie

Using browser-session

Note: Please comment another solution, while using one solution

main-page.html

```<code><html>
    <head>
        <title>Main Page</title>
    </head>
    <body>
        <a href="form-1.html">Print</a>
    </body>
</html>
</code>```

form-1.html

```<code><html>
    <head>
        <title>Form Printing</title>
    </head>
    <body onload="loadNextSeqToForm()">
        <form>
            <input id="serial" class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
        </form>
    </body>
    <script>
        /*
        //Solution 1: Using Cookies
        function getNextSeq() {
           var decodedCookie = decodeURIComponent(document.cookie);
           var ca = decodedCookie.split(';');
           for(var i = 0; i <ca.length; i++) {
               var c = ca[i];
               while (c.charAt(0) == ' ') {
                   c = c.substring(1);//Trim the empty space if exists
               }
               if (c.indexOf("next") == 0) {
                var fragments = c.split("=");
                if(fragments.length == 2 && !isNaN(fragments[1])) {
                    return parseInt(fragments[1]) + 1;
                }
               }
           }
           return "1";//default
        }
        function loadNextSeqToForm() {
           var nextValue = getNextSeq();
           document.cookie = "next=" + nextValue + ";";
           document.getElementById("serial").value = formatToSixCharacters(nextValue);
        }

        function formatToSixCharacters(num) {
           var numStr = num + "";
           if(numStr.length < 6) {
               var zeros = 6 - numStr.length;
               for(var i = 1; i <= zeros; i++) {
                   numStr = "0" + numStr;
               }
            }
            return numStr;
        }
        */

        //Solution 2: Using Session
        function loadNextSeqToForm() {
            var nextValue = sessionStorage.getItem("next") != null? sessionStorage.getItem("next") : 1;
            document.getElementById("serial").value = formatToSixCharacters(nextValue);
            sessionStorage.setItem("next", parseInt(nextValue) + 1)
        }

        function formatToSixCharacters(num) {
            var numStr = num + "";
            if(numStr.length < 6) {
                var zeros = 6 - numStr.length;
                for(var i = 1; i <= zeros; i++) {
                    numStr = "0" + numStr;
                }
            }
            return numStr;
        }
    </script>
</html>
</code>```

++ Code using PHP and MySQL

main-page.html

```<code><html>
    <head>
        <title>Main Page</title>
    </head>
    <body>
        <!-- Note this time we have to use PHP file reference -->
        <a href="form-1.php">Print</a>
    </body>
</html>
</code>```

form-1.php

```<code><?php
session_start();
function getNextSequnceNumber() {
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "orders";
    $nextSeq = 1;
    $conn = new mysqli($servername, $username, $password, $dbname);
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    $sql = "SELECT next_seq FROM order_sequence";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        if($row = $result->fetch_assoc()) {
            $nextSeq = $row["next_seq"];
        }
    }
    //Update next sequence number in db
    $sql = "UPDATE order_sequence SET next_seq = ".($nextSeq + 1);
    if (mysqli_query($conn, $sql)) {
        //Updated successfully
        //Write in log may be
    }
    $conn->close();
    return formatToSixCharacters($nextSeq);
}
function formatToSixCharacters($num) {
    $numStr = $num . "";
    if(strlen($numStr) < 6) {
        $zeros = 6 - strlen($numStr);
        for($i = 1; $i <= $zeros; $i++) {
            $numStr = "0" . $numStr;
        }
    }
    return $numStr;
}
?>
<html>
    <head>
        <title>Form Printing</title>
    </head>
    <body>
        <form>
            <input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
        </form>
    </body>
</html>
</code>```

DB Scripts

```<code>CREATE DATABASE orders;
USE orders;
CREATE TABLE order_sequence (
    next_seq INT NOT NULL
);
-- DEFAULT VALUE
INSERT INTO order_sequence (next_seq)
    VALUES(1);
</code>```

Note: Make sure you replace your DB user name and password

SQLITE3 version of code as requested

form-sqlite.php

```<code><?php
session_start();
class DBUtil extends SQLite3 {
    function __construct() {
        //Open db
        $this->open("orders.db");
    }

    function createTableIfNotExists() {
        //create table if not exists already
        $sql = "CREATE TABLE IF NOT EXISTS order_sequence ("
            ."    next_seq INT NOT NULL"
            .")";
        $result = $this->exec($sql);
        return $result;//Whether table created successfully or not
    }

    function updateNextSeqNumber($nextSeq) {
        //update next sequnce number in db
        $sql = "UPDATE order_sequence SET next_seq = ".$nextSeq;
        $result = $this->exec($sql);
        return $result;
    }

    function insertFirstTime() {
        //insert first time
        $sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
        $result = $this->exec($sql);
        return $result;
    }

    function getNextSeq() {
        //get next sequence number
        $sql = "SELECT next_seq FROM order_sequence";
        $result = $this->query($sql);
        $nextSeq = 1;
        if($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $nextSeq = $row["next_seq"];
        } else {
            $this->insertFirstTime();//First sequence number, so that next update queries will be always successfull
        }
        $this->updateNextSeqNumber($nextSeq + 1);
        return $nextSeq;
    }
}

function getNextSequnceNumber() {
    //Create new object of utility class
    $db = new DBUtil();
    if(!$db){
        die("Connection failed: " . $db->lastErrorMsg());
    }
    //Check if connected
    if($db->createTableIfNotExists()) {
        $nextSeq = $db->getNextSeq();
        return formatToSixCharacters($nextSeq);
    } else {
        die ("Error: " . $db->lastErrorMsg());
    }
    //close connection finally
    $db->close();
}

function formatToSixCharacters($num) {
    $numStr = $num . "";
    if(strlen($numStr) < 6) {
        $zeros = 6 - strlen($numStr);
        for($i = 1; $i <= $zeros; $i++) {
            $numStr = "0" . $numStr;
        }
    }
    return $numStr;
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Form Printing</title>
    </head>
    <body>
        <form>
            <input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
        </form>
    </body>
</html>
</code>```

++PHPDesktop With Sqlite Version

form-php-desktop-sqlite.php

Please include this PHPDesktop Helper file pdo.php provided by PHPDesktop. However this is small helper file, it does not serve big purpose, but it will help you for now.

Also read Using Sqlite with PHP Desktop

```<code><?php
session_start();
include "./pdo.php";

function getNextSequnceNumber() {
    //Open connection
    $db_file = "./orders.sqlite3";
    PDO_Connect("sqlite:$db_file");
    //Create table if not exists
    $sql = "CREATE TABLE IF NOT EXISTS order_sequence ("
        ."    next_seq INT NOT NULL"
        .")";
    PDO_Execute($sql);

    //get next sequence number
    $sql = "SELECT next_seq FROM order_sequence";
    $nextSeq = PDO_FetchOne($sql);
    if($nextSeq == null) {
        $nextSeq = 1;
        //Also insert first time record
        $sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
        PDO_Execute($sql);
    }
    //Update next time sequence
    $sql = "UPDATE order_sequence SET next_seq = ".($nextSeq + 1);
    PDO_Execute($sql);
    return formatToSixCharacters($nextSeq);
}

function formatToSixCharacters($num) {
    $numStr = $num . "";
    if(strlen($numStr) < 6) {
        $zeros = 6 - strlen($numStr);
        for($i = 1; $i <= $zeros; $i++) {
            $numStr = "0" . $numStr;
        }
    }
    return $numStr;
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Form Printing</title>
    </head>
    <body>
        <form>
            <input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
        </form>
    </body>
</html>
</code>```

Body:
I have a form created using HTML and CSS, this form is not for submitting any data in fact it's only for printing purposes.

This form has an input field at top left corner to put a unique 6 digit number to uniquely identify each form.

On the homepage, there is a button link to that form page and I want to increment that serial no which is by default 000000 every time a link button to this form page is clicked.

index.html:

form-1.html:

<input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">

Body:
You have two solution:

Using cookie

Using browser-session

Note: Please comment another solution, while using one solution

main-page.html

<html>
    <head>
        <title>Main Page</title>
    </head>
    <body>
        <a href="form-1.html">Print</a>
    </body>
</html>

form-1.html

<html>
    <head>
        <title>Form Printing</title>
    </head>
    <body onload="loadNextSeqToForm()">
        <form>
            <input id="serial" class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
        </form>
    </body>
    <script>
        /*
        //Solution 1: Using Cookies
        function getNextSeq() {
           var decodedCookie = decodeURIComponent(document.cookie);
           var ca = decodedCookie.split(';');
           for(var i = 0; i <ca.length; i++) {
               var c = ca[i];
               while (c.charAt(0) == ' ') {
                   c = c.substring(1);//Trim the empty space if exists
               }
               if (c.indexOf("next") == 0) {
                var fragments = c.split("=");
                if(fragments.length == 2 && !isNaN(fragments[1])) {
                    return parseInt(fragments[1]) + 1;
                }
               }
           }
           return "1";//default
        }
        function loadNextSeqToForm() {
           var nextValue = getNextSeq();
           document.cookie = "next=" + nextValue + ";";
           document.getElementById("serial").value = formatToSixCharacters(nextValue);
        }

        function formatToSixCharacters(num) {
           var numStr = num + "";
           if(numStr.length < 6) {
               var zeros = 6 - numStr.length;
               for(var i = 1; i <= zeros; i++) {
                   numStr = "0" + numStr;
               }
            }
            return numStr;
        }
        */

        //Solution 2: Using Session
        function loadNextSeqToForm() {
            var nextValue = sessionStorage.getItem("next") != null? sessionStorage.getItem("next") : 1;
            document.getElementById("serial").value = formatToSixCharacters(nextValue);
            sessionStorage.setItem("next", parseInt(nextValue) + 1)
        }

        function formatToSixCharacters(num) {
            var numStr = num + "";
            if(numStr.length < 6) {
                var zeros = 6 - numStr.length;
                for(var i = 1; i <= zeros; i++) {
                    numStr = "0" + numStr;
                }
            }
            return numStr;
        }
    </script>
</html>

++ Code using PHP and MySQL

main-page.html

<html>
    <head>
        <title>Main Page</title>
    </head>
    <body>
        <!-- Note this time we have to use PHP file reference -->
        <a href="form-1.php">Print</a>
    </body>
</html>

form-1.php

<?php
session_start();
function getNextSequnceNumber() {
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "orders";
    $nextSeq = 1;
    $conn = new mysqli($servername, $username, $password, $dbname);
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    $sql = "SELECT next_seq FROM order_sequence";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        if($row = $result->fetch_assoc()) {
            $nextSeq = $row["next_seq"];
        }
    }
    //Update next sequence number in db
    $sql = "UPDATE order_sequence SET next_seq = ".($nextSeq + 1);
    if (mysqli_query($conn, $sql)) {
        //Updated successfully
        //Write in log may be
    }
    $conn->close();
    return formatToSixCharacters($nextSeq);
}
function formatToSixCharacters($num) {
    $numStr = $num . "";
    if(strlen($numStr) < 6) {
        $zeros = 6 - strlen($numStr);
        for($i = 1; $i <= $zeros; $i++) {
            $numStr = "0" . $numStr;
        }
    }
    return $numStr;
}
?>
<html>
    <head>
        <title>Form Printing</title>
    </head>
    <body>
        <form>
            <input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
        </form>
    </body>
</html>

DB Scripts

CREATE DATABASE orders;
USE orders;
CREATE TABLE order_sequence (
    next_seq INT NOT NULL
);
-- DEFAULT VALUE
INSERT INTO order_sequence (next_seq)
    VALUES(1);

Note: Make sure you replace your DB user name and password

SQLITE3 version of code as requested

form-sqlite.php

<?php
session_start();
class DBUtil extends SQLite3 {
    function __construct() {
        //Open db
        $this->open("orders.db");
    }

    function createTableIfNotExists() {
        //create table if not exists already
        $sql = "CREATE TABLE IF NOT EXISTS order_sequence ("
            ."    next_seq INT NOT NULL"
            .")";
        $result = $this->exec($sql);
        return $result;//Whether table created successfully or not
    }

    function updateNextSeqNumber($nextSeq) {
        //update next sequnce number in db
        $sql = "UPDATE order_sequence SET next_seq = ".$nextSeq;
        $result = $this->exec($sql);
        return $result;
    }

    function insertFirstTime() {
        //insert first time
        $sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
        $result = $this->exec($sql);
        return $result;
    }

    function getNextSeq() {
        //get next sequence number
        $sql = "SELECT next_seq FROM order_sequence";
        $result = $this->query($sql);
        $nextSeq = 1;
        if($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $nextSeq = $row["next_seq"];
        } else {
            $this->insertFirstTime();//First sequence number, so that next update queries will be always successfull
        }
        $this->updateNextSeqNumber($nextSeq + 1);
        return $nextSeq;
    }
}

function getNextSequnceNumber() {
    //Create new object of utility class
    $db = new DBUtil();
    if(!$db){
        die("Connection failed: " . $db->lastErrorMsg());
    }
    //Check if connected
    if($db->createTableIfNotExists()) {
        $nextSeq = $db->getNextSeq();
        return formatToSixCharacters($nextSeq);
    } else {
        die ("Error: " . $db->lastErrorMsg());
    }
    //close connection finally
    $db->close();
}

function formatToSixCharacters($num) {
    $numStr = $num . "";
    if(strlen($numStr) < 6) {
        $zeros = 6 - strlen($numStr);
        for($i = 1; $i <= $zeros; $i++) {
            $numStr = "0" . $numStr;
        }
    }
    return $numStr;
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Form Printing</title>
    </head>
    <body>
        <form>
            <input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
        </form>
    </body>
</html>

++PHPDesktop With Sqlite Version

form-php-desktop-sqlite.php

Please include this PHPDesktop Helper file pdo.php provided by PHPDesktop. However this is small helper file, it does not serve big purpose, but it will help you for now.

Also read Using Sqlite with PHP Desktop

<?php
session_start();
include "./pdo.php";

function getNextSequnceNumber() {
    //Open connection
    $db_file = "./orders.sqlite3";
    PDO_Connect("sqlite:$db_file");
    //Create table if not exists
    $sql = "CREATE TABLE IF NOT EXISTS order_sequence ("
        ."    next_seq INT NOT NULL"
        .")";
    PDO_Execute($sql);

    //get next sequence number
    $sql = "SELECT next_seq FROM order_sequence";
    $nextSeq = PDO_FetchOne($sql);
    if($nextSeq == null) {
        $nextSeq = 1;
        //Also insert first time record
        $sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
        PDO_Execute($sql);
    }
    //Update next time sequence
    $sql = "UPDATE order_sequence SET next_seq = ".($nextSeq + 1);
    PDO_Execute($sql);
    return formatToSixCharacters($nextSeq);
}

function formatToSixCharacters($num) {
    $numStr = $num . "";
    if(strlen($numStr) < 6) {
        $zeros = 6 - strlen($numStr);
        for($i = 1; $i <= $zeros; $i++) {
            $numStr = "0" . $numStr;
        }
    }
    return $numStr;
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Form Printing</title>
    </head>
    <body>
        <form>
            <input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
        </form>
    </body>
</html>


问:
Difference in uses between malloc and calloc
```<code>gcc 4.5.1 c89
</code>```

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

```<code>dev = malloc(number * sizeof *devices);
</code>```

is equal to this calloc. I am not concerned about clearing the memory.

```<code>dev = calloc(number, sizeof *devices);
</code>```

What is that exactly, compared to doing this 5 times in a while loop:

```<code>dev = malloc(sizeof *devices);
</code>```

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

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

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}
</code>```

答:
As you point out, calloc zeroes out the memory is allocates, while malloc doesn't.

Your examples 1 & 2 each allocate a single contiguous block of five structs (and returns a pointer to that block), whereas example 3 allocates five separate blocks of one struct each (and gives you five pointers unrelated to one another.)

Body:
gcc 4.5.1 c89

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

dev = malloc(number * sizeof *devices);

is equal to this calloc. I am not concerned about clearing the memory.

dev = calloc(number, sizeof *devices);

What is that exactly, compared to doing this 5 times in a while loop:

dev = malloc(sizeof *devices);

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

#include <stdio.h>
#include <stdlib.h>

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}


问:
Using RegExp to split value in Array, pattern only works half the time
I'm attempting to use RexExp and JS to parse bible verses. Output doesn't matter, because some of my regexes are giving me false negatives (unless I just don't understand something about RegExp, which is probably the case).

Consider the following function:

```<code>function wtf() {
 var s = "1:1-8, 3:5, 4:-8-10, 25-36, 5:1-6:1-26, 32-40, 55, 7:8",
 exp1 = new RegExp('(\\d+:)?([\\d-]+(?=\\d:)|[\\d-]+)','g'),
 result = s.split(exp1),
 exp2 = new RegExp('\\d+[ :]+','g'), //tests for \d:
 exp3 = new RegExp('\\d+[-]\\B','g'), //tests for \d-
 exp4 = new RegExp('\\b\\d{1,3}[ -]+\\d{1,3}\\b','g'), //tests for \d-\d
 exp5 = new RegExp('\\d:.*\\b','g'), //tests for d: followed by anything
 exp6 = new RegExp('^\\d{1,3}$','g'), //tests for 1,12,123,etc.
 output = [];

 for(i=0;i<result.length;i++) {
        var t = String(result[i]);
        if(result[i] == "" | result[i] == ","| result[i] == " ," | result[i] == ", " | result[i] == undefined) {}
        else if(exp5.test(result[i]) == true) {}
        else {output[i] = result[i];}
    }

    output = output.filter(function(val){return val});

 console.log(JSON.stringify(output));

 for(i=0;i<output.length;i++) {
    if(exp2.test(output[i]) == true) { //tests for '3:','10:','100:', etc
        console.log("Current Index: "+output[i]);
        console.log("IF Branch: "+exp2);
     }
     else if(exp4.test(output[i]) == true){//tests for '1-1','12-34','123-456', etc.
        console.log("Current Index: "+output[i]);
        console.log("IF Branch: "+exp4);
     }
     else if(exp3.test(output[i]) == true) { //tests for '/\\d[-]\\B/g'
        console.log("Current Index: "+output[i]);
        console.log("IF Branch: "+exp3);
     }
     else if(exp6.test(output[i]) == true) { //tests for '1','12','123',etc.
        console.log("Current Index: "+output[i]);
        console.log("IF Branch: "+exp6);
     }
     else {
        console.log("Current Index: "+output[i]);
        console.log("IF Branch: else");
     }
  console.log("");
 }
}
</code>```

The above code parses the string into an array, removes extraneous indices, renumbers the remaining indices, and then loops through each index, running a test to determine which block of code to run on each index.

For the most part, this works fine. The function mostly works on strings that follow the corresponding pattern. But there is a problem, as you can see below in the function's output:

```<code>["1:","1-8","3:","5","4:","-8-10","25-36","5:","1-","6:","1-26","32-40","55","7:","8"]

Current Index: 1:
IF Branch: /\d+[ :]+/g

Current Index: 1-8
IF Branch: /\b\d{1,3}[ -]+\d{1,3}\b/g

Current Index: 3:
IF Branch: /\d+[ :]+/g

Current Index: 5
IF Branch: /^\d{1,3}$/g

Current Index: 4:
IF Branch: /\d+[ :]+/g

Current Index: -8-10
IF Branch: /\b\d{1,3}[ -]+\d{1,3}\b/g

Current Index: 25-36
IF Branch: else

Current Index: 5:
IF Branch: /\d+[ :]+/g

Current Index: 1-
IF Branch: /\d+[-]\B/g

Current Index: 6:
IF Branch: /\d+[ :]+/g

Current Index: 1-26
IF Branch: /\b\d{1,3}[ -]+\d{1,3}\b/g

Current Index: 32-40
IF Branch: else

Current Index: 55
IF Branch: /^\d{1,3}$/g

Current Index: 7:
IF Branch: /\d+[ :]+/g

Current Index: 8
IF Branch: else
</code>```

As you can tell, the JSON.stringified Array is first, followed by a loop of the indices of the array. For each index, the value and the pattern the index matched are output. You'll notice that when the index value is "25-36", "32-40", and "8" that the else branch is triggered, even though they all clearly match the patterns used. Moreover, in each case, there are preceding indices formatted in exactly the same way that DO trigger the appropriate branch of the if statement.

What on earth is going on? What don't I understand about what is happening here? I am checking to make certain the patterns are correct on regex101, so I am certain they are working. What gives?

答:
You’re creating regular expressions with the global flag, which keep their state across matches:

```<code>var re = /\d/g;
re.exec('123')  // ['1']
re.exec('123')  // ['2']
re.exec('123')  // ['3']
re.exec('123')  // null
</code>```

So, for test:

```<code>var re = /\d/g;
re.test('123')  // true
re.test('123')  // true
re.test('123')  // true
re.test('123')  // false
</code>```

Solution: don’t add the global flag when you don’t want it.

Generally simplified:

```<code>const output = [
    "1:1-8", "3:5", "4:-8-10", "25-36", "5:1-6:1-26", "32-40", "55", "7:8"];

const patterns = [
    /\d+[ :]+/,
    /\b\d{1,3}[ -]+\d{1,3}\b/,
    /\d+[-]\B/,
    /^\d{1,3}$/,
];

output.forEach(t => {
    const matched = patterns.find(p => p.test(t));

    console.log("Item: " + t);
    console.log("Matched: " + matched);
    console.log();
});
</code>```

Body:
I'm attempting to use RexExp and JS to parse bible verses. Output doesn't matter, because some of my regexes are giving me false negatives (unless I just don't understand something about RegExp, which is probably the case).

Consider the following function:

function wtf() {
 var s = "1:1-8, 3:5, 4:-8-10, 25-36, 5:1-6:1-26, 32-40, 55, 7:8",
 exp1 = new RegExp('(\\d+:)?([\\d-]+(?=\\d:)|[\\d-]+)','g'),
 result = s.split(exp1),
 exp2 = new RegExp('\\d+[ :]+','g'), //tests for \d:
 exp3 = new RegExp('\\d+[-]\\B','g'), //tests for \d-
 exp4 = new RegExp('\\b\\d{1,3}[ -]+\\d{1,3}\\b','g'), //tests for \d-\d
 exp5 = new RegExp('\\d:.*\\b','g'), //tests for d: followed by anything
 exp6 = new RegExp('^\\d{1,3}$','g'), //tests for 1,12,123,etc.
 output = [];

 for(i=0;i<result.length;i++) {
        var t = String(result[i]);
        if(result[i] == "" | result[i] == ","| result[i] == " ," | result[i] == ", " | result[i] == undefined) {}
        else if(exp5.test(result[i]) == true) {}
        else {output[i] = result[i];}
    }

    output = output.filter(function(val){return val});

 console.log(JSON.stringify(output));

 for(i=0;i<output.length;i++) {
    if(exp2.test(output[i]) == true) { //tests for '3:','10:','100:', etc
        console.log("Current Index: "+output[i]);
        console.log("IF Branch: "+exp2);
     }
     else if(exp4.test(output[i]) == true){//tests for '1-1','12-34','123-456', etc.
        console.log("Current Index: "+output[i]);
        console.log("IF Branch: "+exp4);
     }
     else if(exp3.test(output[i]) == true) { //tests for '/\\d[-]\\B/g'
        console.log("Current Index: "+output[i]);
        console.log("IF Branch: "+exp3);
     }
     else if(exp6.test(output[i]) == true) { //tests for '1','12','123',etc.
        console.log("Current Index: "+output[i]);
        console.log("IF Branch: "+exp6);
     }
     else {
        console.log("Current Index: "+output[i]);
        console.log("IF Branch: else");
     }
  console.log("");
 }
}

The above code parses the string into an array, removes extraneous indices, renumbers the remaining indices, and then loops through each index, running a test to determine which block of code to run on each index.

For the most part, this works fine. The function mostly works on strings that follow the corresponding pattern. But there is a problem, as you can see below in the function's output:

["1:","1-8","3:","5","4:","-8-10","25-36","5:","1-","6:","1-26","32-40","55","7:","8"]

Current Index: 1:
IF Branch: /\d+[ :]+/g

Current Index: 1-8
IF Branch: /\b\d{1,3}[ -]+\d{1,3}\b/g

Current Index: 3:
IF Branch: /\d+[ :]+/g

Current Index: 5
IF Branch: /^\d{1,3}$/g

Current Index: 4:
IF Branch: /\d+[ :]+/g

Current Index: -8-10
IF Branch: /\b\d{1,3}[ -]+\d{1,3}\b/g

Current Index: 25-36
IF Branch: else

Current Index: 5:
IF Branch: /\d+[ :]+/g

Current Index: 1-
IF Branch: /\d+[-]\B/g

Current Index: 6:
IF Branch: /\d+[ :]+/g

Current Index: 1-26
IF Branch: /\b\d{1,3}[ -]+\d{1,3}\b/g

Current Index: 32-40
IF Branch: else

Current Index: 55
IF Branch: /^\d{1,3}$/g

Current Index: 7:
IF Branch: /\d+[ :]+/g

Current Index: 8
IF Branch: else

As you can tell, the JSON.stringified Array is first, followed by a loop of the indices of the array. For each index, the value and the pattern the index matched are output. You'll notice that when the index value is "25-36", "32-40", and "8" that the else branch is triggered, even though they all clearly match the patterns used. Moreover, in each case, there are preceding indices formatted in exactly the same way that DO trigger the appropriate branch of the if statement.

What on earth is going on? What don't I understand about what is happening here? I am checking to make certain the patterns are correct on regex101, so I am certain they are working. What gives?

Body:
You’re creating regular expressions with the global flag, which keep their state across matches:

var re = /\d/g;
re.exec('123')  // ['1']
re.exec('123')  // ['2']
re.exec('123')  // ['3']
re.exec('123')  // null

So, for test:

var re = /\d/g;
re.test('123')  // true
re.test('123')  // true
re.test('123')  // true
re.test('123')  // false

Solution: don’t add the global flag when you don’t want it.

Generally simplified:

const output = [
    "1:1-8", "3:5", "4:-8-10", "25-36", "5:1-6:1-26", "32-40", "55", "7:8"];

const patterns = [
    /\d+[ :]+/,
    /\b\d{1,3}[ -]+\d{1,3}\b/,
    /\d+[-]\B/,
    /^\d{1,3}$/,
];

output.forEach(t => {
    const matched = patterns.find(p => p.test(t));

    console.log("Item: " + t);
    console.log("Matched: " + matched);
    console.log();
});


问:
Tabulate the data after reducing it using frequency count
I have the following dataset:

```<code>5   3   3   5   10  10  3   8   2   12  8   6   2   5   6   5   10  4   3   5   4   3   3   5   8   3   5   6   6   1   10  3   6   6   5   8   3   4   3   4   4   3   2.5 1   4   2   2   3   5   10  4   4   6   3   2   3   8   3   4   4   3   3   4   8   4   4   2   4   4   3   2   10  6   3   7   3   5   3   1   4   3   4   3   4   4   2   3   2   4   7   4   6   3.5 3.5 5   3   4   3   5   3   1.5 2.5 3   7   2   5   3   4   2   4   5   3   4   5   4.5 4   6   3   2   1   3   2   2   3   4   6   2   4   2   3   6   1.5 3   3   1   4   3   3   2   3   2   2   6   3   15  1   4   5   2   6   2   4   8   2   8   4   4   4   3   8   4   4   8.5 3   2   7   0.5 3   3   3   2   3   2   4   5   6   2   3.5 3   3   2   2   2.5 2   2   5   2   8   2   4   3   3   2   7   2   4   2   4   4   3   2.5 3   3   3   5
</code>```

The function table() return the following values:

```<code>table(df$var)

0.5   1 1.5   2 2.5   3 3.5   4 4.5   5   6   7   8 8.5  10  12  15
  1   6   2  35   4  54   3  41   1  19  15   5  10   1   6   1   1
</code>```

What I want to do is to omit all these numbers for which count() is <=6 so that when the table() function run on the data, it will return results that would look like as shown below:

```<code>2    3    4    5   6   8
35  54   41   19  15  10
</code>```

What I am trying:

```<code>test <- as.data.frame(table(df$var))
test[test$Freq > 6,2]
</code>```

And then using it to get the table().
This is really bad work.

Can there be any other shortest method, maybe a one-liner?

答:
This is a good candidate for the Filter function too:

```<code>Filter(function(y) y > 6, table(x))
## x
##  2  3  4  5  6  8
## 35 54 41 19 15 10
</code>```

("x" is from @d.b's answer.)

Body:
I have the following dataset:

5   3   3   5   10  10  3   8   2   12  8   6   2   5   6   5   10  4   3   5   4   3   3   5   8   3   5   6   6   1   10  3   6   6   5   8   3   4   3   4   4   3   2.5 1   4   2   2   3   5   10  4   4   6   3   2   3   8   3   4   4   3   3   4   8   4   4   2   4   4   3   2   10  6   3   7   3   5   3   1   4   3   4   3   4   4   2   3   2   4   7   4   6   3.5 3.5 5   3   4   3   5   3   1.5 2.5 3   7   2   5   3   4   2   4   5   3   4   5   4.5 4   6   3   2   1   3   2   2   3   4   6   2   4   2   3   6   1.5 3   3   1   4   3   3   2   3   2   2   6   3   15  1   4   5   2   6   2   4   8   2   8   4   4   4   3   8   4   4   8.5 3   2   7   0.5 3   3   3   2   3   2   4   5   6   2   3.5 3   3   2   2   2.5 2   2   5   2   8   2   4   3   3   2   7   2   4   2   4   4   3   2.5 3   3   3   5

The function table() return the following values:

table(df$var)

0.5   1 1.5   2 2.5   3 3.5   4 4.5   5   6   7   8 8.5  10  12  15
  1   6   2  35   4  54   3  41   1  19  15   5  10   1   6   1   1

What I want to do is to omit all these numbers for which count() is <=6 so that when the table() function run on the data, it will return results that would look like as shown below:

2    3    4    5   6   8
35  54   41   19  15  10

What I am trying:

test <- as.data.frame(table(df$var))
test[test$Freq > 6,2]

And then using it to get the table().
This is really bad work.

Can there be any other shortest method, maybe a one-liner?

Body:
This is a good candidate for the Filter function too:

Filter(function(y) y > 6, table(x))
## x
##  2  3  4  5  6  8
## 35 54 41 19 15 10

("x" is from @d.b's answer.)


问:
Netty channelActive vs channelRead0
I am using netty 4.0.33 to build a SSL/TLS client/server. For every connection, I want to log a message that TLS connection is successful between the 2 peers.
Where should I put this code snippet? channelActive or channelRead0? I am a bit confused about the purpose of channelActive and channelRead0. Looks like on the server side, we don't need channelActive at all. Is that true?</p>

答: You can add LoggingHandler to your pipeline and it will log if client is active. Active means connected. ChannelRead is called after channelActive and here you can read messages. In channelActive you can initialize some helpful stuff if you need (e.g. add connected channel to queue).</p>

Title: Netty channelActive vs channelRead0


问:
Using the App.config file out of a shared project
How can I use the App.config file from a shared project in Visual Studio 2015 C# application?

```<code> ConfigurationManager.AppSettings[pathKey];
</code>```

This uses the App.config from the project you are in!

答:
You could do this by adding an app.config file as a solution item

Right click on solution > Add Item > Application Configuration File

And then add that shared file to required projects as references.

Add Item > Add Existing Item > Add As Link

Ensure that the properties are set to:

Build Action: Content

Copy To Output Directory: Copy if newer

Be aware that when using this method the config file will not be compiled with the name of the assembly - you may have to load the configuration from file.

Body:
How can I use the App.config file from a shared project in Visual Studio 2015 C# application?

 ConfigurationManager.AppSettings[pathKey];

This uses the App.config from the project you are in!


答:
What's the expected output of 12.3 % 4.2 ?
If you have an answer for that, you also have to roll your own implementation, built in operator% works for integer types only.

If you are fine with that, but your arguments happen to be floating point values, round/floow/ceil/cast them. e.g:

```<code>static_cast<uint64_t>(double_value);
</code>```

Title: invalid operands of types 'double' and 'double' to binary 'operator%'

Body:
What's the expected output of 12.3 % 4.2 ?
If you have an answer for that, you also have to roll your own implementation, built in operator% works for integer types only.

If you are fine with that, but your arguments happen to be floating point values, round/floow/ceil/cast them. e.g:

static_cast<uint64_t>(double_value);


问:
How to get the value of a custom attribute in angular js
I have created a custom attribute called test in angular js. When I write the test attribute just beside the ng-controller keyword i.d.

 then I can access that test from the controller by using alert($attrs.test). But if I write the custom attribute test other than beside of the ng-controller keyword, I can't access that. i.e.

In this case I got undefined in alert($attrs.test)

Full code...

```<code><html>
<script src="angular.min.js"></script>
<body ng-app="myApp">

<div ng-controller="kumar" >
 <button ng-click="check()" test="def">Click</button>
</div>

 <script>
 var app = angular.module("myApp", []);
 app.directive("test", function() {
  return {
    //template : "<h1>Hello</h1>"
  };
});

 app.controller("kumar",function($scope,$attrs){
    $scope.check=function(){
      alert(JSON.stringify($attrs.test));   //getting undefined. I
                      //should get def.
  }
});
</script>

</body>
</html>
</code>```

答:
```<code>app.directive("test", function() {
  return {
     restrict: "A",
        scope: {
            text: "@test"
        }
  };
});
</code>```

Update your directive scope and add restrict . For better understanding refer to this question

Body:
I have created a custom attribute called test in angular js. When I write the test attribute just beside the ng-controller keyword i.d.

 then I can access that test from the controller by using alert($attrs.test). But if I write the custom attribute test other than beside of the ng-controller keyword, I can't access that. i.e.

In this case I got undefined in alert($attrs.test)

Full code...

 <button ng-click="check()" test="def">Click</button>

Body:
app.directive("test", function() {
  return {
     restrict: "A",
        scope: {
            text: "@test"
        }
  };
});

Update your directive scope and add restrict . For better understanding refer to this question


问:
Node.js project naming conventions for files & folders
What are the naming conventions for files and folders in a large Node.js project?

Should I capitalize, camelCase, or under-score?

Ie. is this considered valid?

```<code>project-name
    app
        controllers
            someThings.js
            users.js
        models
                someThing.js
                user.js
        views
            some-things
                index.jade
            users
                logIn.jade
                signUp.jade
    ...
</code>```

答:
According to me: For files, use lower camel case if module.exports is an object, I mean a singleton module. This is also applicable to JSON files as they are also in a way single ton. Use upper camel case if module.exports returns a constructor function where it acts like a class.

For folders use short names. If there is need to have multiple words, let it be completely lower case separated by "-" so that it works across all platforms consistently.

Body:
What are the naming conventions for files and folders in a large Node.js project?

Should I capitalize, camelCase, or under-score?

Ie. is this considered valid?

project-name
    app
        controllers
            someThings.js
            users.js
        models
                someThing.js
                user.js
        views
            some-things
                index.jade
            users
                logIn.jade
                signUp.jade
    ...


问:
Initiate Python Script on AWS from Wordpress
I have the following use case in which I need to run a Python script on a AWS hosted VM with information from a Wordpress site:

1) User enters a number of parameters in a form:

```<code>x = 3
y = 5
</code>```

2) parameters are stored in the WP backend along with other user information from the WP backend database:

```<code>user = "John Doe"
</code>```

3) as soon as all data is inputed, data is sent to Python server, which runs a very complex script (cannot be replicated in PHP)

```<code>def foo(x,y, user):
    bar = x + y
    print(user, " receives ", bar," as an answer.")
</code>```

4) result of the script (bar) is then returned to WP and stored for further use

Data security is also a big issue in this case, so secured connections are a must.

Is this even possible?

答:
This is straight-forward enough to do - you need to develop a REST API endpoint in Python, running on your AWS instance and must be accessible from your wordpress site (with whatever security you need in place).

Checkout Flask / Flask-restful for the back-end piece and then you'll need to update your wordpress site to make the API call to execute the function and return the result.

Don't know a lot about wordpress, but I would be surprised if it was not a straightforward task to make an API call from it to any arbitrary endpoint with just a bit of custom code.

Body:
I have the following use case in which I need to run a Python script on a AWS hosted VM with information from a Wordpress site:

1) User enters a number of parameters in a form:

x = 3
y = 5

2) parameters are stored in the WP backend along with other user information from the WP backend database:

user = "John Doe"

3) as soon as all data is inputed, data is sent to Python server, which runs a very complex script (cannot be replicated in PHP)

def foo(x,y, user):
    bar = x + y
    print(user, " receives ", bar," as an answer.")

4) result of the script (bar) is then returned to WP and stored for further use

Data security is also a big issue in this case, so secured connections are a must.

Is this even possible?


问:
String.replaceAll without RegEx
I'd like to replace all instances of a substring in a string but String.replaceAll() only accepts a pattern. The string that I have came from a previous match. Is it possible to add escapes to the pattern that I have or is there a version of replaceAll() in another class which accepts a literal string instead of a pattern?

答:
Just use String.replace(CharSequence,CharSequence) rather than replaceAll.

NB: replace doesn't just replace the first occurrence, it replaces all occurrences, like replaceAll.

Title: String.replaceAll without RegEx

ContentLicense: CC BY-SA 4.0


问:
I need to split an array of data into cells in excel
I have a spreadsheet that queries a data source and returns an array of about 230 rows of comma separated results. The data looks like this:

I need to have all those comma separated values that are now in one cell (column B) split into separate cells. There are typically 21 results for each row. So the result should look like this:

The row the data starts on could vary, but typically starts around row 80. The top rows are used for displaying results from the data below it. The starting point could be fixed at say row 120 (if that makes scripting easier), which would leave plenty of room for future dev.

I've tried modifying a few different solutions I've found on here, but none worked. Any help is supremely appreciated!

答: You ought to be able to do what you want with Excel's Text To Columns feature explained at this link. You can re-write individual rows or big blocks of them in one click. I draw your attention especially to the parameter on the third tab where you can define a destination for the data, such as the B120 you have mentioned. </p>