问:
Add ssh key in bash script (jenkins pipeline)
I have a Jenkins job which needs to execute a shell script. It does a connection via ssh key to a remote computer. Here is the pipeline job :

```<code>    stage ('Run') {
        try {
            sh "chmod +x \$(find . -name '*.sh')"
            wrap([$class: 'AnsiColorBuildWrapper', 'colorMapName': 'XTerm']) {
                sh "./run-ansible-playbook.sh -f ansible-playbook.yml"
            }
etc...
</code>```

The .sh file does the ssh-agent and the ssh-add commands.

```<code>sshAgentCount=$(pgrep ssh-agent | wc -l)

if [[ $sshAgentCount -eq 0 ]]; then
        echo "# run ssh-agent #"
        eval `ssh-agent -s`
       ssh-add /var/lib/jenkins/id_rsa_ansible
fi
</code>```

Problem is that sometimes this works and sometimes not. I think it is because of the tty of the user (here jenkins) which changes all time and the ssh-agent process is linked to a tty.
I don't want to call eval ssh-agent -s always because it causes a out of memory on the machine by time.

Here the ps aux | grep ssh-agent status :

```<code>jenkins   1243  0.0  0.0  11140   320 ?        Ss   17:20   0:00 ssh-agent -s
jenkins   1397  0.0  0.0  11140   320 ?        Ss   17:23   0:00 ssh-agent -s
jenkins   1435  0.0  0.0  11140   320 ?        Ss   17:23   0:00 ssh-agent -s
</code>```

Do you have an elegant solution for this problem ? (one ssh-agent only if needed)

Thank you a lot :)

答:
Thank you for your answer. Indeed it works with a file.

But I found something easier, just kill the process at the end of the job :

```<code># add ssh key
echo "# run ssh-agent #"
eval `ssh-agent -s`
ssh-add /var/lib/jenkins/id_rsa_ansible

work...

kill $SSH_AGENT_PID
</code>```

Body:
I have a Jenkins job which needs to execute a shell script. It does a connection via ssh key to a remote computer. Here is the pipeline job :

    stage ('Run') {
        try {
            sh "chmod +x \$(find . -name '*.sh')"
            wrap([$class: 'AnsiColorBuildWrapper', 'colorMapName': 'XTerm']) {
                sh "./run-ansible-playbook.sh -f ansible-playbook.yml"
            }
etc...

The .sh file does the ssh-agent and the ssh-add commands.

sshAgentCount=$(pgrep ssh-agent | wc -l)

if [[ $sshAgentCount -eq 0 ]]; then
        echo "# run ssh-agent #"
        eval `ssh-agent -s`
       ssh-add /var/lib/jenkins/id_rsa_ansible
fi

Problem is that sometimes this works and sometimes not. I think it is because of the tty of the user (here jenkins) which changes all time and the ssh-agent process is linked to a tty.
I don't want to call eval ssh-agent -s always because it causes a out of memory on the machine by time.

Here the ps aux | grep ssh-agent status :

jenkins   1243  0.0  0.0  11140   320 ?        Ss   17:20   0:00 ssh-agent -s
jenkins   1397  0.0  0.0  11140   320 ?        Ss   17:23   0:00 ssh-agent -s
jenkins   1435  0.0  0.0  11140   320 ?        Ss   17:23   0:00 ssh-agent -s

Do you have an elegant solution for this problem ? (one ssh-agent only if needed)

Thank you a lot :)

Body:
Thank you for your answer. Indeed it works with a file.

But I found something easier, just kill the process at the end of the job :

# add ssh key
echo "# run ssh-agent #"
eval `ssh-agent -s`
ssh-add /var/lib/jenkins/id_rsa_ansible

work...

kill $SSH_AGENT_PID


来源: stackexchange

问:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/fs/FSDataInputStream
I'm submitting remote spark jobs to the Hadoop cluster. But getting below error message help me to solve this. </p>

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/fs/FSDataInputStream
    at org.apache.spark.Logging$.<init>(Logging.scala:162)
    at org.apache.spark.Logging$.<clinit>(Logging.scala)
    at org.apache.spark.Logging$class.initializeIfNecessary(Logging.scala:103)
    at org.apache.spark.Logging$class.log(Logging.scala:50)
    at org.apache.spark.deploy.yarn.ApplicationMaster$.log(ApplicationMaster.scala:635)
    at org.apache.spark.deploy.yarn.ApplicationMaster$.main(ApplicationMaster.scala:649)
    at org.apache.spark.deploy.yarn.ExecutorLauncher$.main(ApplicationMaster.scala:674)
    at org.apache.spark.deploy.yarn.ExecutorLauncher.main(ApplicationMaster.scala)
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.fs.FSDataInputStream
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 8 more
</code>```

答:
To resolve this issue  run spark with the following command:</p>

```<code>/usr/local/spark/bin/spark-shell
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm submitting remote spark jobs to the Hadoop cluster. But getting below error message help me to solve this.

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/fs/FSDataInputStream
    at org.apache.spark.Logging$.<init>(Logging.scala:162)
    at org.apache.spark.Logging$.<clinit>(Logging.scala)
    at org.apache.spark.Logging$class.initializeIfNecessary(Logging.scala:103)
    at org.apache.spark.Logging$class.log(Logging.scala:50)
    at org.apache.spark.deploy.yarn.ApplicationMaster$.log(ApplicationMaster.scala:635)
    at org.apache.spark.deploy.yarn.ApplicationMaster$.main(ApplicationMaster.scala:649)
    at org.apache.spark.deploy.yarn.ExecutorLauncher$.main(ApplicationMaster.scala:674)
    at org.apache.spark.deploy.yarn.ExecutorLauncher.main(ApplicationMaster.scala)
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.fs.FSDataInputStream
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 8 more

Body:
To resolve this issue  run spark with the following command:

/usr/local/spark/bin/spark-shell


问:
iPad development tools that run on Windows?
I've done a lot of looking around and have not found what I'm looking for. Does anyone know of dev tools for the iPad (and iPhone) that run on Windows?  I want to explore iPad application writing but do not want to buy a Mac quite yet.

I searched for related questions but didn't find anything, so apologies in advance if I blew that search.

答: iOS development (both iPad and iPhone) is only available on OS X and Intel-based Mac computers.</p>

ContentLicense: CC BY-SA 2.5


问:
Can I call a function inside a Lambda expression in python
I have a function with including if, else condition and for loop. I want to write this function inside a lambda expression. I tried from many ways to create this lambda function. But still I couldn't do it. This is my function with another rules.

```<code>negation ='no,not,never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')

def f(sentence):
  s = sentence.split()
  l = [s.index(word) for word in s if word in list2]
# Will returns list of indices (of sentence) where word is in list2
   if len(l) > 0:
    for e in l:
        # Check previous word
        if s[e-1] not in negation:
            print 'sad'
</code>```

Can I express this function inside a lambda expression since I developing a rule based classifier for detect emotion from a sentence like happy, sad, angry. Following is my lambda function.

```<code>rules = [(lambda x: word_tokenize(x)[-1] == '?', "neutral"),
         (lambda x: word_tokenize(x)[0] in question, "neutral"),
         (lambda x: any(word in list2 for word in [WordNetLemmatizer().lemmatize(word,'v') for word in word_tokenize(x)]), "sad"),
     (lambda x: any(word in list1 for word in [WordNetLemmatizer().lemmatize(word,'v') for word in word_tokenize(x)]), "happy")]

         print classify("I miss you", rules)
</code>```

答:
Your function could use some improvement:</p>

```<code>negation_words = {"no", "not", "never"}
sad_words = {"miss", "loss", "gone", "give", "lost"}

def count_occurrences(s, search_words, negation_words=negation_words):
    count = 0
    neg = False
    for word in s.lower().split():    # should also strip punctuation
        if word in search_words and not neg:
            count += 1
        neg = word in negation_words
    return count

print("\n".join(["sad"] * count_occurrences(s, sad_words)))
</code>```

Body:
I have a function with including if, else condition and for loop. I want to write this function inside a lambda expression. I tried from many ways to create this lambda function. But still I couldn't do it. This is my function with another rules.

negation ='no,not,never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')

def f(sentence):
  s = sentence.split()
  l = [s.index(word) for word in s if word in list2]
# Will returns list of indices (of sentence) where word is in list2
   if len(l) > 0:
    for e in l:
        # Check previous word
        if s[e-1] not in negation:
            print 'sad'

Can I express this function inside a lambda expression since I developing a rule based classifier for detect emotion from a sentence like happy, sad, angry. Following is my lambda function.

rules = [(lambda x: word_tokenize(x)[-1] == '?', "neutral"),
         (lambda x: word_tokenize(x)[0] in question, "neutral"),
         (lambda x: any(word in list2 for word in [WordNetLemmatizer().lemmatize(word,'v') for word in word_tokenize(x)]), "sad"),
     (lambda x: any(word in list1 for word in [WordNetLemmatizer().lemmatize(word,'v') for word in word_tokenize(x)]), "happy")]

         print classify("I miss you", rules)

Body:
Your function could use some improvement:

negation_words = {"no", "not", "never"}
sad_words = {"miss", "loss", "gone", "give", "lost"}

def count_occurrences(s, search_words, negation_words=negation_words):
    count = 0
    neg = False
    for word in s.lower().split():    # should also strip punctuation
        if word in search_words and not neg:
            count += 1
        neg = word in negation_words
    return count

