问:
How do I change the Development language in Xcode before internationalizing my app?
I'm taking over an app that was written entirely in French. Strings are hardcoded in French in the code, and all the messages in the storyboard are in French. But the initial development region in Info.plist was left to English. So I changed CFBundleDevelopmentRegion to fr so that it matches the real language that was used. But XCode keeps telling me that my Development language is English:

How can I correct that? The goal is to be able to activate Base Internationalization and have it use French as the Base language instead of English.

答:
I wanted to develop the project in my own "developer" language by using placeholders instead of real texts in example "WLAN_NOT_AVAILABLE" inside of NSLocalizedString which later on will be translated in different languages including english, off course. I do not like when I must write whole sentences right in the code.

I did just open *.pbxproj file inside of *.xcodeproj folder and changed the following line to:

```<code>developmentRegion = Base;
</code>```

After that English was no more set as development language and I was able to treat it as any one else. This gives you as developer the possibility to write short text placeholders and delegate the correct spelling to another in your team.

ContentLicense: CC BY-SA 4.0

Body:
I wanted to develop the project in my own "developer" language by using placeholders instead of real texts in example "WLAN_NOT_AVAILABLE" inside of NSLocalizedString which later on will be translated in different languages including english, off course. I do not like when I must write whole sentences right in the code.

I did just open *.pbxproj file inside of *.xcodeproj folder and changed the following line to:

developmentRegion = Base;

After that English was no more set as development language and I was able to treat it as any one else. This gives you as developer the possibility to write short text placeholders and delegate the correct spelling to another in your team.


来源: stackexchange

问:
functions with different names but same arguments
I have a set of functions with the same number of arguments, but different names (suppose each implement different method). I have the name of the requested method in a string. Is it possible to call the corresponding function using the method name. to make it clear, suppose that I have the following function (I just mentioned their name and argument):

```<code>search_esa(int a, int b);
search_tss(int a, int b);
search_fss(int a, int b);
search_ds(int a, int b);
</code>```

now lets assume I have the name of the requested method, lets assume esa, in a string:

```<code>string methodName = "esa"
</code>```

is it possible to call the corresponding function by using macros?
I tested

```<code>#define CALL_SEARCH_MV(method) search_##method
</code>```

and then try to call it by:

```<code>CALL_SEARCH_MV(methodName.c_str())
</code>```

but it calls search_methodName function, which does not exist. Any other suggestions would be greatly appreciated (except suggesting switch case method or if).

答:
Not Possible!
the methods defined must be call with the same name. we cannot manipulate the method name.

ContentLicense: CC BY-SA 3.0

Body:
I have a set of functions with the same number of arguments, but different names (suppose each implement different method). I have the name of the requested method in a string. Is it possible to call the corresponding function using the method name. to make it clear, suppose that I have the following function (I just mentioned their name and argument):

search_esa(int a, int b);
search_tss(int a, int b);
search_fss(int a, int b);
search_ds(int a, int b);

now lets assume I have the name of the requested method, lets assume esa, in a string:

string methodName = "esa"

is it possible to call the corresponding function by using macros?
I tested

#define CALL_SEARCH_MV(method) search_##method

and then try to call it by:

CALL_SEARCH_MV(methodName.c_str())

but it calls search_methodName function, which does not exist. Any other suggestions would be greatly appreciated (except suggesting switch case method or if).


问:
Use threading to process file chunk by chunk
I have a arraylist which consists of 5000 IP Addresses. For each IP Address, I want to execute a SNMPGet request and a FTPDownload command. I want to implement it in a fashion, wherein at a time 2 different threads run simultaneously for the first five IP Addresses. After the execution of these IP Addresses, next 2 IP Addresses will be executed on these threads. Can anyone help how to do it?

Here, connection is a class which extends the thread and the work to be implemented is written in its run() method. Please help.

```<code>Connection newConnection =new Connection(0);
Connection newConnection1 =new Connection(1);

for(int i = 0; i < NE_list.getRowCount(); i=i+2)
{
if(NE_list.getValueAt(i, 0).toString().equals("true")) //Some condition here for the IP Address
{

            newConnection.i=i;
            newConnection1.i=i+1;
            newConnection.runprogram();
            newConnection1.runprogram();
 }

    }

class Connection extends Thread{
int  i;
Connection(int val){
  i=val;
}
void runprogram(){
start();
}
public void run(){
//SNMP and FTP Code here for IP Address in index i of NE_list
}
}
</code>```

答:
Herewith adding working example having 5 threads. Just put the test.txt in your CLASS_PATH of the application.

```<code>class MyRunnable implements Runnable {
List<List<String>> records;
MyRunnable(List<List<String>> records){
    this.records = records;
}
public void run(){
    for(List list : records){
        System.out.println(Thread.currentThread().getName() + " : "+list.toString());
    }
}}
</code>```

Main Class -

```<code>public class FileProcessThreads {
public List<List<String>> process(String fileName) throws IOException {
    List<List<String>> records = new ArrayList<>();
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    String line = null;
    while((line = br.readLine()) != null){
        List<String> listValues = Arrays.asList(line.split(" "));
        records.add(listValues);
    }
    System.out.println(records.size());
    return records;
}
public static void main(String[] args) throws IOException {
    FileProcessThreads fp = new FileProcessThreads();
    List<List<String>> records = fp.process("test.txt");
    ExecutorService es = Executors.newFixedThreadPool(5);
    int recordsInEachThread = (int) (records.size()/5);
    System.out.println(recordsInEachThread);

    MyRunnable my1 = new MyRunnable(records.subList(0, recordsInEachThread));
    MyRunnable my2 = new MyRunnable(records.subList(recordsInEachThread+1, recordsInEachThread*2));
    MyRunnable my3 = new MyRunnable(records.subList(recordsInEachThread*2 + 1, recordsInEachThread*3));
    MyRunnable my4 = new MyRunnable(records.subList(recordsInEachThread*3 + 1, recordsInEachThread*4));
    MyRunnable my5 = new MyRunnable(records.subList(recordsInEachThread*4 + 1, records.size() - 1));
    es.execute(my1);
    es.execute(my2);
    es.execute(my3);
    es.execute(my4);
    es.execute(my5);
    es.shutdown();
}}
</code>```

Body:
I have a arraylist which consists of 5000 IP Addresses. For each IP Address, I want to execute a SNMPGet request and a FTPDownload command. I want to implement it in a fashion, wherein at a time 2 different threads run simultaneously for the first five IP Addresses. After the execution of these IP Addresses, next 2 IP Addresses will be executed on these threads. Can anyone help how to do it?

Here, connection is a class which extends the thread and the work to be implemented is written in its run() method. Please help.

Connection newConnection =new Connection(0);
Connection newConnection1 =new Connection(1);

for(int i = 0; i < NE_list.getRowCount(); i=i+2)
{
if(NE_list.getValueAt(i, 0).toString().equals("true")) //Some condition here for the IP Address
{

            newConnection.i=i;
            newConnection1.i=i+1;
            newConnection.runprogram();
            newConnection1.runprogram();
 }

    }

class Connection extends Thread{
int  i;
Connection(int val){
  i=val;
}
void runprogram(){
start();
}
public void run(){
//SNMP and FTP Code here for IP Address in index i of NE_list
}
}

Body:
Herewith adding working example having 5 threads. Just put the test.txt in your CLASS_PATH of the application.

class MyRunnable implements Runnable {
List<List<String>> records;
MyRunnable(List<List<String>> records){
    this.records = records;
}
public void run(){
    for(List list : records){
        System.out.println(Thread.currentThread().getName() + " : "+list.toString());
    }
}}

Main Class -

public class FileProcessThreads {
public List<List<String>> process(String fileName) throws IOException {
    List<List<String>> records = new ArrayList<>();
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    String line = null;
    while((line = br.readLine()) != null){
        List<String> listValues = Arrays.asList(line.split(" "));
        records.add(listValues);
    }
    System.out.println(records.size());
    return records;
}
public static void main(String[] args) throws IOException {
    FileProcessThreads fp = new FileProcessThreads();
    List<List<String>> records = fp.process("test.txt");
    ExecutorService es = Executors.newFixedThreadPool(5);
    int recordsInEachThread = (int) (records.size()/5);
    System.out.println(recordsInEachThread);

    MyRunnable my1 = new MyRunnable(records.subList(0, recordsInEachThread));
    MyRunnable my2 = new MyRunnable(records.subList(recordsInEachThread+1, recordsInEachThread*2));
    MyRunnable my3 = new MyRunnable(records.subList(recordsInEachThread*2 + 1, recordsInEachThread*3));
    MyRunnable my4 = new MyRunnable(records.subList(recordsInEachThread*3 + 1, recordsInEachThread*4));
    MyRunnable my5 = new MyRunnable(records.subList(recordsInEachThread*4 + 1, records.size() - 1));
    es.execute(my1);
    es.execute(my2);
    es.execute(my3);
    es.execute(my4);
    es.execute(my5);
    es.shutdown();
}}


问:
Odoo inheritance button
I need to add new  button to project.task model but i definitely have something mixed up here, can you guys help me with that and explain what's wrong  with my logic. i bet there is problem not only in method. maybe i need to add a field in my class called "`message_follower_ids" ?

```<code>class ProjectTaskFollowers(models.Model):
    _name = 'project.task.followers'
    _inherit = 'project.task'

@api.multi
def parameters_transfer(self):
    self.message_follower_ids = project_id.message_follower_ids

 <?xml version="1.0" encoding="utf-8"?>
<odoo>

<record id="act_project_task_inherited" model="ir.actions.act_window">
        <field name="name">taks.project.fallowers.inh.act</field>
        <field name="res_model">project.task.followers</field>
        <field name="view_mode">kanban,tree,form,calendar,pivot,graph</field>
        <field name="help" type="html">
        </field>
    </record>

<!-- Inherit Form View to Modify it -->
<record id="view_form_project_task_inherited" model="ir.ui.view">
    <field name="name">task.project.fallowers.inher</field>
    <field name="model">project.task.followers</field>
    <field name="inherit_id" ref="project.view_task_form2"/>
    <field name="arch" type="xml">
       <xpath expr="//div[@name='button_box']" postition='inside'>
       <button class="oe_link" type="action" name="%(act_project_task_inherited)%">
           <field string="Assign Project Followers" name="project_id.message_follower_ids" widget="statinfo"/>
       </button>
       </xpath>
    </field>
</record>
</code>```

答:
You have to indent your python code correctly, and i don't know if your code is working well. You also have to extend project.task the right way. Your code is creating a completly new model project.task.followers. I will provide another way to add followers (i changed the method name!):

class ProjectTask(models.Model):
    _inherit = "project.task"
    _name = "project.task"  # optional

    @api.multi
    def add_project_followers(self):
        for task in self:
            partner_ids = task.project_id.message_follower_ids.ids
            task.message_subscribe(partner_ids)
