问:
Preprocess node from a module: not getting same vars as template.php
I'd like to preprocess and theme my nodes from a module instead of template.php.  Before, I'd have a giant switch statement in theme_preprocess_node().  But this only ever applied to my primary tab - subtabs were being templated from the modules they were defined in.  So I like the idea of consolidating all my preprocess functions and templates into one organized module.

The structure I want is essentially like this (pulling out details for a summary):

```<code>function foomodule_menu()
{
    $items['foo/%node'] = array(
        'page callback' => 'page_foo_overview',
        'page arguments' => array(1),
        'type' => MENU_NORMAL_ITEM,
    );
        $items['foo/%node/overview'] = array(
            'type' => MENU_DEFAULT_LOCAL_TASK,
        );
        $items['foo/%node/details'] = array(
            'page callback' => 'page_foo_details',
            'page arguments' => array(1),
            'type' => MENU_LOCAL_TASK,
        );
}

function foomodule_theme()
{
    return array(
        'page_foo_overview' => array(
            'arguments' => array('node' => NULL),
            'template' => 'templates/page-foo-overview'
        ),
        'page_foo_details' => array(
            'arguments' => array('node' => NULL),
            'template' => 'templates/page-foo-details'
        ),
    );
}

function page_foo_overview($node)
{
    // Used to do this, and themed it from template.php
    // return node_view($node, FALSE, TRUE);

    // Instead, I'd like to theme all pages directly in this module:
    return theme('page_foo_overview', $node);
}

function template_preprocess_page_foo_overview(&$vars)
{
    // But $vars doesn't contain the same data as when I themed from template.php
    // Specifically the ['view'] element of CKK fields, and flags like $teaser
    // What do I need to do to get at the same data?
    dsm($vars);
}
</code>```

All works great, but the $vars available in my preprocess are not what I'm used to in the template.php's theme_preprocess_node() function.  For one, it looks like CCK fields haven't been run through content_format() (no ['view'] element), and flags like teaser and page are missing.

What's being called before theme_preprocess_node() that I could invoke here?

Am I asking for trouble by doing this?  It makes so much more sense to me to have it organized like this and be in control of each step: menu > page callback > theme > preprocess > template, and to be able to organize this across multiple modules as I see fit.

答:
AK,

My suggestion is to execute the following code to check the available variables

```<code><?php
$arr = get_defined_vars();
dsm($arr);
?>
</code>```

If that doesn't help you can check the weight of your module on the system table. Maybe changing it (to make your module run after other modules) can help you.

Body:
I'd like to preprocess and theme my nodes from a module instead of template.php.  Before, I'd have a giant switch statement in theme_preprocess_node().  But this only ever applied to my primary tab - subtabs were being templated from the modules they were defined in.  So I like the idea of consolidating all my preprocess functions and templates into one organized module.

The structure I want is essentially like this (pulling out details for a summary):

function foomodule_menu()
{
    $items['foo/%node'] = array(
        'page callback' => 'page_foo_overview',
        'page arguments' => array(1),
        'type' => MENU_NORMAL_ITEM,
    );
        $items['foo/%node/overview'] = array(
            'type' => MENU_DEFAULT_LOCAL_TASK,
        );
        $items['foo/%node/details'] = array(
            'page callback' => 'page_foo_details',
            'page arguments' => array(1),
            'type' => MENU_LOCAL_TASK,
        );
}

function foomodule_theme()
{
    return array(
        'page_foo_overview' => array(
            'arguments' => array('node' => NULL),
            'template' => 'templates/page-foo-overview'
        ),
        'page_foo_details' => array(
            'arguments' => array('node' => NULL),
            'template' => 'templates/page-foo-details'
        ),
    );
}

function page_foo_overview($node)
{
    // Used to do this, and themed it from template.php
    // return node_view($node, FALSE, TRUE);

    // Instead, I'd like to theme all pages directly in this module:
    return theme('page_foo_overview', $node);
}

function template_preprocess_page_foo_overview(&$vars)
{
    // But $vars doesn't contain the same data as when I themed from template.php
    // Specifically the ['view'] element of CKK fields, and flags like $teaser
    // What do I need to do to get at the same data?
    dsm($vars);
}

All works great, but the $vars available in my preprocess are not what I'm used to in the template.php's theme_preprocess_node() function.  For one, it looks like CCK fields haven't been run through content_format() (no ['view'] element), and flags like teaser and page are missing.

What's being called before theme_preprocess_node() that I could invoke here?

Am I asking for trouble by doing this?  It makes so much more sense to me to have it organized like this and be in control of each step: menu > page callback > theme > preprocess > template, and to be able to organize this across multiple modules as I see fit.

Body:
AK,

My suggestion is to execute the following code to check the available variables

<?php
$arr = get_defined_vars();
dsm($arr);
?>

If that doesn't help you can check the weight of your module on the system table. Maybe changing it (to make your module run after other modules) can help you.


来源: stackexchange

问:
Azure REST API does not return encryption settings for Virtual Machine
I have a 16.04-LTS Ubuntu Virtual Machine in my Azure account and I am trying Azure Disk Encryption for this virtual machine making use of this azure cli sample script. On running the encryption script, the azure portal shows its OS disk is encrypted. There is Enabled under Encryption header.

However, the Azure REST API (api link) for getting information about the virtual machine does not return the encryptionSettings under properties.storageProfile.osDisk. I tried both Model View and Model View and Instance View for the api-version 2017-03-30 as well as 2017-12-01. Here is the partial response from the API:

```<code>{
    "name": "ubuntu",
    "properties": {
        "osProfile": {},
        "networkProfile": {},
        "storageProfile": {
            "imageReference": {
                "sku": "16.04-LTS",
                "publisher": "Canonical",
                "version": "latest",
                "offer": "UbuntuServer"
            },
            "osDisk": {
                "name": "ubuntu-OsDisk",
                "diskSizeGB": 30,
                "managedDisk": {
                    "storageAccountType": "Premium_LRS",
                    "id": "..."
                },
                "caching": "ReadWrite",
                "createOption": "FromImage",
                "osType": "Linux"
            },
            "dataDisks": []
        },
        "diagnosticsProfile": {},
        "vmId": "",
        "hardwareProfile": {
            "vmSize": "Standard_B1s"
        },
        "provisioningState": "Succeeded"
    },
    "location": "eastus",
    "type": "Microsoft.Compute/virtualMachines",
    "id": ""
}
</code>```

But for my other encrypted windows virtual machine, I get the correct response which contains encryptionSettings in properties.storageProfile.osDisk:

```<code>{
    "name": "win1",
    "properties": {
        "osProfile": {},
        "networkProfile": {},
        "storageProfile": {
            "imageReference": {
                "sku": "2016-Datacenter-smalldisk",
                "publisher": "MicrosoftWindowsServer",
                "version": "latest",
                "offer": "WindowsServer"
            },
            "osDisk": {
                "name": "win1_OsDisk_1",
                "diskSizeGB": 31,
                "managedDisk": {
                    "storageAccountType": "Premium_LRS",
                    "id": "..."
                },
                "encryptionSettings": {
                    "diskEncryptionKey": {
                        "secretUrl": "...",
                        "sourceVault": {
                            "id": "..."
                        }
                    },
                    "keyEncryptionKey": {
                        "keyUrl": "...",
                        "sourceVault": {
                            "id": "..."
                        }
                    },
                    "enabled": true
                },
                "caching": "ReadWrite",
                "createOption": "FromImage",
                "osType": "Windows"
            },
            "dataDisks": []
        },
        "diagnosticsProfile": {},
        "vmId": "...",
        "hardwareProfile": {
            "vmSize": "Standard_B1s"
        },
        "provisioningState": "Succeeded"
    },
    "location": "eastus",
    "type": "Microsoft.Compute/virtualMachines",
    "id": "..."
}
</code>```

Why is the Virtual Machine Get API not returning the encryptionSettings for some VMs? Any help would be greatly appreciated.

答:
I create VM using following command.

```<code>az vm create \
    --resource-group shuivm \
    --name shuivm \
    --image Canonical:UbuntuServer:16.04-LTS:latest \
    --admin-username azureuser \
    --generate-ssh-keys
</code>```

When I use the following API, I could get encryption setting.

```<code>https://management.azure.com/subscriptions/**********/resourceGroups/shuivm/providers/Microsoft.Compute/virtualMachines/shuivm?api-version=2017-03-30"
</code>```

Note: When OS is encrypted  successful, I could use API to get encryption setting.

ContentLicense: CC BY-SA 3.0

Body:
I have a 16.04-LTS Ubuntu Virtual Machine in my Azure account and I am trying Azure Disk Encryption for this virtual machine making use of this azure cli sample script. On running the encryption script, the azure portal shows its OS disk is encrypted. There is Enabled under Encryption header.

However, the Azure REST API (api link) for getting information about the virtual machine does not return the encryptionSettings under properties.storageProfile.osDisk. I tried both Model View and Model View and Instance View for the api-version 2017-03-30 as well as 2017-12-01. Here is the partial response from the API:

{
    "name": "ubuntu",
    "properties": {
        "osProfile": {},
        "networkProfile": {},
        "storageProfile": {
            "imageReference": {
                "sku": "16.04-LTS",
                "publisher": "Canonical",
                "version": "latest",
                "offer": "UbuntuServer"
            },
            "osDisk": {
                "name": "ubuntu-OsDisk",
                "diskSizeGB": 30,
                "managedDisk": {
                    "storageAccountType": "Premium_LRS",
                    "id": "..."
                },
                "caching": "ReadWrite",
                "createOption": "FromImage",
                "osType": "Linux"
            },
            "dataDisks": []
        },
        "diagnosticsProfile": {},
        "vmId": "",
        "hardwareProfile": {
            "vmSize": "Standard_B1s"
        },
        "provisioningState": "Succeeded"
    },
    "location": "eastus",
    "type": "Microsoft.Compute/virtualMachines",
    "id": ""
}

But for my other encrypted windows virtual machine, I get the correct response which contains encryptionSettings in properties.storageProfile.osDisk:

{
    "name": "win1",
    "properties": {
        "osProfile": {},
        "networkProfile": {},
        "storageProfile": {
            "imageReference": {
                "sku": "2016-Datacenter-smalldisk",
                "publisher": "MicrosoftWindowsServer",
                "version": "latest",
                "offer": "WindowsServer"
            },
            "osDisk": {
                "name": "win1_OsDisk_1",
                "diskSizeGB": 31,
                "managedDisk": {
                    "storageAccountType": "Premium_LRS",
                    "id": "..."
                },
                "encryptionSettings": {
                    "diskEncryptionKey": {
                        "secretUrl": "...",
                        "sourceVault": {
                            "id": "..."
                        }
                    },
                    "keyEncryptionKey": {
                        "keyUrl": "...",
                        "sourceVault": {
                            "id": "..."
                        }
                    },
                    "enabled": true
                },
                "caching": "ReadWrite",
                "createOption": "FromImage",
                "osType": "Windows"
            },
            "dataDisks": []
        },
        "diagnosticsProfile": {},
        "vmId": "...",
        "hardwareProfile": {
            "vmSize": "Standard_B1s"
        },
        "provisioningState": "Succeeded"
    },
    "location": "eastus",
    "type": "Microsoft.Compute/virtualMachines",
    "id": "..."
}