print("\n".join(["sad"] * count_occurrences(s, sad_words)))


问:
How to prevent Soft Keyboard hiding button in custom dialog?
I have a custom dialog like following

When soft keyboard comes it hides the Button like below.

my code

https://mcaf.ee/9qhnef

How to avoid Submit button being hide?  i have added autoresize and auto pan but no luck so far.

答:
I had similar problem and I found out that the problem was because it was Full Screen.  Try to remove this (if you have it) from your styles.xml:

```<code> <item name="android:windowFullscreen">true</item>
</code>```

Body:
I had similar problem and I found out that the problem was because it was Full Screen.  Try to remove this (if you have it) from your styles.xml:

 <item name="android:windowFullscreen">true</item>


问:
how to make event like button click event for using in xaml
```<code><layoutToolkit:Accordion.ContentTemplate>
                    <DataTemplate>
                        <ListView ItemsSource="{Binding Attributes,Mode=TwoWay}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <control:AccTemplate BindModel ="{Binding BindModel, Mode=TwoWay}" Height="50" OnShowDetailEmployee="OnShowDetailEmployeeClicked"/>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>
                    </DataTemplate>
                </layoutToolkit:Accordion.ContentTemplate>
</code>```

I have list view and custom templage into my xaml file. I'm like to make event to my templete and use the event in xaml. I tried like this, But I'm xaml parse error.

```<code> public sealed partial class AccTemplate
{
    public List<AttrOptionModel> Options { get; set; }
    public AttributeModel Attribute { get; set; }

    public event EventHandler OnShowDetailEmployee; OnShowDetailEmployee="OnShowDetailEmployeeClicked"
</code>```

how can make the event?

答:
You should implement the event handler in the code-behind file of the XAML file where your DataTemplate is defined. So if your XAML is called UserControl1.xaml, the event handler should be implemented in UserControl1.xaml.cs.

UserControl1.xaml.cs:

```<code>private void AccTemplate_OnShowDetailEmployee(object sender, EventArgs e)
{

}
</code>```

UserControl1.xaml:

```<code><control:AccTemplate BindModel ="{Binding BindModel, Mode=TwoWay}" Height="50" OnShowDetailEmployee="AccTemplate_OnShowDetailEmployee"/>
</code>```

The event itself is implemented in the control class:

```<code>public class AccTemplate : UIElement
{
    public List<AttrOptionModel> Options { get; set; }
    public AttributeModel Attribute { get; set; }

    public event EventHandler OnShowDetailEmployee;
}
</code>```

Body:
<layoutToolkit:Accordion.ContentTemplate>
                    <DataTemplate>
                        <ListView ItemsSource="{Binding Attributes,Mode=TwoWay}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <control:AccTemplate BindModel ="{Binding BindModel, Mode=TwoWay}" Height="50" OnShowDetailEmployee="OnShowDetailEmployeeClicked"/>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>
                    </DataTemplate>
                </layoutToolkit:Accordion.ContentTemplate>

I have list view and custom templage into my xaml file. I'm like to make event to my templete and use the event in xaml. I tried like this, But I'm xaml parse error.

 public sealed partial class AccTemplate
{
    public List<AttrOptionModel> Options { get; set; }
    public AttributeModel Attribute { get; set; }

    public event EventHandler OnShowDetailEmployee; OnShowDetailEmployee="OnShowDetailEmployeeClicked"

how can make the event?

Body:
You should implement the event handler in the code-behind file of the XAML file where your DataTemplate is defined. So if your XAML is called UserControl1.xaml, the event handler should be implemented in UserControl1.xaml.cs.

UserControl1.xaml.cs:

private void AccTemplate_OnShowDetailEmployee(object sender, EventArgs e)
{

}

UserControl1.xaml:

<control:AccTemplate BindModel ="{Binding BindModel, Mode=TwoWay}" Height="50" OnShowDetailEmployee="AccTemplate_OnShowDetailEmployee"/>

The event itself is implemented in the control class:

public class AccTemplate : UIElement
{
    public List<AttrOptionModel> Options { get; set; }
    public AttributeModel Attribute { get; set; }

    public event EventHandler OnShowDetailEmployee;
}


问:
Golang Invalid Receiver Type in Method Func
I'm trying to make a simple package to send SSH commands to a server.

I have the following code:

```<code>type Connection *ssh.Client

func Connect(addr, user, password string) (conn Connection, err error) {
    sshConfig := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.Password(password),
        },
        HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
    }

    conn, err = ssh.Dial("tcp", addr, sshConfig)
    return
}

func (conn Connection) SendCommand() ([]byte, error) {
    session, err := (*ssh.Client)(conn).NewSession()
    // ...
}
</code>```

My problem is on the two lines func (conn Connection) SendCommand() ([]byte, error) and session, err := (*ssh.Client)(conn).NewSession().

I can't figure out how to use the methods available for *ssh.Client from my overlaying Connection type.

I understand that I need to do some conversion, and using ssh.Client(*conn).NewSession() would work, but it copies the values of the *ssh.Client which doesn't seem to be the right method.

What should do to access the methods available for a *ssh.Client when working with my custom type Connection *ssh.Client type?

答:
You can't declare a new type with a pointer TypeSpec. Also declaring a new type is used specifically to remove the entire method set, so you won't have any of the original methods from the *ssh.Client.

What you want is to use composition by embedding the *ssh.Client in your own struct type:

```<code>type Connection struct {
    *ssh.Client
}

func Connect(addr, user, password string) (*Connection, error) {
    sshConfig := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.Password(password),
        },
        HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
    }

    conn, err = ssh.Dial("tcp", addr, sshConfig)
    if err != nil {
        return nil, err
    }

    return &Connection{conn}, nil
}

func (conn *Connection) SendCommand() ([]byte, error) {
    session, err := conn.NewSession()
    // ...
}
</code>```

Body:
I'm trying to make a simple package to send SSH commands to a server.

I have the following code:

type Connection *ssh.Client

func Connect(addr, user, password string) (conn Connection, err error) {
    sshConfig := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.Password(password),
        },
        HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
    }

    conn, err = ssh.Dial("tcp", addr, sshConfig)
    return
}

func (conn Connection) SendCommand() ([]byte, error) {
    session, err := (*ssh.Client)(conn).NewSession()
    // ...
}

My problem is on the two lines func (conn Connection) SendCommand() ([]byte, error) and session, err := (*ssh.Client)(conn).NewSession().

I can't figure out how to use the methods available for *ssh.Client from my overlaying Connection type.

I understand that I need to do some conversion, and using ssh.Client(*conn).NewSession() would work, but it copies the values of the *ssh.Client which doesn't seem to be the right method.

What should do to access the methods available for a *ssh.Client when working with my custom type Connection *ssh.Client type?

Body:
You can't declare a new type with a pointer TypeSpec. Also declaring a new type is used specifically to remove the entire method set, so you won't have any of the original methods from the *ssh.Client.

What you want is to use composition by embedding the *ssh.Client in your own struct type:

type Connection struct {
    *ssh.Client
}

func Connect(addr, user, password string) (*Connection, error) {
    sshConfig := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.Password(password),
        },
        HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
    }

    conn, err = ssh.Dial("tcp", addr, sshConfig)
    if err != nil {
        return nil, err
    }

    return &Connection{conn}, nil
}

func (conn *Connection) SendCommand() ([]byte, error) {
    session, err := conn.NewSession()
    // ...
}


问:
MS-SQL 2000: Turn off logging during stored procedure
Here's my scenario:

I have a simple stored procedure that removes a specific set of rows from a table (we'll say about 30k rows), and then inserts about the same amount of rows.  This generally should only take a few seconds; however, the table has a trigger on it that watches for inserts/deletes, and tries to mimic what happened to a linked table on another server.

This process in turn is unbareably slow due to the trigger, and the table is also locked during this process.  So here are my two questions:

I'm guessing a decent part of the slowdown is due to the transaction log.  Is there a way for me to specify in my stored procedure that I do not want what's in the procedure to be logged?

Is there a way for me to do my 'DELETE FROM' and 'INSERT INTO' commands without me locking the table during the entire process?

Thanks!

edit - Thanks for the answers; I figured it was the case (not being able to do either of the above), but wanted to make sure.  The trigger was created a long time ago, and doesn't look very effecient, so it looks like my next step will be to go in to that and find out what's needed and how it can be improved.  Thanks!

答: I wouldn't automatically assume that the performance problem is due to logging.  In fact, it's likely that the trigger is written in such a way that is causing your performance problems.  I encourage you to modify your original question and show the code for the trigger.</p>

OwnerDisplayName: John

LastEditorDisplayName: CodeSlave

OwnerDisplayName: G Mastros


问:
Set up virtualenv with Paramiko SSH
I have some limited experience with Python and Django in Windows, and now I am trying to understand how to deploy my code to an Ubuntu 16.04 LTS VPS. Having read various tutorials and a lot of answers on SE, I managed to proceed pretty far (well, for me), but now I am stuck.

Manually (via Putty) I can do the following:

```<code># check that Python 3.5 is installed
python3 --version
# install pip
sudo -kS apt-get -y install python3-pip
# upgrade pip to newest version
pip3 install --upgrade pip
# check result
pip3 --version
# install venv
sudo -kS pip3 install virtualenv virtualenvwrapper
# create venv
virtualenv ~/Env/firstsite
# make sure venv is created
ls -l ~/Env/firstsite/bin/python  # /home/droplet/Env/firstsite/bin/python3.5 -> python3
# switch on venv
source ~/Env/firstsite/bin/activate  # (firstsite) droplet@hostname:~$
# check that python3 is taken from venv
which python3  # /home/droplet/Env/firstsite/bin/python3
</code>```

So the virtual environment is properly created and switched on. I could proceed installing Django.

However when I am trying to do exactly the same in the automated regime, using Paramiko (I execute commands using paramiko.SSHClient().exec_command(cmd, input_string, get_pty=False), everything goes exactly the same way, until the last command:

```<code>exec_command('which python3')
</code>```

returns /usr/bin/python3. So I assume source activate doesn't work via Paramiko's SSH.

Why?

How can I cope with it?

Can I check that the venv is enabled in some more direct (and reliable) way?

答:
Taken from @Pablo Navarro's answer here :How to source virtualenv activate in a Bash script helped me with this same issue (activating environments in a paramiko ssh session).

In the exec_command give the path to the python executable within the environment eg:

```<code>stdin, stdout, stderr = ssh.exec_command(/path/to/env/bin/python script.py)
</code>```

In my case (using miniconda and a env called pyODBC):

```<code>stdin, stdout, stderr = ssh.exec_command(~/miniconda2/envs/pyODBC/bin/python run_script.py)
</code>```

running the command ~/miniconda2/envs/pyODBC/bin/python -m pip list printed the list of modules in this env to confirm

Title: Set up virtualenv with Paramiko SSH

Body:
I have some limited experience with Python and Django in Windows, and now I am trying to understand how to deploy my code to an Ubuntu 16.04 LTS VPS. Having read various tutorials and a lot of answers on SE, I managed to proceed pretty far (well, for me), but now I am stuck.

Manually (via Putty) I can do the following:

# check that Python 3.5 is installed
python3 --version
# install pip
sudo -kS apt-get -y install python3-pip
# upgrade pip to newest version
pip3 install --upgrade pip
# check result
pip3 --version
# install venv
sudo -kS pip3 install virtualenv virtualenvwrapper
# create venv
virtualenv ~/Env/firstsite
# make sure venv is created
ls -l ~/Env/firstsite/bin/python  # /home/droplet/Env/firstsite/bin/python3.5 -> python3
# switch on venv
source ~/Env/firstsite/bin/activate  # (firstsite) droplet@hostname:~$
# check that python3 is taken from venv
which python3  # /home/droplet/Env/firstsite/bin/python3

So the virtual environment is properly created and switched on. I could proceed installing Django.

However when I am trying to do exactly the same in the automated regime, using Paramiko (I execute commands using paramiko.SSHClient().exec_command(cmd, input_string, get_pty=False), everything goes exactly the same way, until the last command:

exec_command('which python3')

returns /usr/bin/python3. So I assume source activate doesn't work via Paramiko's SSH.

Why?

How can I cope with it?

Can I check that the venv is enabled in some more direct (and reliable) way?

Body:
Taken from @Pablo Navarro's answer here :How to source virtualenv activate in a Bash script helped me with this same issue (activating environments in a paramiko ssh session).

In the exec_command give the path to the python executable within the environment eg:

stdin, stdout, stderr = ssh.exec_command(/path/to/env/bin/python script.py)

In my case (using miniconda and a env called pyODBC):

stdin, stdout, stderr = ssh.exec_command(~/miniconda2/envs/pyODBC/bin/python run_script.py)

running the command ~/miniconda2/envs/pyODBC/bin/python -m pip list printed the list of modules in this env to confirm


问:
Get word that is surrounded by [tag] in brackets[/tag]
I would like to get a list of words, that is surrounded by a BBCode-like "tag".

E.g.:

```<code>$string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";
</code>```

This should return an array like this:

world

fine

because both are surrounded by [tag], but "are" should not be added, because it is surrounded by another tag.

At the moment I try to check and replace the findings this way:

```<code>$e->innertext = preg_replace(
                                '/\b' . preg_quote( "[tag]".$text."[/tag]", "/" ) . '\b/i',
                                "<a href='$url'>\$0</a>",
                                $e->innertext,
                                1
                            );
</code>```

答:
You can also get by try this code..

```<code><?php
 $string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";
 $s2 = explode('[tag]', $string);
 $s3 = array();
 foreach($s2 as $val){
 if (strpos($val, '[/tag]') !== false) {
   $s3[] = explode('[/tag]', $val)[0];
  }
}
echo '```'; print_r($s3);
```

?>

Body:
I would like to get a list of words, that is surrounded by a BBCode-like "tag".

E.g.:

$string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";

This should return an array like this:

world

fine

because both are surrounded by [tag], but "are" should not be added, because it is surrounded by another tag.

At the moment I try to check and replace the findings this way:

$e->innertext = preg_replace(
                                '/\b' . preg_quote( "[tag]".$text."[/tag]", "/" ) . '\b/i',
                                "\$0",
                                $e->innertext,
                                1
                            );

Body:
You can also get by try this code..

<?php
 $string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";
 $s2 = explode('[tag]', $string);
 $s3 = array();
 foreach($s2 as $val){
 if (strpos($val, '[/tag]') !== false) {
   $s3[] = explode('[/tag]', $val)[0];
  }
}
echo '<pre>'; print_r($s3);

?>


问:
How do I create an extended message ID in CAPL?
CAPL does accept message definitions like the following

message 100x mymsg

It does not however accept long message IDs, which is the case of extended payloads. In other words, this is what I would like to do (and CAPL does not accept):

message 18FEF889x mymsg

I know there is the function mkExtId(), though I haven't still figured out how it works. I tried something like

message 18FEF889x mymsg

mkExtId(mymsg.id)

but it still doesn't work. Does anybody have any ideas?

Thanks

答:
You can simply declare the message in this way:</p>

```<code>message 0x114455x msg;
</code>```

Body:
You can simply declare the message in this way:

message 0x114455x msg;


问:
How can I move Eclipse RCP projects .pref files
I've been looking for a way to do this and I'm seeing mixed info, Lars Vogel's article suggests you can use the -Data program argument.

This moves the workspace, which is part of what I wanted, because I don't want my application to be writing any files to the run directory (it doesn't have access to do that) but it doesn't move my .pref files.

Most resources i'm seeing claim that the .pref files get stored in the workspace, but mine don't at all, they are under /configuration/.settings/ which is not in the workspace, but in the run directory of my exported exe.

Is there any way to get these preferences to go to the user home directory?

答:
The majority of preferences are in the workspace (these are 'InstanceScope' preferences)

There are a few which are global to all workspaces which are stored in the /configuration/.settings location (mostly to do with the recent workspaces values) - these are 'ConfigurationScope' preferences.

The 'multi-user install' support does allow some changes to be made to locations - see Eclipse multi-user installs in the help


问:
How to check if HTML5 canvas element contains something in given coordinate region using javascript
I am currently working with Chart.js to generate bar graphs in a project. I've set it up to return data to the chart through an ASP.NET webmethod, and I've set it up to use static labels.

I've done this by iterating through the datasets and data after the onComplete callback, then using the fillText command to write onto the canvas.

Now, I'm having the issue where labels sometimes overlap or overlap with the contents of the chart.

What I want to do is check if the canvas already has something on it at a given point / region. Is this possible? If so, how can it be done?

I'm an experienced programmer but am very new to JavaScript. I searched for a few hours trying to find a suitable solution but could not find anything that worked correctly.

I can provide sample code and images if needed, but I do not think it is required given the scope of the question.

Current project resources: JavaScript, JQuery, Chart.js, bootstrap, ASP.NET webmethods

Thank you

答:
Well, my requirements changed and I no longer need to worry about this, but I will post the code I used anyways:

var imgData = context.getImageData(0,0,canvas.width,canvas.height);

// Function to find the hex color of a specific pixel in the imgData context.
function getPixel(imgData, index) {
    var i = index * 4, d = imgData.data;
    return rgbToHex(d[i], d[i + 1], d[i + 2])
    // returns hex string of rgb values.
}

// Function to caluclate offset of imgData context and then return hex color from getPixel function call.
function getPixelFromCoordinate(imgData, x, y) {
    return getPixel(imgData, y * imgData.width + x);
}

// Function to convert a given rgb value to a hex string.

function rgbToHex(r, g, b) {
    // Left shift values to allow for cheap hex construction
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}```

This code worked fine, so hopefully it will be helpful to others.

Reference 1: getPixel from HTML Canvas?

Reference 2: How to use JavaScript or jQuery to read a pixel of an image when user clicks it?

Body:
Well, my requirements changed and I no longer need to worry about this, but I will post the code I used anyways:

var imgData = context.getImageData(0,0,canvas.width,canvas.height);

// Function to find the hex color of a specific pixel in the imgData context.
function getPixel(imgData, index) {
    var i = index * 4, d = imgData.data;
    return rgbToHex(d[i], d[i + 1], d[i + 2])
    // returns hex string of rgb values.
}

// Function to caluclate offset of imgData context and then return hex color from getPixel function call.
function getPixelFromCoordinate(imgData, x, y) {
    return getPixel(imgData, y * imgData.width + x);
}

// Function to convert a given rgb value to a hex string.

function rgbToHex(r, g, b) {
    // Left shift values to allow for cheap hex construction
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

This code worked fine, so hopefully it will be helpful to others.

Reference 1: getPixel from HTML Canvas?

Reference 2: How to use JavaScript or jQuery to read a pixel of an image when user clicks it?


问:
Can't center a View in an activity in XML (Android)
I have created a new (second) activity in my android app, and right now there is one view in the content_area_reduction.xml (EditText). The file looks like this:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.myname.appname.AreaReductionActivity"
    tools:showIn="@layout/activity_area_reduction">

        <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>
</code>```

The problem is, the view appears on the left of the screen instead of center. How do I fix this issue? Will post more code if needed.

Thank you

答:
Just use android:layout_centerInParent="true" in your edittext. You will get edittext in center of layout.

sample code

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <EditText
        android:id="@+id/edit2"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:textAlignment="center"
        android:layout_centerInParent="true" />

</RelativeLayout>
</code>```

Body:
I have created a new (second) activity in my android app, and right now there is one view in the content_area_reduction.xml (EditText). The file looks like this:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.myname.appname.AreaReductionActivity"
    tools:showIn="@layout/activity_area_reduction">

        <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>

The problem is, the view appears on the left of the screen instead of center. How do I fix this issue? Will post more code if needed.

Thank you

Body:
Just use android:layout_centerInParent="true" in your edittext. You will get edittext in center of layout.

sample code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <EditText
        android:id="@+id/edit2"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:textAlignment="center"
        android:layout_centerInParent="true" />

</RelativeLayout>


问:
Convert & sort javascript array numerically using non-numeric key
I have a JS array in following structure:

```<code>Array(
    [0] => Array(
        reference : "8926"
        name : "xyz1"
        id_product : "78"
    )
    [1] => Array(
        reference : "11588"
        name : "xyz2"
        id_product : "21"
    )
    [2] => Array(
        reference : "119"
        name : "xyz3"
        id_product : "135"
    )
)
</code>```

I needed to sort this array using the reference key, I have done it using multisort function;

But the problem is : even though reference is numeric but in the array structure it is defined as string and hence instead of sorting like:
119, 8926, 11588 it is sorting it like 11588 119 8926, i.e., like string.

I cannot re-structure the array because I receive it through an API, is there anyway to sort it numerically without having to recreate it in numeric data type separately (because I have to pass the array forward in same format & hence double-conversion will make the script hectic)?

PS - Current sorting (non-numeric) is done using this function.

答:
Try with parseFloat its convert the string to number.Then sorting with ASC order

var Arr = [{"reference":"8926","name":"xyz1","id_product":"78"},{"reference":"11588","name":"xyz2","id_product":"21"},{"reference":"119","name":"xyz3","id_product":"135"}]

Arr.sort((a, b) => parseFloat(a.reference) - parseFloat(b.reference));
console.log(Arr)```

Body:
I have a JS array in following structure:

Array(
    [0] => Array(
        reference : "8926"
        name : "xyz1"
        id_product : "78"
    )
    [1] => Array(
        reference : "11588"
        name : "xyz2"
        id_product : "21"
    )
    [2] => Array(
        reference : "119"
        name : "xyz3"
        id_product : "135"
    )
)

I needed to sort this array using the reference key, I have done it using multisort function;

But the problem is : even though reference is numeric but in the array structure it is defined as string and hence instead of sorting like:
119, 8926, 11588 it is sorting it like 11588 119 8926, i.e., like string.

I cannot re-structure the array because I receive it through an API, is there anyway to sort it numerically without having to recreate it in numeric data type separately (because I have to pass the array forward in same format & hence double-conversion will make the script hectic)?

PS - Current sorting (non-numeric) is done using this function.


问:
Examples Realm Butterknife
I was wondering if anyone had any examples of using realm and butter knife together. Is it possible to use the two together? </p>

<p>So far what I have tried is the following, But I am not certain it is correct. I was told to use ExecuteTransaction but I'm not certain it's appropriate. </p>

```<code>public class MainFragmentActivity extends FragmentActivity {

    MainFragmentAdaptor mMainFragmentAdaptor;
    ViewPager mViewPager;
    Player player;
    Realm realm;

    @BindView(R.id.et_character_name)
    EditText et_character_name;

    @OnTextChanged(R.id.et_character_name)
    protected void onTextChanged(CharSequence text) {
        String name = text.toString();
        player.setName(name);

        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {

                    realm.copyToRealmOrUpdate(player);
                    player.setCurrentHP(37);
                }
            });
        } catch (Exception e) {
            Log.e("REALM SET PLAYER ERROR", e.toString());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        realm = Realm.getDefaultInstance();
        setContentView(R.layout.activity_main_fragment);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mViewPager.setAdapter(mMainFragmentAdaptor);

        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    player = realm.createObject(Player.class);
                    player.setCurrentHP(37);
                }
            });
        } catch (Exception e) {
            Log.e("REALM SET PLAYER ERROR", e.toString());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (realm != null) { // guard against weird low-budget phones
            realm.close();
            realm = null;
        }
    }
}
</code>```

答:
It is absolutely fine to use ButterKnife and Realm. Both serve different purpose altogether.

Realm    The Realm Mobile Platform is a data layer for applications.  Like a database, data in Realms can be queried and filtered, interconnected, and persisted

Butterknife   Light weight library to inject views into Android components. It uses annotation processing.

As per Christian Melchior who is Android Tech Lead at Realm,
executeTransaction() is equivalent to

```<code>try {
    realm.beginTransaction();
    // body of executeTransaction
    realm.commitTransaction();
} catch(Exception e) {
    if(realm.isInTransaction()) {
         realm.cancelTransaction();
    }
    throw new RuntimeException(e);
}
</code>```

Because executeTransaction() it handles errors for the developer, where as beginTransaction() is for custom error handling if required.

Title: Examples Realm Butterknife

Body:
I was wondering if anyone had any examples of using realm and butter knife together. Is it possible to use the two together?

So far what I have tried is the following, But I am not certain it is correct. I was told to use ExecuteTransaction but I'm not certain it's appropriate.

public class MainFragmentActivity extends FragmentActivity {

    MainFragmentAdaptor mMainFragmentAdaptor;
    ViewPager mViewPager;
    Player player;
    Realm realm;

    @BindView(R.id.et_character_name)
    EditText et_character_name;

    @OnTextChanged(R.id.et_character_name)
    protected void onTextChanged(CharSequence text) {
        String name = text.toString();
        player.setName(name);

        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {

                    realm.copyToRealmOrUpdate(player);
                    player.setCurrentHP(37);
                }
            });
        } catch (Exception e) {
            Log.e("REALM SET PLAYER ERROR", e.toString());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        realm = Realm.getDefaultInstance();
        setContentView(R.layout.activity_main_fragment);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mViewPager.setAdapter(mMainFragmentAdaptor);

        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    player = realm.createObject(Player.class);
                    player.setCurrentHP(37);
                }
            });
        } catch (Exception e) {
            Log.e("REALM SET PLAYER ERROR", e.toString());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (realm != null) { // guard against weird low-budget phones
            realm.close();
            realm = null;
        }
    }
}

Body:
It is absolutely fine to use ButterKnife and Realm. Both serve different purpose altogether.

Realm    The Realm Mobile Platform is a data layer for applications.  Like a database, data in Realms can be queried and filtered, interconnected, and persisted

Butterknife   Light weight library to inject views into Android components. It uses annotation processing.

As per Christian Melchior who is Android Tech Lead at Realm,
executeTransaction() is equivalent to

try {
    realm.beginTransaction();
    // body of executeTransaction
    realm.commitTransaction();
} catch(Exception e) {
    if(realm.isInTransaction()) {
         realm.cancelTransaction();
    }
    throw new RuntimeException(e);
}

Because executeTransaction() it handles errors for the developer, where as beginTransaction() is for custom error handling if required.


问:
build managed c++ project in .net 3.5 using vs2010 (msbuild4)
Is it possible to build a managed c++ project in .net 3.5 using vs2010 ?
There are different opinions around but I haven't being able to do this. Any ideas?</p>

答: The build system for VS2010 was dramatically changed and only directly supports building for 4.0.  Targeting 3.5 requires having VS2008 on your machine.  More about this in this answer.</p>


问:
set new page in HTML using iTextSharp HTMLWorker (html to pdf)
I using iTextSharp (V 5.4.2.0) to convert a html page to pdf. But I would like to be able to set a new page.

I've tried this:

```<code><div style="page-break-before:always"> </div>
</code>```

and the tag <newpage />

But it doesn't work.
What is the best way, to create a html page, including new page tags (or something) to be able to convert it correctly using iTextSharp?

Kind regards,

Matthijs

答:
Use this in C#
document.NewPage();</p>

Body:
I using iTextSharp (V 5.4.2.0) to convert a html page to pdf. But I would like to be able to set a new page.

I've tried this:

and the tag <newpage />

But it doesn't work.
What is the best way, to create a html page, including new page tags (or something) to be able to convert it correctly using iTextSharp?

Kind regards,

Matthijs

Body:
Use this in C#
document.NewPage();


问:
Firebase CLI not responding
I have previously been able to successfully deploy my static site. Now it hangs and tells me I need to re-authenticate, even though I appear to be authenticated.

```<code>$ firebase -V
3.9.0
$ firebase login
Already logged in as <>
$ firebase deploy