```

<p>EDIT: if you want to use a method for a button, you have to use <code>type="object"</code> and set the method name into <code>name</code>. You also have to use the correct model:</p>

<pre class="lang-xml prettyprint-override"><code><record id="view_form_project_task_inherited" model="ir.ui.view">
    <field name="name">task.project.fallowers.inher</field>
    <field name="model">project.task</field>
    <field name="inherit_id" ref="project.view_task_form2"/>
    <field name="arch" type="xml">
        <xpath expr="//div[@name='button_box']" postition='inside'>
            <button string="Add Followers" type="object" name="add_project_followers" />
        </xpath>
    </field>
</record>
</code>```

Title: Odoo inheritance button

Body:
I need to add new  button to project.task model but i definitely have something mixed up here, can you guys help me with that and explain what's wrong  with my logic. i bet there is problem not only in method. maybe i need to add a field in my class called "`message_follower_ids" ?

class ProjectTaskFollowers(models.Model):
    _name = 'project.task.followers'
    _inherit = 'project.task'

@api.multi
def parameters_transfer(self):
    self.message_follower_ids = project_id.message_follower_ids

 <?xml version="1.0" encoding="utf-8"?>
<odoo>

<record id="act_project_task_inherited" model="ir.actions.act_window">
        <field name="name">taks.project.fallowers.inh.act</field>
        <field name="res_model">project.task.followers</field>
        <field name="view_mode">kanban,tree,form,calendar,pivot,graph</field>
        <field name="help" type="html">
        </field>
    </record>

<record id="view_form_project_task_inherited" model="ir.ui.view">
    <field name="name">task.project.fallowers.inher</field>
    <field name="model">project.task.followers</field>
    <field name="inherit_id" ref="project.view_task_form2"/>
    <field name="arch" type="xml">
       <xpath expr="//div[@name='button_box']" postition='inside'>
       <button class="oe_link" type="action" name="%(act_project_task_inherited)%">
           <field string="Assign Project Followers" name="project_id.message_follower_ids" widget="statinfo"/>
       </button>
       </xpath>
    </field>
</record>

Body:
You have to indent your python code correctly, and i don't know if your code is working well. You also have to extend project.task the right way. Your code is creating a completly new model project.task.followers. I will provide another way to add followers (i changed the method name!):

class ProjectTask(models.Model):
    _inherit = "project.task"
    _name = "project.task"  # optional

    @api.multi
    def add_project_followers(self):
        for task in self:
            partner_ids = task.project_id.message_follower_ids.ids
            task.message_subscribe(partner_ids)

EDIT: if you want to use a method for a button, you have to use type="object" and set the method name into name. You also have to use the correct model:

<record id="view_form_project_task_inherited" model="ir.ui.view">
    <field name="name">task.project.fallowers.inher</field>
    <field name="model">project.task</field>
    <field name="inherit_id" ref="project.view_task_form2"/>
    <field name="arch" type="xml">
        <xpath expr="//div[@name='button_box']" postition='inside'>
            <button string="Add Followers" type="object" name="add_project_followers" />
        </xpath>
    </field>
</record>


问:
How to create a Singleton in C?
What's the best way to create a singleton in C? A concurrent solution would be nice.

I am aware that C isn't the first language you would use for a singleton.

答:
Here's another perspective: every file in a C program is effectively a singleton class that is auto instantiated at runtime and cannot be subclassed.

Global static variables are your private class members.

Global non static are public (just declare them using extern in some header file).

Static functions are private methods

Non-static functions are the public ones.

Give everything a proper prefix and now you can use my_singleton_method() in lieu of my_singleton.method().

If your singleton is complex you can write a generate_singleton() method to initialize it before use, but then you need to make sure all the other public methods check if it was called and error out if not.

Title: How to create a Singleton in C?


问:
change deployed artifact name based on profile
I have in a web application's pom file, a build profile, which does some necessary things (in my code) for qa testing.

I have this code on svn and this code is compiled in Hudson, which deploys artifacts in nexus..

Hudson has two jobs, one for qa profile (-P qa) and one for customers.

What i need is that i change in my qa profile the artifact's name during deploy phase, so that nexus has two different war files, one for qa and one for customer.

I use (after Google search) the following which looks like it does nothing in hudshon!

```<code>    <profile>
        <id>qa</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.5</version>
                    <configuration>
                        <classifier>qa</classifier>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</code>```

any ideas someone?

答:
You actually need to set the "classifier" configuration option on the plugin that's building the package that's being deployed: maven-(ear|ejb|jar|rar|war|shade)-plugin:

For instance, to build a WAR with a qa classifier, you would do the following:

```<code><profile>
    <id>qa</id>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <classifier>qa</classifier>
                </configuration>
            </plugin>
        </plugins>
    </build>
</profile>
</code>```

Also, instead of setting the classifier you could set any of the following (most default to project.build.finalName, so setting that property updates many of these):

General

project.build.finalName

War Plugin

warName

Ear|Jar|Rar|Shade Plugin

finalName

EJB Plugin

jarName

One final note: I never realized this before, but looking over the documentation, it looks like the RAR plugin doesn't support the "classification" option.  Shade does support the classifier concept, but does it via the "shadedClassifierName" property.

ContentLicense: CC BY-SA 2.5

Body:
I have in a web application's pom file, a build profile, which does some necessary things (in my code) for qa testing.

I have this code on svn and this code is compiled in Hudson, which deploys artifacts in nexus..

Hudson has two jobs, one for qa profile (-P qa) and one for customers.

What i need is that i change in my qa profile the artifact's name during deploy phase, so that nexus has two different war files, one for qa and one for customer.

I use (after Google search) the following which looks like it does nothing in hudshon!

    <profile>
        <id>qa</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.5</version>
                    <configuration>
                        <classifier>qa</classifier>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

any ideas someone?

Body:
You actually need to set the "classifier" configuration option on the plugin that's building the package that's being deployed: maven-(ear|ejb|jar|rar|war|shade)-plugin:

For instance, to build a WAR with a qa classifier, you would do the following:

<profile>
    <id>qa</id>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <classifier>qa</classifier>
                </configuration>
            </plugin>
        </plugins>
    </build>
</profile>

Also, instead of setting the classifier you could set any of the following (most default to project.build.finalName, so setting that property updates many of these):

General

project.build.finalName

War Plugin

warName

Ear|Jar|Rar|Shade Plugin

finalName

EJB Plugin

jarName

One final note: I never realized this before, but looking over the documentation, it looks like the RAR plugin doesn't support the "classification" option.  Shade does support the classifier concept, but does it via the "shadedClassifierName" property.


问:
Bash script: Replace a line in a file
I have the following script:

```<code>#!/bin/bash

LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1"
NEW_LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline"

#sed -i "/${LINE}/c ${NEW_LINE}" grub.cfg

LINE1="insmod lvm"
NEW_LINE1="insmod lvm x"

sed -i "/${LINE1}/c ${NEW_LINE1}" grub.cfg
</code>```