Why is the Virtual Machine Get API not returning the encryptionSettings for some VMs? Any help would be greatly appreciated.

Body:
I create VM using following command.

az vm create \
    --resource-group shuivm \
    --name shuivm \
    --image Canonical:UbuntuServer:16.04-LTS:latest \
    --admin-username azureuser \
    --generate-ssh-keys

When I use the following API, I could get encryption setting.

https://management.azure.com/subscriptions/**********/resourceGroups/shuivm/providers/Microsoft.Compute/virtualMachines/shuivm?api-version=2017-03-30"

Note: When OS is encrypted  successful, I could use API to get encryption setting.


问:
Passing a structure member name to a function in C++
Here is a basic code that does not work.

```<code>struct s_date {
   int day;
   int month;
   int year;
} date;

void showMonth(date.month);

int main()
{

cout << "Enter a number";
cin >> date.month;

showMonth(date.month);

return 0;
}

void showMonth(date.month) {
switch (date.month) {
    case 1:
    cout << "January";
    break;

    //...
    }
}
</code>```

How can I pass a specific structure member name (such as date.month) to a function as shown here?

答:
Your showMonth() function is structured wrong.  It needs to be more like this instead:

```<code>struct s_date {
   int day;
   int month;
   int year;
} date;

void showMonth(int month);

int main()
{
    cout << "Enter a number";
    cin >> date.month;

    showMonth(date.month);

    return 0;
}

void showMonth(int month) {
    switch (month) {
        case 1:
            cout << "January";
            break;
        //...
    }
}
</code>```

Body:
Here is a basic code that does not work.

struct s_date {
   int day;
   int month;
   int year;
} date;

void showMonth(date.month);

int main()
{

cout << "Enter a number";
cin >> date.month;

showMonth(date.month);

return 0;
}

void showMonth(date.month) {
switch (date.month) {
    case 1:
    cout << "January";
    break;

    //...
    }
}

How can I pass a specific structure member name (such as date.month) to a function as shown here?

Body:
Your showMonth() function is structured wrong.  It needs to be more like this instead:

struct s_date {
   int day;
   int month;
   int year;
} date;

void showMonth(int month);

int main()
{
    cout << "Enter a number";
    cin >> date.month;

    showMonth(date.month);

    return 0;
}

void showMonth(int month) {
    switch (month) {
        case 1:
            cout << "January";
            break;
        //...
    }
}


问:
Cannot login into Salesforce with Java using Proxy Server
I wrote Java code to login to Salesforce and ran this code on a firewalled server. For this, I have to specify the proxy url and proxy port before connecting to Salesforce due to the firewall. However, I'm getting an unknownhostexception error for the proxy url. If I try to login via curl with the proxy settings, I am able to connect. How come there is a problem connecting using Java then? Any help is appreciated.</p>

答:
Depending on your HTTP library the System settings might not be enough or not needed. In the Salesforce context it is quite possible that one would try using the Jetty HTTP Client. In this case the System properties are ignored and proxy needs to be handled by the Jetty client:

```<code>ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration();
HttpProxy proxy = new HttpProxy("proxyHost", proxyPort);
proxyConfig.getProxies().add(proxy);
</code>```

The Apache HTTP Client, another popular choice, also uses its own little mechanism:

```<code> HttpHost proxy = new HttpHost("proxyHost", proxyPort, "https");
 RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
 HttpGet request = new HttpGet(someURL);
 request.setConfig(config);
</code>```

Interesting here: one can specify to use http or https as the proxy protocol.

In general I found using one of the http client much easier that the JDK low level functions.

Body:
Depending on your HTTP library the System settings might not be enough or not needed. In the Salesforce context it is quite possible that one would try using the Jetty HTTP Client. In this case the System properties are ignored and proxy needs to be handled by the Jetty client:

ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration();
HttpProxy proxy = new HttpProxy("proxyHost", proxyPort);
proxyConfig.getProxies().add(proxy);

The Apache HTTP Client, another popular choice, also uses its own little mechanism:

 HttpHost proxy = new HttpHost("proxyHost", proxyPort, "https");
 RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
 HttpGet request = new HttpGet(someURL);
 request.setConfig(config);

Interesting here: one can specify to use http or https as the proxy protocol.

In general I found using one of the http client much easier that the JDK low level functions.


问:
Does this MVC controller code need to be refactored or not?
I am writing an CSV/Excel-->MySQL import manager for an MVC application (Kohana/PHP).

I have a controller named "ImportManager" which has an action named "index" (default) which displays in a grid all the valid .csv and .xls files that are in a specific directory and ready for import. The user can then choose the files he wants to import.

However, since .csv files import into one database table and .xls files import into multiple database tables, I needed to handle this abstraction. Hence I created a helper class called SmartImportFile to which I send each file be it .csv or .xls and then I get then ask this "smart" object to add the worksheets from that file (be they one or many) to my collection. Here is my action method in PHP code:

```<code>public function action_index()
{
    $view = new View('backend/application/importmanager');

    $smart_worksheets = array();
    $raw_files = glob('/data/import/*.*');
    if (count($raw_files) > 0)
    {
        foreach ($raw_files as $raw_file)
        {
            $smart_import_file = new Backend_Application_Smartimportfile($raw_file);
            $smart_worksheets = $smart_import_file->add_smart_worksheets_to($smart_worksheets);
        }
    }
    $view->set('smart_worksheets', $smart_worksheets);

    $this->request->response = $view;
}
</code>```

The SmartImportFile class looks like this:

```<code>class Backend_Application_Smartimportfile
{
    protected $file_name;
    protected $file_extension;
    protected $file_size;
    protected $when_file_copied;
    protected $file_name_without_extension;
    protected $path_info;
    protected $current_smart_worksheet = array();

    protected $smart_worksheets = array();

    public function __construct($file_name)
    {
        $this->file_name = $file_name;
        $this->file_name_without_extension = current(explode('.', basename($this->file_name)));

        $this->path_info = pathinfo($this->file_name);
        $this->when_file_copied = date('Y-m-d H:i:s', filectime($this->file_name));
        $this->file_extension = strtolower($this->path_info['extension']);
        $this->file_extension = strtolower(pathinfo($this->file_name, PATHINFO_EXTENSION));
        if(in_array($this->file_extension, array('csv','xls','xlsx')))
        {
            $this->current_smart_worksheet = array();
            $this->process_file();
        }
    }

    private function process_file()
    {
        $this->file_size = filesize($this->file_name);
        if(in_array($this->file_extension, array('xls','xlsx')))
        {
            if($this->file_size < 4000000)
            {
                $this->process_all_worksheets_of_excel_file();
            }
        }
        else if($this->file_extension == 'csv')
        {
            $this->process_csv_file();
        }

    }

    private function process_all_worksheets_of_excel_file()
    {
        $worksheet_names = Import_Driver_Excel::get_worksheet_names_as_array($this->file_name);
        if (count($worksheet_names) > 0)
        {
            foreach ($worksheet_names as $worksheet_name)
            {
                $this->current_smart_worksheet['name'] = basename($this->file_name).' ('.$worksheet_name.')';
                $this->current_smart_worksheet['kind'] = strtoupper($this->file_extension);
                $this->current_smart_worksheet['file_size'] = $this->file_size;
                $this->current_smart_worksheet['when_file_copied'] = $this->when_file_copied;
                $this->current_smart_worksheet['table_name'] = $this->file_name_without_extension.'__'.$worksheet_name;
                $this->assign_database_table_fields();
                $this->smart_worksheets[] = $this->current_smart_worksheet;
            }
        }
    }

    private function process_csv_file()
    {
        $this->current_smart_worksheet['name'] = basename($this->file_name);
        $this->current_smart_worksheet['kind'] = strtoupper($this->file_extension);
        $this->current_smart_worksheet['file_size'] = $this->file_size;
        $this->current_smart_worksheet['when_file_copied'] = $this->when_file_copied;

        $this->current_smart_worksheet['table_name'] = $this->file_name_without_extension;
        $this->assign_database_table_fields();

        $this->smart_worksheets[] = $this->current_smart_worksheet;
    }

    private function assign_database_table_fields()
    {
        $db = Database::instance('import_excel');
        $sql = "SHOW TABLE STATUS WHERE name = '".$this->current_smart_worksheet['table_name']."'";
        $result = $db->query(Database::SELECT, $sql, FALSE)->as_array();
        if(count($result))
        {
            $when_table_created = $result[0]['Create_time'];
            $when_file_copied_as_date = strtotime($this->when_file_copied);
            $when_table_created_as_date = strtotime($when_table_created);
            if($when_file_copied_as_date > $when_table_created_as_date)
            {
                $this->current_smart_worksheet['status'] = 'backend.application.import.status.needtoreimport';
            }
            else
            {
                $this->current_smart_worksheet['status'] = 'backend.application.import.status.isuptodate';
            }
            $this->current_smart_worksheet['when_table_created'] = $when_table_created;
        }
        else
        {
            $this->current_smart_worksheet['when_table_created'] = 'backend.application.import.status.tabledoesnotexist';
            $this->current_smart_worksheet['status'] = 'backend.application.import.status.needtoimport';
        }
    }

    public function add_smart_worksheets_to(Array $smart_worksheets = array())
    {
        return array_merge($smart_worksheets, $this->get_smart_worksheets());
    }

    public function get_smart_worksheets()
    {
        if ( ! is_array($this->smart_worksheets))
        {
            return array();
        }

        return $this->smart_worksheets;
    }

}
</code>```

In a code review I was told that it might be better not to have a helper class like this but to keep the bulk of the code in the controller action method itself. The argumentation was that you should be able to look at the code in a controller action and see what it does instead of having it call external helper classes outside of itself. I disagree. My argumentation is:

you should create a helper class anytime it makes code clearer, as in this case, it abstracts away the fact that some files have one worksheet or many worksheets in them, and allows for easy future extension, if, say, we want to also import from sqlite files or even directories with files in them, this class abstraction would be able to handle this nicely.

moving the bulk of the code from this helper class back into the controller would force me to create internal variables in the controller which make sense for this particular action, but may or may not make sense to other action methods within the controller.