⚠  Your CLI authentication needs to be updated to take advantage of new features.
⚠  Please run firebase login --reauth
</code>```

Other firebase commands just hang. I tried

```<code>$ firebase list --debug
</code>```

and it hangs on

```<code>>>> HTTP REQUEST GET https://admin.firebase.com/v1/projects
</code>```

Until eventually I get

```<code>Error: connect ETIMEDOUT 104.197.85.31:443
    at Object.exports._errnoException (util.js:1050:11)
    at exports._exceptionWithHostPort (util.js:1073:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1093:14)

Error: Server Error. connect ETIMEDOUT 104.197.85.31:443
</code>```

Any ideas?

答: Turns out it was a networking/firewall issue blocking access on port 443.</p>

Title: Firebase CLI not responding

Body:
I have previously been able to successfully deploy my static site. Now it hangs and tells me I need to re-authenticate, even though I appear to be authenticated.

$ firebase -V
3.9.0
$ firebase login
Already logged in as <>
$ firebase deploy

⚠  Your CLI authentication needs to be updated to take advantage of new features.
⚠  Please run firebase login --reauth

Other firebase commands just hang. I tried

$ firebase list --debug

and it hangs on

>>> HTTP REQUEST GET https://admin.firebase.com/v1/projects

Until eventually I get

Error: connect ETIMEDOUT 104.197.85.31:443
    at Object.exports._errnoException (util.js:1050:11)
    at exports._exceptionWithHostPort (util.js:1073:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1093:14)

Error: Server Error. connect ETIMEDOUT 104.197.85.31:443

Any ideas?


问:
Angular 2 - Array of Objects is still undefined after a HTTP Request
I'm using this guide to learn angular 2 http requests. My array of objects is still undefined after an http.get() request.

Service code:

```<code>getUserCompaniesByUserId(userId: string) : Observable<ApplicationUserCompany[]> {
    return this.http.get(`${this.url}/${userId}`)
                    .map(res => res.json())
                    .catch(this.handleError);
}