Can someone tell me why the commented sed does not work (Error: sed: -e expression #1, char 10: extra characters after command), but the uncommented one does, when only the strings are different?

答:
Since there are slashes in the line that you're looking for, you need to use a different character to mark the boundaries of the s/// command.  For example, you don't have any % symbols in the strings, so:

```<code>LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1"
NEW_LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline"

sed -i "s%.*${LINE}.*%${NEW_LINE}%" grub.cfg
</code>```

Or, keeping the change command, you need to use a different character in the match — you use a backslash in front of it to indicate that's what you're doing.

```<code>LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1"
NEW_LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline"

sed -i "\%${LINE}%c ${NEW_LINE}" grub.cfg
</code>```

The POSIX specification for sed says:

The sed utility shall support the BREs described in XBD Basic Regular Expressions, with the following additions:

In a context address, the construction "\cBREc", where c is any character other than <backslash> or <newline>, shall be identical to "/BRE/". If the character designated by c appears following a <backslash>, then it shall be considered to be that literal character, which shall not terminate the BRE. For example, in the context address "\xabc\xdefx", the second x stands for itself, so that the BRE is "abcxdef".

and:

[2addr]s/BRE/replacement/flags

Substitute the replacement string for instances of the BRE in the pattern space. Any character other than <backslash> or <newline> can be used instead of a <slash> to delimit the BRE and the replacement. Within the BRE and the replacement, the BRE delimiter itself can be used as a literal character if it is preceded by a <backslash>.

Title: Bash script: Replace a line in a file

Body:
I have the following script:

#!/bin/bash

LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1"
NEW_LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline"

#sed -i "/${LINE}/c ${NEW_LINE}" grub.cfg

LINE1="insmod lvm"
NEW_LINE1="insmod lvm x"

sed -i "/${LINE1}/c ${NEW_LINE1}" grub.cfg

Can someone tell me why the commented sed does not work (Error: sed: -e expression #1, char 10: extra characters after command), but the uncommented one does, when only the strings are different?

Body:
Since there are slashes in the line that you're looking for, you need to use a different character to mark the boundaries of the s/// command.  For example, you don't have any % symbols in the strings, so:

LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1"
NEW_LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline"

sed -i "s%.*${LINE}.*%${NEW_LINE}%" grub.cfg

Or, keeping the change command, you need to use a different character in the match — you use a backslash in front of it to indicate that's what you're doing.

LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1"
NEW_LINE="linux /disk0/vmlinuz rw root=/dev/mapper/VolGroup1-disk0_root console=tty0 clock=pit aacraid.msi=1 elevator=deadline"

sed -i "\%${LINE}%c ${NEW_LINE}" grub.cfg

The POSIX specification for sed says:

The sed utility shall support the BREs described in XBD Basic Regular Expressions, with the following additions:

In a context address, the construction "\cBREc", where c is any character other than <backslash> or <newline>, shall be identical to "/BRE/". If the character designated by c appears following a <backslash>, then it shall be considered to be that literal character, which shall not terminate the BRE. For example, in the context address "\xabc\xdefx", the second x stands for itself, so that the BRE is "abcxdef".

and:

[2addr]s/BRE/replacement/flags

Substitute the replacement string for instances of the BRE in the pattern space. Any character other than <backslash> or <newline> can be used instead of a <slash> to delimit the BRE and the replacement. Within the BRE and the replacement, the BRE delimiter itself can be used as a literal character if it is preceded by a <backslash>.


问:
How do you fetch a remote branch without "checking it out"
I am working on a branch "branch-A" and using the command git branch I can see that its the only branch locally.

If I use git branch -a I can see the remote copy of "remotes/origin/branch-B"

What I want to do is bring branch-B locally, but I don't want to actually check it out... I mean I could do that and then checkout my other branch to go back, but its slightly more painful since I am doing this to lots of repos.

I was thinking some sort of fetch? but I can't figure out how to phrase the command. Is it possible?

So I have:

```<code>user@pc> git branch
* branch-A
  master
</code>```

and

```<code>user@pc> git branch -a
* branch-A
  remotes/origin/branch-B
  remotes/origin/branch-A
  remotes/origin/master
</code>```

I want to be able to get:

```<code>user@pc> git branch
* branch-A
  branch-B
  master
</code>```

答:
I think there's some ambiguity about what "bring branch-B locally" means.

If you see origin/branch-B then you already have it locally.  The commits, the trees they contain, the files they contain... all are already in your local repo.  The only thing you don't have is a local branch (branch-B) tracking the remote branch (origin/branch-B).

If you don't want to check branch-B out, then there aren't a lot of reasons to create the local branch.  Just about anything you can do with a local branch, you can do with the remote branch reference.  e.g.:

```<code>git merge origin/branch_B
</code>```

But if you want one, you can create it:

```<code>git branch --set-upstream branch_B origin/branch_B
</code>```

Body:
I am working on a branch "branch-A" and using the command git branch I can see that its the only branch locally.

If I use git branch -a I can see the remote copy of "remotes/origin/branch-B"

What I want to do is bring branch-B locally, but I don't want to actually check it out... I mean I could do that and then checkout my other branch to go back, but its slightly more painful since I am doing this to lots of repos.

I was thinking some sort of fetch? but I can't figure out how to phrase the command. Is it possible?

So I have:

user@pc> git branch
* branch-A
  master

and

user@pc> git branch -a
* branch-A
  remotes/origin/branch-B
  remotes/origin/branch-A
  remotes/origin/master

I want to be able to get:

user@pc> git branch
* branch-A
  branch-B
  master

Body:
I think there's some ambiguity about what "bring branch-B locally" means.

If you see origin/branch-B then you already have it locally.  The commits, the trees they contain, the files they contain... all are already in your local repo.  The only thing you don't have is a local branch (branch-B) tracking the remote branch (origin/branch-B).

If you don't want to check branch-B out, then there aren't a lot of reasons to create the local branch.  Just about anything you can do with a local branch, you can do with the remote branch reference.  e.g.:

git merge origin/branch_B

But if you want one, you can create it:

git branch --set-upstream branch_B origin/branch_B


问:
Report filter parameter
I'm trying to add a filter parameter in a report in Visual Studio 2013 like this tutorial

Reporting Service Tutorial - Basic Parameters

but in VS2013, when I click on add parameter, I can't find the option to prompt the parameter to the user, like in youtube video I linked.

Add Parameter Screenshot

Someone can help me please?

答: Can you please give a little bot more detail? In the screen shot your in the parameter properties window which is the correct location to configure a parameter for a report. If you want to see it as if a user was interacting with it you need to click on the preview tab.</p>

Title: Report filter parameter


问:
Python: Best way to decorate a function only locally
What is the best way to decorate a function, but only in a local scope. For example we have the following:

```<code>def a():
    do stuff
    b()
    do stuff
</code>```

I want to make a function c() that does the same stuff but decorates b so it adds some extra stuff. I found a way to do that but it changes b() globally:

```<code>def c():
    global b
    b = decorator(b)
    a()
</code>```

Is there a way to do that but without changing the function b globally?

答:
Since you're rebinding b() so that calling a() will respect the updated b(), you can save the original b(), and restore it afterwards. This may not be the most efficient way, but it worked for me.

```<code>import copy
def c():
    global b
    orig_b = copy.deepcopy(b)
    b = decorator(b)
    a()
    b = orig_b
</code>```

Body:
What is the best way to decorate a function, but only in a local scope. For example we have the following:

def a():
    do stuff
    b()
    do stuff

I want to make a function c() that does the same stuff but decorates b so it adds some extra stuff. I found a way to do that but it changes b() globally:

def c():
    global b
    b = decorator(b)
    a()

Is there a way to do that but without changing the function b globally?

Body:
Since you're rebinding b() so that calling a() will respect the updated b(), you can save the original b(), and restore it afterwards. This may not be the most efficient way, but it worked for me.

import copy
def c():
    global b
    orig_b = copy.deepcopy(b)
    b = decorator(b)
    a()
    b = orig_b


问:
A better way how to make Eclipse resistant to Java updates
It is a know problem, when you update Java, JDK or JRE, on Windows Eclipse will likely to fail to start as it points to outdated JDK/JRE folder. Fix is relatively simple, it was discussed and solved on several threads like here or here.

But I found those solutions unsatisfyingly inflexible. This solutions suggest to manually fix path in eclipse.ini to something like:

```<code>-vm C:\Program Files\Java\<jdk-version-just-installed>\bin\javaw.exe
</code>```

This means you have to do it after every update, again and again. If you update JDK frequently, and everyone should to have latest security patches, that makes it very annoying.

I expect that after a smart installation every Java program would just run out of box without any manual step involved; any solution less than that I would not consider satisfactory.

I can think of two ways:

using environmental (system) variable like JAVA_HOME. Can eclipse.ini reference environmental variables?

using symbolic link pointing to the latest JDK. And if you wonder, yes, Windows with NTFS support symlinks.

Both ways however need some cooperation from the installer, both JAVA_HOME or symlink as to be updated to the new value. Automatically of course, otherwise there would be no reason why to have them in the first place.
Please correct me if I am wrong, but JDK/JRE installation on linux does exactly that, provides and updates symlink to latest JDK/JRE. Why not Windows installer?

Is there a hidden parameter, option or a toggle in Java install tool doing that?

If not, is there a better, an alternative installation tool?

Can Eclipse launcher itself find a latest Java?

Is there a better eclipse.ini parameter for that?

答:
The purpose of specifying the VM in either eclipse.ini or on the command line is to isolate it from system updates. For example, in the past it has been a big problem that some programs install their own JVM and include it on the system PATH (Oracle was particularly bad about this). So the entire idea is to isolate Eclipse from those kinds of changes; it should not care what other JVMs you have on your system, it refers to a "known" good one for running Eclipse.

Another alternative is to place a JVM directly under the Eclipse installation directory, in a directory named jre, as documented here. I don't personally ever do that, however; I find it to be unnecessary and cumbersome.

What I do that would probably help you is to not install JVM updates into separate directories with names that reflect the actual update version. Instead, I install JDKs into a consistent place based on the major java version. For example:

```<code>/Java/
    /JDK/
        /1.7/
            /bin/
            <etc...>
        /1.8/
            /bin/
            <etc...>
</code>```

That way, in eclipse.ini (or any other place a need to refer to a particular JVM) I just use /Java/JDK/1.8 and that will continue to work no matter how many updates I install into that location.

Body:
It is a know problem, when you update Java, JDK or JRE, on Windows Eclipse will likely to fail to start as it points to outdated JDK/JRE folder. Fix is relatively simple, it was discussed and solved on several threads like here or here.

But I found those solutions unsatisfyingly inflexible. This solutions suggest to manually fix path in eclipse.ini to something like:

-vm C:\Program Files\Java\<jdk-version-just-installed>\bin\javaw.exe

This means you have to do it after every update, again and again. If you update JDK frequently, and everyone should to have latest security patches, that makes it very annoying.

I expect that after a smart installation every Java program would just run out of box without any manual step involved; any solution less than that I would not consider satisfactory.

I can think of two ways:

using environmental (system) variable like JAVA_HOME. Can eclipse.ini reference environmental variables?

using symbolic link pointing to the latest JDK. And if you wonder, yes, Windows with NTFS support symlinks.

Both ways however need some cooperation from the installer, both JAVA_HOME or symlink as to be updated to the new value. Automatically of course, otherwise there would be no reason why to have them in the first place.
Please correct me if I am wrong, but JDK/JRE installation on linux does exactly that, provides and updates symlink to latest JDK/JRE. Why not Windows installer?

Is there a hidden parameter, option or a toggle in Java install tool doing that?

If not, is there a better, an alternative installation tool?

Can Eclipse launcher itself find a latest Java?

Is there a better eclipse.ini parameter for that?

Body:
The purpose of specifying the VM in either eclipse.ini or on the command line is to isolate it from system updates. For example, in the past it has been a big problem that some programs install their own JVM and include it on the system PATH (Oracle was particularly bad about this). So the entire idea is to isolate Eclipse from those kinds of changes; it should not care what other JVMs you have on your system, it refers to a "known" good one for running Eclipse.

Another alternative is to place a JVM directly under the Eclipse installation directory, in a directory named jre, as documented here. I don't personally ever do that, however; I find it to be unnecessary and cumbersome.

What I do that would probably help you is to not install JVM updates into separate directories with names that reflect the actual update version. Instead, I install JDKs into a consistent place based on the major java version. For example:

/Java/
    /JDK/
        /1.7/
            /bin/
            <etc...>
        /1.8/
            /bin/
            <etc...>

That way, in eclipse.ini (or any other place a need to refer to a particular JVM) I just use /Java/JDK/1.8 and that will continue to work no matter how many updates I install into that location.


问:
List sorting - two lists into one
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

```<code>names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])
</code>```

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

答:
Edit: no functions, seriously... no len(), no range(), no .sort()

Initialize our stuff,

```<code>In [1]: names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
   ...: wages = [15000,1500,200,14500,2600]
   ...:
</code>```

compute the length of the list

```<code>In [2]: l = 0
   ...: for w in wages: l += 1
   ...:
</code>```

perform a simple bubble sort, in which we swap elements not only in the list that we are sorting but also in the sibling list

```<code>In [3]: j = 0
   ...: while j<(l-1):
   ...:     i = 0
   ...:     while i<(l-1-j):
   ...:         if wages[i]>wages[i+1]:
   ...:             wages[i], wages[i+1] = wages[i+1], wages[i]
   ...:             names[i], names[i+1] = names[i+1], names[i]
   ...:         i += 1
   ...:     j += 1
   ...:
</code>```

and print the results

```<code>In [4]: print names, '\n', wages
['Aneta', 'Łukasz', 'Mikołaj', 'Ola', 'Asia']
[200, 1500, 2600, 14500, 15000]
</code>```

In a bubble sort every subsequent inner loop operates on a shorter (by 1) sub list because the net effect of each inner loop is to place the greatest element of the current sub list in the last position available in it.

We need only l-1 of those loops because during l-1-th inner loop we operate on a length 2 sub list and when it is completed the whole sublist is completely sorted.

The bubble sort is not an efficient algorithm but given the homeworkicity of the question I think it is more important to use a very simple algorithm than an efficient one.

Title: List sorting - two lists into one

Body:
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

Body:
Edit: no functions, seriously... no len(), no range(), no .sort()

Initialize our stuff,

In [1]: names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
   ...: wages = [15000,1500,200,14500,2600]
   ...:

compute the length of the list

In [2]: l = 0
   ...: for w in wages: l += 1
   ...:

perform a simple bubble sort, in which we swap elements not only in the list that we are sorting but also in the sibling list

In [3]: j = 0
   ...: while j<(l-1):
   ...:     i = 0
   ...:     while i<(l-1-j):
   ...:         if wages[i]>wages[i+1]:
   ...:             wages[i], wages[i+1] = wages[i+1], wages[i]
   ...:             names[i], names[i+1] = names[i+1], names[i]
   ...:         i += 1
   ...:     j += 1
   ...:

and print the results

In [4]: print names, '\n', wages
['Aneta', 'Łukasz', 'Mikołaj', 'Ola', 'Asia']
[200, 1500, 2600, 14500, 15000]

In a bubble sort every subsequent inner loop operates on a shorter (by 1) sub list because the net effect of each inner loop is to place the greatest element of the current sub list in the last position available in it.

We need only l-1 of those loops because during l-1-th inner loop we operate on a length 2 sub list and when it is completed the whole sublist is completely sorted.

The bubble sort is not an efficient algorithm but given the homeworkicity of the question I think it is more important to use a very simple algorithm than an efficient one.


问:
Difference between instances and reserved instances on AWS
In AWS EC2 console I have 2 tabs, Instances and Reserved instances.
In Instances I can launch instance and in Reserved instances i can only purchase.

What are difference between them?
How to launch a reserved instance?

答:
Reserved instances are only a billing feature: When you purchase reserved instances, they will be automatically assigned to your current running instances at the time of billing. The Instances tab is where you manage your current infrastructure.

Note that if you have reserved instances that don't match any running instance type/region/zone they won't be assigned but you'll still pay for them.


问:
Socket.io client not working properly
I have created chat application using following

Rails

Rabbitmq

nodejs ( with amqplib/callback_api and socket.io )

I have following code in server side

```<code>var amqp = require('amqplib/callback_api');
var amqpConn = null;

var app = require('http').createServer()
var io = require('socket.io')(app);
var fs = require('fs');

io.on('connection', function (socket) {
        socket.emit('news/1', msg.content.toString());
        // socket.disconnect()
});
</code>```

client side

```<code><%= javascript_include_tag "http://localhost:53597/socket.io/socket.io.js"  %>
<script>

var socket = io('http://localhost:53597', {reconnect: true});

  socket.on('connect', function () {
    console.log('connected');

    socket.on('news/1', function (msg) {
      console.log('inside coming');
      console.log(msg);
    });
  });

</script>
</code>```

When I send message, message successfully pushed to queue and messages emitted to socket. The problem is I can get messages when only refresh page and messages are not deleted.

I can't understand what was wrong here ?

答:
Eventually I fixed my issue, the problem is I have placed emit function inside connection event, so that I can get data when only connection established, connection is established when page load that is the reason I get data when only page load.

I have the following code for emit data

io.sockets.emit('news/1', msg.content.toString());

Title: Socket.io client not working properly

Body:
I have created chat application using following

Rails

Rabbitmq

nodejs ( with amqplib/callback_api and socket.io )

I have following code in server side

var amqp = require('amqplib/callback_api');
var amqpConn = null;

var app = require('http').createServer()
var io = require('socket.io')(app);
var fs = require('fs');

io.on('connection', function (socket) {
        socket.emit('news/1', msg.content.toString());
        // socket.disconnect()
});

client side

<%= javascript_include_tag "http://localhost:53597/socket.io/socket.io.js"  %>

When I send message, message successfully pushed to queue and messages emitted to socket. The problem is I can get messages when only refresh page and messages are not deleted.

I can't understand what was wrong here ?


问:
How to successfully get out of this do-while loop?
This code was smooth sailing until I SPECIFICALLY include the IF-STATEMENT containing a BREAK inside the DO-WHILE LOOP which SHOULD report a math error if fv1 = 0 (for anything divided by zero is undefined). However, unexpected results were printed.</p>

```<code>#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

const double R = 0.082054;
double f(double a,double b,double P,double T,double v);
double f(double a,double b,double P,double T,double v)
{
    double q =P*pow(v,3)-(P*b+R*T)*pow(v,2)+a*v-a*b;
    return q;
}
double fPrime(double a,double b,double P,double T,double v);
double fPrime(double a,double b,double P,double T,double v)
{
    double s =3*P*pow(v,2)-2*(P*b+R*T)*pow(v,1)+a;
    return s;
}
int main()
{
//INPUT STAGE!
cout << "Use gas constant, R: " << R << endl;

double a,b,P,T,Tc;
cout << "\nUse test value, a: ";
cin >> a;
cout << "\nUse test value, b: ";
cin >> b;
cout << "\nUse pressure, P (atm): ";
cin >> P;
cout << "\nUse absolute temperature, T (K): ";
cin >> T;

double v,v1=0,fv,fv1,N,e;
int iteration = 0;
cout << "\nUse initial guess for molal volume, v: ";
cin >> v;
cout << "\nUse maximum number of iterations, N: ";
cin >> N;
cout << "\nUse tolerance, e: ";
cin >> e;
cout << "\n";

do
{
    v = v1;
    fv = f(a,b,P,T,v);
    fv1 = fPrime(a,b,P,T,v);
    if (fv1=0)
    {
       cout << "Math Error";
       break;
    }
    v1 = v-(fv/fv1);
    cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
    iteration++;
}
while(iteration<N && abs(v1-v)>e);

return 0;
}
</code>```

答:
The break statement ends execution of the nearest enclosing loop or conditional statement in which it appears -

And by the way you're assigning 0 to fv1.

use

```<code>if (fv1 == 0)
</code>```

or

```<code>if (0 == fv1)
</code>```

Body:
This code was smooth sailing until I SPECIFICALLY include the IF-STATEMENT containing a BREAK inside the DO-WHILE LOOP which SHOULD report a math error if fv1 = 0 (for anything divided by zero is undefined). However, unexpected results were printed.

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

const double R = 0.082054;
double f(double a,double b,double P,double T,double v);
double f(double a,double b,double P,double T,double v)
{
    double q =P*pow(v,3)-(P*b+R*T)*pow(v,2)+a*v-a*b;
    return q;
}
double fPrime(double a,double b,double P,double T,double v);
double fPrime(double a,double b,double P,double T,double v)
{
    double s =3*P*pow(v,2)-2*(P*b+R*T)*pow(v,1)+a;
    return s;
}
int main()
{
//INPUT STAGE!
cout << "Use gas constant, R: " << R << endl;

double a,b,P,T,Tc;
cout << "\nUse test value, a: ";
cin >> a;
cout << "\nUse test value, b: ";
cin >> b;
cout << "\nUse pressure, P (atm): ";
cin >> P;
cout << "\nUse absolute temperature, T (K): ";
cin >> T;

double v,v1=0,fv,fv1,N,e;
int iteration = 0;
cout << "\nUse initial guess for molal volume, v: ";
cin >> v;
cout << "\nUse maximum number of iterations, N: ";
cin >> N;
cout << "\nUse tolerance, e: ";
cin >> e;
cout << "\n";

do
{
    v = v1;
    fv = f(a,b,P,T,v);
    fv1 = fPrime(a,b,P,T,v);
    if (fv1=0)
    {
       cout << "Math Error";
       break;
    }
    v1 = v-(fv/fv1);
    cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
    iteration++;
}
while(iteration<N && abs(v1-v)>e);

return 0;
}

Body:
The break statement ends execution of the nearest enclosing loop or conditional statement in which it appears -

And by the way you're assigning 0 to fv1.

use

if (fv1 == 0)

or

if (0 == fv1)


问:
on register, check if username exists -- capitalization problem
My homefried account registration system proceeds thusly:

complete registration form

check if username already exists - reject/pass

copy data to temp user table, send confirmation email

upon using link in confirmation email, copy data from temp to active user table

The other day a user emailed me to say he was getting the error message "Could not create user."

I couldn't recall ever hearing that, so I dug into my registration code and that error pops out if the query to insert the temp data into the active user table fails.

It failed because his username, which has a unique index in the table, already existed in the active user table... but he had passed the initial existing username check...?

Turned out the name he had tried to register was "User" but there was already a "user" -- so case-insensitivity is coming into play.

Does username exist? query string:

```<code>SELECT username FROM user_basic_data WHERE username='$cleanTempUsername'
</code>```

Confirmed, now insert into active table string:

```<code>INSERT INTO user_basic_data (username, ...) VALUES ('$activeUsername', ...)
</code>```

So the case-sensitivity apparently applies when I run a select statement ("User" != "user") but does not apply when I run an insert.

Capitalization is important to many users, so what's my fix of least resistance from here?

答:
Best move would probably be to use a case-sensitive collation for your tables.

Maybe try latin1_bin or utf8_bin.

Body:
My homefried account registration system proceeds thusly:

complete registration form

check if username already exists - reject/pass

copy data to temp user table, send confirmation email

upon using link in confirmation email, copy data from temp to active user table

The other day a user emailed me to say he was getting the error message "Could not create user."

I couldn't recall ever hearing that, so I dug into my registration code and that error pops out if the query to insert the temp data into the active user table fails.

It failed because his username, which has a unique index in the table, already existed in the active user table... but he had passed the initial existing username check...?

Turned out the name he had tried to register was "User" but there was already a "user" -- so case-insensitivity is coming into play.

Does username exist? query string:

SELECT username FROM user_basic_data WHERE username='$cleanTempUsername'

Confirmed, now insert into active table string:

INSERT INTO user_basic_data (username, ...) VALUES ('$activeUsername', ...)

So the case-sensitivity apparently applies when I run a select statement ("User" != "user") but does not apply when I run an insert.

Capitalization is important to many users, so what's my fix of least resistance from here?


问:
How can I deploy a DB2 stored procedure which writes to a table that does not yet exist (but will by the time it does so)?
As you would most likely have deduced from the following question, I am new to DB2 in general. I am attempting to write my second ever stored procedure using IBM Data Studio and am running into an error when trying to deploy it. The point of the stored procedure is to search for a text string in fields across different tables. NOTE: The code is not complete and is not useful in its current form. I am attempting to test each step as I go along.

Here is all of the code I have so far:

```<code>CREATE OR REPLACE PROCEDURE sp_find_string (in in_search_string varchar(200), in in_schema varchar(50))
    DYNAMIC RESULT SETS 1
P1: BEGIN
    -- #######################################################################
    -- #
    -- #######################################################################
    declare table_a varchar(200);
    declare colname varchar(200);
    declare sqlcmd  varchar(2000);
    declare eof smallint default 0;
    declare not_found condition for sqlstate '02000';

    -- Declare cursor
    DECLARE cursor1 CURSOR WITH RETURN for
        select tabname, colname from syscat.columns c
        --inner join syscat.tables t on t.tabschema = c.tabschema
        --  and t.tabname = c.tabname
        where tabname like 'MERLIN%'
        and tabschema = in_schema;
    DECLARE CONTINUE HANDLER FOR SQLSTATE '42704'  -- or SQLEXCEPTION

    -------------------------------------------------
    if (exists
            (
                select 1 from sysibm.systables
                where creator = 'A2815'
                and name = 'DBP_TEMP_SEARCH_RESULTS'
            )
        ) then drop table A2815.DBP_TEMP_SEARCH_RESULTS;
    end if;

    create table A2815.DBP_TEMP_SEARCH_RESULTS
    (text_to_match varchar(200)
    ,table_a varchar(200)
    ,colname varchar(200)
    ,match_count bigint);

    -- Cursor left open for client application
    OPEN cursor1;
        while eof = 0 do
            p2: begin
                declare continue handler for not_found set eof = 1;
                fetch from cursor1 into table_a, colname;
                insert into A2815.DPB_TEMP_SEARCH_RESULTS
                values(table_a, colname);
            end p2;
        end while;
    close cursor1;
    --return;

END P1
</code>```

I am getting this error when attempting to deploy:

```<code>Deploy [TIO_D]A2815.SP_FIND_STRING(VARCHAR(200), VARCHAR(50))

Running
A2815.SP_FIND_STRING - Deploy started.
Create stored procedure returns SQLCODE: -204, SQLSTATE: 42704.
A2815.SP_FIND_STRING: 44: "A2815.DPB_TEMP_SEARCH_RESULTS" is an undefined name.. SQLCODE=-204, SQLSTATE=42704, DRIVER=4.18.60
"A2815.DPB_TEMP_SEARCH_RESULTS" is an undefined name.. SQLCODE=-204, SQLSTATE=42704, DRIVER=4.18.60
A2815.SP_FIND_STRING - Deploy failed.
A2815.SP_FIND_STRING - Roll back completed successfully.
</code>```

When I comment out the insert statement, it deploys just fine (but of course the procedure doesn't do me much good without the ability to insert):

```<code>OPEN cursor1;
        while eof = 0 do
            p2: begin
                declare continue handler for not_found set eof = 1;
                fetch from cursor1 into table_a, colname;
                --insert into A2815.DPB_TEMP_SEARCH_RESULTS
                --values(table_a, colname);
            end p2;
        end while;
    close cursor1;
</code>```

It is true that the table does not exist yet, because it should be created by the procedure. However, if I create the table then deploy the procedure I get this error:

```<code>Deploy [TIO_D]A2815.SP_FIND_STRING(VARCHAR(200), VARCHAR(50))

    Running
    A2815.SP_FIND_STRING - Deploy started.
    Create stored procedure returns SQLCODE: -601, SQLSTATE: 42710.
    A2815.SP_FIND_STRING: 32: The name of the object to be created is identical to the existing name "A2815.DBP_TEMP_SEARCH_RESULTS" of type "TABLE".. SQLCODE=-601, SQLSTATE=42710, DRIVER=4.18.60
    The name of the object to be created is identical to the existing name "A2815.DBP_TEMP_SEARCH_RESULTS" of type "TABLE".. SQLCODE=-601, SQLSTATE=42710, DRIVER=4.18.60
    A2815.SP_FIND_STRING - Deploy failed.
    A2815.SP_FIND_STRING - Roll back completed successfully.
</code>```

Can anyone tell me how to get this procedure deployed either when the table exists, when it doesn't exist, or both?

Thank you very much and let me know what other detail is needed. Also, suggestions on how to improve the code in general would be great as well.

答: Might be a bit late, but the best way to do this would be to create a string with your query, instead of using the query directly, and then using EXECUTE IMMEDIATELY </p>

Body:
As you would most likely have deduced from the following question, I am new to DB2 in general. I am attempting to write my second ever stored procedure using IBM Data Studio and am running into an error when trying to deploy it. The point of the stored procedure is to search for a text string in fields across different tables. NOTE: The code is not complete and is not useful in its current form. I am attempting to test each step as I go along.

Here is all of the code I have so far:

CREATE OR REPLACE PROCEDURE sp_find_string (in in_search_string varchar(200), in in_schema varchar(50))
    DYNAMIC RESULT SETS 1
P1: BEGIN
    -- #######################################################################
    -- #
    -- #######################################################################
    declare table_a varchar(200);
    declare colname varchar(200);
    declare sqlcmd  varchar(2000);
    declare eof smallint default 0;
    declare not_found condition for sqlstate '02000';

    -- Declare cursor
    DECLARE cursor1 CURSOR WITH RETURN for
        select tabname, colname from syscat.columns c
        --inner join syscat.tables t on t.tabschema = c.tabschema
        --  and t.tabname = c.tabname
        where tabname like 'MERLIN%'
        and tabschema = in_schema;
    DECLARE CONTINUE HANDLER FOR SQLSTATE '42704'  -- or SQLEXCEPTION

    -------------------------------------------------
    if (exists
            (
                select 1 from sysibm.systables
                where creator = 'A2815'
                and name = 'DBP_TEMP_SEARCH_RESULTS'
            )
        ) then drop table A2815.DBP_TEMP_SEARCH_RESULTS;
    end if;

    create table A2815.DBP_TEMP_SEARCH_RESULTS
    (text_to_match varchar(200)
    ,table_a varchar(200)
    ,colname varchar(200)
    ,match_count bigint);

    -- Cursor left open for client application
    OPEN cursor1;
        while eof = 0 do
            p2: begin
                declare continue handler for not_found set eof = 1;
                fetch from cursor1 into table_a, colname;
                insert into A2815.DPB_TEMP_SEARCH_RESULTS
                values(table_a, colname);
            end p2;
        end while;
    close cursor1;
    --return;

END P1

I am getting this error when attempting to deploy:

Deploy [TIO_D]A2815.SP_FIND_STRING(VARCHAR(200), VARCHAR(50))

Running
A2815.SP_FIND_STRING - Deploy started.
Create stored procedure returns SQLCODE: -204, SQLSTATE: 42704.
A2815.SP_FIND_STRING: 44: "A2815.DPB_TEMP_SEARCH_RESULTS" is an undefined name.. SQLCODE=-204, SQLSTATE=42704, DRIVER=4.18.60
"A2815.DPB_TEMP_SEARCH_RESULTS" is an undefined name.. SQLCODE=-204, SQLSTATE=42704, DRIVER=4.18.60
A2815.SP_FIND_STRING - Deploy failed.
A2815.SP_FIND_STRING - Roll back completed successfully.

When I comment out the insert statement, it deploys just fine (but of course the procedure doesn't do me much good without the ability to insert):

OPEN cursor1;
        while eof = 0 do
            p2: begin
                declare continue handler for not_found set eof = 1;
                fetch from cursor1 into table_a, colname;
                --insert into A2815.DPB_TEMP_SEARCH_RESULTS
                --values(table_a, colname);
            end p2;
        end while;
    close cursor1;

It is true that the table does not exist yet, because it should be created by the procedure. However, if I create the table then deploy the procedure I get this error:

Deploy [TIO_D]A2815.SP_FIND_STRING(VARCHAR(200), VARCHAR(50))

    Running
    A2815.SP_FIND_STRING - Deploy started.
    Create stored procedure returns SQLCODE: -601, SQLSTATE: 42710.
    A2815.SP_FIND_STRING: 32: The name of the object to be created is identical to the existing name "A2815.DBP_TEMP_SEARCH_RESULTS" of type "TABLE".. SQLCODE=-601, SQLSTATE=42710, DRIVER=4.18.60
    The name of the object to be created is identical to the existing name "A2815.DBP_TEMP_SEARCH_RESULTS" of type "TABLE".. SQLCODE=-601, SQLSTATE=42710, DRIVER=4.18.60
    A2815.SP_FIND_STRING - Deploy failed.
    A2815.SP_FIND_STRING - Roll back completed successfully.

Can anyone tell me how to get this procedure deployed either when the table exists, when it doesn't exist, or both?

Thank you very much and let me know what other detail is needed. Also, suggestions on how to improve the code in general would be great as well.


答:
Something like this would probably work:

```<code>std::map<std::string, std::function<void(int, int)>> functions{
    {"esa", search_esa},
    {"tss", search_tss},
    {"fss", search_fss},
    {"ds", search_ds}
};

int main(int argc, char ** argv) {
    std::string cmd = argv[1];
    functions.at(cmd)(5, 10);
    return 0;
}
</code>```

It's worth noting, though, that you can't really generalize this. If you added another function, like say, search_rsa, you'd have to manually add an entry for it to the map. C++ doesn't have the comprehensive reflection capabilities that a language like Java or Python has, so you can't just write a function that takes a string and searches for a method that has a name matching that string.

Title: functions with different names but same arguments

Body:
I have a set of functions with the same number of arguments, but different names (suppose each implement different method). I have the name of the requested method in a string. Is it possible to call the corresponding function using the method name. to make it clear, suppose that I have the following function (I just mentioned their name and argument):

search_esa(int a, int b);
search_tss(int a, int b);
search_fss(int a, int b);
search_ds(int a, int b);

now lets assume I have the name of the requested method, lets assume esa, in a string:

string methodName = "esa"

is it possible to call the corresponding function by using macros?
I tested

#define CALL_SEARCH_MV(method) search_##method

and then try to call it by:

CALL_SEARCH_MV(methodName.c_str())

but it calls search_methodName function, which does not exist. Any other suggestions would be greatly appreciated (except suggesting switch case method or if).

Body:
Something like this would probably work:

std::map<std::string, std::function<void(int, int)>> functions{
    {"esa", search_esa},
    {"tss", search_tss},
    {"fss", search_fss},
    {"ds", search_ds}
};

int main(int argc, char ** argv) {
    std::string cmd = argv[1];
    functions.at(cmd)(5, 10);
    return 0;
}

It's worth noting, though, that you can't really generalize this. If you added another function, like say, search_rsa, you'd have to manually add an entry for it to the map. C++ doesn't have the comprehensive reflection capabilities that a language like Java or Python has, so you can't just write a function that takes a string and searches for a method that has a name matching that string.


问:
How to run a mixed language program
I want to write a mixed language program where part of the code will be written in C, and part of the code in assembly. I was given a sample code, so i know what should my work look like.

```<code> .globl _addArrayinA

_addArrayinA:
    pushl %ebp
    movl  %esp,%ebp
    subl  $8,%esp
    movl  8(%ebp), %ebx
    xorl  %esi,%esi
    xor   %eax,%eax

bak:
    addl  (%ebx),%eax
    addl  $4,%ebx
    incl  %esi
    cmpl  $10, %esi
    jne   bak

    movl %ebp, %esp
    popl  %ebp
    ret
 # Return value is in %ea
</code>```

Above is the assembly part.

```<code>int  addArrayinC(int *myArray, int num)
{
    int c;
    int i;

    c = 0;

    for (i=0; i<num; i++)
        {c += *myArray;
        myArray++;
        }

    return (c);

}
</code>```

This is the second function written in C.
And below is the main file, which is supposed to use two functions above.

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

extern int addArrayinC(int *numbers,int count);
extern int addArrayinA(int *numbers, int count);

    int main(void) {
        int mynumbers[10]={1,2,3,4,5,6,7,8,9,0};
        int sum;

        sum = addArrayinC(mynumbers, 10);
        printf("\nThe sum of array computed in C  is : %d ",sum);

        sum = addArrayinA(mynumbers, 10);
        printf("\nThe sum of array computed in assembly is : %d ",sum);

        return EXIT_SUCCESS;
    }
</code>```

I tried to open these three files in codeblocks, but could not get to run them. I have no idea how to run a mixed language program. Generally, I use cloud9 for compilations of code. Anyways... How can i run code like this?

答:
fun.c

```<code>unsigned int fun ( unsigned int x )
{
  return(x+1);
}
</code>```

build and examine

```<code>gcc -c -O2 fun.c -o fun.o
objdump -D fun.o
</code>```

producing

```<code>0000000000000000 <fun>:
   0:   8d 47 01                lea    0x1(%rdi),%eax
   3:   c3                      retq
</code>```

So we can make fun.s

```<code>.globl fun
fun:
  lea 0x1(%rdi),%eax
  retq

as fun.s -o fun.o
objdump -D fun.o

0000000000000000 <fun>:
   0:   8d 47 01                lea    0x1(%rdi),%eax
   3:   c3                      retq
</code>```

C code so.c

```<code>#include <stdio.h>
unsigned int fun ( unsigned int x );

int main ( void )
{
    printf("%u\n",fun(1));
    printf("%u\n",fun(2));
    printf("%u\n",fun(3));
    return(0);
}
</code>```

gcc lets you feed it assembly language

```<code>gcc so.c fun.s -o so
./so
2
3
4
</code>```

as well as objects

```<code>gcc so.c fun.o
./so
2
3
4
</code>```

so you dont have to mess with the linker directly

Title: How to run a mixed language program

Body:
I want to write a mixed language program where part of the code will be written in C, and part of the code in assembly. I was given a sample code, so i know what should my work look like.

 .globl _addArrayinA

_addArrayinA:
    pushl %ebp
    movl  %esp,%ebp
    subl  $8,%esp
    movl  8(%ebp), %ebx
    xorl  %esi,%esi
    xor   %eax,%eax

bak:
    addl  (%ebx),%eax
    addl  $4,%ebx
    incl  %esi
    cmpl  $10, %esi
    jne   bak

    movl %ebp, %esp
    popl  %ebp
    ret
 # Return value is in %ea

Above is the assembly part.

int  addArrayinC(int *myArray, int num)
{
    int c;
    int i;

    c = 0;

    for (i=0; i<num; i++)
        {c += *myArray;
        myArray++;
        }

    return (c);

}

This is the second function written in C.
And below is the main file, which is supposed to use two functions above.

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

extern int addArrayinC(int *numbers,int count);
extern int addArrayinA(int *numbers, int count);

    int main(void) {
        int mynumbers[10]={1,2,3,4,5,6,7,8,9,0};
        int sum;

        sum = addArrayinC(mynumbers, 10);
        printf("\nThe sum of array computed in C  is : %d ",sum);

        sum = addArrayinA(mynumbers, 10);
        printf("\nThe sum of array computed in assembly is : %d ",sum);

        return EXIT_SUCCESS;
    }

I tried to open these three files in codeblocks, but could not get to run them. I have no idea how to run a mixed language program. Generally, I use cloud9 for compilations of code. Anyways... How can i run code like this?

Body:
fun.c

unsigned int fun ( unsigned int x )
{
  return(x+1);
}

build and examine

gcc -c -O2 fun.c -o fun.o
objdump -D fun.o

producing

0000000000000000 <fun>:
   0:   8d 47 01                lea    0x1(%rdi),%eax
   3:   c3                      retq

So we can make fun.s

.globl fun
fun:
  lea 0x1(%rdi),%eax
  retq

as fun.s -o fun.o
objdump -D fun.o

0000000000000000 <fun>:
   0:   8d 47 01                lea    0x1(%rdi),%eax
   3:   c3                      retq

C code so.c

#include <stdio.h>
unsigned int fun ( unsigned int x );

int main ( void )
{
    printf("%u\n",fun(1));
    printf("%u\n",fun(2));
    printf("%u\n",fun(3));
    return(0);
}

gcc lets you feed it assembly language

gcc so.c fun.s -o so
./so
2
3
4

as well as objects

gcc so.c fun.o
./so
2
3
4

so you dont have to mess with the linker directly


问:
visual basic 2010, Importing excel files to my SQL using bulkcopy
hello guys I'm having a problem with a project that I build
I'm trying to import excel files to sql server 2016 using bulkcopy and I got this error

"'DAFTAR1$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long"

I think there is a problem with this code
Dim query_excel As String = "SELECT * from [" & file & "$]"

i tried all of this code on another pc and it works perfectly but on my pc it's getting that error, I don't know what did I wrong, I'm using visual basic 2010 professional edition, sql management server 2016 and microsoft office 2016

can anyone help me to figure what is wrong with the code ?

```<code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    If OpenFileDialog1.ShowDialog = DialogResult.OK Then
        TextBox1.Text = OpenFileDialog1.FileName
        file = System.IO.Path.GetFileNameWithoutExtension(TextBox1.Text)

    End If

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

    Dim koneksi_excel As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ace.OLEDB.12.0;Data Source='" & TextBox1.Text & "';Extended Properties=""Excel 12.0 Xml;HDR=YES;""")
    koneksi_excel.Open()

    Dim query_excel As String = "SELECT * from [" & file & "$]"
    Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(query_excel, koneksi_excel)
    Dim rd As OleDb.OleDbDataReader

    rd = cmd.ExecuteReader()

    Dim koneksi As New SqlClient.SqlConnection()
    Dim koneksidatabase As String = "server=DESKTOP-KJQ8PNO\SQLEXPRESS;database=otto;Integrated Security=True"
    koneksi.ConnectionString = koneksidatabase

    koneksi.Open()
    Dim da As New OleDb.OleDbDataAdapter
    Dim ds As New DataSet()
    Dim dt As New DataTable
    ds.Tables.Add(dt)
    da = New OleDb.OleDbDataAdapter(query_excel, koneksi_excel)
    da.Fill(dt)

    Using bulkcopy As SqlClient.SqlBulkCopy = New SqlClient.SqlBulkCopy(koneksi)
        bulkcopy.DestinationTableName = file
        bulkcopy.BulkCopyTimeout = 600
        bulkcopy.WriteToServer(rd)
        rd.Close()

        MsgBox("Data uploaded to database", MsgBoxStyle.Information, "Uploaded")
        TextBox1.Text = ""
    End Using
End Sub
</code>```

答:
If you're using a DataGridView or some other grid to view the data, this is one way that you can view the data and load it into the grid.

```<code>Using ofd As New OpenFileDialog
      ofd.InitialDirectory = dir
      ofd.Filter = "Excel Files (*.xlsx)|*.xlsx| XLS Files (*.xls)|*.xls"
      ofd.FilterIndex = 1

    If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
       txtFile.Text = ofd.FileName

       fi = New FileInfo(ofd.FileName)
       fileName = ofd.FileName

       excel = fi.FullName

       eCon = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
                                   excel & ";Extended Properties='Excel 12.0;IMEX=1;';")
       eCon.Open()

      Dim dtSheets As DataTable = eCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
      Dim listSheet As New List(Of String)
      Dim drSheet As DataRow

      For Each drSheet In dtSheets.Rows
           If drSheet.Item("TABLE_NAME").ToString() <> "Sheet1$" Then
              listSheet.Add(drSheet("TABLE_NAME").ToString())
          Else
          End If
      Next

     Me.Cursor = Cursors.WaitCursor

     Dim myTable = ""
     myTable = listSheet.Item(0)

     da = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}]", myTable), eCon)
     ds = New DataSet
     da.Fill(ds, myTable)
     Dim dt As DataTable = ds.Tables(0).Copy()
</code>```

From here, set the dt as the grid DataSource. This way you know you're always getting the first worksheet, and don't have to worry about what the name is as such, the program is getting it for you.

Have a play around a let me know. Alternatively, you can just use this code to get the Excel sheet and use what you have already for the import.

Body:
hello guys I'm having a problem with a project that I build
I'm trying to import excel files to sql server 2016 using bulkcopy and I got this error

"'DAFTAR1$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long"

I think there is a problem with this code
Dim query_excel As String = "SELECT * from [" & file & "$]"

i tried all of this code on another pc and it works perfectly but on my pc it's getting that error, I don't know what did I wrong, I'm using visual basic 2010 professional edition, sql management server 2016 and microsoft office 2016

can anyone help me to figure what is wrong with the code ?

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    If OpenFileDialog1.ShowDialog = DialogResult.OK Then
        TextBox1.Text = OpenFileDialog1.FileName
        file = System.IO.Path.GetFileNameWithoutExtension(TextBox1.Text)

    End If

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

    Dim koneksi_excel As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ace.OLEDB.12.0;Data Source='" & TextBox1.Text & "';Extended Properties=""Excel 12.0 Xml;HDR=YES;""")
    koneksi_excel.Open()

    Dim query_excel As String = "SELECT * from [" & file & "$]"
    Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(query_excel, koneksi_excel)
    Dim rd As OleDb.OleDbDataReader

    rd = cmd.ExecuteReader()

    Dim koneksi As New SqlClient.SqlConnection()
    Dim koneksidatabase As String = "server=DESKTOP-KJQ8PNO\SQLEXPRESS;database=otto;Integrated Security=True"
    koneksi.ConnectionString = koneksidatabase

    koneksi.Open()
    Dim da As New OleDb.OleDbDataAdapter
    Dim ds As New DataSet()
    Dim dt As New DataTable
    ds.Tables.Add(dt)
    da = New OleDb.OleDbDataAdapter(query_excel, koneksi_excel)
    da.Fill(dt)

    Using bulkcopy As SqlClient.SqlBulkCopy = New SqlClient.SqlBulkCopy(koneksi)
        bulkcopy.DestinationTableName = file
        bulkcopy.BulkCopyTimeout = 600
        bulkcopy.WriteToServer(rd)
        rd.Close()

        MsgBox("Data uploaded to database", MsgBoxStyle.Information, "Uploaded")
        TextBox1.Text = ""
    End Using
End Sub

Body:
If you're using a DataGridView or some other grid to view the data, this is one way that you can view the data and load it into the grid.

Using ofd As New OpenFileDialog
      ofd.InitialDirectory = dir
      ofd.Filter = "Excel Files (*.xlsx)|*.xlsx| XLS Files (*.xls)|*.xls"
      ofd.FilterIndex = 1

    If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
       txtFile.Text = ofd.FileName

       fi = New FileInfo(ofd.FileName)
       fileName = ofd.FileName

       excel = fi.FullName

       eCon = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
                                   excel & ";Extended Properties='Excel 12.0;IMEX=1;';")
       eCon.Open()

      Dim dtSheets As DataTable = eCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
      Dim listSheet As New List(Of String)
      Dim drSheet As DataRow

      For Each drSheet In dtSheets.Rows
           If drSheet.Item("TABLE_NAME").ToString() <> "Sheet1$" Then
              listSheet.Add(drSheet("TABLE_NAME").ToString())
          Else
          End If
      Next

     Me.Cursor = Cursors.WaitCursor

     Dim myTable = ""
     myTable = listSheet.Item(0)

     da = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}]", myTable), eCon)
     ds = New DataSet
     da.Fill(ds, myTable)
     Dim dt As DataTable = ds.Tables(0).Copy()