if I were programming this in C# I would make this helper class a nested class which would literally be an internal data structure that is inside of and only available to the controller class, but since PHP does not allow nested classes, I need to call a class "outside" the controller to help manage this abstraction in a way that makes the code clear and readable

Based on your experience of programming in the MVC pattern, should the above helper class be refactored back into the controller or not?

答:
There are two approaches to controllers: make it thin or thick. When I started my adventure with MVC I made a mistake of creating thick controllers - now I prefer make it as thin as possible. Your solution is good in my opinion.

Here is how I would redesigned your code even further:

```<code>class Backend_Application_SmartImport {

    public function __construct( $raw_files ) {
    }

    public function process() {
        foreach ($raw_files as $raw_file) {
            // (...)
            $oSmartImportFileInstance = $this->getSmartImportFileInstance( $smart_import_file_extension );
        }
    }

    protected function getSmartImportFileInstance( $smart_import_file_extension ) {
        switch ( $smart_import_file_extension ) {
            case 'xml':
                return new Backend_Application_SmartImportFileXml();
            // (...)
        }
    }
}

abstract class Backend_Application_SmartImportFile {
    // common methods for importing from xml or cvs
    abstract function process();
}

class Backend_Application_SmartImportFileCVS extends Backend_Application_SmartImportFile {
    // methods specified for cvs importing
}

class Backend_Application_SmartImportFileXls extends Backend_Application_SmartImportFile {
    // methods specified for xls importing
}
</code>```

The idea is to have two classes responsible for processing xml and cvs inheriting from a base class. The main class uses a special method to detect how the data should be processed (Strategy Pattern). The controller just passed a list of files to the instance of Backend_Application_SmartImport class and passes result of process method to the view.

The advantage of my solution is that code is more decoupled and you can easily and in a clean way add new types of processing like xml, pdf, etc.

ContentLicense: CC BY-SA 2.5

Body:
I am writing an CSV/Excel-->MySQL import manager for an MVC application (Kohana/PHP).

I have a controller named "ImportManager" which has an action named "index" (default) which displays in a grid all the valid .csv and .xls files that are in a specific directory and ready for import. The user can then choose the files he wants to import.

However, since .csv files import into one database table and .xls files import into multiple database tables, I needed to handle this abstraction. Hence I created a helper class called SmartImportFile to which I send each file be it .csv or .xls and then I get then ask this "smart" object to add the worksheets from that file (be they one or many) to my collection. Here is my action method in PHP code:

public function action_index()
{
    $view = new View('backend/application/importmanager');

    $smart_worksheets = array();
    $raw_files = glob('/data/import/*.*');
    if (count($raw_files) > 0)
    {
        foreach ($raw_files as $raw_file)
        {
            $smart_import_file = new Backend_Application_Smartimportfile($raw_file);
            $smart_worksheets = $smart_import_file->add_smart_worksheets_to($smart_worksheets);
        }
    }
    $view->set('smart_worksheets', $smart_worksheets);

    $this->request->response = $view;
}

The SmartImportFile class looks like this:

class Backend_Application_Smartimportfile
{
    protected $file_name;
    protected $file_extension;
    protected $file_size;
    protected $when_file_copied;
    protected $file_name_without_extension;
    protected $path_info;
    protected $current_smart_worksheet = array();

    protected $smart_worksheets = array();

    public function __construct($file_name)
    {
        $this->file_name = $file_name;
        $this->file_name_without_extension = current(explode('.', basename($this->file_name)));

        $this->path_info = pathinfo($this->file_name);
        $this->when_file_copied = date('Y-m-d H:i:s', filectime($this->file_name));
        $this->file_extension = strtolower($this->path_info['extension']);
        $this->file_extension = strtolower(pathinfo($this->file_name, PATHINFO_EXTENSION));
        if(in_array($this->file_extension, array('csv','xls','xlsx')))
        {
            $this->current_smart_worksheet = array();
            $this->process_file();
        }
    }

    private function process_file()
    {
        $this->file_size = filesize($this->file_name);
        if(in_array($this->file_extension, array('xls','xlsx')))
        {
            if($this->file_size < 4000000)
            {
                $this->process_all_worksheets_of_excel_file();
            }
        }
        else if($this->file_extension == 'csv')
        {
            $this->process_csv_file();
        }

    }

    private function process_all_worksheets_of_excel_file()
    {
        $worksheet_names = Import_Driver_Excel::get_worksheet_names_as_array($this->file_name);
        if (count($worksheet_names) > 0)
        {
            foreach ($worksheet_names as $worksheet_name)
            {
                $this->current_smart_worksheet['name'] = basename($this->file_name).' ('.$worksheet_name.')';
                $this->current_smart_worksheet['kind'] = strtoupper($this->file_extension);
                $this->current_smart_worksheet['file_size'] = $this->file_size;
                $this->current_smart_worksheet['when_file_copied'] = $this->when_file_copied;
                $this->current_smart_worksheet['table_name'] = $this->file_name_without_extension.'__'.$worksheet_name;
                $this->assign_database_table_fields();
                $this->smart_worksheets[] = $this->current_smart_worksheet;
            }
        }
    }

    private function process_csv_file()
    {
        $this->current_smart_worksheet['name'] = basename($this->file_name);
        $this->current_smart_worksheet['kind'] = strtoupper($this->file_extension);
        $this->current_smart_worksheet['file_size'] = $this->file_size;
        $this->current_smart_worksheet['when_file_copied'] = $this->when_file_copied;

        $this->current_smart_worksheet['table_name'] = $this->file_name_without_extension;
        $this->assign_database_table_fields();

        $this->smart_worksheets[] = $this->current_smart_worksheet;
    }

    private function assign_database_table_fields()
    {
        $db = Database::instance('import_excel');
        $sql = "SHOW TABLE STATUS WHERE name = '".$this->current_smart_worksheet['table_name']."'";
        $result = $db->query(Database::SELECT, $sql, FALSE)->as_array();
        if(count($result))
        {
            $when_table_created = $result[0]['Create_time'];
            $when_file_copied_as_date = strtotime($this->when_file_copied);
            $when_table_created_as_date = strtotime($when_table_created);
            if($when_file_copied_as_date > $when_table_created_as_date)
            {
                $this->current_smart_worksheet['status'] = 'backend.application.import.status.needtoreimport';
            }
            else
            {
                $this->current_smart_worksheet['status'] = 'backend.application.import.status.isuptodate';
            }
            $this->current_smart_worksheet['when_table_created'] = $when_table_created;
        }
        else
        {
            $this->current_smart_worksheet['when_table_created'] = 'backend.application.import.status.tabledoesnotexist';
            $this->current_smart_worksheet['status'] = 'backend.application.import.status.needtoimport';
        }
    }

    public function add_smart_worksheets_to(Array $smart_worksheets = array())
    {
        return array_merge($smart_worksheets, $this->get_smart_worksheets());
    }

    public function get_smart_worksheets()
    {
        if ( ! is_array($this->smart_worksheets))
        {
            return array();
        }

        return $this->smart_worksheets;
    }

}

In a code review I was told that it might be better not to have a helper class like this but to keep the bulk of the code in the controller action method itself. The argumentation was that you should be able to look at the code in a controller action and see what it does instead of having it call external helper classes outside of itself. I disagree. My argumentation is:

you should create a helper class anytime it makes code clearer, as in this case, it abstracts away the fact that some files have one worksheet or many worksheets in them, and allows for easy future extension, if, say, we want to also import from sqlite files or even directories with files in them, this class abstraction would be able to handle this nicely.

moving the bulk of the code from this helper class back into the controller would force me to create internal variables in the controller which make sense for this particular action, but may or may not make sense to other action methods within the controller.

if I were programming this in C# I would make this helper class a nested class which would literally be an internal data structure that is inside of and only available to the controller class, but since PHP does not allow nested classes, I need to call a class "outside" the controller to help manage this abstraction in a way that makes the code clear and readable

Based on your experience of programming in the MVC pattern, should the above helper class be refactored back into the controller or not?

Body:
There are two approaches to controllers: make it thin or thick. When I started my adventure with MVC I made a mistake of creating thick controllers - now I prefer make it as thin as possible. Your solution is good in my opinion.

Here is how I would redesigned your code even further:

class Backend_Application_SmartImport {

    public function __construct( $raw_files ) {
    }

    public function process() {
        foreach ($raw_files as $raw_file) {
            // (...)
            $oSmartImportFileInstance = $this->getSmartImportFileInstance( $smart_import_file_extension );
        }
    }

    protected function getSmartImportFileInstance( $smart_import_file_extension ) {
        switch ( $smart_import_file_extension ) {
            case 'xml':
                return new Backend_Application_SmartImportFileXml();
            // (...)
        }
    }
}

abstract class Backend_Application_SmartImportFile {
    // common methods for importing from xml or cvs
    abstract function process();
}

class Backend_Application_SmartImportFileCVS extends Backend_Application_SmartImportFile {
    // methods specified for cvs importing
}

class Backend_Application_SmartImportFileXls extends Backend_Application_SmartImportFile {
    // methods specified for xls importing
}

The idea is to have two classes responsible for processing xml and cvs inheriting from a base class. The main class uses a special method to detect how the data should be processed (Strategy Pattern). The controller just passed a list of files to the instance of Backend_Application_SmartImport class and passes result of process method to the view.

The advantage of my solution is that code is more decoupled and you can easily and in a clean way add new types of processing like xml, pdf, etc.


问:
Create Bulk XML from template for POST request using gatling/scala
I want to send bulk xml to my soap request body. I want to know is there any way to generate them dynamically through Gatling/Scala
This is how I am doing

private val request=exec(   http("Post request to create")
      .post("/endPoint")
      .headers(Utils.soapHeaders)
      .body(ElFileBody("requestbody/ids.xml"))
      .check(status.is(Utils.successStatus)) )

private val feedId = Iterator.continually(   Map(
        "id" -> Random.alphanumeric.take(13).mkString,
        "transactionId" -> Random.alphanumeric.take(14).mkString
      )   )

val scnPostVehicleAsn=Utils.createScenario("soapService", feedId,
  request)

and requestbody/ids.xml has the template with dynamic values ${transactionId} & ${id}.

So Is there any way to dynamically generate xml based on the template, I am not looking for repeat functionality.
 Just generate xml once before execution and pass it and later I will make rest calls to validate them

答:
I figured it out myself. I have created a list of random number and passed it to xml directly