private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }

    console.error(errMsg);
    return Observable.throw(errMsg);
}
</code>```

Component code:

```<code>getCompanies() {
    this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id'))
                            .subscribe(
                                uc => this.userCompanies = uc,
                                error => this.errorMsg = <any>error
                        );

    this.userCompanies.forEach(uc => {
        ...
        ...
    });
}
</code>```

Because the userCompanies array is undefined after the request, it won't enter in the forEach() loop. It throws this error: "TypeError: Cannot read property 'forEach' of undefined".

Not the request is the error, because I tested it with Postman and Application Insights (my API is .NET Core API). The response code is 200.
Somewhere else is the problem, but I cannot find it.

Thank you!

答:
Try something like</p>

```<code>this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id'))
                        .subscribe(uc => {
                         this.userCompanies = uc
                         this.userCompanies.forEach(uc => {});
})
</code>```

Body:
I'm using this guide to learn angular 2 http requests. My array of objects is still undefined after an http.get() request.

Service code:

getUserCompaniesByUserId(userId: string) : Observable<ApplicationUserCompany[]> {
    return this.http.get(`${this.url}/${userId}`)
                    .map(res => res.json())
                    .catch(this.handleError);
}

private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }

    console.error(errMsg);
    return Observable.throw(errMsg);
}

Component code:

getCompanies() {
    this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id'))
                            .subscribe(
                                uc => this.userCompanies = uc,
                                error => this.errorMsg = <any>error
                        );

    this.userCompanies.forEach(uc => {
        ...
        ...
    });
}

Because the userCompanies array is undefined after the request, it won't enter in the forEach() loop. It throws this error: "TypeError: Cannot read property 'forEach' of undefined".

Not the request is the error, because I tested it with Postman and Application Insights (my API is .NET Core API). The response code is 200.
Somewhere else is the problem, but I cannot find it.

Thank you!

Body:
Try something like

this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id'))
                        .subscribe(uc => {
                         this.userCompanies = uc
                         this.userCompanies.forEach(uc => {});
})


问:
How to convert between different color maps on OpenCV?
I have a set of thermal images which are encoded with different types of color maps.

I want to use a constant color map to make fault intelligence easier.
Please guide me on how to go about this.

答:
I think it is a little more complicated than what is suggested in the comments, since you are dealing with temperatures. You need to revert the color mapping to a temperature value image, then apply one colormap with OpenCV that you like.

Going back to greyscale is not so straightforward as converting the image from BGR to greyscale, because you have colors like dark red that will may be mapped as dark grey as well as dark blue colors, however they are in totally opposite parts of the scale.

Both of your images are in different scale (temperature wise) as well, so, if you pass them back to grey scale, black is not the same temperature as the other one, so it is not possible to compare them directly.

To get a proper scale value you can try to get the upper rectangle (the one that shows the scale) and separate them in equal pieces and divide the temperature range with the same number of divisions. This will give you a color for each temperature. Then transform both images to cv::Mat double and each pixel will have the temperature value.

Finally you must decide what will be your temperature range to decide the colors for all the images you have. For example you can choose 25-45. Then normalize the images with temperatures (the one with doubles) with the range you selected and normalize them to greyscale images (0 will be 25 and 255 will be 45) and apply the color map to this images.

I hope this helps.


问:
In Eclipse, how do I execute all files in a folder using py.test?
I have a folder containing several files starting with "test_" that each contain tests. How do I execute all the files, using py.test, under a single run, with Eclipse?</p>

答: Right click on Parent/Test module, select Run As and then select Python unit-test. It will run all the test cases which starts with test_ of that module


问:
Collapsing toolbar title overlaps with my menu icons
I am using the collapsing Toolbar in a project that I am working on currently. I am setting the title of the collapsing toolbar from my code but the problem is if the title is too big then it overlaps with my menu icons in the toolbar. So how can I fix this issue?

Title OverLaps with menu Icon:

My xml code:

```<code><android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="205dp"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/agent_profile_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginBottom="87dp"
            app:expandedTitleMarginStart="130dp"
            app:expandedTitleTextAppearance="@style/expandedappbar"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#fff"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax">

                <ImageView
                    android:id="@+id/backdrop"
                    android:layout_width="match_parent"
                    android:layout_height="170dp"
                    android:fitsSystemWindows="true"
                    android:scaleType="centerCrop"
                    android:src="@drawable/back" />

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="170dp"
                    android:background="#66000000">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:layout_marginBottom="8dp"
                        android:layout_marginLeft="130dp"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/lbl_agent_profile_position"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@+id/lbl_agent_profile_Name"
                            android:layout_marginBottom="5dp"
                            android:ellipsize="end"
                            android:maxLines="1"
                            android:text="Real Estate Professional at Exit Alliance Realty"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:textColor="#fff"
                            android:textSize="12sp"
                            android:typeface="sans" />

                        <TextView
                            android:id="@+id/lbl_agent_profile_ibaaxid"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:background="#33ffffff"
                            android:paddingBottom="1dp"
                            android:paddingEnd="3dp"
                            android:paddingLeft="3dp"
                            android:paddingRight="3dp"
                            android:paddingStart="3dp"
                            android:paddingTop="1dp"
                            android:text="iBaax ID : 123456789"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:textColor="#fff"
                            android:textSize="12sp"
                            android:typeface="sans" />
                    </LinearLayout>
                </RelativeLayout>

                <LinearLayout
                    android:id="@+id/lnr_img"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="2dp"
                    android:background="#fff"
                    android:layout_marginLeft="10dp"
                    android:layout_marginStart="10dp"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true">

                    <ImageView
                        android:id="@+id/img_agent_profile_image"
                        android:layout_width="110dp"
                        android:layout_height="110dp"

                        android:scaleType="centerCrop"
                        android:src="@drawable/no_profile" />
                </LinearLayout>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="22dp"
                    android:layout_below="@+id/backdrop"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="8dp"
                    android:layout_toRightOf="@+id/lnr_img"
                    android:background="#4d6088"
                    android:paddingEnd="3dp"
                    android:paddingLeft="3dp"
                    android:paddingRight="3dp"
                    android:paddingStart="3dp"
                    android:text="Write Review"
                    android:textAllCaps="false"
                    android:textSize="12sp" />
            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