From here, set the dt as the grid DataSource. This way you know you're always getting the first worksheet, and don't have to worry about what the name is as such, the program is getting it for you.

Have a play around a let me know. Alternatively, you can just use this code to get the Excel sheet and use what you have already for the import.


问:
WebRatio: Unable to locate companion shared library
I'm having this issue on Mac, WebRatio.app is showing this error after extracting the package.

The WebRatio executable launcher was unable to locate its companion
  shared library

I haven't changed any file location or renamed any folder, I have installed Java SE Runtime Environment as well.

Am I missing anything Important?

答:
The only way i've found by 'showing package contents' of WebRatio.app and accessing WebRatio.exec

Contents>MacOS>WebRatio.exec


问:
Regex find optional entries in Java
I'm currently working on some stuff with regex and struggel alot with regex latetly.

I wanted to build some script engine, for that I need to load some presets:

example:

```<code>create <Type> [after;before;at;between(2);<Integer>, <DateTime>, <Date>, <Time>, <String>] : Creator
edit <Type> [after;before;at;between(2);<Integer>, <DateTime>, <Date>, <Time>, <String>]
run [<File>, <Command>]
</code>```

So I want to make sure I can read <Type> [after;before;at;between(2);<Integer>, <DateTime>, <Date>, <Time>, <String>] and [<File>, <Command>].