val randomNumbers =
  List.fill(number)(prefix.concat(Random.alphanumeric.take(13).mkString))
  {    randomNumbers.map( i => i }

Then,

val file = new File(System.getProperty("user.dir")
  +"/performance-tests/src/test/resources/requestBody/ids.xml") val bw = new BufferedWriter(new FileWriter(file))
  bw.write(VehicleAsns.toString()) bw.close()


问:
spring-cloud-starter-stream-kafka does not creates topic provided to spring.boot.cloud.stream.bindings.output.destination
I am using spring-cloud-starter-stream-kafka and spring-cloud-stream jars for kafka in the spring boot application.

The version of the jar is 1.1.1.RELEASE and we are creating producer named as Test. For the same following is application.yml file.

```<code>spring.boot.cloud.stream.bindings.output:
                                    destination: Test
                                    content-type: application/octet-stream
                                    producer:
                                      headerMode: raw
                                      requiredGroups: testConsumerGroup
</code>```

The problem is sometimes when we run the application in docker(using docker-compose) instead of creating Test topic, it is creating "output" as a topic.
For kafka I am using wurstmeister/kafka(Tag 0.9.0.1-1) image and wurstmeister/zookeeper.
Tried updating the properties but it is not working.

Update: After the debugging get to know that bindingServiceProperties does not hold the bindings and hence spring cloud stream is creating topic as "output"

答: It looks like this version of the library has the bug. So, Updated the version of the library and now its working fine. </p>

Body:
I am using spring-cloud-starter-stream-kafka and spring-cloud-stream jars for kafka in the spring boot application.

The version of the jar is 1.1.1.RELEASE and we are creating producer named as Test. For the same following is application.yml file.

spring.boot.cloud.stream.bindings.output:
                                    destination: Test
                                    content-type: application/octet-stream
                                    producer:
                                      headerMode: raw
                                      requiredGroups: testConsumerGroup

The problem is sometimes when we run the application in docker(using docker-compose) instead of creating Test topic, it is creating "output" as a topic.
For kafka I am using wurstmeister/kafka(Tag 0.9.0.1-1) image and wurstmeister/zookeeper.
Tried updating the properties but it is not working.

Update: After the debugging get to know that bindingServiceProperties does not hold the bindings and hence spring cloud stream is creating topic as "output"


问:
Find two Binary Tree are structurally identical
I was recently asked in the interview

What would be the efficient algorithm to find if two given binary trees are structurally identical but not the content?

```<code>  a
/   \
b    c
      \
       e

  z
/   \
u    v
      \
       t
</code>```

are structurally identical.

Next question was find out if 2 binary tree are structurally mirror ?

Any pointer or help are appreciated.

My attempt was

```<code>boolean isStrucutrallyIdentitical(BinaryNode root1, BinayNode root2)  {
   if(root1==null && root2==null) return true;
   if(root1==null || root2==null) return false;
   if(root1!=null && roo2!=null) return true; // instead of value just check if its null or not
   return isStrucutrallyIdentitical(root1.getLeft(), root2.getLeft()) &&  isStrucutrallyIdentitical(root1.getRight(), root2.getRight());
}
</code>```

答:
```<code>private static boolean compare(TNode curRoot, TNode newRoot) {
    if (curRoot == null && newRoot == null) {
        return true;
    } else if ((curRoot == null && newRoot != null) || (curRoot != null && newRoot == null))
        return false;
    else {
        if (compare(curRoot.left, newRoot.left) && compare(curRoot.right, newRoot.right))
            return true;
        return false;
    }
}
</code>```

Body:
I was recently asked in the interview

What would be the efficient algorithm to find if two given binary trees are structurally identical but not the content?

  a
/   \
b    c
      \
       e

  z
/   \
u    v
      \
       t

are structurally identical.

Next question was find out if 2 binary tree are structurally mirror ?

Any pointer or help are appreciated.

My attempt was

boolean isStrucutrallyIdentitical(BinaryNode root1, BinayNode root2)  {
   if(root1==null && root2==null) return true;
   if(root1==null || root2==null) return false;
   if(root1!=null && roo2!=null) return true; // instead of value just check if its null or not
   return isStrucutrallyIdentitical(root1.getLeft(), root2.getLeft()) &&  isStrucutrallyIdentitical(root1.getRight(), root2.getRight());
}


问:
How to find the different indexes of the same value?
For example I have:

```<code>l = [4, 1 ,3, 4, 7 , 4]
</code>```

if I use

```<code>l.index(4)
</code>```

it returns back 0

How do I get it to return back 0, 3, 5?

答:
Try this: </p>

```<code>l = [4, 1 ,3, 4, 7 , 4]
index = [i for i, x in enumerate(l) if x == 4]
print(index)
</code>```

Body:
For example I have:

l = [4, 1 ,3, 4, 7 , 4]

if I use

l.index(4)

it returns back 0

How do I get it to return back 0, 3, 5?

Body:
Try this:

l = [4, 1 ,3, 4, 7 , 4]
index = [i for i, x in enumerate(l) if x == 4]
print(index)


问:
RCTBridge is Always Nil
I have been using React Native for a mobile app project for over a year now. I have a native component to bridge the BLE stack to the React Native portion of the app. Recently I upgraded to version 9.1 of XCode and I cannot get the React-Native Bridge to work within the iOS version. The RCTBridge is always nil so I can never use the eventDispatcher(). Here is my setup:

I have a native Swift component which I integrate into the app via a bridgin header. The origanization looks like this:

```<code>BLEScanner.swift (This is the native component)
BluetoothModuleBridge.m
Module-Practive-Bridging-Header.h (The bridging header)
</code>```

Relevant code snippets from each file:

BLEScanner.swift

```<code>import Foundation

@objc(BLEScanner)
class BLEScanner: NSObject {

  //....

  var bridge: RCTBridge!  // THIS IS ALWAYS NIL

  //....

  @objc func requestBluetoothState() -> Void {
    print("REQUEST BLE STATE")
    let ret = [
      "enabled" : true
    ]

    //THIS LINE WILL FAIL BECAUSE bridge IS NIL
    self.bridge.eventDispatcher().sendDeviceEvent(withName: "BluetoothStateEvent", body: ret)
  }

}
</code>```

BluetoothModuleBridge.m

```<code>#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(BLEScanner, NSObject)

RCT_EXTERN_METHOD(requestBluetoothState)

@end
</code>```

Module-Practive-Bridging-Header.h

```<code>// BluetoothModule-Bridging-Header.h
#import <React/RCTBridge.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventDispatcher.h>

#import <React/RCTRootView.h>
#import <React/RCTUtils.h>
#import <React/RCTConvert.h>

#import "AppDelegate.h"
#import "BugsnagReactNative/BugsnagReactNative.h"

#import "nokeLockSDK.h"
#import "nokeServerSDK.h"
#import "TI_aes_128.h"
</code>```

What I have Tried

Updated React Native from 0.36 to 0.50.3

Tried running on multiple devices

Tried on older version of XCode

Tried compiling on different machine

Compared to a similar app that works and uses this same design.

I am very confused as to why the RCTBridge is returning as nil. It seems odd to me that an XCode update would cause this, however, it is the only change made.

Can anyone point me in the right direction in debugging this issue?

I am using XCode 9.1 and React Native 0.50.3

答:
If you upgraded to 9.1 and also React Native to 50.x from 30.x at the same time, you could have wrong imports, as that is something that changed around version 40.

It should be

```<code>#import <React/RCTBridgeModule.h>
</code>```

Title: RCTBridge is Always Nil

Body:
I have been using React Native for a mobile app project for over a year now. I have a native component to bridge the BLE stack to the React Native portion of the app. Recently I upgraded to version 9.1 of XCode and I cannot get the React-Native Bridge to work within the iOS version. The RCTBridge is always nil so I can never use the eventDispatcher(). Here is my setup:

I have a native Swift component which I integrate into the app via a bridgin header. The origanization looks like this:

BLEScanner.swift (This is the native component)
BluetoothModuleBridge.m
Module-Practive-Bridging-Header.h (The bridging header)

Relevant code snippets from each file:

BLEScanner.swift

import Foundation

@objc(BLEScanner)
class BLEScanner: NSObject {

  //....

  var bridge: RCTBridge!  // THIS IS ALWAYS NIL

  //....

  @objc func requestBluetoothState() -> Void {
    print("REQUEST BLE STATE")
    let ret = [
      "enabled" : true
    ]

    //THIS LINE WILL FAIL BECAUSE bridge IS NIL
    self.bridge.eventDispatcher().sendDeviceEvent(withName: "BluetoothStateEvent", body: ret)
  }

}

BluetoothModuleBridge.m

#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(BLEScanner, NSObject)

RCT_EXTERN_METHOD(requestBluetoothState)

@end

Module-Practive-Bridging-Header.h

// BluetoothModule-Bridging-Header.h
#import <React/RCTBridge.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventDispatcher.h>

#import <React/RCTRootView.h>
#import <React/RCTUtils.h>
#import <React/RCTConvert.h>

#import "AppDelegate.h"
#import "BugsnagReactNative/BugsnagReactNative.h"

#import "nokeLockSDK.h"
#import "nokeServerSDK.h"
#import "TI_aes_128.h"

What I have Tried

Updated React Native from 0.36 to 0.50.3

Tried running on multiple devices

Tried on older version of XCode

Tried compiling on different machine

Compared to a similar app that works and uses this same design.

I am very confused as to why the RCTBridge is returning as nil. It seems odd to me that an XCode update would cause this, however, it is the only change made.

Can anyone point me in the right direction in debugging this issue?

I am using XCode 9.1 and React Native 0.50.3

Body:
If you upgraded to 9.1 and also React Native to 50.x from 30.x at the same time, you could have wrong imports, as that is something that changed around version 40.

It should be

#import <React/RCTBridgeModule.h>


问:
A little help required on sending email notifications something similar to Job alerts
I'm trying to create a email notifications system which are sent when a new item is added into the database.

Users register by providing their email address and by selecting their preferences which are as below -

```<code>Color [n/a, pink, red, blue, and green]
Shape [n/a, square, rectangle, and circle]
width [n/a, narrow, wide]
</code>```

These all are dropdown lists.

So if a user selects Color as red and leaves all other options as n/a, then it would mean they wanted to receive notifications for any new item which has color as red. If they select Colore = red and Shape = circle, they want to receive notifications for only those items which have color red AND shape as circle.

Item table

```<code>id, color, shape, width, height, name, description, image
</code>```

sample rows

```<code>1, red, circle, narrow, tall, ABC, ABC Descrip, yellowFlag.jpg
2, blue, circle, wide, short, XYZ, XYZ Descrip, redFlag.jpg
</code>```

Notifications table

```<code>id, email, color, shape, width
</code>```

sample rows

```<code>1, test@dummy.org.uk, red, 0, 0, 0
2, xyz@alpha.com, blue, circle, 0
3, abc@abcdef.com, pink, square, wide
</code>```

A use can opt for any of the selections. For example, see below, they can select

```<code>color = red, shape = 0, width = 0 [0 is n/a, selected red only]
color = 0, shape = square, width= 0 [selected shape only]
color = 0, shape = 0, width= 'narrow' [selected width only]
color = red, shape = square, width= 0 [selected both color and shape but not width]
color = 0, shape = square, width= 'narrow' [selected both shape and width but not color]
color = red, shape = square, width= narrow [selected all 3 options]
color = red, shape = 0, width= narrow [selected color and width but not shape]
</code>```

My questions are -
If I add number 2 item (above in item table) into DB, I want to send notifications to the users who have a match in notifications table. The only way to query notifications table I can think of is something like

```<code>1. SELECT email FROM notifications WHERE color = 'blue', shape = '0', '0'
2. SELECT email FROM notifications WHERE color = 'blue', shape = 'circle', '0'
3. SELECT email FROM notifications WHERE color = 'blue', shape = 'circle', 'wide'
4. SELECT email FROM notifications WHERE color = '0', shape = '0', 'wide'
5. SELECT email FROM notifications WHERE color = 'blue', shape = 'circle', '0'
6. SELECT email FROM notifications WHERE color = 'blue', shape = 'circle', 'wide'
</code>```

... and so on

It is an inefficient method. Also as of now number of options is 3 (color, shape, width) but If  have to add another couple of options it will all go mad (alongwith me).  There must a better way to achieve this as there are lots of application already doing it like job alerts etc. Could you suggest me a better alternative/idea to manage these. I have not got any problem changing structure of tables etc so any ideas are welcome. If you have any questions please ask. I appreciate your help.

Thanks a ton.

答:
I'd have a table that gathers all the preferences for a given user:

Table criteria:

```<code>id: some ID for the criteria
label: human readable description of the criteria
column: name of the corresponding column in the notification table
values: optional comma-separated list of possible values
</code>```

Table user_preferences

```<code>id: some id for the preference
user_id: the user
criteria_id: the criteria
value: the chosen value for the criteria
</code>```

Now to find the users with blue color and square shape preferences:

```<code>SELECT u.id, u.email
FROM user u, criteria c, user_preferences up
WHERE
      up.id = u.id
  AND c.id = up.criteria_id
  AND c.column = 'shape'
  AND up.value='square'

INTERSECT

SELECT u.id, u.email
FROM user u, criteria c, user_preferences up
WHERE
      up.id = u.id
  AND c.id = up.criteria_id
  AND c.column = 'color'
  AND up.value='blue'
</code>```

And when you add an item, you'll want to find users with blue color or square shape preferences:

```<code>SELECT u.id, u.email
FROM user u, criteria c, user_preferences up
WHERE
      up.id = u.id
  AND c.id = up.criteria_id
  AND ( (c.column = 'shape' AND up.value='square')
     OR (c.column = 'color' AND up.value='blue')
  )
</code>```

Body:
I'm trying to create a email notifications system which are sent when a new item is added into the database.

Users register by providing their email address and by selecting their preferences which are as below -

Color [n/a, pink, red, blue, and green]
Shape [n/a, square, rectangle, and circle]
width [n/a, narrow, wide]

These all are dropdown lists.

So if a user selects Color as red and leaves all other options as n/a, then it would mean they wanted to receive notifications for any new item which has color as red. If they select Colore = red and Shape = circle, they want to receive notifications for only those items which have color red AND shape as circle.

Item table

id, color, shape, width, height, name, description, image

sample rows

1, red, circle, narrow, tall, ABC, ABC Descrip, yellowFlag.jpg
2, blue, circle, wide, short, XYZ, XYZ Descrip, redFlag.jpg

Notifications table

id, email, color, shape, width

sample rows

1, test@dummy.org.uk, red, 0, 0, 0
2, xyz@alpha.com, blue, circle, 0
3, abc@abcdef.com, pink, square, wide

A use can opt for any of the selections. For example, see below, they can select

color = red, shape = 0, width = 0 [0 is n/a, selected red only]
color = 0, shape = square, width= 0 [selected shape only]
color = 0, shape = 0, width= 'narrow' [selected width only]
color = red, shape = square, width= 0 [selected both color and shape but not width]
color = 0, shape = square, width= 'narrow' [selected both shape and width but not color]
color = red, shape = square, width= narrow [selected all 3 options]
color = red, shape = 0, width= narrow [selected color and width but not shape]

My questions are -
If I add number 2 item (above in item table) into DB, I want to send notifications to the users who have a match in notifications table. The only way to query notifications table I can think of is something like

1. SELECT email FROM notifications WHERE color = 'blue', shape = '0', '0'
2. SELECT email FROM notifications WHERE color = 'blue', shape = 'circle', '0'
3. SELECT email FROM notifications WHERE color = 'blue', shape = 'circle', 'wide'
4. SELECT email FROM notifications WHERE color = '0', shape = '0', 'wide'
5. SELECT email FROM notifications WHERE color = 'blue', shape = 'circle', '0'
6. SELECT email FROM notifications WHERE color = 'blue', shape = 'circle', 'wide'

... and so on

It is an inefficient method. Also as of now number of options is 3 (color, shape, width) but If  have to add another couple of options it will all go mad (alongwith me).  There must a better way to achieve this as there are lots of application already doing it like job alerts etc. Could you suggest me a better alternative/idea to manage these. I have not got any problem changing structure of tables etc so any ideas are welcome. If you have any questions please ask. I appreciate your help.

Thanks a ton.

Body:
I'd have a table that gathers all the preferences for a given user:

Table criteria:

id: some ID for the criteria
label: human readable description of the criteria
column: name of the corresponding column in the notification table
values: optional comma-separated list of possible values

Table user_preferences

id: some id for the preference
user_id: the user
criteria_id: the criteria
value: the chosen value for the criteria

Now to find the users with blue color and square shape preferences:

SELECT u.id, u.email
FROM user u, criteria c, user_preferences up
WHERE
      up.id = u.id
  AND c.id = up.criteria_id
  AND c.column = 'shape'
  AND up.value='square'

INTERSECT

SELECT u.id, u.email
FROM user u, criteria c, user_preferences up
WHERE
      up.id = u.id
  AND c.id = up.criteria_id
  AND c.column = 'color'
  AND up.value='blue'

And when you add an item, you'll want to find users with blue color or square shape preferences:

SELECT u.id, u.email
FROM user u, criteria c, user_preferences up
WHERE
      up.id = u.id
  AND c.id = up.criteria_id
  AND ( (c.column = 'shape' AND up.value='square')
     OR (c.column = 'color' AND up.value='blue')
  )


问:
How to get the last executed SQL statement in HANA?
I am inside a SQLScript procedure and would like to return the last SQL Statement from this procedure, like the last rowcount:

```<code>/********* Begin Procedure Script ************/
BEGIN
    select 1 as "my_data" from dummy;
    select '::last_SQL' as "last executed sql" from dummy;
    select ::ROWCOUNT as "rowcount" from dummy;
END;
 /********* End Procedure Script ************/
</code>```

The column "last executed SQL" should be populated with select 1 as "my_data" from dummy in this case. Is there any variable holding the last statement (or any easy way to retrieve the query plan)?

答:
There is no way to programmatically get the last executed SQL statement in SQLScript. This is due to the fact that not all statements will be executed in the form and order as they appear in the source code.

If you want to analyse the performance of a procedure, you can run PlanViz against the procedure call. Generally, there is no such thing as "the performance of a procedure/function" as they always occur in a specific context.
If used within a SQL query, things like query-transformation can radically change the way certain results are computed.

ContentLicense: CC BY-SA 4.0

Body:
I am inside a SQLScript procedure and would like to return the last SQL Statement from this procedure, like the last rowcount:

/********* Begin Procedure Script ************/
BEGIN
    select 1 as "my_data" from dummy;
    select '::last_SQL' as "last executed sql" from dummy;
    select ::ROWCOUNT as "rowcount" from dummy;
END;
 /********* End Procedure Script ************/

The column "last executed SQL" should be populated with select 1 as "my_data" from dummy in this case. Is there any variable holding the last statement (or any easy way to retrieve the query plan)?


问:
Safe access operator (&.) gives an "undefined local variable or method for #<Api::V1::Controller:x123abc>"
I want to get the name property from the first one among the values corresponding to some keys in params that I try to get it from.

In my console this works:

```<code>company = Company.find_by_id(params[:company_id])
contract = Contract.find_by_id(params[:contract_id])

company&.name || contract&.company&.name || "Default Text"
</code>```

but when I run it, I get an error. Here's the error:

```<code>undefined local variable or method `name' for #<Api::V1::ReportsController:0x007fb7e2570660>
</code>```

I looks like it's just trying to access the varible/method name, rather than trying to access it from company, contract.company, or nil. Any reason why this might happen? Also why would it happen in the controller, but not the console?

答:
It's most likely due to a typo. Make sure you wrote:

contract&.company&.name, not contract&.company.&name

The .&name typo would raise that very same "undefined local variable or method" error you're encountering.

Body:
I want to get the name property from the first one among the values corresponding to some keys in params that I try to get it from.

In my console this works:

company = Company.find_by_id(params[:company_id])
contract = Contract.find_by_id(params[:contract_id])

company&.name || contract&.company&.name || "Default Text"

but when I run it, I get an error. Here's the error:

undefined local variable or method `name' for #<Api::V1::ReportsController:0x007fb7e2570660>

I looks like it's just trying to access the varible/method name, rather than trying to access it from company, contract.company, or nil. Any reason why this might happen? Also why would it happen in the controller, but not the console?


问:
Regex for decimal values accepting zero but not blank space
I need some help to create a regex for decimal values to be used in jquery, where:

Valid inputs-

- 0.1

- 1222.0

- 0.22

- 0.00

- 22.223

Not valid inputs-

- .1

- 1.

- 22.

- .234

- 0.

- .00

Thanks!

答:
If I read your requirements correctly, a valid decimal is a number which has a decimal point, and one or more numbers on both sides of that decimal point.  If so, then the following regex should work:

```<code>^\d+\.\d+$
</code>```

Demo

Body:
If I read your requirements correctly, a valid decimal is a number which has a decimal point, and one or more numbers on both sides of that decimal point.  If so, then the following regex should work:

^\d+\.\d+$

Demo


问:
Issue with getting a 'foreignObject` d3v3 example to work in d3v4
I have been trying to get this example SVG foreignObject tooltips in D3 to work with D3v4. I've been poking at it for a few hours now without success.

It d3v4, it seemed to choke on object arguments for .attr so I flattened those out. Now it is failing on the line below

```<code>var foHeight = div[0][0].getBoundingClientRect().height;
</code>```

with the error "Cannot read property '0' of undefined"

The error will occur when one runs the code below and rolls over the violet circle. Is this an issue with how selections changed with d3v4?

Any tips?

var margin = {
  top: 20,
  right: 10,
  bottom: 20,
  left: 10
};
var width = 800 - margin.left - margin.right;
var height = 480 - margin.top - margin.bottom;
var svg = d3.select('body')
  .append('svg')
  .attr('width', width + margin.left + margin.right)
  .attr('height', height + margin.top + margin.bottom)
  .append('g')
  .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
svg.append('rect')
  .attr('width', width * 0.8)
  .attr('height', height * 0.8)
  .attr('x', width * 0.1)
  .attr('y', height * 0.1)
  .attr('fill', '#F8F8F8');

var foWidth = 300;
var anchor = {
  'w': width / 3,
  'h': height / 3
};
var t = 50,
  k = 15;
var tip = {
  'w': (3 / 4 * t),
  'h': k
};
svg.append('circle')
  .attr('r', 50)
  .attr('cx', anchor.w)
  .attr('cy', anchor.h)
  .attr('fill', '#7413E8')
  .attr('opacity', 0.35)
  .on('mouseover', function() {
    var fo = svg.append('foreignObject')
      .attr('x', anchor.w - tip.w)
      .attr('y', anchor.h + tip.h)
      .attr('width', foWidth)
      .attr('class', 'svg-tooltip');

    var div = fo.append('xhtml:div')
      .append('div')
      .attr('class', 'tooltip');
    div.append('p')
      .attr('class', 'lead')
      .html('Holmes was certainly not a difficult man to live with.');
    div.append('p')
      .html('He was quiet in his ways, and his habits were regular. It was rare for him to be up after ten at night, and he had invariably breakfasted and gone out before I rose in the morning.');
    var foHeight = div[0][0].getBoundingClientRect().height;
    fo.attr({
      'height': foHeight
    });
    svg.insert('polygon', '.svg-tooltip')
      .attr({
        'points': "0,0 0," + foHeight + " " + foWidth + "," + foHeight + " " + foWidth + ",0 " + (t) + ",0 " + tip.w + "," + (-tip.h) + " " + (t / 2) + ",0",
        'height': foHeight + tip.h,
        'width': foWidth,
        'fill': '#D8D8D8',
        'opacity': 0.75,
        'transform': 'translate(' + (anchor.w - tip.w) + ',' + (anchor.h + tip.h) + ')'
      });
  })
  .on('mouseout', function() {
    svg.selectAll('.svg-tooltip').remove();
    svg.selectAll('polygon').remove();
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg {
  display: block;
  margin: 0 auto;
}

.svg-tooltip {
  pointer-events: none;
}

.tooltip {
  padding: 10px;
  color: #4A22FF;
}

.lead {
  font-style: italic;
}

p {
  margin: 5px 0px;
}

polygon {
  pointer-events: none;
}</code>```

  <meta charset='utf-8'>
  <title>
    SVG foreignObject tooltips in D3
  </title>

```

答:
In D3 v3 selections used to be arrays. Not anymore in V4: now they are objects instead.

The changelog says:

Selections no longer subclass Array using prototype chain injection; they are now plain objects, improving performance.

Let's show it. In D3 v3...

console.log(d3.select("body"))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v3.min.js"></script></code>```

Now in D3 v4:

console.log(d3.select("body"))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

Therefore, since the selection is not an array anymore, this:

```<code>div[0]
</code>```

... will not work.

The solution here is simple, just use node() to get the DOM element:

```<code>var foHeight = div.node().getBoundingClientRect().height;
</code>```

Here is your code with that change:

var margin = {
  top: 20,
  right: 10,
  bottom: 20,
  left: 10
};
var width = 800 - margin.left - margin.right;
var height = 480 - margin.top - margin.bottom;
var svg = d3.select('body')
  .append('svg')
  .attr('width', width + margin.left + margin.right)
  .attr('height', height + margin.top + margin.bottom)
  .append('g')
  .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
svg.append('rect')
  .attr('width', width * 0.8)
  .attr('height', height * 0.8)
  .attr('x', width * 0.1)
  .attr('y', height * 0.1)
  .attr('fill', '#F8F8F8');

var foWidth = 300;
var anchor = {
  'w': width / 3,
  'h': height / 3
};
var t = 50,
  k = 15;
var tip = {
  'w': (3 / 4 * t),
  'h': k
};
svg.append('circle')
  .attr('r', 50)
  .attr('cx', anchor.w)
  .attr('cy', anchor.h)
  .attr('fill', '#7413E8')
  .attr('opacity', 0.35)
  .on('mouseover', function() {
    var fo = svg.append('foreignObject')
      .attr('x', anchor.w - tip.w)
      .attr('y', anchor.h + tip.h)
      .attr('width', foWidth)
      .attr('class', 'svg-tooltip');

    var div = fo.append('xhtml:div')
      .append('div')
      .attr('class', 'tooltip');
    div.append('p')
      .attr('class', 'lead')
      .html('Holmes was certainly not a difficult man to live with.');
    div.append('p')
      .html('He was quiet in his ways, and his habits were regular. It was rare for him to be up after ten at night, and he had invariably breakfasted and gone out before I rose in the morning.');
    var foHeight = div.node().getBoundingClientRect().height;
    fo.attr({
      'height': foHeight
    });
    svg.insert('polygon', '.svg-tooltip')
      .attr({
        'points': "0,0 0," + foHeight + " " + foWidth + "," + foHeight + " " + foWidth + ",0 " + (t) + ",0 " + tip.w + "," + (-tip.h) + " " + (t / 2) + ",0",
        'height': foHeight + tip.h,
        'width': foWidth,
        'fill': '#D8D8D8',
        'opacity': 0.75,
        'transform': 'translate(' + (anchor.w - tip.w) + ',' + (anchor.h + tip.h) + ')'
      });
  })
  .on('mouseout', function() {
    svg.selectAll('.svg-tooltip').remove();
    svg.selectAll('polygon').remove();
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg {
  display: block;
  margin: 0 auto;
}

.svg-tooltip {
  pointer-events: none;
}

.tooltip {
  padding: 10px;
  color: #4A22FF;
}

.lead {
  font-style: italic;
}

p {
  margin: 5px 0px;
}

polygon {
  pointer-events: none;
}</code>```

  <meta charset='utf-8'>
  <title>
    SVG foreignObject tooltips in D3
  </title>

```

Body:
I have been trying to get this example SVG foreignObject tooltips in D3 to work with D3v4. I've been poking at it for a few hours now without success.

It d3v4, it seemed to choke on object arguments for .attr so I flattened those out. Now it is failing on the line below

var foHeight = div[0][0].getBoundingClientRect().height;

with the error "Cannot read property '0' of undefined"

The error will occur when one runs the code below and rolls over the violet circle. Is this an issue with how selections changed with d3v4?

Any tips?

var margin = {
  top: 20,
  right: 10,
  bottom: 20,
  left: 10
};
var width = 800 - margin.left - margin.right;
var height = 480 - margin.top - margin.bottom;
var svg = d3.select('body')
  .append('svg')
  .attr('width', width + margin.left + margin.right)
  .attr('height', height + margin.top + margin.bottom)
  .append('g')
  .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
svg.append('rect')
  .attr('width', width * 0.8)
  .attr('height', height * 0.8)
  .attr('x', width * 0.1)
  .attr('y', height * 0.1)
  .attr('fill', '#F8F8F8');

var foWidth = 300;
var anchor = {
  'w': width / 3,
  'h': height / 3
};
var t = 50,
  k = 15;
var tip = {
  'w': (3 / 4 * t),
  'h': k
};
svg.append('circle')
  .attr('r', 50)
  .attr('cx', anchor.w)
  .attr('cy', anchor.h)
  .attr('fill', '#7413E8')
  .attr('opacity', 0.35)
  .on('mouseover', function() {
    var fo = svg.append('foreignObject')
      .attr('x', anchor.w - tip.w)
      .attr('y', anchor.h + tip.h)
      .attr('width', foWidth)
      .attr('class', 'svg-tooltip');

    var div = fo.append('xhtml:div')
      .append('div')
      .attr('class', 'tooltip');
    div.append('p')
      .attr('class', 'lead')
      .html('Holmes was certainly not a difficult man to live with.');
    div.append('p')
      .html('He was quiet in his ways, and his habits were regular. It was rare for him to be up after ten at night, and he had invariably breakfasted and gone out before I rose in the morning.');
    var foHeight = div[0][0].getBoundingClientRect().height;
    fo.attr({
      'height': foHeight
    });
    svg.insert('polygon', '.svg-tooltip')
      .attr({
        'points': "0,0 0," + foHeight + " " + foWidth + "," + foHeight + " " + foWidth + ",0 " + (t) + ",0 " + tip.w + "," + (-tip.h) + " " + (t / 2) + ",0",
        'height': foHeight + tip.h,
        'width': foWidth,
        'fill': '#D8D8D8',
        'opacity': 0.75,
        'transform': 'translate(' + (anchor.w - tip.w) + ',' + (anchor.h + tip.h) + ')'
      });
  })
  .on('mouseout', function() {
    svg.selectAll('.svg-tooltip').remove();
    svg.selectAll('polygon').remove();
  });

svg {
  display: block;
  margin: 0 auto;
}

.svg-tooltip {
  pointer-events: none;
}

.tooltip {
  padding: 10px;
  color: #4A22FF;
}

.lead {
  font-style: italic;
}

p {
  margin: 5px 0px;
}

polygon {
  pointer-events: none;
}

  <meta charset='utf-8'>
  <title>
    SVG foreignObject tooltips in D3
  </title>

Body:
In D3 v3 selections used to be arrays. Not anymore in V4: now they are objects instead.

The changelog says:

Selections no longer subclass Array using prototype chain injection; they are now plain objects, improving performance.

Let's show it. In D3 v3...

console.log(d3.select("body"))

<script src="https://d3js.org/d3.v3.min.js"></script>

Now in D3 v4:

console.log(d3.select("body"))

<script src="https://d3js.org/d3.v4.min.js"></script>

Therefore, since the selection is not an array anymore, this:

div[0]

... will not work.

The solution here is simple, just use node() to get the DOM element:

var foHeight = div.node().getBoundingClientRect().height;

Here is your code with that change:

var margin = {
  top: 20,
  right: 10,
  bottom: 20,
  left: 10
};
var width = 800 - margin.left - margin.right;
var height = 480 - margin.top - margin.bottom;
var svg = d3.select('body')
  .append('svg')
  .attr('width', width + margin.left + margin.right)
  .attr('height', height + margin.top + margin.bottom)
  .append('g')
  .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
svg.append('rect')
  .attr('width', width * 0.8)
  .attr('height', height * 0.8)
  .attr('x', width * 0.1)
  .attr('y', height * 0.1)
  .attr('fill', '#F8F8F8');

var foWidth = 300;
var anchor = {
  'w': width / 3,
  'h': height / 3
};
var t = 50,
  k = 15;
var tip = {
  'w': (3 / 4 * t),
  'h': k
};
svg.append('circle')
  .attr('r', 50)
  .attr('cx', anchor.w)
  .attr('cy', anchor.h)
  .attr('fill', '#7413E8')
  .attr('opacity', 0.35)
  .on('mouseover', function() {
    var fo = svg.append('foreignObject')
      .attr('x', anchor.w - tip.w)
      .attr('y', anchor.h + tip.h)
      .attr('width', foWidth)
      .attr('class', 'svg-tooltip');

    var div = fo.append('xhtml:div')
      .append('div')
      .attr('class', 'tooltip');
    div.append('p')
      .attr('class', 'lead')
      .html('Holmes was certainly not a difficult man to live with.');
    div.append('p')
      .html('He was quiet in his ways, and his habits were regular. It was rare for him to be up after ten at night, and he had invariably breakfasted and gone out before I rose in the morning.');
    var foHeight = div.node().getBoundingClientRect().height;
    fo.attr({
      'height': foHeight
    });
    svg.insert('polygon', '.svg-tooltip')
      .attr({
        'points': "0,0 0," + foHeight + " " + foWidth + "," + foHeight + " " + foWidth + ",0 " + (t) + ",0 " + tip.w + "," + (-tip.h) + " " + (t / 2) + ",0",
        'height': foHeight + tip.h,
        'width': foWidth,
        'fill': '#D8D8D8',
        'opacity': 0.75,
        'transform': 'translate(' + (anchor.w - tip.w) + ',' + (anchor.h + tip.h) + ')'
      });
  })
  .on('mouseout', function() {
    svg.selectAll('.svg-tooltip').remove();
    svg.selectAll('polygon').remove();
  });

svg {
  display: block;
  margin: 0 auto;
}

.svg-tooltip {
  pointer-events: none;
}

.tooltip {
  padding: 10px;
  color: #4A22FF;
}

.lead {
  font-style: italic;
}

p {
  margin: 5px 0px;
}

polygon {
  pointer-events: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js" integrity="sha256-aYYnqVVhAJ4lDammP4Qybmxg3/HVpA7/sNSCntyCyu4=" crossorigin="anonymous"></script>

<head>
  <meta charset='utf-8'>
  <title>
    SVG foreignObject tooltips in D3
  </title>

</head>

<body>
</body>

</html>


问:
ReachabilityWithAddress error giving it an ip address
hey Im trying to see if I can connect to an IP address.

My code atm:

```<code>#import "ViewController.h"
#import "SystemConfiguration/SystemConfiguration.h"

@implementation ViewController
struct sockaddr_in ;

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

Reachability *d = [Reachability reachabilityWithAddress:const struct sockaddr_in     ???????];
NetworkStatus internetStatus = [d currentReachabilityStatus];
//NetworkStatus internetStatus = [d currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus!= ReachableViaWWAN)){
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No internet" message:@"No internet" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
   [alert release];
}
else {
    UIAlertView *notify = [[UIAlertView alloc] initWithTitle:@"Internet" message:@"There is internet!(not)" delegate:self cancelButtonTitle:@"funny" otherButtonTitles:nil];
    [notify show];
    [notify release];

    }
}
</code>```

Can someone tell me plz how to make this work?

I have no idea how to insert an ip address there...

答:
This code works for me:</p>

```<code>    struct sockaddr_in localWifiAddress;
    bzero(&localWifiAddress, sizeof(localWifiAddress));
    localWifiAddress.sin_len = sizeof(localWifiAddress);
    localWifiAddress.sin_family = AF_INET;
    localWifiAddress.sin_addr.s_addr = htonl(0x0A0A0A7B); // hex representation of your local IP

    Reachability *reachability = [Reachability reachabilityWithAddress:&localWifiAddress];
    reachability.key = kLocalWiFiConnection;
    return [reachability isReachable];
</code>```

Body:
hey Im trying to see if I can connect to an IP address.

My code atm:

#import "ViewController.h"
#import "SystemConfiguration/SystemConfiguration.h"

@implementation ViewController
struct sockaddr_in ;

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

Reachability *d = [Reachability reachabilityWithAddress:const struct sockaddr_in     ???????];
NetworkStatus internetStatus = [d currentReachabilityStatus];
//NetworkStatus internetStatus = [d currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus!= ReachableViaWWAN)){
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No internet" message:@"No internet" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
   [alert release];
}
else {
    UIAlertView *notify = [[UIAlertView alloc] initWithTitle:@"Internet" message:@"There is internet!(not)" delegate:self cancelButtonTitle:@"funny" otherButtonTitles:nil];
    [notify show];
    [notify release];

    }
}

Can someone tell me plz how to make this work?

I have no idea how to insert an ip address there...

Body:
This code works for me:

    struct sockaddr_in localWifiAddress;
    bzero(&localWifiAddress, sizeof(localWifiAddress));
    localWifiAddress.sin_len = sizeof(localWifiAddress);
    localWifiAddress.sin_family = AF_INET;
    localWifiAddress.sin_addr.s_addr = htonl(0x0A0A0A7B); // hex representation of your local IP

    Reachability *reachability = [Reachability reachabilityWithAddress:&localWifiAddress];
    reachability.key = kLocalWiFiConnection;
    return [reachability isReachable];


问:
How to handle Data Structure of size greater than 16 Mb in RPGLE
I am unable to compile a RPGLE program as it includes a data structure array of size greater than 16Mb.

Compilation Error:

RNF0376 - The data item is larger than the maximum of 16,773,104
  bytes.

I know we can use pointers as workaround, is there any other solution ?

答:
Would a dynamic array solve your problem?

I'm curious, how are you returning this to a web service? Is it a SQLRPGLE program using SET RESULTS ARRAY and acting as an external stored procedure?

If so you could declare a GLOBAL TEMPORARY TABLE, fill it, and SET RESULTS CURSOR ...


问:
For images, what is the benefit of using the name element? name="...."
I want to know what the difference is between alt="" and name=""

Would it be better to put the filename within the alt tag, or the description of the photo?

What makes better sense, both from SEO and validation stand-point?

答:
The name attribute exists only to provide a name to refer to in JavaScript.

The alt attribute provides an alternate description for search engines, blind people, when the image could not be loaded, etc.

The title attribute provides a description which will be shown when the user hovers over the image with his mouse - some (but not all) browsers will use the alt attribute for this purpose when there is no title

OwnerDisplayName: Brad

OwnerDisplayName: Michael Borgwardt


答:
That means if you insert a row in item table, values color=red,shape=0,width=0.............

then you select the email id of particular matching values color=red,shape=0,width=0 from
Notifications table.

am i correct???????

Go to your process page. that is insert query page. then select the data from there by using this post data.

for example

```<code>$color=$_POST['color'];
$shape=$_POST['shape'];
$width=$_POST['width'];
</code>```

then use the select query

```<code>"select email from notifications where color='$color' and shape='$shape' and width='$width'"
</code>```

i hope this is your needs......

but thats not a problem
in notification table also you use the value 0.

if a user choose red only, your insertion query enter color=red and shape,width as 0.
so that will ensure your needs

Title: A little help required on sending email notifications something similar to Job alerts

Body:
That means if you insert a row in item table, values color=red,shape=0,width=0.............

then you select the email id of particular matching values color=red,shape=0,width=0 from
Notifications table.

am i correct???????

Go to your process page. that is insert query page. then select the data from there by using this post data.

for example

$color=$_POST['color'];
$shape=$_POST['shape'];
$width=$_POST['width'];

then use the select query

"select email from notifications where color='$color' and shape='$shape' and width='$width'"

i hope this is your needs......

but thats not a problem
in notification table also you use the value 0.

if a user choose red only, your insertion query enter color=red and shape,width as 0.
so that will ensure your needs


问:
How to push 2 branches from local to remote repo in git?
I have 2 branches in my local, for example:

FirstApp

SecondApp

How to push both of them to remote repo? Do I also need to create two branches in remote as well?

Many thanks!

答:
Now I use SourceTree to help managing my local repository.

It helps to push all local branches that have not been created at repo by:

Press Push button on top bar

Check the Push and Track columns for each branches that have not been pushed to remote

Press Ok button


问:
ggplot2: geom_bar with group, position_dodge and fill
I am trying to generate a barplot such that the x-axes is by patient with each patient having multiple samples. So for instance (using the mtcars data as a template of what the data would look like):

library("ggplot2")
ggplot(mtcars, aes(x = factor(cyl), group = factor(gear))) +
   geom_bar(position = position_dodge(width = 0.8), binwidth = 25) +
   xlab("Patient") +
   ylab("Number of Mutations per Patient Sample")
```

<p>This would produce something like this:</p>

<p><img src="https://i.stack.imgur.com/WXneV.png" alt="enter image description here"></p>

<p>With each barplot representing a sample in each patient. </p>

<p>I want to add additional information about each patient sample by using colors to fill the barplots (e.g. different types of mutations in each patient sample). I was thinking I could specify the fill parameter like this:</p>

<pre class="lang-r prettyprint-override"><code>ggplot(mtcars, aes(x = factor(cyl), group = factor(gear), fill = factor(vs))) +
   geom_bar(position = position_dodge(width = 0.8), binwidth = 25) +
   xlab("Patient") +
   ylab("Number of Mutations per Patient Sample")
</code>```

But this doesn't produce "stacked barplots" for each patient sample barplot. I am assuming this is because the position_dodge() is set.  Is there anyway to get around this? Basically, what I want is:

ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs))) +
   geom_bar() +
   xlab("Patient") +
   ylab("Number of Mutations per Patient Sample")
```

But with these colors available in the first plot I listed. Is this possible with ggplot2?

答:
I have hacked around this a few times by layering multiple geom_cols on top of each other in the order I prefer. For example, the code

```<code>    ggplot(data, aes(x=cert, y=pct, fill=Party, group=Treatment, shape=Treatment)) +
      geom_col(aes(x=cert, y=1), position=position_dodge(width=.9), fill="gray90") +
      geom_col(position=position_dodge(width=.9)) +
      scale_fill_manual(values=c("gray90", "gray60"))
</code>```

Allowed me to produce the feature you're looking for without faceting. Notice how I set the background layer's y value to 1. To add more layers, you can just cumulatively sum your variables.

Image of the plot:

Body:
I am trying to generate a barplot such that the x-axes is by patient with each patient having multiple samples. So for instance (using the mtcars data as a template of what the data would look like):

library("ggplot2")
ggplot(mtcars, aes(x = factor(cyl), group = factor(gear))) +
   geom_bar(position = position_dodge(width = 0.8), binwidth = 25) +
   xlab("Patient") +
   ylab("Number of Mutations per Patient Sample")

This would produce something like this:

With each barplot representing a sample in each patient.

I want to add additional information about each patient sample by using colors to fill the barplots (e.g. different types of mutations in each patient sample). I was thinking I could specify the fill parameter like this:

ggplot(mtcars, aes(x = factor(cyl), group = factor(gear), fill = factor(vs))) +
   geom_bar(position = position_dodge(width = 0.8), binwidth = 25) +
   xlab("Patient") +
   ylab("Number of Mutations per Patient Sample")

But this doesn't produce "stacked barplots" for each patient sample barplot. I am assuming this is because the position_dodge() is set.  Is there anyway to get around this? Basically, what I want is:

ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs))) +
   geom_bar() +
   xlab("Patient") +
   ylab("Number of Mutations per Patient Sample")

But with these colors available in the first plot I listed. Is this possible with ggplot2?

Body:
I have hacked around this a few times by layering multiple geom_cols on top of each other in the order I prefer. For example, the code

    ggplot(data, aes(x=cert, y=pct, fill=Party, group=Treatment, shape=Treatment)) +
      geom_col(aes(x=cert, y=1), position=position_dodge(width=.9), fill="gray90") +
      geom_col(position=position_dodge(width=.9)) +
      scale_fill_manual(values=c("gray90", "gray60"))

Allowed me to produce the feature you're looking for without faceting. Notice how I set the background layer's y value to 1. To add more layers, you can just cumulatively sum your variables.

Image of the plot:


问:
How to reverse geocoding using gms?
I noticed that there exists the GMSGeocoder for reverse geocoding for iOS, but not found the similarity in Google play service.

Of course, I can use the Geocoder in the Android Location api, or, there also a way for reverse geocoding using http request for this. but with the applied API key, I did find the corresponding XXGeocoder in GMS for Android in Google play service.

Did I miss it?

答:
Seems the android Geocoder could do the work good enough.

From this ariticle:

The Android Geocoder API is also only available on GMS devices with location services although it does not depend on the GoogleApiClient like Geofencing and Activity Recognition.  The Geocoder class offers both geocoding and reverse geocoding meaning it will return a lat / long based on an address and vice-versa.  In my experience the API provides very accurate results and it has clear benefits to package delivery use cases.

Title: How to reverse geocoding using gms?


问:
How can I remove all old related items in an array list when I insert a new item? i.e. Cube 1 removed when adding Cube 2
```<code>String[] total = new String[] {
  };

final List<String> total_list = new ArrayList<String>(Arrays.asList(total));
</code>```

I add the total string 1 by 1 by pressing a button

```<code>total_list.add(newstring);
</code>```

So, my array will be like this:

```<code>ArrayList {"Cube 1", "Cube 2", "Cube 3", "Square 1", "Square 2", "Square 3" ...}
</code>```

How to delete the prior inserted data?

So when I add data array Cube 3 all data with Cube 1, Cube 2 will be deleted, and the other same too, Square 1, Square 2 will be deleted when I insert Square 3.

答:
For the question that you ask, how to delete last new inserted data?

```<code>total_list.remove(total_list.size()-1);
</code>```

This will remove the last new inserted data.

Body:
String[] total = new String[] {
  };

final List<String> total_list = new ArrayList<String>(Arrays.asList(total));

I add the total string 1 by 1 by pressing a button

total_list.add(newstring);

So, my array will be like this:

ArrayList {"Cube 1", "Cube 2", "Cube 3", "Square 1", "Square 2", "Square 3" ...}

How to delete the prior inserted data?

So when I add data array Cube 3 all data with Cube 1, Cube 2 will be deleted, and the other same too, Square 1, Square 2 will be deleted when I insert Square 3.

Body:
For the question that you ask, how to delete last new inserted data?

total_list.remove(total_list.size()-1);

This will remove the last new inserted data.


问:
Continued - Vehicle License Plate Detection
Continuing from this thread:

What are good algorithms for vehicle license plate detection?

I've developed my image manipulation techniques to emphasise the license plate as much as possible, and overall I'm happy with it, here are two samples.

Now comes the most difficult part, actually detecting the license plate. I know there are a few edge detection methods, but my maths is quite poor so I'm unable to translate some of the complex formulas into code.

My idea so far is to loop through every pixel within the image (for loop based on img width & height) From this compare each pixel against a list of colours, from this an algorithm is checked to see if the colors keep differentiating between the license plate white, and the black of the text. If this happens to be true these pixels are built into a new bitmap within memory, then an OCR scan is performed once this pattern has stopped being detected.

I'd appreciate some input on this as it might be a flawed idea, too slow or intensive.

Thanks

答: If you have a lot of samples, you could try to check face detection method developed by Paul Viola and Michael Jones. It's good for face detection, maybe it'll do fine with license plate detection (especially if combined with some other method)</p>


答:
```<code>[x[0] for x in enumerate(l) if x[1] == 4]
</code>```

Title: How to find the different indexes of the same value?

Body:
For example I have:

l = [4, 1 ,3, 4, 7 , 4]

if I use

l.index(4)

it returns back 0

How do I get it to return back 0, 3, 5?


问:
Replacement for Azure MobileService.Client.GetPush().RegisterAsync()
Since the Microsoft.Azure.MobileClient nuget currently is only supporting .net standard I am considering dropping it from my app-project.
The only thing I am using it for is the RegisterAsync() call.

Can I do this in the backend (using the Azure Notification services) instead? I have my Firebase token and my apple token. I just need to register them in the Azure notification hub.

thanks!

答:
Can I do this in the backend (using the Azure Notification services) instead?

If I understand you correctly, you could build the WebAPI backend for your mobile clients to register the notifications. And you could install the Microsoft.Azure.NotificationHubs NuGet package for processing the notifications. More details, you could refer to Register for notifications by using the WebAPI back end and here for communicating with your WebAPI for creating the registration.


问:
node: command not found on Debian
So, I'm working on a mac and as webserver, I got Debian 8 installed. However, I'm currently working on a node application which I developed on my localhost most of the time, where everything works fine - I can use node index.js without issues.

However, I installed node on my webserver via the recommendation of the node.js website, which is ...

```<code>sudo apt-get install -y nodejs
</code>```

... which didn't throw any errors. After that, I could use the npm command. But when I try to execute node index.js, I receive bash: node: command not found. Also, node is not installed in my /usr/local/bin folder. So I can't even run in via /usr/local/bin/node which was recommended here.

So what exactly did I do wrong? I'm rather confused right now and really don't know how to fix the problem.

答:
My problem was that I didn't load the distributions repo...

for the curl url, you'll need to change your setup_#.x number based on your version of Debian.

Adding the NodeSource APT repository for Debian-based distributions repository AND the PGP key for verifying packages

$ sudo curl -sL https://deb.nodesource.com/setup_6.x | bash -

Install Node.js from the Debian-based distributions repository

$ sudo apt-get install -y nodejs

Hope this helps!

More information here...
http://nodesource.com/blog/installing-node-js-tutorial-debian-linux/

Title: node: command not found on Debian

Body:
So, I'm working on a mac and as webserver, I got Debian 8 installed. However, I'm currently working on a node application which I developed on my localhost most of the time, where everything works fine - I can use node index.js without issues.

However, I installed node on my webserver via the recommendation of the node.js website, which is ...

sudo apt-get install -y nodejs

... which didn't throw any errors. After that, I could use the npm command. But when I try to execute node index.js, I receive bash: node: command not found. Also, node is not installed in my /usr/local/bin folder. So I can't even run in via /usr/local/bin/node which was recommended here.

So what exactly did I do wrong? I'm rather confused right now and really don't know how to fix the problem.


问:
Dynamically resolve property type based on another property value in TypeScript
I have the following TypeScript interface:

```<code>interface SelectProps {
    options: Option[];
    value: string[];
    onChange: (value: string[]) => void;
}
</code>```

I want to add boolean called isMultiple that will change the types of the other properties.

When isMultiple=true

enforce value:string[]

enforce onChange: (value: string[]) => void;

When isMultiple=false

enforce value:string

enforce onChange: (value: string) => void;

Is it possible to dynamically set the type of other properties based on the value of one property?

答:
It's a bit late but I hope it helps others like it helped me.

Discriminated unions, also known as tagged unions or algebraic data types can be used to solve this problem.

interface MultipleSelectProps {
    isMultiple: true;
    options: string[];
    value: string[];
    onChange: (value: string[]) => void;
}

interface SingleSelectProps {
    isMultiple: false;
    options: string[];
    value: string;
    onChange: (value: string) => void;
}

type SelectProps = MultipleSelectProps | SingleSelectProps;
```

<p>Usage example:</p>

```function Select(props: SelectProps) {
    if (props.isMultiple) {
        const { value, onChange } = props;
        onChange(value);
    } else if (props.isMultiple === false) {
        const { value, onChange } = props;
        onChange(value);
    }
}
```

Note: When isMultiple is undefined or null it is not possible to infer the specific type of SelectProps. In these cases is necessary to do a strict comparison isMultiple === false.

Source: https://blog.mariusschulz.com/2016/11/03/typescript-2-0-tagged-union-types

Body:
I have the following TypeScript interface:

interface SelectProps {
    options: Option[];
    value: string[];
    onChange: (value: string[]) => void;
}

I want to add boolean called isMultiple that will change the types of the other properties.

When isMultiple=true

enforce value:string[]

enforce onChange: (value: string[]) => void;

When isMultiple=false

enforce value:string

enforce onChange: (value: string) => void;

Is it possible to dynamically set the type of other properties based on the value of one property?

Body:
It's a bit late but I hope it helps others like it helped me.

Discriminated unions, also known as tagged unions or algebraic data types can be used to solve this problem.

interface MultipleSelectProps {
    isMultiple: true;
    options: string[];
    value: string[];
    onChange: (value: string[]) => void;
}

interface SingleSelectProps {
    isMultiple: false;
    options: string[];
    value: string;
    onChange: (value: string) => void;
}

type SelectProps = MultipleSelectProps | SingleSelectProps;

Usage example:

function Select(props: SelectProps) {
    if (props.isMultiple) {
        const { value, onChange } = props;
        onChange(value);
    } else if (props.isMultiple === false) {
        const { value, onChange } = props;
        onChange(value);
    }
}

Note: When isMultiple is undefined or null it is not possible to infer the specific type of SelectProps. In these cases is necessary to do a strict comparison isMultiple === false.

Source: https://blog.mariusschulz.com/2016/11/03/typescript-2-0-tagged-union-types