</code>```

And the code in my activity's OnCreate Method:

```<code>setContentView(R.layout.activity_agent_profile2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    //getSupportActionBar().setTitle("Name");
    agent = (Agent) getIntent().getSerializableExtra("Agent");
    CollapsingToolbarLayout collapsingToolbar =
            (CollapsingToolbarLayout) findViewById(R.id.agent_profile_toolbar);
    collapsingToolbar.setTitle(agent.name);
</code>```

答:
My solution is listen collapsing progress of CollapsingToolbarLayout. When it totally collapse I disable title of AppBarLayout and set it to activity:

```<code>@Override
public void onAppBarOffsetChanged(AppBarLayout appBarLayout, int offset) {
    boolean collapsed = offset == appBarLayout.getTotalScrollRange();
    collapsingToolbarLayout.setTitleEnabled(!collapsed);
    getActivity().setTitle(collapsed ? title : null);
}
</code>```

Body:
I am using the collapsing Toolbar in a project that I am working on currently. I am setting the title of the collapsing toolbar from my code but the problem is if the title is too big then it overlaps with my menu icons in the toolbar. So how can I fix this issue?

Title OverLaps with menu Icon:

My xml code:

<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="205dp"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/agent_profile_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginBottom="87dp"
            app:expandedTitleMarginStart="130dp"
            app:expandedTitleTextAppearance="@style/expandedappbar"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#fff"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax">

                <ImageView
                    android:id="@+id/backdrop"
                    android:layout_width="match_parent"
                    android:layout_height="170dp"
                    android:fitsSystemWindows="true"
                    android:scaleType="centerCrop"
                    android:src="@drawable/back" />

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="170dp"
                    android:background="#66000000">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:layout_marginBottom="8dp"
                        android:layout_marginLeft="130dp"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/lbl_agent_profile_position"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@+id/lbl_agent_profile_Name"
                            android:layout_marginBottom="5dp"
                            android:ellipsize="end"
                            android:maxLines="1"
                            android:text="Real Estate Professional at Exit Alliance Realty"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:textColor="#fff"
                            android:textSize="12sp"
                            android:typeface="sans" />

                        <TextView
                            android:id="@+id/lbl_agent_profile_ibaaxid"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:background="#33ffffff"
                            android:paddingBottom="1dp"
                            android:paddingEnd="3dp"
                            android:paddingLeft="3dp"
                            android:paddingRight="3dp"
                            android:paddingStart="3dp"
                            android:paddingTop="1dp"
                            android:text="iBaax ID : 123456789"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:textColor="#fff"
                            android:textSize="12sp"
                            android:typeface="sans" />
                    </LinearLayout>
                </RelativeLayout>

                <LinearLayout
                    android:id="@+id/lnr_img"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="2dp"
                    android:background="#fff"
                    android:layout_marginLeft="10dp"
                    android:layout_marginStart="10dp"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true">

                    <ImageView
                        android:id="@+id/img_agent_profile_image"
                        android:layout_width="110dp"
                        android:layout_height="110dp"

                        android:scaleType="centerCrop"
                        android:src="@drawable/no_profile" />
                </LinearLayout>

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="22dp"
                    android:layout_below="@+id/backdrop"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="8dp"
                    android:layout_toRightOf="@+id/lnr_img"
                    android:background="#4d6088"
                    android:paddingEnd="3dp"
                    android:paddingLeft="3dp"
                    android:paddingRight="3dp"
                    android:paddingStart="3dp"
                    android:text="Write Review"
                    android:textAllCaps="false"
                    android:textSize="12sp" />
            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

And the code in my activity's OnCreate Method:

setContentView(R.layout.activity_agent_profile2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    //getSupportActionBar().setTitle("Name");
    agent = (Agent) getIntent().getSerializableExtra("Agent");
    CollapsingToolbarLayout collapsingToolbar =
            (CollapsingToolbarLayout) findViewById(R.id.agent_profile_toolbar);
    collapsingToolbar.setTitle(agent.name);

Body:
My solution is listen collapsing progress of CollapsingToolbarLayout. When it totally collapse I disable title of AppBarLayout and set it to activity:

@Override
public void onAppBarOffsetChanged(AppBarLayout appBarLayout, int offset) {
    boolean collapsed = offset == appBarLayout.getTotalScrollRange();
    collapsingToolbarLayout.setTitleEnabled(!collapsed);
    getActivity().setTitle(collapsed ? title : null);
}


问:
how can add my private key to a target host through ansible
i have an shh key from /home/renz/.shh/id_rsa.pub. I want to add this to my target host in /root/.shh/authorized_keys through ansible. I tried this but didn't work.

```<code>---
- hosts: snapzio
  tasks:
    - name: Set authorized key took from file
      authorized_key:
        user: master
        state: present
        key: "{{ lookup('file', '/home/renz/.ssh/id_rsa.pub') }}"
        path: /root/.ssh/authorized_keys
</code>```

because in the first place, i cannot communicate with the host because my key is not in the authorized keys. I think this idea makes sense if i want to communicate to many hosts. instead of just manually copy and paste the key.

答:
As others have mentioned, if the account you use with Ansible doesn't have a SSH key installed, you'll have to fall back to using password authentication.  Assuming InstallMyKey.yml is your playbook, you could run something like this:

```<code>ansible-playbook InstallMyKey.yml --ask-become-pass
</code>```

You'll need to add the remote_user: root line to your YML between the hosts: and tasks: lines, then type in the root password.

Assuming the playbook succeds and everything else in the root SSH settings are correct, your next run of a playbook should use the renz ssh key and get on without a password.

Body:
i have an shh key from /home/renz/.shh/id_rsa.pub. I want to add this to my target host in /root/.shh/authorized_keys through ansible. I tried this but didn't work.

---
- hosts: snapzio
  tasks:
    - name: Set authorized key took from file
      authorized_key:
        user: master
        state: present
        key: "{{ lookup('file', '/home/renz/.ssh/id_rsa.pub') }}"
        path: /root/.ssh/authorized_keys

because in the first place, i cannot communicate with the host because my key is not in the authorized keys. I think this idea makes sense if i want to communicate to many hosts. instead of just manually copy and paste the key.

Body:
As others have mentioned, if the account you use with Ansible doesn't have a SSH key installed, you'll have to fall back to using password authentication.  Assuming InstallMyKey.yml is your playbook, you could run something like this:

ansible-playbook InstallMyKey.yml --ask-become-pass

You'll need to add the remote_user: root line to your YML between the hosts: and tasks: lines, then type in the root password.

Assuming the playbook succeds and everything else in the root SSH settings are correct, your next run of a playbook should use the renz ssh key and get on without a password.


问:
Could not build module Firebase
I have been trying to wire up Firebase analytics into a Objective C/Swift project. I have followed the instructions properly.  My search paths are set. My linker flags is set to -ObjC.  I can get the project to compile properly.  As soon a I @import Firebase and build, I get an error that says cannot build Firebase module.  When I look into the logs I see there is a parse issue building Firebase analytics and Firebase Core.  I have wired this into three other projects fine not using cocoa pods. Please advise.</p>

答:
I have faced this issue and tried everything possible:

```<code>- (Checked that I was actually using .xcworkspace instead of .xcproj)
- Deleted Derived Data
- Cleaned Pods folder, deleted Podfile.lock, pod deintegrate and pod install / update again
- Deleted cached file everywhere on my mac (including hidden folders in Library/Caches/Cocoapods), /var/folders etc.
- Deleted the project, uninstalled Xcode, reinstalled, cloned again etc.
- Check all Build Settings in Xcode, desperately tried all options
</code>```

Nothing worked.

The only solution (and the correct one) was to run a sudo gem install cocoapods to go from 1.2.0 to 1.2.1.

Indeed, you can see that in the changelog for 1.2.1 there is this pull request that fixes import issues with vendor frameworks

TL;DR If you are running cocoapods 1.2.0, you will want to run sudo gem install cocoapodsand make sure you are at least running 1.2.1.

You can check your version by typing pod --version anywhere on your terminal.

Title: Could not build module Firebase

Body:
I have faced this issue and tried everything possible:

- (Checked that I was actually using .xcworkspace instead of .xcproj)
- Deleted Derived Data
- Cleaned Pods folder, deleted Podfile.lock, pod deintegrate and pod install / update again
- Deleted cached file everywhere on my mac (including hidden folders in Library/Caches/Cocoapods), /var/folders etc.
- Deleted the project, uninstalled Xcode, reinstalled, cloned again etc.
- Check all Build Settings in Xcode, desperately tried all options

Nothing worked.

The only solution (and the correct one) was to run a sudo gem install cocoapods to go from 1.2.0 to 1.2.1.

Indeed, you can see that in the changelog for 1.2.1 there is this pull request that fixes import issues with vendor frameworks

TL;DR If you are running cocoapods 1.2.0, you will want to run sudo gem install cocoapodsand make sure you are at least running 1.2.1.

You can check your version by typing pod --version anywhere on your terminal.


问:
Wildfly CLI "resolve-parameter-values" does not work as expected
I am using JBoss EAP 7.0.5 and I want to use internal configuration values in my standalone-ha.xml like:

```<code><property name="javax.net.ssl.trustStore" value="${jboss.server.config.dir}/stores/trustCA.jks"/>
</code>```

I added this value using the wildly maven plugin 1.2.0 Alpha 5 and CLI command:

```<code>/system-property=javax.net.ssl.trustStore:add(value="${jboss.server.config.dir}/stores/trustCA.jks")
</code>```

Sadly it didnt went as expected:

```<code><property name="javax.net.ssl.trustStore" value="/stores/trustCA.jks"/>
</code>```

The jboss-cli.xml looks like this:

```<code><?xml version='1.0' encoding='UTF-8'?>

<!--
   WildFly Command-line Interface configuration.
-->
<jboss-cli xmlns="urn:jboss:cli:2.0">

    <default-protocol use-legacy-override="true">http-remoting</default-protocol>

    <!-- The default controller to connect to when 'connect' command is executed w/o arguments -->
    <default-controller>
        <protocol>http-remoting</protocol>
        <host>localhost</host>
        <port>9990</port>
    </default-controller>

    <!-- Example controller alias named 'Test'
    <controllers>
        <controller name="Test">
            <protocol>http-remoting</protocol>
            <host>localhost</host>
            <port>9990</port>
        </controller>
    </controllers>
    -->

    <validate-operation-requests>true</validate-operation-requests>

    <!-- Command and operation history log configuration -->
    <history>
        <enabled>true</enabled>
        <file-name>.jboss-cli-history</file-name>
        <file-dir>${user.home}</file-dir>
        <max-size>500</max-size>
    </history>

    <!-- whether to resolve system properties specified as command argument or operation parameter values
                  in the CLI VM before sending the operation requests to the controller -->
    <resolve-parameter-values>false</resolve-parameter-values>

    <!-- Whether to write info and error messages to the terminal output -->
    <silent>false</silent>

    <!-- Whether to filter out commands and attributes based on user's permissions -->
    <access-control>false</access-control>
</jboss-cli>
</code>```

I also tried using the variable like this and it still gets resolved:

```<code>${jboss.server.config.dir:}
</code>```

Am I just using it wrong or can this possibly be a CLI or maven plugin error?

答:
This works:

```<code>$${jboss.server.config.dir}
</code>```

Can someone please post a link to where this is documented? :)

Body:
I am using JBoss EAP 7.0.5 and I want to use internal configuration values in my standalone-ha.xml like:

<property name="javax.net.ssl.trustStore" value="${jboss.server.config.dir}/stores/trustCA.jks"/>

I added this value using the wildly maven plugin 1.2.0 Alpha 5 and CLI command:

/system-property=javax.net.ssl.trustStore:add(value="${jboss.server.config.dir}/stores/trustCA.jks")

Sadly it didnt went as expected:

<property name="javax.net.ssl.trustStore" value="/stores/trustCA.jks"/>

The jboss-cli.xml looks like this:

<?xml version='1.0' encoding='UTF-8'?>

<jboss-cli xmlns="urn:jboss:cli:2.0">

    <default-protocol use-legacy-override="true">http-remoting</default-protocol>

    <default-controller>
        <protocol>http-remoting</protocol>
        <host>localhost</host>
        <port>9990</port>
    </default-controller>

    <validate-operation-requests>true</validate-operation-requests>

    <history>
        <enabled>true</enabled>
        <file-name>.jboss-cli-history</file-name>
        <file-dir>${user.home}</file-dir>
        <max-size>500</max-size>
    </history>

    <resolve-parameter-values>false</resolve-parameter-values>

    <silent>false</silent>

    <access-control>false</access-control>
</jboss-cli>

I also tried using the variable like this and it still gets resolved:

${jboss.server.config.dir:}

Am I just using it wrong or can this possibly be a CLI or maven plugin error?

Body:
This works:

$${jboss.server.config.dir}

Can someone please post a link to where this is documented? :)


问:
iPhone cannot create CGBitmapContext
I have a problem with creating a CGBitmapContext.

```<code>CGContextRef bitmapContext = CGBitmapContextCreate(nil, imageSize.width, imageSize.height, 8, imageSize.width * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst)
</code>```

When I run my application normally it works. But when I run it in my 'Test application' (a running app that will perform my tests) the context is logged as (null) and I get the following errors:

```<code><Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextFillRects: invalid context 0x0
<Error>: CGContextDrawImage: invalid context 0x0
<Error>: CGContextDrawImage: invalid context 0x0
<Error>: CGBitmapContextCreateImage: invalid context 0x0
</code>```

My application doesn't crash. But apparently there is something wrong. (I know the errors are created by calling those methods with a nil context).

答:
Do you check for the CGBitmapContextCreate return value to be non-nil?  You will get a nil value if there isn't enough memory available on the device to create the context.

How much memory are you using in the app and for what size bitmap are you asking?

Title: iPhone cannot create CGBitmapContext

Body:
I have a problem with creating a CGBitmapContext.

CGContextRef bitmapContext = CGBitmapContextCreate(nil, imageSize.width, imageSize.height, 8, imageSize.width * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst)

When I run my application normally it works. But when I run it in my 'Test application' (a running app that will perform my tests) the context is logged as (null) and I get the following errors:

<Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextFillRects: invalid context 0x0
<Error>: CGContextDrawImage: invalid context 0x0
<Error>: CGContextDrawImage: invalid context 0x0
<Error>: CGBitmapContextCreateImage: invalid context 0x0

My application doesn't crash. But apparently there is something wrong. (I know the errors are created by calling those methods with a nil context).


问:
Java - proper cancel execution of thread after TimeoutException
I have a java-program which runs on a schedule and fetches some data from external sources via RFC calls. The RFC calls are threaded and shall be canceled after 60 seconds. This is how I do it:

```<code>Future<String> future = executor.submit(new MyCallable());
try {
    future.get(60, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    future.cancel(true);
}
</code>```

This worked for a long time until I came accross a situation, where the external RFC call became stuck and future.cancel(true) was unable to interrupt the thread-execution. So my java-program never finished and continued running until I manually canceled the corresponding process within the external system.

My question now is, how can one guarantee the code to finish in any situation? I saw that stopping the thread is depreciated.

Would it be a good idea to do sth like this?

```<code>try {
     future.get(60, TimeUnit.SECONDS);
} catch (TimeoutException e) {
     future.cancel(true);
     if(!future.isDone()){
        System.exit(1);
     }
}
</code>```

Thanks for any ideas on this.

Cheers, Jooo

答:
I believe that there's no way in Java to just kill off a thread if during execution not implemented InterruptedException . If the thread is executing, it just sets a flag and it's up to the thread to notice it. if the thread is waiting or sleeping, it will throw an InterruptedException.

No need  to check after every line, of course, but methods which can take a long time to execute are responsible for properly handling interrupts

kill the process in which the thread is running. (E.g., call System.exit(int).)

Body:
I have a java-program which runs on a schedule and fetches some data from external sources via RFC calls. The RFC calls are threaded and shall be canceled after 60 seconds. This is how I do it:

Future<String> future = executor.submit(new MyCallable());
try {
    future.get(60, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    future.cancel(true);
}

This worked for a long time until I came accross a situation, where the external RFC call became stuck and future.cancel(true) was unable to interrupt the thread-execution. So my java-program never finished and continued running until I manually canceled the corresponding process within the external system.

My question now is, how can one guarantee the code to finish in any situation? I saw that stopping the thread is depreciated.

Would it be a good idea to do sth like this?

try {
     future.get(60, TimeUnit.SECONDS);
} catch (TimeoutException e) {
     future.cancel(true);
     if(!future.isDone()){
        System.exit(1);
     }
}

Thanks for any ideas on this.

Cheers, Jooo


问:
How to correctly override a class method in Wordpress?
How to correctly override a class method of this class preview_handler (), whether it is possible to make it in a child class?</p>

```<code>class WP_some_class {

public function __construct() {
add_action( 'wp', array( $this, 'process' ) );

$this->steps  = (array) apply_filters( 'submit_job_steps', array(
    'submit' => array(
        'name'     => __( 'Submit Details', 'wp-job-manager' ),
        'view'     => array( $this, 'submit' ),
        'handler'  => array( $this, 'submit_handler' ),
        'priority' => 10
        ),
    'preview' => array(
        'name'     => __( 'Preview', 'wp-job-manager' ),
        'view'     => array( $this, 'preview' ),
        'handler'  => array( $this, 'preview_handler' ),
        'priority' => 20
    ),
    'done' => array(
        'name'     => __( 'Done', 'wp-job-manager' ),
        'view'     => array( $this, 'done' ),
        'priority' => 30
    )
) );

public function preview_handler() {
    // .. some code
}

}
</code>```

答:
You can simply extend the class.

```<code>class Extending_class extends WP_some_class
{
    public function preview_handler()
    {
        // Your code
    }
}
</code>```

Beware that you have to mantain the same method parameters (no one, in this case) as the original class.

From the PHP documentation:

[...] when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.

Body:
How to correctly override a class method of this class preview_handler (), whether it is possible to make it in a child class?

class WP_some_class {

public function __construct() {
add_action( 'wp', array( $this, 'process' ) );

$this->steps  = (array) apply_filters( 'submit_job_steps', array(
    'submit' => array(
        'name'     => __( 'Submit Details', 'wp-job-manager' ),
        'view'     => array( $this, 'submit' ),
        'handler'  => array( $this, 'submit_handler' ),
        'priority' => 10
        ),
    'preview' => array(
        'name'     => __( 'Preview', 'wp-job-manager' ),
        'view'     => array( $this, 'preview' ),
        'handler'  => array( $this, 'preview_handler' ),
        'priority' => 20
    ),
    'done' => array(
        'name'     => __( 'Done', 'wp-job-manager' ),
        'view'     => array( $this, 'done' ),
        'priority' => 30
    )
) );

public function preview_handler() {
    // .. some code
}

}

Body:
You can simply extend the class.

class Extending_class extends WP_some_class
{
    public function preview_handler()
    {
        // Your code
    }
}

Beware that you have to mantain the same method parameters (no one, in this case) as the original class.

From the PHP documentation:

[...] when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.


问:
Angular Cli - SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'
I am trying to generate coverage report with angular cli. however I keep getting following error. I am not quite sure if This is cli error or problem with my Karma.conf? ng test /npm test Runs fine... So something to do with code-coverage option?

```<code>    Error: Module build failed: SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' (3:0)
        at Parser.pp$5.raise (C:\Development\source\\node_modules\babylon\lib\index.js:4443:13)
        at Parser.pp$1.parseStatement (C:\Development\source\\node_modules\babylon\lib\index.js:1875:16)
        at Parser.parseStatement (C:\Development\source\\node_modules\babylon\lib\index.js:5795:22)
        at Parser.pp$1.parseBlockBody (C:\Development\source\\node_modules\babylon\lib\index.js:2262:21)
        at Parser.pp$1.parseTopLevel (C:\Development\source\\node_modules\babylon\lib\index.js:1772:8)
        at Parser.parse (C:\Development\source\\node_modules\babylon\lib\index.js:1667:17)
        at Object.parse (C:\Development\source\\node_modules\babylon\lib\index.js:7163:37)
        at Instrumenter.instrumentSync (C:\Development\source\\node_modules\istanbul-lib-instrument\dist\instrumenter.js:121:31)
        at Instrumenter.instrument (C:\Development\source\\node_modules\istanbul-lib-instrument\dist\instrumenter.js:176:32)
        at Object.module.exports (C:\Development\source\\node_modules\istanbul-instrumenter-loader\index.js:25:25),Module build failed: SyntaxError: 'import
    ' and 'export' may appear only with 'sourceType: module' (2:0)
        at Parser.pp$5.raise (C:\Development\source\\node_modules\babylon\lib\index.js:4443:13)
        at Parser.pp$1.parseStatement (C:\Development\source\\node_modules\babylon\lib\index.js:1875:16)
        at Parser.parseStatement (C:\Development\source\\node_modules\babylon\lib\index.js:5795:22)
        at Parser.pp$1.parseBlockBody (C:\Development\source\\node_modules\babylon\lib\index.js:2262:21)
        at Parser.pp$1.parseTopLevel (C:\Development\source\\node_modules\babylon\lib\index.js:1772:8)
        at Parser.parse (C:\Development\source\\node_modules\babylon\lib\index.js:1667:17)
        at Object.parse (C:\Development\source\\node_modules\babylon\lib\index.js:7163:37)
        at Instrumenter.instrumentSync (C:\Development\source\\node_modules\istanbul-lib-instrument\dist\instrumenter.js:121:31)
        at Instrumenter.instrument (C:\Development\source\\node_modules\istanbul-lib-instrument\dist\instrumenter.js:176:32)
        at Object.module.exports (C:\Development\source\\node_modules\istanbul-instrumenter-loader\index.js:25:25)
        at Compiler.compiler.plugin (C:\Development\source\\node_modules\@angular\cli\plugins\karma-webpack-throw-error.js:10:23)
        at Compiler.applyPlugins (C:\Development\source\\node_modules\tapable\lib\Tapable.js:61:14)
        at Watching._done (C:\Development\source\\node_modules\webpack\lib\Compiler.js:91:17)
        at onCompiled (C:\Development\source\\node_modules\webpack\lib\Compiler.js:50:17)
        at C:\Development\source\\node_modules\webpack\lib\Compiler.js:480:13
        at next (C:\Development\source\\node_modules\tapable\lib\Tapable.js:138:11)
        at Compiler.<anonymous> (C:\Development\source\\node_modules\webpack\lib\CachePlugin.js:62:5)
        at Compiler.applyPluginsAsyncSeries (C:\Development\source\\node_modules\tapable\lib\Tapable.js:142:13)
        at C:\Development\source\\node_modules\webpack\lib\Compiler.js:477:10
        at Compilation.applyPluginsAsyncSeries (C:\Development\source\\node_modules\tapable\lib\Tapable.js:131:46)
        at self.applyPluginsAsync.err (C:\Development\source\\node_modules\webpack\lib\Compilation.js:640:19)
        at next (C:\Development\source\\node_modules\tapable\lib\Tapable.js:138:11)
        at Compilation.<anonymous> (C:\Development\source\\node_modules\webpack\lib\ProgressPlugin.js:122:5)
        at Compilation.applyPluginsAsyncSeries (C:\Development\source\\node_modules\tapable\lib\Tapable.js:142:13)
        at self.applyPluginsAsync.err (C:\Development\source\\node_modules\webpack\lib\Compilation.js:631:11)
        at next (C:\Development\source\\node_modules\tapable\lib\Tapable.js:138:11)
</code>```

My karma.conf looks like this

```<code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('karma-chrome-launcher'),
      require('@angular/cli/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['@angular/cli']
    },
    mime: {
      'text/x-typescript': ['ts', 'tsx']
    },
    coverageIstanbulReporter: {
      reports: ['html', 'lcovonly', 'json'],
      fixWebpackSourcePaths: true
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
      ? ['progress', 'coverage-istanbul']
      : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
</code>```

答:
I hit the same issue today, the fix in my case was a change to the tsconfig.spec.json file. I changed the module entry from "module": "es2015"
to "module": "commonjs"

This resolved the compilation error running ng test --cc and created the expected coverage report. Hope this helps!

Body:
I am trying to generate coverage report with angular cli. however I keep getting following error. I am not quite sure if This is cli error or problem with my Karma.conf? ng test /npm test Runs fine... So something to do with code-coverage option?

    Error: Module build failed: SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' (3:0)
        at Parser.pp$5.raise (C:\Development\source\\node_modules\babylon\lib\index.js:4443:13)
        at Parser.pp$1.parseStatement (C:\Development\source\\node_modules\babylon\lib\index.js:1875:16)
        at Parser.parseStatement (C:\Development\source\\node_modules\babylon\lib\index.js:5795:22)
        at Parser.pp$1.parseBlockBody (C:\Development\source\\node_modules\babylon\lib\index.js:2262:21)
        at Parser.pp$1.parseTopLevel (C:\Development\source\\node_modules\babylon\lib\index.js:1772:8)
        at Parser.parse (C:\Development\source\\node_modules\babylon\lib\index.js:1667:17)
        at Object.parse (C:\Development\source\\node_modules\babylon\lib\index.js:7163:37)
        at Instrumenter.instrumentSync (C:\Development\source\\node_modules\istanbul-lib-instrument\dist\instrumenter.js:121:31)
        at Instrumenter.instrument (C:\Development\source\\node_modules\istanbul-lib-instrument\dist\instrumenter.js:176:32)
        at Object.module.exports (C:\Development\source\\node_modules\istanbul-instrumenter-loader\index.js:25:25),Module build failed: SyntaxError: 'import
    ' and 'export' may appear only with 'sourceType: module' (2:0)
        at Parser.pp$5.raise (C:\Development\source\\node_modules\babylon\lib\index.js:4443:13)
        at Parser.pp$1.parseStatement (C:\Development\source\\node_modules\babylon\lib\index.js:1875:16)
        at Parser.parseStatement (C:\Development\source\\node_modules\babylon\lib\index.js:5795:22)
        at Parser.pp$1.parseBlockBody (C:\Development\source\\node_modules\babylon\lib\index.js:2262:21)
        at Parser.pp$1.parseTopLevel (C:\Development\source\\node_modules\babylon\lib\index.js:1772:8)
        at Parser.parse (C:\Development\source\\node_modules\babylon\lib\index.js:1667:17)
        at Object.parse (C:\Development\source\\node_modules\babylon\lib\index.js:7163:37)
        at Instrumenter.instrumentSync (C:\Development\source\\node_modules\istanbul-lib-instrument\dist\instrumenter.js:121:31)
        at Instrumenter.instrument (C:\Development\source\\node_modules\istanbul-lib-instrument\dist\instrumenter.js:176:32)
        at Object.module.exports (C:\Development\source\\node_modules\istanbul-instrumenter-loader\index.js:25:25)
        at Compiler.compiler.plugin (C:\Development\source\\node_modules\@angular\cli\plugins\karma-webpack-throw-error.js:10:23)
        at Compiler.applyPlugins (C:\Development\source\\node_modules\tapable\lib\Tapable.js:61:14)
        at Watching._done (C:\Development\source\\node_modules\webpack\lib\Compiler.js:91:17)
        at onCompiled (C:\Development\source\\node_modules\webpack\lib\Compiler.js:50:17)
        at C:\Development\source\\node_modules\webpack\lib\Compiler.js:480:13
        at next (C:\Development\source\\node_modules\tapable\lib\Tapable.js:138:11)
        at Compiler.<anonymous> (C:\Development\source\\node_modules\webpack\lib\CachePlugin.js:62:5)
        at Compiler.applyPluginsAsyncSeries (C:\Development\source\\node_modules\tapable\lib\Tapable.js:142:13)
        at C:\Development\source\\node_modules\webpack\lib\Compiler.js:477:10
        at Compilation.applyPluginsAsyncSeries (C:\Development\source\\node_modules\tapable\lib\Tapable.js:131:46)
        at self.applyPluginsAsync.err (C:\Development\source\\node_modules\webpack\lib\Compilation.js:640:19)
        at next (C:\Development\source\\node_modules\tapable\lib\Tapable.js:138:11)
        at Compilation.<anonymous> (C:\Development\source\\node_modules\webpack\lib\ProgressPlugin.js:122:5)
        at Compilation.applyPluginsAsyncSeries (C:\Development\source\\node_modules\tapable\lib\Tapable.js:142:13)
        at self.applyPluginsAsync.err (C:\Development\source\\node_modules\webpack\lib\Compilation.js:631:11)
        at next (C:\Development\source\\node_modules\tapable\lib\Tapable.js:138:11)

My karma.conf looks like this

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('karma-chrome-launcher'),
      require('@angular/cli/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['@angular/cli']
    },
    mime: {
      'text/x-typescript': ['ts', 'tsx']
    },
    coverageIstanbulReporter: {
      reports: ['html', 'lcovonly', 'json'],
      fixWebpackSourcePaths: true
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
      ? ['progress', 'coverage-istanbul']
      : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};