For the understanding:

NAME <IMPORTANT_PARAMETER> [TEXT_PARAMETER(AMOUNT_OF_OPTIONAL_PAREMETER);<OPTIONAL_PARAMETER(S)>].

In this example I used 'command names' as IMPORTANT_PARAMETER.

For the first rule I made this regex: \<(\w+)\>(?:\s+\[(?:(.*;))(.*)\])?(?:\s+\:\s+(\w+))? and it kinda works within my code:

```<code>Pattern p = Pattern.compile("\\<(\\w+)\\>(?:\\s+\\[(?:(.*;))(.*)\\])?(?:\\s+\\:\\s+(\\w+))?");
Matcher m = p.matcher(parameters);
if(m.matches()){
    Command command2 = new Command(command);
    command2.addParameter(new Parameter(m.group(1)));

    String text = m.group(2);
    String[] texts = null;
    if(text != null){
        texts = text.split(";");
        command2.addTexts(Arrays.asList(texts));
    }
    String type = m.group(3);
    String[] types = null;
    if(type != null){
        types = type.split(", ");
        for (String string : types) {
            Pattern pTypes = Pattern.compile("\\<(?:(\\w+))\\>");
            Matcher mTypes = pTypes.matcher(string);
            if(mTypes.matches()){
                command2.addParameter(new Parameter(mTypes.group(1), true));
            }
        }
    }
    String className = m.group(4);
    if(className != null){
        command2.addClassName(className);
    }
    commandslist.add(command2);
}
</code>```

I tried to use \[\<(\w+)\>(?:,\s+\<(\w+)\>)+\] but it only worked for two entries -> example run [<File>, <Command>]. It would be better having a "list" of those optional elements [<File>, <Command>]. So in the end I want to have m.group(1) = File; m.group(2) = Command; m.group(3) = blablabla; and so on.

I hope I could show you my problem good enough, hit me with questions if there is anything more to explain.

Here is a link to the regexr: REGEXR or regex101: REGEX101

Thanks for helping :)

答:
My suggestion is to match the stuff between the words you are after:

```<code>public static void main (String[] args) {
    final String STR1 = "run [<File>, <Command1>, <Command2>, <Command3>]";
    final String STR2 = "run [<File>, <Command1>, <Command2>, <Command3>, <Command4>]";

    System.out.println(parse(STR1));
    System.out.println(parse(STR2));
}

private static List parse(String str) {
    List<String> list = new ArrayList<>();

    Pattern p = Pattern.compile("(?:\\G,\\s+|^run\\s+\\[(?:<\\w+>,\\s+)+?)<(\\w+)>");
    Matcher m = p.matcher(str);
    while (m.find()) {
        list.add(m.group(1));
    }

    return list;
}
</code>```

which results in the output:

```<code>[Command1, Command2, Command3]
[Command1, Command2, Command3, Command4]
</code>```

Title: Regex find optional entries in Java

Body:
I'm currently working on some stuff with regex and struggel alot with regex latetly.

I wanted to build some script engine, for that I need to load some presets:

example:

create <Type> [after;before;at;between(2);<Integer>, <DateTime>, <Date>, <Time>, <String>] : Creator
edit <Type> [after;before;at;between(2);<Integer>, <DateTime>, <Date>, <Time>, <String>]
run [<File>, <Command>]

So I want to make sure I can read <Type> [after;before;at;between(2);<Integer>, <DateTime>, <Date>, <Time>, <String>] and [<File>, <Command>].

For the understanding:

NAME <IMPORTANT_PARAMETER> [TEXT_PARAMETER(AMOUNT_OF_OPTIONAL_PAREMETER);<OPTIONAL_PARAMETER(S)>].

In this example I used 'command names' as IMPORTANT_PARAMETER.

For the first rule I made this regex: \<(\w+)\>(?:\s+\[(?:(.*;))(.*)\])?(?:\s+\:\s+(\w+))? and it kinda works within my code:

Pattern p = Pattern.compile("\\<(\\w+)\\>(?:\\s+\\[(?:(.*;))(.*)\\])?(?:\\s+\\:\\s+(\\w+))?");
Matcher m = p.matcher(parameters);
if(m.matches()){
    Command command2 = new Command(command);
    command2.addParameter(new Parameter(m.group(1)));

    String text = m.group(2);
    String[] texts = null;
    if(text != null){
        texts = text.split(";");
        command2.addTexts(Arrays.asList(texts));
    }
    String type = m.group(3);
    String[] types = null;
    if(type != null){
        types = type.split(", ");
        for (String string : types) {
            Pattern pTypes = Pattern.compile("\\<(?:(\\w+))\\>");
            Matcher mTypes = pTypes.matcher(string);
            if(mTypes.matches()){
                command2.addParameter(new Parameter(mTypes.group(1), true));
            }
        }
    }
    String className = m.group(4);
    if(className != null){
        command2.addClassName(className);
    }
    commandslist.add(command2);
}

I tried to use \[\<(\w+)\>(?:,\s+\<(\w+)\>)+\] but it only worked for two entries -> example run [<File>, <Command>]. It would be better having a "list" of those optional elements [<File>, <Command>]. So in the end I want to have m.group(1) = File; m.group(2) = Command; m.group(3) = blablabla; and so on.

I hope I could show you my problem good enough, hit me with questions if there is anything more to explain.

Here is a link to the regexr: REGEXR or regex101: REGEX101

Thanks for helping :)

Body:
My suggestion is to match the stuff between the words you are after:

public static void main (String[] args) {
    final String STR1 = "run [<File>, <Command1>, <Command2>, <Command3>]";
    final String STR2 = "run [<File>, <Command1>, <Command2>, <Command3>, <Command4>]";

    System.out.println(parse(STR1));
    System.out.println(parse(STR2));
}

private static List parse(String str) {
    List<String> list = new ArrayList<>();

    Pattern p = Pattern.compile("(?:\\G,\\s+|^run\\s+\\[(?:<\\w+>,\\s+)+?)<(\\w+)>");
    Matcher m = p.matcher(str);
    while (m.find()) {
        list.add(m.group(1));
    }

    return list;
}

which results in the output:

[Command1, Command2, Command3]
[Command1, Command2, Command3, Command4]


问:
Reorganize/reshape data frame
I have a data frame of live trapping. There are two systems, each with different status. The week and the number of individuals in each status is given.

```<code>df <- data.frame (sys = rep(c("a","b"), each=3),
              sta = rep(c("L","T","P"), times=2),
              w01 = c("0","2","5","2","2","5"),
              w02 = c("3","2","2","4","6","1"),
              w03 = c("4","1","0","5","3","0"))
df
sys  sta  w01  w02  w03
a    L    0    3    4
a    T    2    2    1
a    P    5    2    0
b    L    2    4    5
b    T    2    6    3
b    P    5    1    0
</code>```

I want a data frame showing for each number the system and status. The Result would look like this:

```<code>sys sta Num
a   L   0
a   L   3
a   L   4
a   T   2
a   T   2
a   T   1
a   P   5
a   P   2
a   P   0
b   L   2
b   L   4
b   L   5
b   T   2
b   T   6
b   T   3
b   P   5
b   P   1
b   P   0
</code>```

I have absolutely no idea how doing this. I found this two questions/answers
Reorganise 2x36 dataframe to a 6x6 dataframe. Dice throw visualisation
Reshaping data.frame from wide to long format
but cannot find a way to fit it for my problem.
Also i tried reshape but direction = "wide" does not give the output I need and I am sucked with the varying part of direction = "long". Here is what I tried, but did not work...

```<code>a <- as.vector(colnames(df[-c(1,2)]))
df2 <- reshape(df, idvar = "sys", timevar = "sta", varying = a , direction = "long")
</code>```

Any suggestions how I can solve this problem?
Thank you all and kind regards!

P.S.: I need the "new format" of my dataset for a friedman test (friedman.test). Will it work out in this way?

答:
You can use melt from reshape2

```<code>melt(df, id.vars = c("sys","sta"), value.name = "num")

#     sys sta variable num
# 1    a   L      w01   0
# 2    a   T      w01   2
# 3    a   P      w01   5
# 4    b   L      w01   2
# 5    b   T      w01   2
# 6    b   P      w01   5
# 7    a   L      w02   3
# 8    a   T      w02   2
# 9    a   P      w02   2
# 10   b   L      w02   4
# 11   b   T      w02   6
# 12   b   P      w02   1
# 13   a   L      w03   4
# 14   a   T      w03   1
# 15   a   P      w03   0
# 16   b   L      w03   5
# 17   b   T      w03   3
# 18   b   P      w03   0
</code>```

If you want to remove the variable column use

melt(df, id.vars = c("sys","sta"), value.name = "num")[,c(1,2,4)]

Title: Reorganize/reshape data frame

Body:
I have a data frame of live trapping. There are two systems, each with different status. The week and the number of individuals in each status is given.

df <- data.frame (sys = rep(c("a","b"), each=3),
              sta = rep(c("L","T","P"), times=2),
              w01 = c("0","2","5","2","2","5"),
              w02 = c("3","2","2","4","6","1"),
              w03 = c("4","1","0","5","3","0"))
df
sys  sta  w01  w02  w03
a    L    0    3    4
a    T    2    2    1
a    P    5    2    0
b    L    2    4    5
b    T    2    6    3
b    P    5    1    0

I want a data frame showing for each number the system and status. The Result would look like this:

sys sta Num
a   L   0
a   L   3
a   L   4
a   T   2
a   T   2
a   T   1
a   P   5
a   P   2
a   P   0
b   L   2
b   L   4
b   L   5
b   T   2
b   T   6
b   T   3
b   P   5
b   P   1
b   P   0

I have absolutely no idea how doing this. I found this two questions/answers
Reorganise 2x36 dataframe to a 6x6 dataframe. Dice throw visualisation
Reshaping data.frame from wide to long format
but cannot find a way to fit it for my problem.
Also i tried reshape but direction = "wide" does not give the output I need and I am sucked with the varying part of direction = "long". Here is what I tried, but did not work...

a <- as.vector(colnames(df[-c(1,2)]))
df2 <- reshape(df, idvar = "sys", timevar = "sta", varying = a , direction = "long")

Any suggestions how I can solve this problem?
Thank you all and kind regards!

P.S.: I need the "new format" of my dataset for a friedman test (friedman.test). Will it work out in this way?

Body:
You can use melt from reshape2

melt(df, id.vars = c("sys","sta"), value.name = "num")

#     sys sta variable num
# 1    a   L      w01   0
# 2    a   T      w01   2
# 3    a   P      w01   5
# 4    b   L      w01   2
# 5    b   T      w01   2
# 6    b   P      w01   5
# 7    a   L      w02   3
# 8    a   T      w02   2
# 9    a   P      w02   2
# 10   b   L      w02   4
# 11   b   T      w02   6
# 12   b   P      w02   1
# 13   a   L      w03   4
# 14   a   T      w03   1
# 15   a   P      w03   0
# 16   b   L      w03   5
# 17   b   T      w03   3
# 18   b   P      w03   0

If you want to remove the variable column use

melt(df, id.vars = c("sys","sta"), value.name = "num")[,c(1,2,4)]


问:
Angular 2 basic app not working
I am a newbie to Angular2. I was trying to setup Angular 2 using this reference: https://github.com/angular/quickstart. But unfortunately, I am unable to run my basic application.
I have installed npm. While running "npm start", I am getting below output in my command prompt:

```<code>`E:\Extrawork\Angular>npm start
> angular-quickstart@1.0.0 prestart E:\Extrawork\Angular
> npm run build
> angular-quickstart@1.0.0 build E:\Extrawork\Angular
> tsc -p src/
> angular-quickstart@1.0.0 start E:\Extrawork\Angular
> concurrently "npm run build:watch" "npm run serve"
[0]
[0] > angular-quickstart@1.0.0 build:watch E:\Extrawork\Angular
[0] > tsc -p src/ -w
[0]
[1]
[1] > angular-quickstart@1.0.0 serve E:\Extrawork\Angular
[1] > lite-server -c=bs-config.json
[1]
[1] ** browser-sync config **
[1] { injectChanges: false,
[1]   files: [ './**/*.{html,htm,css,js}' ],
[1]   watchOptions: { ignored: 'node_modules' },
[1]   server:
[1]    { baseDir: 'src',
[1]      middleware: [ [Function], [Function] ],
[1]      routes: { '/node_modules': 'node_modules' } } }
[0] 4:59:12 PM - Compilation complete. Watching for file changes.
`
</code>```

It stops here. I did wait for 20-30 mins but it doesn't proceed.
Can anyone tell me what am I doing wrong, Please?

答:
This is freaking me out, guys!
I did setup it again to integrate with node to built a basic MEAN app and it gave me the same error again.That is insane!!!
Luckily, I was checking on youtube to setup and I found the same error with this video : https://www.youtube.com/watch?v=MWsrJ2T6GFM. But the app was still able to execute. I thought of trying and it worked for me too!!

If it happens to you then I would suggest you to try to execute once even if it gives you a warning. It may work.

Title: Angular 2 basic app not working

Body:
I am a newbie to Angular2. I was trying to setup Angular 2 using this reference: https://github.com/angular/quickstart. But unfortunately, I am unable to run my basic application.
I have installed npm. While running "npm start", I am getting below output in my command prompt:

`E:\Extrawork\Angular>npm start
> angular-quickstart@1.0.0 prestart E:\Extrawork\Angular
> npm run build
> angular-quickstart@1.0.0 build E:\Extrawork\Angular
> tsc -p src/
> angular-quickstart@1.0.0 start E:\Extrawork\Angular
> concurrently "npm run build:watch" "npm run serve"
[0]
[0] > angular-quickstart@1.0.0 build:watch E:\Extrawork\Angular
[0] > tsc -p src/ -w
[0]
[1]
[1] > angular-quickstart@1.0.0 serve E:\Extrawork\Angular
[1] > lite-server -c=bs-config.json
[1]
[1] ** browser-sync config **
[1] { injectChanges: false,
[1]   files: [ './**/*.{html,htm,css,js}' ],
[1]   watchOptions: { ignored: 'node_modules' },
[1]   server:
[1]    { baseDir: 'src',
[1]      middleware: [ [Function], [Function] ],
[1]      routes: { '/node_modules': 'node_modules' } } }
[0] 4:59:12 PM - Compilation complete. Watching for file changes.
`

It stops here. I did wait for 20-30 mins but it doesn't proceed.
Can anyone tell me what am I doing wrong, Please?


问:
Error 1045 (28000) Access deneied for user 'root'@'localhost'
I am using ubuntu 16.04 and have just installed mysql. However, I am not able to access the mysql shell. I keep getting the Error 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Could you please help. Thanks.

答:
Maybe hard resetting the password helps. Alot of people are getting this issue.

Take a look here: https://stackoverflow.com/a/21685641/1863487


问:
How to exclude a directory from ant fileset, based on directories contents
How can I create an ant fileset which excludes certain directories based on the contents of the directory?

I use ant to create a distribution jar which has each localization in separate directories, some of which are incomplete and should not be released.

I would like to add something to the directory (for example a file named incomplete.flag) so that ant excludes the directory. Then I can delete the file when translation is complete, and include it in the build without modifying build.xml.

Given this directory structure:

```<code>proj
+ locale
  + de-DE
  + en-US
  + fr-FR
</code>```

This fileset excludes all incompelte.flag files, but how can I exclude the entire directories that contain them?

```<code>  <fileset dir="${basedir}">
    <include name="locale/"/>
    <exclude name="locale/*/incomplete.flag">
  </fileset>
</code>```

I can write an ant task if need be, but I'm hoping the fileset can handle this use case.

答:
works for me:

```<code><target name="build2-jar" depends="compile" >
   <jar destfile="./myJjar.jar">
        <fileset dir="./WebContent/WEB-INF/lib" includes="hibernate*.jar,mysql*.jar" />
        <fileset dir="./WebContent/WEB-INF/classes" excludes="**/controlador/*.class,**/form/*.class,**/orm/*.class,**/reporting/*.class,**/org/w3/xmldsig/*.class"/>
   </jar>
</code>```

Body:
How can I create an ant fileset which excludes certain directories based on the contents of the directory?

I use ant to create a distribution jar which has each localization in separate directories, some of which are incomplete and should not be released.

I would like to add something to the directory (for example a file named incomplete.flag) so that ant excludes the directory. Then I can delete the file when translation is complete, and include it in the build without modifying build.xml.

Given this directory structure:

proj
+ locale
  + de-DE
  + en-US
  + fr-FR

This fileset excludes all incompelte.flag files, but how can I exclude the entire directories that contain them?

  <fileset dir="${basedir}">
    <include name="locale/"/>
    <exclude name="locale/*/incomplete.flag">
  </fileset>

I can write an ant task if need be, but I'm hoping the fileset can handle this use case.

Body:
works for me:

<target name="build2-jar" depends="compile" >
   <jar destfile="./myJjar.jar">
        <fileset dir="./WebContent/WEB-INF/lib" includes="hibernate*.jar,mysql*.jar" />
        <fileset dir="./WebContent/WEB-INF/classes" excludes="**/controlador/*.class,**/form/*.class,**/orm/*.class,**/reporting/*.class,**/org/w3/xmldsig/*.class"/>
   </jar>


问:
Slick: how to repeat infinitely?
I have 4 images in total, that are all displayed on the screen. What I want, is once a user clicks on the next button to make 4th image to appear as 1st, while previously 1st picture would be now 2nd and so on.

This is a piece of my js code:

```<code>    infinite: true,
    slidesToShow: 4,
    slidesToScroll: 1,
</code>```

Infinite is set to true, but it does not work the way I want it if there are less than 5 images in total.

I've searched for the answer here, and were able to find two similar questions, however both of them had no proper answer. Links for those:
How to make slick carousel images repeat infinitely and how could i make slides infinite (slick slider).

答:
This doesn't explain why that code doesn't work but here is a hot fix!

You can duplicate your set of images, so where you once had:

A B C D

you now have:

A B C D A B C D

This will now loop infinitely the way you want it to.

Title: Slick: how to repeat infinitely?

Body:
I have 4 images in total, that are all displayed on the screen. What I want, is once a user clicks on the next button to make 4th image to appear as 1st, while previously 1st picture would be now 2nd and so on.

This is a piece of my js code:

    infinite: true,
    slidesToShow: 4,
    slidesToScroll: 1,

Infinite is set to true, but it does not work the way I want it if there are less than 5 images in total.

I've searched for the answer here, and were able to find two similar questions, however both of them had no proper answer. Links for those:
How to make slick carousel images repeat infinitely and how could i make slides infinite (slick slider).


问:
phpmail always go to spam
how to optimize php_mail() w/o sending the email to a spam?
everything that my webpage is doing sends the email into spam?how to make it not go to spam??</p>

答:
Most of the time, it all depends on your domain name or server IP. If you are using a shared hosting server where many other domains were used to spam, the spam filters such as Yahoo, Hotmail or Google may remember it and get your IP blacklisted. If you have already sent lots of mail without the double opt-in system, lots of your recipients may just throw your messages into spam or junk folders and that might get your domain blacklisted too.

Hope it helps a bit.

Title: phpmail always go to spam


问:
Counting the number of function calls in an executable
I am trying to find the exact number of function calls to one of my implemented C function inside my code. The project includes several C files. What is the easiest solution to figure out how many times a function is called during the execution of the program? Specifically, I am interested to know how many times a specific function calls another function. For instance I have a C file like:

```<code>//file1.c
int main(){
foo1();
return 0;
}
</code>```

and other C files like:

```<code>//file2.c
void  foo1(){
    foo2();
    ...
    foo2();
}
</code>```

and

```<code>//file3.c
void foo2(){
    foo3();
    foo3();
    foo3();
}
</code>```

Now I have my final executable a.out and want to know how many times foo3() is called inside foo1().
  BTW, I am compiling and running my project on Linux.

答:
You can count function calls using a static variable instead of global variable.</p>

```<code>int inc(){
    static int counter = 1;
    counter++;
    return counter;
}
int main(){
    int i;

    for (i = 0; i < 10; i++)
        printf("%d\n", inc());

    return 0;
}
</code>```

Body:
I am trying to find the exact number of function calls to one of my implemented C function inside my code. The project includes several C files. What is the easiest solution to figure out how many times a function is called during the execution of the program? Specifically, I am interested to know how many times a specific function calls another function. For instance I have a C file like:

//file1.c
int main(){
foo1();
return 0;
}

and other C files like:

//file2.c
void  foo1(){
    foo2();
    ...
    foo2();
}

and

//file3.c
void foo2(){
    foo3();
    foo3();
    foo3();
}

Now I have my final executable a.out and want to know how many times foo3() is called inside foo1().
  BTW, I am compiling and running my project on Linux.

Body:
You can count function calls using a static variable instead of global variable.

int inc(){
    static int counter = 1;
    counter++;
    return counter;
}
int main(){
    int i;

    for (i = 0; i < 10; i++)
        printf("%d\n", inc());

    return 0;
}