问:
Manual ssh-add works but fails when run from shell script in Ansible. ssh-agent forwarding
When I run the following commands manually [one after the other], the ssh-agent forwarding works with remote hosts:

```<code>eval `ssh-agent -s`
ssh-add <>.pem
</code>```

But, when I bundle them in a shell script and run as an Ansible play, the ssh forwarding doesn't work. Like this:

```<code>   changed: [localhost] => {
        "changed": true,
        "cmd": "sh test.sh",
        "delta": "0:00:00.008763",
        "end": "2017-03-29 12:10:12.337557",
        "invocation": {
            "module_args": {
                "_raw_params": "sh test.sh",
                "_uses_shell": true,
                "chdir": null,
                "creates": null,
                "executable": null,
                "removes": null,
                "warn": true
            },
            "module_name": "command"
        },
        "rc": 0,
        "start": "2017-03-29 12:10:12.328794",
        "stderr": "Identity added: <>.pem (<>.pem)",
        "stdout": "Agent pid <>",
        "stdout_lines": [
            "Agent pid <>"
        ],
        "warnings": []
    }
</code>```

It returns this same error:

```<code>fatal: [<>]: UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey).\r\n",
    "unreachable": true
}
</code>```

My ansible.cfg looks like this:

```<code>[ssh_connection]
ssh_args=-o ControlMaster=auto -o ControlPersist=60s -o ControlPath=/tmp/ansible-ssh-%h-%p-%r -o ForwardAgent=yes
</code>```

So, how do I enable ssh-agent forwarding (maybe via ansible itself?) without manually entering the ssh-add commands in the host?

答:
This is what you are looking for
http://docs.ansible.com/ansible/intro_configuration.html#private-key-file

Add the pem file in path to avoid unnecessary complications.

Body:
When I run the following commands manually [one after the other], the ssh-agent forwarding works with remote hosts:

eval `ssh-agent -s`
ssh-add <>.pem

But, when I bundle them in a shell script and run as an Ansible play, the ssh forwarding doesn't work. Like this:

   changed: [localhost] => {
        "changed": true,
        "cmd": "sh test.sh",
        "delta": "0:00:00.008763",
        "end": "2017-03-29 12:10:12.337557",
        "invocation": {
            "module_args": {
                "_raw_params": "sh test.sh",
                "_uses_shell": true,
                "chdir": null,
                "creates": null,
                "executable": null,
                "removes": null,
                "warn": true
            },
            "module_name": "command"
        },
        "rc": 0,
        "start": "2017-03-29 12:10:12.328794",
        "stderr": "Identity added: <>.pem (<>.pem)",
        "stdout": "Agent pid <>",
        "stdout_lines": [
            "Agent pid <>"
        ],
        "warnings": []
    }

It returns this same error:

fatal: [<>]: UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey).\r\n",
    "unreachable": true
}

My ansible.cfg looks like this:

[ssh_connection]
ssh_args=-o ControlMaster=auto -o ControlPersist=60s -o ControlPath=/tmp/ansible-ssh-%h-%p-%r -o ForwardAgent=yes

So, how do I enable ssh-agent forwarding (maybe via ansible itself?) without manually entering the ssh-add commands in the host?


来源: stackexchange

问:
How to use the threads to create the images thumbnail
I'm use QTreeView to get the images path, then I'm use QListView to display the images that in specific path as thumbnail.

The problem in the period, create and display the thumbnail images.

The previous process, take a long time to done, depend on the number of images.

And for that reason I decided to use the threads, maybe helps to prevent the hung up which occur in application and increase the speed of create and display the thumbnail images.

```<code>void mainWidget::on_treeView_clicked(const QModelIndex &index){
    filesModel->clear();
    QFileSystemModel *sysModel = qobject_cast<QFileSystemModel*>(ui->treeView->model());
    QDir dir(sysModel->filePath(ui->treeView->currentIndex()));
    QFileInfoList filesList = dir.entryInfoList(QStringList() << "*.jpg" << "*.jpeg" << "*.tif" << "*.png" << "*.gif" << "*.bmp" ,QDir::Files);
    int filesCount = filesList.size();
    for(int i=0;i<filesCount;i++){
        QPixmap originalImage(filesList[i].filePath());
        if(!originalImage.isNull()){
            QPixmap scaledImage = originalImage.scaled(150, 120);
            filesModel->setItem(i, new QStandardItem(QIcon(scaledImage), filesList[i].baseName()));
        }
    }
}
</code>```

How can I use threads with the previous code ?

答: This is an older thread, but still comes up in Google.  Check out the answer to this related question. I found the use of QIdentityProxyModel to be a bit more elegant, as it allowed QFileSystemModel to be used as the list view's model.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm use QTreeView to get the images path, then I'm use QListView to display the images that in specific path as thumbnail.

The problem in the period, create and display the thumbnail images.

The previous process, take a long time to done, depend on the number of images.

And for that reason I decided to use the threads, maybe helps to prevent the hung up which occur in application and increase the speed of create and display the thumbnail images.

void mainWidget::on_treeView_clicked(const QModelIndex &index){
    filesModel->clear();
    QFileSystemModel *sysModel = qobject_cast<QFileSystemModel*>(ui->treeView->model());
    QDir dir(sysModel->filePath(ui->treeView->currentIndex()));
    QFileInfoList filesList = dir.entryInfoList(QStringList() << "*.jpg" << "*.jpeg" << "*.tif" << "*.png" << "*.gif" << "*.bmp" ,QDir::Files);
    int filesCount = filesList.size();
    for(int i=0;i<filesCount;i++){
        QPixmap originalImage(filesList[i].filePath());
        if(!originalImage.isNull()){
            QPixmap scaledImage = originalImage.scaled(150, 120);
            filesModel->setItem(i, new QStandardItem(QIcon(scaledImage), filesList[i].baseName()));
        }
    }
}

How can I use threads with the previous code ?


问:
angular 2 validation on dynamic generated fields in loop
I have a list of input fields that are generated with a model. I am trying to add validation to them.
The requirement is they should not be empty or less than 2 characters.
problem is in the documentation only shows validation with non-dynamically generated variable Name. My fields are all generated dynamically. So there is no tempVariableName I can hardcode (otherwise they conflict), so I created temp variable from the name of the property I binded the field to. So I came up with something like this :

```<code>    <div *ngFor="let field of connector.configFields">
    <label>{{field.name}}</label>
    <input [(ngModel)]="field.value" [type]="field.name === 'Password' ? 'password' : 'text'"
           placeholder="{{field.name}} (required)"
           ngControl="[fieldName+field.name]"
           required minlength="2"
           #fieldName+[field.name]="ngModel" />
    <div *ngIf="(fieldName+[field.name]).errors && ((fieldName+[field.name]).dirty || (fieldName+[field.name]).touched)">
        <span *ngIf="(fieldName+[field.name]).errors.required">Enter Name</span>
        <span *ngIf="(fieldName+[field.name]).errors.minlength">Name minimum at 2 characters</span>
    </div>
</div>
</code>```

and the configFields in typescript look like this :

```<code>export class FieldModel {
public name: string;
public type: string;
public value: any;
</code>```

}

But this simply would not work. I am new to angular 2 so I am not exactly sure what I did wrong.

答: Prepare data in model and return to angular. Angular and hard logic in the template = bad friends.</p>

Body:
I have a list of input fields that are generated with a model. I am trying to add validation to them.
The requirement is they should not be empty or less than 2 characters.
problem is in the documentation only shows validation with non-dynamically generated variable Name. My fields are all generated dynamically. So there is no tempVariableName I can hardcode (otherwise they conflict), so I created temp variable from the name of the property I binded the field to. So I came up with something like this :

    {{field.name}}
    <input [(ngModel)]="field.value" [type]="field.name === 'Password' ? 'password' : 'text'"
           placeholder="{{field.name}} (required)"
           ngControl="[fieldName+field.name]"
           required minlength="2"
           #fieldName+[field.name]="ngModel" />

        Enter Name
        Name minimum at 2 characters

and the configFields in typescript look like this :

export class FieldModel {
public name: string;
public type: string;
public value: any;

}

But this simply would not work. I am new to angular 2 so I am not exactly sure what I did wrong.


问:
Returning ints versus void

Possible Duplicate:

  What is the proper declaration of main?

A little while ago I took a course on c++ algorithms. We used visual studio in the classroom and sometimes when writing the main function we would declare it void main() { as opposed to int main(){return 0;} . This worked fine although I knew it normally you should use int. Just recently I tried compiling the same code from the class in netbeans in linux. This time, it would not accept the main function to be declared void. Why is it that the g++ compiler requires the main function to be declared an int? Sorry if this is a silly question.

答:
The standard says that it needs to be int main() (emphasis here on the return type, not the arguments).

void main() is not standard, and as such bound to break on various platforms.

ContentLicense: CC BY-SA 2.5

Title: Returning ints versus void


问:
Git SVN clone with complex structure
I need to clone an SVN repository to git. The SVN repository is structured as if it's a repository of repositories, like so:

```<code>SVNRepo
|____ProjectA
|    |___branches
|    |___tags
|    |___trunk
|            file
|____ProjectB
|    |___branches
|    |___tags
|    |___trunk
             file
</code>```

I need to clone the repository so that I end up with a single git repository, without the svn specific folders (branches, tags, trunk). I originally dumped then split the SVN repo into separate repos for each project and migrated to git using git svn clone with the --stdlayout command. This worked but came with it's own issues that have been vetoed by our team.

I tried the git svn clone with the --stdlayout command but that doesn't work. I end up with an empty git repo with 2 commits (out of hundreds) and no actual files. There were no errors so I'm not sure what happened.

Trying git svn clone without the --stdlayout sort of works, in that I get a single git repo with all files and history. However, I still have all of the branches, tags and trunk folders which I've like to remove.

I've considered dumping the SVN repo and using sed to edit the binary but that seems like a lot of work. I imagine someone else has encountered this and solved the problem but can't find anything that works.

答:
For a one-time migration git-svn is not the right tool for conversions of repositories or repository parts. It is a great tool if you want to use Git as frontend for an existing SVN server, but for one-time conversions you should not use git-svn, but svn2git which is much more suited for this use-case.

There are plenty tools called svn2git, the probably best one is the KDE one from https://github.com/svn-all-fast-export/svn2git. I strongly recommend using that svn2git tool. It is the best I know available out there and it is very flexible in what you can do with its rules files.

You will be easily able to configure svn2gits rule file to produce the result you want from your current SVN layout.

If you are not 100% about the history of your repository, svneverever from http://blog.hartwork.org/?p=763 is a great tool to investigate the history of an SVN repository when migrating it to Git.

Even though git-svn is easier to start with, here are some further reasons why using the KDE svn2git instead of git-svn is superior, besides its flexibility:

the history is rebuilt much better and cleaner by svn2git (if the correct one is used), this is especially the case for more complex histories with branches and merges and so on

the tags are real tags and not branches in Git

with git-svn the tags contain an extra empty commit which also makes them not part of the branches, so a normal fetch will not get them until you give --tags to the command as by default only tags pointing to fetched branches are fetched also. With the proper svn2git tags are where they belong

if you changed layout in SVN you can easily configure this with svn2git, with git-svn you will loose history eventually

with svn2git you can also split one SVN repository into multiple Git repositories easily

or combine multiple SVN repositories in the same SVN root into one Git repository easily

the conversion is a gazillion times faster with the correct svn2git than with git-svn

You see, there are many reasons why git-svn is worse and the KDE svn2git is superior. :-)

Title: Git SVN clone with complex structure

Body:
I need to clone an SVN repository to git. The SVN repository is structured as if it's a repository of repositories, like so:

SVNRepo
|____ProjectA
|    |___branches
|    |___tags
|    |___trunk
|            file
|____ProjectB
|    |___branches
|    |___tags
|    |___trunk
             file

I need to clone the repository so that I end up with a single git repository, without the svn specific folders (branches, tags, trunk). I originally dumped then split the SVN repo into separate repos for each project and migrated to git using git svn clone with the --stdlayout command. This worked but came with it's own issues that have been vetoed by our team.

I tried the git svn clone with the --stdlayout command but that doesn't work. I end up with an empty git repo with 2 commits (out of hundreds) and no actual files. There were no errors so I'm not sure what happened.

Trying git svn clone without the --stdlayout sort of works, in that I get a single git repo with all files and history. However, I still have all of the branches, tags and trunk folders which I've like to remove.

I've considered dumping the SVN repo and using sed to edit the binary but that seems like a lot of work. I imagine someone else has encountered this and solved the problem but can't find anything that works.


问:
Haskell remove trailing and leading whitespace from a file
Let's say I have a file

```<code>mary had a little lamb
         It's fleece was white as snow
Everywhere
    the child went
   The lamb, the lamb was sure to go, yeah
</code>```

How would I read the file as a string, and remove the trailing and leading whitespace? It could be spaces or tabs. It would print like this after removing whitespace:

```<code>mary had a little lamb
It's fleece was white as snow
Everywhere
the child went
The lamb, the lamb was sure to go, yeah
</code>```

Here's what I have currently:

```<code>import Data.Text as T

readTheFile = do
    handle <- openFile "mary.txt" ReadMode
    contents <- hGetContents handle
    putStrLn contents
    hClose handle
    return(contents)

main :: IO ()
main = do
    file <- readTheFile
    file2 <- (T.strip file)
    return()
</code>```

答:
Your code suggests a few misunderstandings about Haskell so let's go through your code before getting to the solution.

```<code>import Data.Text as T
</code>```

You're using Text, great!  I suggest you also use the IO operations that read and write Text types instead of what is provided by the prelude which works on Strings (linked lists of characters).  That is, import Data.Text.IO as T

```<code>readTheFile = do
    handle <- openFile "mary.txt" ReadMode
    contents <- hGetContents handle
    putStrLn contents
    hClose handle
    return(contents)
</code>```

Oh, hey, the use of hGetContents and manually opening and closing a file can be  error prone.  Consider readTheFile = T.readFile "mary.txt".

```<code>main :: IO ()
main = do
    file <- readTheFile
    file2 <- (T.strip file)
    return()
</code>```

Two issues here.

Issue one Notice here you have used strip as though it's an IO action... but it isn't.  I suggest you learn more about IO and binding (do notation) vs let-bound variables.  strip computes a new value of type Text and presumably you want to do something useful with that value, like write it.

Issue two Stripping the whole file is different than stripping each line one at a time.  I suggest you read mathk's answer.

So in the end I think you want:

```<code>-- Qualified imports are accessed via `T.someSymbol`
import qualified Data.Text.IO as T
import qualified Data.Text as T

-- Not really need as a separate function unless you want to also
-- put the stripping here too.
readTheFile :: IO T.Text
readTheFile = T.readFile "mary.txt"

-- First read, then strip each line, then write a new file.
main :: IO ()
main =
    do file <- readTheFile
       let strippedFile = T.unlines $ map T.strip $ T.lines file
       T.writeFile "newfile.txt" (T.strip strippedFile)
</code>```

Body:
Let's say I have a file

mary had a little lamb
         It's fleece was white as snow
Everywhere
    the child went
   The lamb, the lamb was sure to go, yeah

How would I read the file as a string, and remove the trailing and leading whitespace? It could be spaces or tabs. It would print like this after removing whitespace:

mary had a little lamb
It's fleece was white as snow
Everywhere
the child went
The lamb, the lamb was sure to go, yeah

Here's what I have currently:

import Data.Text as T

readTheFile = do
    handle <- openFile "mary.txt" ReadMode
    contents <- hGetContents handle
    putStrLn contents
    hClose handle
    return(contents)

main :: IO ()
main = do
    file <- readTheFile
    file2 <- (T.strip file)
    return()

Body:
Your code suggests a few misunderstandings about Haskell so let's go through your code before getting to the solution.

import Data.Text as T

You're using Text, great!  I suggest you also use the IO operations that read and write Text types instead of what is provided by the prelude which works on Strings (linked lists of characters).  That is, import Data.Text.IO as T

readTheFile = do
    handle <- openFile "mary.txt" ReadMode
    contents <- hGetContents handle
    putStrLn contents
    hClose handle
    return(contents)

Oh, hey, the use of hGetContents and manually opening and closing a file can be  error prone.  Consider readTheFile = T.readFile "mary.txt".

main :: IO ()
main = do
    file <- readTheFile
    file2 <- (T.strip file)
    return()

Two issues here.

Issue one Notice here you have used strip as though it's an IO action... but it isn't.  I suggest you learn more about IO and binding (do notation) vs let-bound variables.  strip computes a new value of type Text and presumably you want to do something useful with that value, like write it.

Issue two Stripping the whole file is different than stripping each line one at a time.  I suggest you read mathk's answer.

So in the end I think you want:

-- Qualified imports are accessed via `T.someSymbol`
import qualified Data.Text.IO as T
import qualified Data.Text as T

-- Not really need as a separate function unless you want to also
-- put the stripping here too.
readTheFile :: IO T.Text
readTheFile = T.readFile "mary.txt"

-- First read, then strip each line, then write a new file.
main :: IO ()
main =
    do file <- readTheFile
       let strippedFile = T.unlines $ map T.strip $ T.lines file
       T.writeFile "newfile.txt" (T.strip strippedFile)


问:
Get the different name of column between 2 tables in SQL Server
In my SQL Server database, I have the same table name in different schemas. For instance schema1.card (table 1) and schema2.card (table 2).

There are around 40 tables in my database. I just want to compare both tables and want to know which are the different column names between those 2 tables.

I have attached a screenshot of the tables. I want to find out all columns which are not in table 2 but exist in table 1 and vice versa.

答:
I tried to add one column in my second schema and wrote following query adn I got the output what I want.</p>

```<code>    select * from information_schema.columns t1 where t1.table_name = 'card' and   t1.table_schema = 'Custom' and
t1.column_name not in(select t2.column_name from information_schema.columns t2 where  t2.table_name = 'card' and   t2.table_schema = 'boston' )
</code>```

Body:
I tried to add one column in my second schema and wrote following query adn I got the output what I want.

    select * from information_schema.columns t1 where t1.table_name = 'card' and   t1.table_schema = 'Custom' and
t1.column_name not in(select t2.column_name from information_schema.columns t2 where  t2.table_name = 'card' and   t2.table_schema = 'boston' )


问:
What's the difference between a stack file and a Compose file?
I'm learning about using Docker Compose to deploy applications in multiple containers, across multiple hosts. And I have come across two configuration files - stack file, and Compose file.

From the Cloud stack file YAML reference, it states a stack file is a file in YAML format that defines one or more services, similar to a docker-compose.yml file but with a few extensions.

And from this post, it states that stacks are very similar to docker-compose except they define services while docker-compose defines containers.

They look very similar, so I am wondering when I would use the stack file, and when to use the Compose file?

答:
Conceptually, both files serve the same purpose - deployment and configuration of your containers on docker engines.

Docker-compose tool was created first and its purpose is "for defining and running multi-container Docker applications" on a single docker engine. (see docker compose overview )

You use docker-compose up to create/update your containers, networks, volumes and so on.

Where Docker Stack is used in Docker Swarm (Docker's orchestration and scheduling tool) and, therefore, it has additional configuration parameters (i.e. replicas, deploy, roles) that are not needed on a single docker engine.

The stack file is interpreted by docker stack command. This command can be invoked from a docker swarm manager only.

You can convert docker-compose.yml to docker-cloud.yml and back. However, as stated in your question, you must pay attention to the differences. Also, you need to keep in mind that there're different versions for docker-compose. Presently, the latest version is version 3. (https://docs.docker.com/compose/compose-file/)

Edit: An interesting blog, that might help to understand the differences, can be found here https://blog.nimbleci.com/2016/09/14/docker-stacks-and-why-we-need-them/

ContentLicense: CC BY-SA 4.0


问:
Print line by line when running a process in python?
I recently worked on using multithreading but ran into an issue where it seems that multiprocessing would be the better way to go. When I run a simple loop counter function as a process, why doesn't it iterate through the loop and print out the output? Instead the code waits for a set amount of time before producing the output. Is there a way this can be solved or am I stuck dealing with processes this way?</p>

```<code>import multiprocessing, time

def loop_process(process_name):
    loopCnt = 0
    print "\nstarting {}".format(process_name)
    for loopCnt in range(15):
        print("value of loopCnt = {}".format(loopCnt))
        loopCnt += 1
        time.sleep(1)
    print('stopping {}'.format(process_name))

if __name__ == '__main__':
    L00P_process = multiprocessing.Process(target=loop_process, args=('L00P_process',))

    L00P_process.start()
    L00P_process.join()

    print('processes stopped')
    print "Exiting Main"
</code>```

答:
I'm not clear on what you're seeing.  On a Windows box just now, running the program from an interactive console ("DOS box"), I saw value of loopCnt = ... once per second until the program ended.  That's what I expected.

Which OS are you running under, how are you running the program, and what exactly are you seeing?

On most (all?) machines, standard output (stdout) is line-buffered if it's attached to an interactive terminal.  Which means output is forced to display each time a line boundary is hit.  For other kinds of output device, it may use other kinds of buffering, and that could account for a delay.

Something to try:  first add

```<code>import sys
</code>```

near the top, then add

```<code>sys.stdout.flush()
</code>```

after your

```<code>print("value of loopCnt = {}".format(loopCnt))
</code>```

That should tell us whether you are, or are not, experiencing a problem with output buffering.

Body:
I recently worked on using multithreading but ran into an issue where it seems that multiprocessing would be the better way to go. When I run a simple loop counter function as a process, why doesn't it iterate through the loop and print out the output? Instead the code waits for a set amount of time before producing the output. Is there a way this can be solved or am I stuck dealing with processes this way?

import multiprocessing, time

def loop_process(process_name):
    loopCnt = 0
    print "\nstarting {}".format(process_name)
    for loopCnt in range(15):
        print("value of loopCnt = {}".format(loopCnt))
        loopCnt += 1
        time.sleep(1)
    print('stopping {}'.format(process_name))

if __name__ == '__main__':
    L00P_process = multiprocessing.Process(target=loop_process, args=('L00P_process',))

    L00P_process.start()
    L00P_process.join()

    print('processes stopped')
    print "Exiting Main"

Body:
I'm not clear on what you're seeing.  On a Windows box just now, running the program from an interactive console ("DOS box"), I saw value of loopCnt = ... once per second until the program ended.  That's what I expected.

Which OS are you running under, how are you running the program, and what exactly are you seeing?

On most (all?) machines, standard output (stdout) is line-buffered if it's attached to an interactive terminal.  Which means output is forced to display each time a line boundary is hit.  For other kinds of output device, it may use other kinds of buffering, and that could account for a delay.

Something to try:  first add

import sys

near the top, then add

sys.stdout.flush()

after your

print("value of loopCnt = {}".format(loopCnt))

That should tell us whether you are, or are not, experiencing a problem with output buffering.


问:
How do I disable END blocks in child processes?
I frequently use fork in programs that also have END { ... } blocks:

```<code>...
END { &some_cleanup_code }
...
my $pid = fork();
if (defined($pid) && $pid==0) {
    &run_child_code;
    exit 0;
}
</code>```

The child process executes the END {} block as it is exiting, but usually I don't want that to happen. Is there a way to prevent a child process from calling the END block at exit? Barring that, is there a way for a program to "know" that it is a child process, so I could say something like

```<code>END { unless (i_am_a_child_process()) { &some_cleanup_code } }
</code>```

?

答:
```<code>use B;
@{; eval { B::end_av->object_2svref } || [] } = ();
</code>```

I thought there was a Devel:: module that also let you do this, but I can't find it now.

Of course, you can't safely do this if you are using arbitrary modules that might be using END blocks for their own purposes...

(edit by OP) You can get control over the END blocks with B::end_av. As a proof-of-concept:

```<code>END { print "This is the first end block.\n"; }
my $END_block_2_line = __LINE__ + 1;
END { print "This is the second end block.\n"; }
END { print "This is the third end block.\n" }

sub disable_specific_END_block {
  use B;
  my ($file, $line) = @_;
  eval {
    my @ENDs = B::end_av->ARRAY;
    for (my $i=$#ENDs; $i>=0; $i--) {
      my $cv = $ENDs[$i];
      if ($cv->START->file eq $file && $cv->START->line == $line) {
        splice @{B::end_av->object_2svref}, $i, 1;
      }
    }
  };
}

disable_specific_END_block(__FILE__, $END_block_2_line);
</code>```

```<code>$ perl endblocks.pl
This is the third end block.
This is the first end block.
</code>```

Usually something like this would be overkill for what I need, but I can see some cases where this would come in handy.

Body:
I frequently use fork in programs that also have END { ... } blocks:

...
END { &some_cleanup_code }
...
my $pid = fork();
if (defined($pid) && $pid==0) {
    &run_child_code;
    exit 0;
}

The child process executes the END {} block as it is exiting, but usually I don't want that to happen. Is there a way to prevent a child process from calling the END block at exit? Barring that, is there a way for a program to "know" that it is a child process, so I could say something like

END { unless (i_am_a_child_process()) { &some_cleanup_code } }

?

Body:
use B;
@{; eval { B::end_av->object_2svref } || [] } = ();

I thought there was a Devel:: module that also let you do this, but I can't find it now.

Of course, you can't safely do this if you are using arbitrary modules that might be using END blocks for their own purposes...

(edit by OP) You can get control over the END blocks with B::end_av. As a proof-of-concept:

END { print "This is the first end block.\n"; }
my $END_block_2_line = __LINE__ + 1;
END { print "This is the second end block.\n"; }
END { print "This is the third end block.\n" }

sub disable_specific_END_block {
  use B;
  my ($file, $line) = @_;
  eval {
    my @ENDs = B::end_av->ARRAY;
    for (my $i=$#ENDs; $i>=0; $i--) {
      my $cv = $ENDs[$i];
      if ($cv->START->file eq $file && $cv->START->line == $line) {
        splice @{B::end_av->object_2svref}, $i, 1;
      }
    }
  };
}

disable_specific_END_block(__FILE__, $END_block_2_line);

$ perl endblocks.pl
This is the third end block.
This is the first end block.

Usually something like this would be overkill for what I need, but I can see some cases where this would come in handy.


问:
Break into multiple rows based on date range of a single row
I have a table which captures appointments, some are single day appointments and some are multi day appointments, so the data looks like

```<code>AppointmentId   StartDate   EndDate
9               2017-04-12  2017-04-12
10              2017-05-01  2017-05-03
11              2017-06-01  2017-06-01
</code>```

I want to split the multi day appointment as single days, so the result I am trying to achieve is like

```<code>AppointmentId   StartDate   EndDate
9               2017-04-12  2017-04-12
10              2017-05-01  2017-05-01
10              2017-05-02  2017-05-02
10              2017-05-03  2017-05-03
11              2017-06-01  2017-06-01
</code>```

So I have split the appointment id 10 into multiple rows. I checked a few other questions like
here but those are to split just based on a single start date and end date and not based on table data

答:
Clearly a Calendar/Tally table would be the way to go as SqlZim illustrated (+1), however you can use an ad-hoc tally table with a CROSS APPLY.

Example

```<code>Select A.AppointmentId
      ,StartDate = B.D
      ,EndDate   = B.D
 From  YourTable A
 Cross Apply (
                Select Top (DateDiff(DD,A.StartDate,A.EndDate)+1) D=DateAdd(DD,-1+Row_Number() Over (Order By Number),A.StartDate)
                 From  master..spt_values
             ) B
</code>```

Returns

```<code>AppointmentId   StartDate   EndDate
9               2017-04-12  2017-04-12
10              2017-05-01  2017-05-01
10              2017-05-02  2017-05-02
10              2017-05-03  2017-05-03
11              2017-06-01  2017-06-01
</code>```

Body:
I have a table which captures appointments, some are single day appointments and some are multi day appointments, so the data looks like

AppointmentId   StartDate   EndDate
9               2017-04-12  2017-04-12
10              2017-05-01  2017-05-03
11              2017-06-01  2017-06-01

I want to split the multi day appointment as single days, so the result I am trying to achieve is like

AppointmentId   StartDate   EndDate
9               2017-04-12  2017-04-12
10              2017-05-01  2017-05-01
10              2017-05-02  2017-05-02
10              2017-05-03  2017-05-03
11              2017-06-01  2017-06-01

So I have split the appointment id 10 into multiple rows. I checked a few other questions like
here but those are to split just based on a single start date and end date and not based on table data

Body:
Clearly a Calendar/Tally table would be the way to go as SqlZim illustrated (+1), however you can use an ad-hoc tally table with a CROSS APPLY.

Example

Select A.AppointmentId
      ,StartDate = B.D
      ,EndDate   = B.D
 From  YourTable A
 Cross Apply (
                Select Top (DateDiff(DD,A.StartDate,A.EndDate)+1) D=DateAdd(DD,-1+Row_Number() Over (Order By Number),A.StartDate)
                 From  master..spt_values
             ) B

Returns

AppointmentId   StartDate   EndDate
9               2017-04-12  2017-04-12
10              2017-05-01  2017-05-01
10              2017-05-02  2017-05-02
10              2017-05-03  2017-05-03
11              2017-06-01  2017-06-01


问:
EPERM: operation not permitted, unlink C:\Users
I am using Meteor 1.4.3.2 on a windows7 dev environment.

A Meteor application I have developed has been great for 6+ months but I have caused a problem by removing modules and apparently something I should not have.
Something outside the application folders (sym-link pointing into \AppData\Local.meteor.. somewhere) is missing/wrong, I think.

All other projects are fine, except this one.

All of my backup copies for this project are failing now too, including fresh clone from repo.
No 'meteor' commands will in this project, or it's backup copies, so 'meteor reset' is not an option.

The error is:

```<code>C:\Users\muser\iNotice>meteor
C:\Users\muser\AppData\Local\.meteor\packages\meteor-tool\1.4.3_2\mt-os.windows.
x86_32\dev_bundle\lib\node_modules\meteor-promise\promise_server.js:190
      throw error;
      ^

Error: EPERM: operation not permitted, unlink 'C:\Users\muser\iNotice\.meteor\lo
cal\dev_bundle'
    at Error (native)
    at Object.fs.unlinkSync (fs.js:932:18)
    at exports.makeLink (C:\tools\cli\dev-bundle-links.js:20:8)
    at [object Object]._.extend.ensureDevBundleLink (C:\tools\project-context.js
:1476:7)
    at [object Object]._.extend._readFile (C:\tools\project-context.js:1410:10)
    at new exports.ReleaseFile (C:\tools\project-context.js:1360:8)
    at C:\tools\cli\main.js:898:22
</code>```

Any suggestions on best approach to fix the application?

Thanks very much for your time and expertise.

答:
Thanks @n3squik!

Here are the actions I took which fixed my problem.

Remove folders:

```<code>C:\Users\muser\testApp\.meteor\local\dev_bundle*\*
C:\Users\muser\AppData\Local\.meteor\packages\meteor-tool\1.4.0-1\*
</code>```

Ran:

```<code>C:\Users\muser\testApp> meteor run
</code>```

The application started up and all seems good.

Thanks again Stack.

Body:
I am using Meteor 1.4.3.2 on a windows7 dev environment.

A Meteor application I have developed has been great for 6+ months but I have caused a problem by removing modules and apparently something I should not have.
Something outside the application folders (sym-link pointing into \AppData\Local.meteor.. somewhere) is missing/wrong, I think.

All other projects are fine, except this one.

All of my backup copies for this project are failing now too, including fresh clone from repo.
No 'meteor' commands will in this project, or it's backup copies, so 'meteor reset' is not an option.

The error is:

C:\Users\muser\iNotice>meteor
C:\Users\muser\AppData\Local\.meteor\packages\meteor-tool\1.4.3_2\mt-os.windows.
x86_32\dev_bundle\lib\node_modules\meteor-promise\promise_server.js:190
      throw error;
      ^

Error: EPERM: operation not permitted, unlink 'C:\Users\muser\iNotice\.meteor\lo
cal\dev_bundle'
    at Error (native)
    at Object.fs.unlinkSync (fs.js:932:18)
    at exports.makeLink (C:\tools\cli\dev-bundle-links.js:20:8)
    at [object Object]._.extend.ensureDevBundleLink (C:\tools\project-context.js
:1476:7)
    at [object Object]._.extend._readFile (C:\tools\project-context.js:1410:10)
    at new exports.ReleaseFile (C:\tools\project-context.js:1360:8)
    at C:\tools\cli\main.js:898:22

Any suggestions on best approach to fix the application?

Thanks very much for your time and expertise.

Body:
Thanks @n3squik!

Here are the actions I took which fixed my problem.

Remove folders:

C:\Users\muser\testApp\.meteor\local\dev_bundle*\*
C:\Users\muser\AppData\Local\.meteor\packages\meteor-tool\1.4.0-1\*

Ran:

C:\Users\muser\testApp> meteor run

The application started up and all seems good.

Thanks again Stack.


问:
PowerShell [wmiclass] Win32_Process.Create() then wait for batch file to complete
I have scheduled a SQLserver agent job that execute a PowerShell script that calls a batch process to start. However, when PowerShell is executed, it did not wait for the batch file to complete before moving to the next job step. What can I do to make it "wait" for the batch file to complete before moving on?

this is the command:

```<code>  ([WMICLASS]"\\SERVER\ROOT\CIMV2:win32_process").Create("cmd.exe /c E:\BatchFiles\First_Batch_File.bat")
</code>```

答:
The Create method will return the ProcessId of the process it creates. You can check if that process has terminated with Get-Process

```<code>$process = ([WMICLASS]"\\SERVER\ROOT\CIMV2:win32_process").Create("cmd.exe /c E:\BatchFiles\First_Batch_File.bat")
while ((Get-Process -Id $process.ProcessId -ErrorAction SilentlyContinue) -ne $null) {
    write-host "waiting"
    sleep 2
}
</code>```

Body:
I have scheduled a SQLserver agent job that execute a PowerShell script that calls a batch process to start. However, when PowerShell is executed, it did not wait for the batch file to complete before moving to the next job step. What can I do to make it "wait" for the batch file to complete before moving on?

this is the command:

  ([WMICLASS]"\\SERVER\ROOT\CIMV2:win32_process").Create("cmd.exe /c E:\BatchFiles\First_Batch_File.bat")

Body:
The Create method will return the ProcessId of the process it creates. You can check if that process has terminated with Get-Process

$process = ([WMICLASS]"\\SERVER\ROOT\CIMV2:win32_process").Create("cmd.exe /c E:\BatchFiles\First_Batch_File.bat")
while ((Get-Process -Id $process.ProcessId -ErrorAction SilentlyContinue) -ne $null) {
    write-host "waiting"
    sleep 2
}


问:
Azure Function Precompile deploy
I have a C# Precompiled Azure function project that I would like to deploy from VS. While the .funproj (the azure function project) deploys normally, the required dlls are not uploaded.

Is there some way of getting those deployed together?

答:
Currently that is a limitation of the .funproj format.

Here's a link to suggest support for precompiled:
https://feedback.azure.com/forums/355860-azure-functions/suggestions/17709979-visual-studio-tooling-for-precompiled-functions

However, there's a relatively easy workaround: instead of using the functions project, use an aspnet project, which allows you to right click project -> publish to your function app. I've attached an example showing the structure of an aspnet project with three functions.

For more details on this approach, see https://aka.ms/precompiled-functions.

Title: Azure Function Precompile deploy


问:
WebSphere ClassNotFoundException when invoking WebService after startup (but not later)
Update: The ClassNotFoundException only occurs if I try to use the web service immediately after starting the application. If I wait (for some unknown event/duration) the application will work. I would like to know what it is that I need to wait for.

Problem: My application fails because a class that does exist is not found by a classloader.

More info:

The class that cannot be found is com.sun.xml.stream.ZephyrParserFactory.

In my EAR I have the sjsxr.jar. This jar contains the class com.sun.xml.stream.ZephyrParserFactory

The EAR also contains MyApp.jar, which contains the EJB entry points for the application. The MyApp.jar manifest references all the needed jars, including sjsxr.jar

```<code>Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.1
Created-By: 1.5.0_18 (Sun Microsystems Inc.)
Built-By: GMM Development Team
Class-Path: aopalliance-1.0.jar commons-codec-1.4.jar commons-collecti
 ons-3.1.jar commons-lang-2.1.jar commons-logging-1.1.1.jar ehcache-co
 re-2.1.0.jar ehcache-spring-annotations-1.1.2.jar joda-time-1.6.1.jar
  log4j-1.2.16.jar org.springframework.context.support-3.0.4.RELEASE.j
 ar sjsxr.jar slf4j-api-1.6.1.jar slf4j-log4j12-1.6.1.jar spring-aop
 -3.0.4.RELEASE.jar spring-asm-3.0.4.RELEASE.jar spring-beans-3.0.4.RE
 LEASE.jar spring-context-3.0.4.RELEASE.jar spring-core-3.0.4.RELEASE.
 jar spring-expression-3.0.4.RELEASE.jar spring-jdbc-3.0.4.RELEASE.jar
  spring-tx-3.0.4.RELEASE.jar swiftVal.jar velocity-1.5.jar vm-startup
 .jar xbean.jar
</code>```

The application contains web services client code generated by WebSphere's wsimport tool. When the application attempts to invoke this code, the following exception is thrown:

```<code>EJB threw an unexpected (non-declared) exception during invocation of method
  "messageIn" on bean "BeanId(MyApp#ejb.jar#NodeEJB, null)".
Exception data: javax.xml.stream.FactoryConfigurationError: Provider
  com.sun.xml.stream.ZephyrParserFactory not found
    at javax.xml.stream.XMLInputFactory.newInstance(Unknown Source)
    at org.apache.axiom.om.util.StAXUtils$7.run(StAXUtils.java:327)
    at java.security.AccessController.doPrivileged(AccessController.java:202)
    at org.apache.axiom.om.util.StAXUtils.getXMLInputFactory_perClassLoader(StAXUtils.java:323)
    at org.apache.axiom.om.util.StAXUtils.getXMLInputFactory(StAXUtils.java:78)
    at org.apache.axiom.om.util.StAXUtils.createXMLStreamReader(StAXUtils.java:133)
    at org.apache.axis2.util.XMLUtils.toOM(XMLUtils.java:596)
    at org.apache.axis2.util.XMLUtils.toOM(XMLUtils.java:581)
    at org.apache.axis2.deployment.DescriptionBuilder.buildOM(DescriptionBuilder.java:97)
    at org.apache.axis2.deployment.AxisConfigBuilder.populateConfig(AxisConfigBuilder.java:90)
    at org.apache.axis2.deployment.DeploymentEngine.populateAxisConfiguration(DeploymentEngine.java:641)
    at com.ibm.ws.websvcs.deployment.WASAxis2ConfigurationBuilder.loadAxisCfg(WASAxis2ConfigurationBuilder.java:492)
    at com.ibm.ws.websvcs.deployment.WASAxis2ConfigurationBuilder.loadAxisClientConfiguration(WASAxis2ConfigurationBuilder.java:191)
    at com.ibm.ws.websvcs.client.WSClientConfigurationFactory.getConfigContext(WSClientConfigurationFactory.java:271)
    at com.ibm.ws.websvcs.client.WSClientConfigurationFactory.getClientConfigurationContext(WSClientConfigurationFactory.java:236)
    at org.apache.axis2.jaxws.description.impl.DescriptionFactoryImpl.createServiceDescription(DescriptionFactoryImpl.java:92)
    at org.apache.axis2.jaxws.description.impl.DescriptionFactoryImpl.createServiceDescription(DescriptionFactoryImpl.java:79)
    at org.apache.axis2.jaxws.description.DescriptionFactory.createServiceDescription(DescriptionFactory.java:76)
    at org.apache.axis2.jaxws.spi.ServiceDelegate.<init>(ServiceDelegate.java:212)
    at org.apache.axis2.jaxws.spi.Provider.createServiceDelegate(Provider.java:59)
    at javax.xml.ws.Service.<init>(Service.java:67)
    at my.generated.Web_Service.<init>(Web_Service.java:44)
...
Caused by: java.lang.ClassNotFoundException: com.sun.xml.stream.ZephyrParserFactory
    at java.lang.Class.forNameImpl(Native Method)
    at java.lang.Class.forName(Class.java:136)
    at javax.xml.stream.FactoryFinder.newInstance(Unknown Source)
    at javax.xml.stream.FactoryFinder.find(Unknown Source)
    at javax.xml.stream.FactoryFinder.find(Unknown Source)
    ... 101 more
</code>```

I have confirmed half a dozen times that the class, jar and manifest are correct before and after deployment.

I have also tried renaming the sjsxr.jar to avoid any potential eclipses but the problem does not go away.

I am using WebSphere 7.0.0.11 ND

Can anyone help?

答:
It's been a long time since I used java, and only touched WebSphere briefly, but maybe this will help? If you are having problems locating the jar file using the manifest, try packaging it in the WEB-INF/lib folder in the jar. It should be found implicitly without having to reference it in the manifest, assuming I read the info on the linked page correctly.

You also may want to have a look at this WebSphere link, about halfway down the page under the heading "Referencing classes within the EAR file".

Body:
Update: The ClassNotFoundException only occurs if I try to use the web service immediately after starting the application. If I wait (for some unknown event/duration) the application will work. I would like to know what it is that I need to wait for.

Problem: My application fails because a class that does exist is not found by a classloader.

More info:

The class that cannot be found is com.sun.xml.stream.ZephyrParserFactory.

In my EAR I have the sjsxr.jar. This jar contains the class com.sun.xml.stream.ZephyrParserFactory

The EAR also contains MyApp.jar, which contains the EJB entry points for the application. The MyApp.jar manifest references all the needed jars, including sjsxr.jar

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.1
Created-By: 1.5.0_18 (Sun Microsystems Inc.)
Built-By: GMM Development Team
Class-Path: aopalliance-1.0.jar commons-codec-1.4.jar commons-collecti
 ons-3.1.jar commons-lang-2.1.jar commons-logging-1.1.1.jar ehcache-co
 re-2.1.0.jar ehcache-spring-annotations-1.1.2.jar joda-time-1.6.1.jar
  log4j-1.2.16.jar org.springframework.context.support-3.0.4.RELEASE.j
 ar sjsxr.jar slf4j-api-1.6.1.jar slf4j-log4j12-1.6.1.jar spring-aop
 -3.0.4.RELEASE.jar spring-asm-3.0.4.RELEASE.jar spring-beans-3.0.4.RE
 LEASE.jar spring-context-3.0.4.RELEASE.jar spring-core-3.0.4.RELEASE.
 jar spring-expression-3.0.4.RELEASE.jar spring-jdbc-3.0.4.RELEASE.jar
  spring-tx-3.0.4.RELEASE.jar swiftVal.jar velocity-1.5.jar vm-startup
 .jar xbean.jar

The application contains web services client code generated by WebSphere's wsimport tool. When the application attempts to invoke this code, the following exception is thrown:

EJB threw an unexpected (non-declared) exception during invocation of method
  "messageIn" on bean "BeanId(MyApp#ejb.jar#NodeEJB, null)".
Exception data: javax.xml.stream.FactoryConfigurationError: Provider
  com.sun.xml.stream.ZephyrParserFactory not found
    at javax.xml.stream.XMLInputFactory.newInstance(Unknown Source)
    at org.apache.axiom.om.util.StAXUtils$7.run(StAXUtils.java:327)
    at java.security.AccessController.doPrivileged(AccessController.java:202)
    at org.apache.axiom.om.util.StAXUtils.getXMLInputFactory_perClassLoader(StAXUtils.java:323)
    at org.apache.axiom.om.util.StAXUtils.getXMLInputFactory(StAXUtils.java:78)
    at org.apache.axiom.om.util.StAXUtils.createXMLStreamReader(StAXUtils.java:133)
    at org.apache.axis2.util.XMLUtils.toOM(XMLUtils.java:596)
    at org.apache.axis2.util.XMLUtils.toOM(XMLUtils.java:581)
    at org.apache.axis2.deployment.DescriptionBuilder.buildOM(DescriptionBuilder.java:97)
    at org.apache.axis2.deployment.AxisConfigBuilder.populateConfig(AxisConfigBuilder.java:90)
    at org.apache.axis2.deployment.DeploymentEngine.populateAxisConfiguration(DeploymentEngine.java:641)
    at com.ibm.ws.websvcs.deployment.WASAxis2ConfigurationBuilder.loadAxisCfg(WASAxis2ConfigurationBuilder.java:492)
    at com.ibm.ws.websvcs.deployment.WASAxis2ConfigurationBuilder.loadAxisClientConfiguration(WASAxis2ConfigurationBuilder.java:191)
    at com.ibm.ws.websvcs.client.WSClientConfigurationFactory.getConfigContext(WSClientConfigurationFactory.java:271)
    at com.ibm.ws.websvcs.client.WSClientConfigurationFactory.getClientConfigurationContext(WSClientConfigurationFactory.java:236)
    at org.apache.axis2.jaxws.description.impl.DescriptionFactoryImpl.createServiceDescription(DescriptionFactoryImpl.java:92)
    at org.apache.axis2.jaxws.description.impl.DescriptionFactoryImpl.createServiceDescription(DescriptionFactoryImpl.java:79)
    at org.apache.axis2.jaxws.description.DescriptionFactory.createServiceDescription(DescriptionFactory.java:76)
    at org.apache.axis2.jaxws.spi.ServiceDelegate.<init>(ServiceDelegate.java:212)
    at org.apache.axis2.jaxws.spi.Provider.createServiceDelegate(Provider.java:59)
    at javax.xml.ws.Service.<init>(Service.java:67)
    at my.generated.Web_Service.<init>(Web_Service.java:44)
...
Caused by: java.lang.ClassNotFoundException: com.sun.xml.stream.ZephyrParserFactory
    at java.lang.Class.forNameImpl(Native Method)
    at java.lang.Class.forName(Class.java:136)
    at javax.xml.stream.FactoryFinder.newInstance(Unknown Source)
    at javax.xml.stream.FactoryFinder.find(Unknown Source)
    at javax.xml.stream.FactoryFinder.find(Unknown Source)
    ... 101 more

I have confirmed half a dozen times that the class, jar and manifest are correct before and after deployment.

I have also tried renaming the sjsxr.jar to avoid any potential eclipses but the problem does not go away.

I am using WebSphere 7.0.0.11 ND

Can anyone help?


问:
SQL Server Script Block number and block line
The error message when running my scripts includes:

Script block number: 9512; Block line 25;

What is a Script block number and how do I go to it in Visual Studio? (I'm using dbUp to create my database.

答: Thinking about Clay's comments, I went out to the source code for dbUp, which is over at the Git website. It turns out that the block line is the same as the sqlException.LineNumber. SqlException.LineNumber Property, according to MSDN, "Gets the line number within the Transact-SQL command batch or stored procedure that generated the error." So, now I have my answer!</p>


问:
Get used or passed datatype of function in c#
Is it possible to grab the type that is used when i call a function ?

Sample

```<code>public T GetRegData<T>(string v)
    {
        RegistryKey key = registryPointer();

        object oValue = key.GetValue(v, null);

        if (oValue != null)
        {
            string sValue = oValue.ToString().ToLower();
        }

        if (oValue is T)
        {
            return (T)oValue;
        }
        else
        {
            try
            {
                return (T)Convert.ChangeType(oValue, typeof(T));
            }
            catch (InvalidCastException)
            {
                return default(T);
            }
        }
    }
</code>```

if I call my function it looks like:

```<code>string x = GetRegData<string>("test1");
bool y = GetRegData<bool>("test2");
</code>```

Now I want to know inside my function what type i try to return. Not the type of my return data.

Reason:

```<code>key.GetValue(v, null);
</code>```

Has NULL as parameter. But this will deny creating the entry in some cases. Eg. I try to add a string in the registry, it will simply skip it. It only adds it if I use string! So the part

```<code>key.GetValue(v, XXXXXX );
</code>```

should be kind of dynamic ^^

Here some Tesing to code that may show more what I'm trying to do...

```<code>public T GetRegData<T>(string v)
{
    RegistryKey key = registryPointer();

    object oValue;

    if ( default(T) is string )
    {
        oValue = key.GetValue(v, "");
    }
    else if (default(T) is int)
    {
        oValue = key.GetValue(v, 0);
    }
    else if (default(T) is bool)
    {
        oValue = key.GetValue(v, false);
    }
    else
    {
        oValue = key.GetValue(v, null);
    }
    ....
</code>```

But Defaut( T ) seems to be null anyway....

PS: Please stop voting close when the other question and its answeres doesnt solve my problem.

答:
You can use the typeof operator.

```<code>public T GetRegData<T>(string v)
{
    RegistryKey key = registryPointer();

    object oValue;

    if ( typeof(T) == typeof(string) )
    {
        oValue = key.GetValue(v, "");
    }
    else if (typeof(T) == typeof(int))
    {
        oValue = key.GetValue(v, 0);
    }
    else if (typeof(T) == typeof(bool))
    {
        oValue = key.GetValue(v, false);
    }
    else
    {
        oValue = key.GetValue(v, null);
    }
    ...
}
</code>```

Body:
Is it possible to grab the type that is used when i call a function ?

Sample

public T GetRegData<T>(string v)
    {
        RegistryKey key = registryPointer();

        object oValue = key.GetValue(v, null);

        if (oValue != null)
        {
            string sValue = oValue.ToString().ToLower();
        }

        if (oValue is T)
        {
            return (T)oValue;
        }
        else
        {
            try
            {
                return (T)Convert.ChangeType(oValue, typeof(T));
            }
            catch (InvalidCastException)
            {
                return default(T);
            }
        }
    }

if I call my function it looks like:

string x = GetRegData<string>("test1");
bool y = GetRegData<bool>("test2");

Now I want to know inside my function what type i try to return. Not the type of my return data.

Reason:

key.GetValue(v, null);

Has NULL as parameter. But this will deny creating the entry in some cases. Eg. I try to add a string in the registry, it will simply skip it. It only adds it if I use string! So the part

key.GetValue(v, XXXXXX );

should be kind of dynamic ^^

Here some Tesing to code that may show more what I'm trying to do...

public T GetRegData<T>(string v)
{
    RegistryKey key = registryPointer();

    object oValue;

    if ( default(T) is string )
    {
        oValue = key.GetValue(v, "");
    }
    else if (default(T) is int)
    {
        oValue = key.GetValue(v, 0);
    }
    else if (default(T) is bool)
    {
        oValue = key.GetValue(v, false);
    }
    else
    {
        oValue = key.GetValue(v, null);
    }
    ....

But Defaut( T ) seems to be null anyway....

PS: Please stop voting close when the other question and its answeres doesnt solve my problem.

Body:
You can use the typeof operator.

public T GetRegData<T>(string v)
{
    RegistryKey key = registryPointer();

    object oValue;

    if ( typeof(T) == typeof(string) )
    {
        oValue = key.GetValue(v, "");
    }
    else if (typeof(T) == typeof(int))
    {
        oValue = key.GetValue(v, 0);
    }
    else if (typeof(T) == typeof(bool))
    {
        oValue = key.GetValue(v, false);
    }
    else
    {
        oValue = key.GetValue(v, null);
    }
    ...
}


问:
loop through a filtered range excel vba
I want to highlight cells when there are 3 or more with the same value, I have the bellow code but it isn't working right because it loop twice into each range. Can someone tell me what is wrong?

```<code>Sub HighlightCells()
Dim k As Integer, myCounter As Integer, firstRow As Integer
Dim myClientExport As Worksheet, myTemplate As Variant
Dim vRange As Range, myRange As Range
Dim myAddr As String

Set myClientExport = Excel.ActiveSheet
Set vRange = myClientExport.UsedRange.SpecialCells(xlCellTypeVisible)

firstRow = vRange.Areas(2).Rows(1).Row
myAddr = Cells(firstRow, 4).Value
myCounter = 0
For Each myRange In vRange.Rows
    k = myRange.Row

    If k > firstRow Then
        If myAddr = Cells(k, 4).Value Then
            myCounter = myCounter + 1
        Else
            myAddr = Cells(k, 4).Value
            myCounter = 0
        End If
        Select Case myCounter
            Case 3

                For i = 0 To 2
                    OId = Cells(k - i, 1).Value
                 Next i
                Cells(k, 4).Interior.ColorIndex = 27
                Cells(k - 1, 4).Interior.ColorIndex = 27
                Cells(k - 2, 4).Interior.ColorIndex = 27
            Case Is > 3
                Cells(k, 4).Interior.ColorIndex = 27
        End Select
    End If
Next myRange
End Sub
</code>```

My data unfiltered look like:

My data filtered look like

I want to highlight all Address with 3 or more Active order status.

答:
I can't get your code to work. Right off I get "Application-defined or object-defined" run-time error on firstRow = vRange.Areas(2).Rows(1).Row.

So what I did is a CountIf formula in column E:
=COUNTIF(D$2:D$7,D2) then set Conditional Formatting. If the range is dynamic, use VBA to determine limits and propagate the formula and Conditional Formatting. Something like:

```<code>Dim rCount As Integer
rCount = Range("D1", Range("D2").End(xlDown)).Rows.Count
Range("D2:D" & rCount).Select
Selection.Cells.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=$E2=3"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 65535
    .TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("E2:E" & rCount).Select
Selection.Formula = "=CountIf($D$2:$D$" & rCount & ", $D2)"
</code>```

Title: loop through a filtered range excel vba

Body:
I want to highlight cells when there are 3 or more with the same value, I have the bellow code but it isn't working right because it loop twice into each range. Can someone tell me what is wrong?

Sub HighlightCells()
Dim k As Integer, myCounter As Integer, firstRow As Integer
Dim myClientExport As Worksheet, myTemplate As Variant
Dim vRange As Range, myRange As Range
Dim myAddr As String

Set myClientExport = Excel.ActiveSheet
Set vRange = myClientExport.UsedRange.SpecialCells(xlCellTypeVisible)

firstRow = vRange.Areas(2).Rows(1).Row
myAddr = Cells(firstRow, 4).Value
myCounter = 0
For Each myRange In vRange.Rows
    k = myRange.Row

    If k > firstRow Then
        If myAddr = Cells(k, 4).Value Then
            myCounter = myCounter + 1
        Else
            myAddr = Cells(k, 4).Value
            myCounter = 0
        End If
        Select Case myCounter
            Case 3

                For i = 0 To 2
                    OId = Cells(k - i, 1).Value
                 Next i
                Cells(k, 4).Interior.ColorIndex = 27
                Cells(k - 1, 4).Interior.ColorIndex = 27
                Cells(k - 2, 4).Interior.ColorIndex = 27
            Case Is > 3
                Cells(k, 4).Interior.ColorIndex = 27
        End Select
    End If
Next myRange
End Sub

My data unfiltered look like:

My data filtered look like

I want to highlight all Address with 3 or more Active order status.

Body:
I can't get your code to work. Right off I get "Application-defined or object-defined" run-time error on firstRow = vRange.Areas(2).Rows(1).Row.

So what I did is a CountIf formula in column E:
=COUNTIF(D$2:D$7,D2) then set Conditional Formatting. If the range is dynamic, use VBA to determine limits and propagate the formula and Conditional Formatting. Something like:

Dim rCount As Integer
rCount = Range("D1", Range("D2").End(xlDown)).Rows.Count
Range("D2:D" & rCount).Select
Selection.Cells.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=$E2=3"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 65535
    .TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("E2:E" & rCount).Select
Selection.Formula = "=CountIf($D$2:$D$" & rCount & ", $D2)"


问:
Must logins be a https page
Several security experts have said in the past that the login page should be on ssl https. So what if my login is a block that's displayed on all pages. Does that mean that my entire website has to be https?

I read it's possible to put the form on http but post it to https, but I read someone saying that it can be exploited with a man in the middle attack. Can someone confirm this? I have a 100 point bounty for someone who can confirm this (and help me with a practical answer how to securely solve this). My login form is on every page, do I need to make the whole website on https? Please feel free to question anything I said here. They're only things I read but don't have experience with and didn't try it myself.

Edit: to those who asked, when I was posting the question, I tried setting the bounty but the system wouldn't let me. I checked the FAQ and saw that bounty can be posted after 2 days from posting the question. That's why you see no bounty yet. But I will not select an answer until I set a bounty in 2 days. Sorry for any confusion.

答: If you want your data to be safe you have to use SSL(certified) on your whole site. But you don't need to have SSL to keep your passwords safe. You could for example use openID, facebook connect, twitter sign-in to handle this part for you. This way never passwords get sent over the wire in plain-text.</p>

Title: Must logins be a https page


问:
SQL Server database - get last record
How do I we get last row in SQL Server if we don't have primary id and numeric column? For example we only have a name and a few other columns in the table</p>

答:
If you mean the highest name, alphabetically,

```<code>select max(columnName) from tableName
</code>```

If you mean the last row added to the table, it's not possible unless you have a column with the date/time inserted, or some other value like an identity column.

Title: SQL Server database - get last record

Body:
If you mean the highest name, alphabetically,

select max(columnName) from tableName

If you mean the last row added to the table, it's not possible unless you have a column with the date/time inserted, or some other value like an identity column.


问:
New line between fields in TCA in TYPO3
I am searching the way for adding a new line between my fields in TYPO3 backend.

Here is my TCA code:

    'tx_name' => array(
        'label'     => 'Your name',
        'config'    => array(
            'type'        => 'input',
            'size'        => '600',
        )
    ),
```
<p>and then the palette:</p>
<pre class="lang-php prettyprint-override"><code>$GLOBALS['TCA']['pages']['palettes']['mypallete'] = array(
    'showitem' => 'tx_name, tx_surename, tx_....'
);
</code>```

I would like to have name, surname always in the new line.

答:
You should include there string --linebreak--

So in your code it will be like this:

$GLOBALS['TCA']['pages']['palettes']['mypallete'] = array(
    'showitem' => 'tx_name,--linebreak--,tx_surename,--linebreak--, tx_....'
);
```

So right now you should have every field on new line.

Title: New line between fields in TCA in TYPO3

Body:
I am searching the way for adding a new line between my fields in TYPO3 backend.

Here is my TCA code:

    'tx_name' => array(
        'label'     => 'Your name',
        'config'    => array(
            'type'        => 'input',
            'size'        => '600',
        )
    ),

and then the palette:

$GLOBALS['TCA']['pages']['palettes']['mypallete'] = array(
    'showitem' => 'tx_name, tx_surename, tx_....'
);

I would like to have name, surname always in the new line.

Body:
You should include there string --linebreak--

So in your code it will be like this:

$GLOBALS['TCA']['pages']['palettes']['mypallete'] = array(
    'showitem' => 'tx_name,--linebreak--,tx_surename,--linebreak--, tx_....'
);

So right now you should have every field on new line.


问:
IWindsorContainer RegisterControllers Missing Method AddLifestyle error
I recently updated a 2.5.2 project to 3.2.1 / MVC 4 recompiling the application after a few code fixes, I am getting a Register Controller issue at run-time. Here is the code:

```<code>    public static void Register(string key, Type interfaceType, Type implementationType)
    {
        //IoC.Container.AddComponent(key, interfaceType, implementationType);
        // IoC.Container.AddComponent is obsolete. Replaced by:
        IoC.Container.Register(Component.For(interfaceType).ImplementedBy(implementationType).Named(key));
    }

    public static void RegisterControllers(params Assembly[] assemblies)
    {
        //IoC.Container.RegisterControllers(assemblies);

        foreach (Assembly assembly in assemblies)
        {
            IoC.Container.RegisterControllers(assembly.GetExportedTypes());
        }
    }

    public static void RegisterAllFromAssemblies(string baseAssembly, string relatedAssembly)
    {
        // AllTypes is obsolete
        //
        //IoC.Container.Register(AllTypes.
        //    FromAssemblyNamed(baseAssembly).
        //    WithService.
        //    FirstNonGenericCoreInterface(relatedAssembly));

        //Update for Castle-Windor 3.2
        IoC.Container.Register(Classes.FromAssemblyNamed(baseAssembly)
                .Pick().WithServiceFirstInterface()
                .LifestylePerWebRequest());
    }
}
</code>```

}

The MissingMethod Exception screen shows after execution of                 IoC.Container.RegisterControllers(assembly.GetExportedTypes());

"Method not found: 'Castle.Windsor.IWindsorContainer Castle.Windsor.IWindsorContainer.AddComponentLifeStyle(System.String, System.Type, Castle.Core.LifestyleType)'."

Pointing me in the right direction would be helpful

答:
I found this unanswered question meanwhile upgrading a Sharp Architecture based project from SharpArch 1.6 to SharpArch 3.0 and thought a final answer to this might be useful. I got the same problem about

"Method not found: 'Castle.Windsor.IWindsorContainer
  Castle.Windsor.IWindsorContainer.AddComponentLifeStyle(System.String,
  System.Type, Castle.Core.LifestyleType)'."

and implemented a solution following the suggestion about IWindsorInstaller from
Charleh.
Basically, I created an IWindsorInstaller implementation moving there all my needed IoC dependencies registrations

```<code>public class ComponentsInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
    {
        AddApplicationServicesTo(container);
        //eventually other services to install
    }

private void AddApplicationServicesTo(IWindsorContainer container)
{

    container.Register(Classes.FromAssemblyNamed("myAssemblyName1").Pick().WithService.FirstInterface());

    container.Register(Classes.FromAssemblyNamed("myAssemblyName2").Pick().WithService.FirstInterface());

}
}
</code>```

and called that installer from Global.asax Application_Start with

```<code>    IWindsorContainer container = new WindsorContainer();
    container.Install(FromAssembly.This());
</code>```

Body:
I recently updated a 2.5.2 project to 3.2.1 / MVC 4 recompiling the application after a few code fixes, I am getting a Register Controller issue at run-time. Here is the code:

    public static void Register(string key, Type interfaceType, Type implementationType)
    {
        //IoC.Container.AddComponent(key, interfaceType, implementationType);
        // IoC.Container.AddComponent is obsolete. Replaced by:
        IoC.Container.Register(Component.For(interfaceType).ImplementedBy(implementationType).Named(key));
    }

    public static void RegisterControllers(params Assembly[] assemblies)
    {
        //IoC.Container.RegisterControllers(assemblies);

        foreach (Assembly assembly in assemblies)
        {
            IoC.Container.RegisterControllers(assembly.GetExportedTypes());
        }
    }

    public static void RegisterAllFromAssemblies(string baseAssembly, string relatedAssembly)
    {
        // AllTypes is obsolete
        //
        //IoC.Container.Register(AllTypes.
        //    FromAssemblyNamed(baseAssembly).
        //    WithService.
        //    FirstNonGenericCoreInterface(relatedAssembly));

        //Update for Castle-Windor 3.2
        IoC.Container.Register(Classes.FromAssemblyNamed(baseAssembly)
                .Pick().WithServiceFirstInterface()
                .LifestylePerWebRequest());
    }
}

}

The MissingMethod Exception screen shows after execution of                 IoC.Container.RegisterControllers(assembly.GetExportedTypes());

"Method not found: 'Castle.Windsor.IWindsorContainer Castle.Windsor.IWindsorContainer.AddComponentLifeStyle(System.String, System.Type, Castle.Core.LifestyleType)'."

Pointing me in the right direction would be helpful

Body:
I found this unanswered question meanwhile upgrading a Sharp Architecture based project from SharpArch 1.6 to SharpArch 3.0 and thought a final answer to this might be useful. I got the same problem about

"Method not found: 'Castle.Windsor.IWindsorContainer
  Castle.Windsor.IWindsorContainer.AddComponentLifeStyle(System.String,
  System.Type, Castle.Core.LifestyleType)'."

and implemented a solution following the suggestion about IWindsorInstaller from
Charleh.
Basically, I created an IWindsorInstaller implementation moving there all my needed IoC dependencies registrations

public class ComponentsInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
    {
        AddApplicationServicesTo(container);
        //eventually other services to install
    }

private void AddApplicationServicesTo(IWindsorContainer container)
{

    container.Register(Classes.FromAssemblyNamed("myAssemblyName1").Pick().WithService.FirstInterface());

    container.Register(Classes.FromAssemblyNamed("myAssemblyName2").Pick().WithService.FirstInterface());

}
}

and called that installer from Global.asax Application_Start with

    IWindsorContainer container = new WindsorContainer();
    container.Install(FromAssembly.This());


问:
using *ngIf as a toggle to display div content in angular 2
I have a div that contains a dropdown box and i would by default the dropdown box is empty and only populated as the user removes items from the view page. I would like to have this div with the dropdown to be not visible when the list is empty and to be displayed once the list has at least 1 item. </p>

```<code><div class="btn-group bootstrap-select show-tick">
   <button type="button" class="btn dropdown-toggle bs-placeholder btn-default" (click)="toggleSelect()">
       <span class="pull-left">List Items</span>
       <span class="bs-caret ">
           <span class="caret "></span>
       </span>
   </button>
        <ul class="dropdown-menu multi-select-popup " [ngStyle]="{display:isOpen ? 'block' : 'none'} " style="display:block; ">
            <li *ngFor="let item of dropdownlist; let i = index ">
                <a (click)="select(item, i) " class="dropdown-item ">
                    <i class="fa fa-fw " [ngClass]="{ 'fa-check': item.checked, 'glyphicon-none': !item.checked} "></i>
                    <span [innerHtml]="item.title "></span>
                </a>
            </li>
        </ul>
    </div>
</code>```

<p>how can i implements this using *ngIf to toggle the display of the div depending on the length of items in the dropdown. </p>

答:
Use a combination of the safe navigation operator and *ngIf:

```<code><ul *ngIf="dropdownlist?.length > 0" ... >
</code>```

This will access the length property of dropdownlist, if it is defined, and will satisfy the condition if the length is > 0.

Using the safe accessor saves you having to chain dropdownlist && dropdownlist.length since it won't throw an exception if dropdownlist is undefined.

Body:
I have a div that contains a dropdown box and i would by default the dropdown box is empty and only populated as the user removes items from the view page. I would like to have this div with the dropdown to be not visible when the list is empty and to be displayed once the list has at least 1 item.

   <button type="button" class="btn dropdown-toggle bs-placeholder btn-default" (click)="toggleSelect()">
       List Items

   </button>

how can i implements this using *ngIf to toggle the display of the div depending on the length of items in the dropdown.

Body:
Use a combination of the safe navigation operator and *ngIf:

<ul *ngIf="dropdownlist?.length > 0" ... >

This will access the length property of dropdownlist, if it is defined, and will satisfy the condition if the length is > 0.

Using the safe accessor saves you having to chain dropdownlist && dropdownlist.length since it won't throw an exception if dropdownlist is undefined.


问:
How to call a function after a loop has ended?
Currently we have part of a function where after JSON data has be collected and assigned to a data object. We then loop through the data object's image data value to update the imageviews. After the loop is finished we reload the tableview.  The problem that is occurring is the tableview is reloading after EVERY single object is updated creating flashing and other visual miscues.  If the tableview can load after ALL the image data has been updated it would be better.  Here is that portion of the code:</p>

```<code>  if let extraImages = self.profileData?.images{

    let extraMovieImages = extraImages.images
    for image in extraMovieImages {
      self.updateImage(ImageType: DownloadPic.personal, ImageString: image.filePath, completion: {_ in

        DispatchQueue.main.async {
          self.TableView.reloadData()
        }
      })
    }
  }
</code>```

答:
Make a variable before the loop:

```<code>let expectedCount = extraMovieImages.count
</code>```

Then count it down in the completion block and when it gets to 0, reload.

Another idea is if you know which row each image is on, just reload that row, not the whole table.

Body:
Currently we have part of a function where after JSON data has be collected and assigned to a data object. We then loop through the data object's image data value to update the imageviews. After the loop is finished we reload the tableview.  The problem that is occurring is the tableview is reloading after EVERY single object is updated creating flashing and other visual miscues.  If the tableview can load after ALL the image data has been updated it would be better.  Here is that portion of the code:

  if let extraImages = self.profileData?.images{

    let extraMovieImages = extraImages.images
    for image in extraMovieImages {
      self.updateImage(ImageType: DownloadPic.personal, ImageString: image.filePath, completion: {_ in

        DispatchQueue.main.async {
          self.TableView.reloadData()
        }
      })
    }
  }

Body:
Make a variable before the loop:

let expectedCount = extraMovieImages.count

Then count it down in the completion block and when it gets to 0, reload.

Another idea is if you know which row each image is on, just reload that row, not the whole table.


问:
SonarQube authentication with LDAP not working
I'm having a problem getting LDAP authentication to work.  Looking at the logs it seems to bind ok, but when i try to login it doesn't look like its hitting ldap at all and i get authentication failed.

In the logs I see:

```<code>2017.03.28 17:17:46 INFO  web[org.sonar.INFO] Security realm: LDAP
2017.03.28 17:17:46 INFO  web[o.s.p.l.LdapSettingsManager] User mapping: LdapUserMapping{baseDn=ou=people,o=intra,dc=sears,dc=com, request=(&(objectClass=*searsorgperson)(uid={0})), realNameAttribute=cn, emailAttribute=mail}
2017.03.28 17:17:46 INFO  web[o.s.p.l.LdapSettingsManager] Groups will not be synchronized, because property 'ldap.group.baseDn' is empty.
2017.03.28 17:17:46 DEBUG web[o.s.p.l.LdapContextFactory] Initializing LDAP context {java.naming.provider.url=ldap://trprdirqr3.intra.searshc.com:389/ou=people,o=intra,dc=sears,dc=com, java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory, com.sun.jndi.ldap.connect.pool=true, java.naming.security.authentication=simple, java.naming.referral=follow}
2017.03.28 17:17:46 INFO  web[o.s.p.l.LdapContextFactory] Test LDAP connection on ldap://trprdirqr3.intra.searshc.com:389/ou=people,o=intra,dc=sears,dc=com: OK
2017.03.28 17:17:46 INFO  web[org.sonar.INFO] Security realm started
</code>```

My config has the following:

```<code># General Configuration
sonar.security.realm=LDAP
sonar.authenticator.createUsers=true
sonar.authenticator.class: org.sonar.plugins.ldap.LdapAuthenticator
sonar.security.savePassword=true
sonar.security.updateUserAttributes=true
ldap.url=ldap://trprdirqr3.intra.searshc.com:389/ou=people,o=intra,dc=sears,dc=com

# User Configuration
ldap.user.baseDn=ou=people,o=intra,dc=sears,dc=com
ldap.user.request=(&(objectClass=*searsorgperson)(uid={login}))
ldap.user.realNameAttribute=cn
ldap.user.emailAttribute=mail
</code>```

According to my LDAP admin, it does an anonumous check when it first comes up, but nothing is else done after that.  So for some reason it doesn't seem to be hitting the LDAP server when i login.  I don't have any local IDs setup besides admin.

答:
You have not configured an authenticated user to do the search.

That is, the first test, anonymous bind tests the connectivity. But to search for the users DN, you need more than anonymous permissions. Then once the DN is found, bind as the logging in user. But first you need to provide the LDAP DN of the user who is the proxy that can search and its password.

Also you have an asterisk (wildcard) in your objectlass search filter:

ldap.user.request=(&(objectClass=*searsorgperson)(uid={login}))

Or is that formatting symbol?  I am not sure ObjectClass can usually be searched that way).

Body:
I'm having a problem getting LDAP authentication to work.  Looking at the logs it seems to bind ok, but when i try to login it doesn't look like its hitting ldap at all and i get authentication failed.

In the logs I see:

2017.03.28 17:17:46 INFO  web[org.sonar.INFO] Security realm: LDAP
2017.03.28 17:17:46 INFO  web[o.s.p.l.LdapSettingsManager] User mapping: LdapUserMapping{baseDn=ou=people,o=intra,dc=sears,dc=com, request=(&(objectClass=*searsorgperson)(uid={0})), realNameAttribute=cn, emailAttribute=mail}
2017.03.28 17:17:46 INFO  web[o.s.p.l.LdapSettingsManager] Groups will not be synchronized, because property 'ldap.group.baseDn' is empty.
2017.03.28 17:17:46 DEBUG web[o.s.p.l.LdapContextFactory] Initializing LDAP context {java.naming.provider.url=ldap://trprdirqr3.intra.searshc.com:389/ou=people,o=intra,dc=sears,dc=com, java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory, com.sun.jndi.ldap.connect.pool=true, java.naming.security.authentication=simple, java.naming.referral=follow}
2017.03.28 17:17:46 INFO  web[o.s.p.l.LdapContextFactory] Test LDAP connection on ldap://trprdirqr3.intra.searshc.com:389/ou=people,o=intra,dc=sears,dc=com: OK
2017.03.28 17:17:46 INFO  web[org.sonar.INFO] Security realm started

My config has the following:

# General Configuration
sonar.security.realm=LDAP
sonar.authenticator.createUsers=true
sonar.authenticator.class: org.sonar.plugins.ldap.LdapAuthenticator
sonar.security.savePassword=true
sonar.security.updateUserAttributes=true
ldap.url=ldap://trprdirqr3.intra.searshc.com:389/ou=people,o=intra,dc=sears,dc=com

# User Configuration
ldap.user.baseDn=ou=people,o=intra,dc=sears,dc=com
ldap.user.request=(&(objectClass=*searsorgperson)(uid={login}))
ldap.user.realNameAttribute=cn
ldap.user.emailAttribute=mail

According to my LDAP admin, it does an anonumous check when it first comes up, but nothing is else done after that.  So for some reason it doesn't seem to be hitting the LDAP server when i login.  I don't have any local IDs setup besides admin.


问:
MSBuild project file: Copy item to specific location in output directory
In the process of cleaning up the folder/file structure on a project I inherited, I'm running into a problem with organizing the required external libraries.  I want to keep them in their own .\dll\ folder, but they're not being copied to the build directory properly.  They should be in the root build directory, but they're being moved to a subfolder instead.

My .csproj file contains the following xml:

```<code><Project>
  <ItemGroup>
    <None Include="dlls\libraryA.dll">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>
</code>```

Then, on build, the libraryA.dll file is copied to the bin\Debug\dll\ folder, but I want it in the bin\Debug\ folder.

答:
If you only want to change it for one file, it may be easier to use the  property:

```<code><None Include="dlls\libraryA.dll">
  <Link>%(Filename)%(Extension)</Link>
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</code>```

Including content files in .csproj that are outside the project cone

Body:
In the process of cleaning up the folder/file structure on a project I inherited, I'm running into a problem with organizing the required external libraries.  I want to keep them in their own .\dll\ folder, but they're not being copied to the build directory properly.  They should be in the root build directory, but they're being moved to a subfolder instead.

My .csproj file contains the following xml:

<Project>
  <ItemGroup>
    <None Include="dlls\libraryA.dll">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>

Then, on build, the libraryA.dll file is copied to the bin\Debug\dll\ folder, but I want it in the bin\Debug\ folder.

Body:
If you only want to change it for one file, it may be easier to use the  property:

<None Include="dlls\libraryA.dll">
  <Link>%(Filename)%(Extension)</Link>
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>

Including content files in .csproj that are outside the project cone


问:
Adding licensing support for Eclipse PDE
I have built an eclipse plugin which basically makes writing Java GUI applications as easy as using a 4GL programming language (Oracle Forms, Visual Basic etc). The plugin generates no GUI code but rather metadata which is parsed at runtime. I am building in a trial licence within the plugin but which will stop the plugin from working when the trial licence has run out. I am unsure of the best way to implement this. MAybe to stop one of the editors opening. I have managed to integrate my licensing software (Protection! from JProductivity), which will get called when the user tries to open on of my editors. But how can I stop an editor from opening?

Any help on this subject would be much appreciated!

答:
Editor and its type alway is contributed by extension. So there is no good way to remove this extension besides early startup your bundle. But I don't think it's a good practice.

So the better way is checking your license in EditorPart.init(IEditorSite, IEditorInput) or createPartControl, throw the exception in init call or not create any widget in createPartControl if the license is invalid or expired.


问:
Ruby on Rails - Adding arrays to column
If I have a Playlist model, how can I push arrays into a column?

```<code>#<Playlist id: 1, title: "This is a playlist", songs_ids: 1>
</code>```

And want to push arrays to the songs_ids column what do I have to do?

This is how the songs_ids column look like

```<code>add_column :playlists, :songs_ids, :integer, array: true, default: []
</code>```

I've tried updating the attributes and adding annother id of a song to it, but I have no luck with it either:

```<code>Playlist.find(1).update_attribute(songs_ids: [1, 2])
</code>```

答:
If you're using Postgresql you can simply use the update_all method to update array columns in your model.

```<code>Playlist.where(id: 1).update_all(songs_ids: [1,2])
</code>```

Note it won't work with Playlist.find(1)....

Using Mysql you can consider to serialize to do this you must use a string type column.

```<code> def change
    add_column :playlists, :songs_ids, :string
  end
</code>```

Then specify the attribute which to serialize in your model.

```<code>class Playlist < ActiveRecord::Base
    serialize :songs_ids, Array
end
</code>```

Then you can test pushing any value to it.

```<code>playlist = Playlist.first
playlist.songs_ids << 1
=> [1]
playlist.save
playlist.songs_ids << 2
=> [2]
playlist.save
playlist.songs_ids
=> [1, 2]
</code>```

Title: Ruby on Rails - Adding arrays to column

Body:
If I have a Playlist model, how can I push arrays into a column?

#<Playlist id: 1, title: "This is a playlist", songs_ids: 1>

And want to push arrays to the songs_ids column what do I have to do?

This is how the songs_ids column look like

add_column :playlists, :songs_ids, :integer, array: true, default: []

I've tried updating the attributes and adding annother id of a song to it, but I have no luck with it either:

Playlist.find(1).update_attribute(songs_ids: [1, 2])

Body:
If you're using Postgresql you can simply use the update_all method to update array columns in your model.

Playlist.where(id: 1).update_all(songs_ids: [1,2])

Note it won't work with Playlist.find(1)....

Using Mysql you can consider to serialize to do this you must use a string type column.

 def change
    add_column :playlists, :songs_ids, :string
  end

Then specify the attribute which to serialize in your model.

class Playlist < ActiveRecord::Base
    serialize :songs_ids, Array
end

Then you can test pushing any value to it.

playlist = Playlist.first
playlist.songs_ids << 1
=> [1]
playlist.save
playlist.songs_ids << 2
=> [2]
playlist.save
playlist.songs_ids
=> [1, 2]


问:
How to take data from URL
I am developing API for my company. Normally, we use POST & GET method to send form data to other website or another page. But what I want, If we want to send data in URL like
      http://www.example.com/data1/data2/data3

like that.
In that case, Data1, Data2, Data3 is our data and I want this data in PHP.
I am searching on that but I can't find what I want.

答:
Look into Apache mod_rewrite (http://httpd.apache.org/docs/current/mod/mod_rewrite.html).

You can rewrite data1/data2/data3 into ?thing1=data1&thing2=data2&thing3=data3, then use $_GET like you usually would...

Title: How to take data from URL


答:
you should use DispatchGroup

```<code>let group = DispatchGroup()
for image in extraMovieImages {
    group.enter()
    self.updateImage(ImageType: DownloadPic.personal, ImageString: image.filePath, completion: {_ in
        group.leave()
    })
}
group.notify(queue: DispatchQueue.main) {
     self.TableView.reloadData()
}
</code>```

Title: How to call a function after a loop has ended?

Body:
you should use DispatchGroup

let group = DispatchGroup()
for image in extraMovieImages {
    group.enter()
    self.updateImage(ImageType: DownloadPic.personal, ImageString: image.filePath, completion: {_ in
        group.leave()
    })
}
group.notify(queue: DispatchQueue.main) {
     self.TableView.reloadData()
}


答:
```<code><div class="btn-group bootstrap-select show-tick">
<button type="button" class="btn dropdown-toggle bs-placeholder btn-default" (click)="toggleSelect()">
    <span class="pull-left">List Items</span>
    <span class="bs-caret ">
        <span class="caret "></span>
    </span>
</button>
      <ul *ngIf="dropdownlist?.length" class="dropdown-menu multi-select-popup " [ngStyle]="{display:isOpen ? 'block' : 'none'} " style="display:block; ">
          <li *ngFor="let item of dropdownlist; let i = index ">
              <a (click)="select(item, i) " class="dropdown-item ">
                  <i class="fa fa-fw " [ngClass]="{ 'fa-check': item.checked, 'glyphicon-none': !item.checked} "></i>
                  <span [innerHtml]="item.title "></span>
              </a>
          </li>
      </ul>
  </div>
</code>```

Title: using *ngIf as a toggle to display div content in angular 2

Body:
<div class="btn-group bootstrap-select show-tick">
<button type="button" class="btn dropdown-toggle bs-placeholder btn-default" (click)="toggleSelect()">
    <span class="pull-left">List Items</span>&nbsp;
    <span class="bs-caret ">
        <span class="caret "></span>
    </span>
</button>
      <ul *ngIf="dropdownlist?.length" class="dropdown-menu multi-select-popup " [ngStyle]="{display:isOpen ? 'block' : 'none'} " style="display:block; ">
          <li *ngFor="let item of dropdownlist; let i = index ">
              <a (click)="select(item, i) " class="dropdown-item ">
                  <i class="fa fa-fw " [ngClass]="{ 'fa-check': item.checked, 'glyphicon-none': !item.checked} "></i>
                  <span [innerHtml]="item.title "></span>
              </a>
          </li>
      </ul>
  </div>


问:
How a function can be automatically called upon a variable change?
I have a class consisting of variable members and a function member. The variable member occasionally changes. I want the function to be called automatically upon the variable changes. In other words, how can I tie the variables inside a class?

```<code>class line
{
   double x, y; // The poition of the lind end. The line starts at the origin (0,0)
   double l; // The length of the line
   void length()
   {
      l = Math.sqrt(x*x+y*y);
   }
}
</code>```

In example above, I need the length to be updated when x and y change.

答:
As BenJ noted, you can use properties.

Instead of declaring x and y as simple fields inside the class. You can declare them as properties the following way :

```<code>private double x;
public double X
get
    {
        return this.x;
    }

    set
    {
        this.x = value;

        this.length()
        //Above line will call your desired method
    }
</code>```

Body:
I have a class consisting of variable members and a function member. The variable member occasionally changes. I want the function to be called automatically upon the variable changes. In other words, how can I tie the variables inside a class?

class line
{
   double x, y; // The poition of the lind end. The line starts at the origin (0,0)
   double l; // The length of the line
   void length()
   {
      l = Math.sqrt(x*x+y*y);
   }
}

In example above, I need the length to be updated when x and y change.

Body:
As BenJ noted, you can use properties.

Instead of declaring x and y as simple fields inside the class. You can declare them as properties the following way :

private double x;
public double X
get
    {
        return this.x;
    }

    set
    {
        this.x = value;

        this.length()
        //Above line will call your desired method
    }


问:
Index, match function doesn't recognize texted format cell
I have TextBox which contain number over 15 digits. When I copy the textbox value into excel cell, starting from digit 15th excel will change it zero number. This is Excel's way if cell format as number. I change the cell format from number to text, and input manually the number, and its work.

But when I use Index, Match function on macros, it doesn't work and I get

Run-time error 1004 "Unable to get match property of the
  WorksheetFunction class

This is the code I use for index, match function

```<code>Dim b As Double

b = TxtCvNo.Text

With Application.WorksheetFunction
    If .CountIf(Sheet2.Range("G:G"), b) = 1 Then
        TxtCVId.Text = .Index(Sheet2.Range("A:A"), .Match((b), Sheet2.Range("G:G"), 0))
    Else
</code>```

b is the TextBox value.

Match function doesn't recognize b as this value were input as 'text' in Excel cell

How can I copy the textbox value into cell as text to avoid digit 15th, 16th and so on change to zero. How can I fix the index, match function after it.

this screen shot of my Data. I use Index and Match to identify whether the coupon 1,2,3 has been use as coupon ref, and then tell me the ID Respondent use that Coupon.
screen shot data

答:
Try the code below (explanation inside the code comments):</p>

```<code>Option Explicit

Sub IndexMatchConv()

Dim b As String
Dim Res As Variant

' for my test format and set a value with 21 digits as Text in cell "G2"
Sheet2.Range("G2").NumberFormat = "@" ' format as Text
Sheet2.Range("G2").Value = "123456789112233445566"
b = Sheet2.Range("G2").Value
MsgBox Len(b) ' <-- result 21

With Application.WorksheetFunction
    Res = .CountIf(Sheet2.Range("G:G"), b)
    If .CountIf(Sheet2.Range("G:G"), b) = 1 Then
        Res = .Match((b), Sheet2.Range("G:G"), 0) < --Res = 2
        'TxtCVId.Text = .Index(Sheet2.Range("A:A"), .Match((b), Sheet2.Range("G:G"), 0))
    Else
        ' do something
    End If
End With

End Sub
</code>```

Body:
I have TextBox which contain number over 15 digits. When I copy the textbox value into excel cell, starting from digit 15th excel will change it zero number. This is Excel's way if cell format as number. I change the cell format from number to text, and input manually the number, and its work.

But when I use Index, Match function on macros, it doesn't work and I get

Run-time error 1004 "Unable to get match property of the
  WorksheetFunction class

This is the code I use for index, match function

Dim b As Double

b = TxtCvNo.Text

With Application.WorksheetFunction
    If .CountIf(Sheet2.Range("G:G"), b) = 1 Then
        TxtCVId.Text = .Index(Sheet2.Range("A:A"), .Match((b), Sheet2.Range("G:G"), 0))
    Else

b is the TextBox value.

Match function doesn't recognize b as this value were input as 'text' in Excel cell

How can I copy the textbox value into cell as text to avoid digit 15th, 16th and so on change to zero. How can I fix the index, match function after it.

this screen shot of my Data. I use Index and Match to identify whether the coupon 1,2,3 has been use as coupon ref, and then tell me the ID Respondent use that Coupon.
screen shot data

Body:
Try the code below (explanation inside the code comments):

Option Explicit

Sub IndexMatchConv()

Dim b As String
Dim Res As Variant

' for my test format and set a value with 21 digits as Text in cell "G2"
Sheet2.Range("G2").NumberFormat = "@" ' format as Text
Sheet2.Range("G2").Value = "123456789112233445566"
b = Sheet2.Range("G2").Value
MsgBox Len(b) ' <-- result 21

With Application.WorksheetFunction
    Res = .CountIf(Sheet2.Range("G:G"), b)
    If .CountIf(Sheet2.Range("G:G"), b) = 1 Then
        Res = .Match((b), Sheet2.Range("G:G"), 0) < --Res = 2
        'TxtCVId.Text = .Index(Sheet2.Range("A:A"), .Match((b), Sheet2.Range("G:G"), 0))
    Else
        ' do something
    End If
End With

End Sub


答:
You can achieve pretty similar behavior using calculated property like

```<code>double Length
{
    get { return Math.sqrt(x*x+y*y); }
}
</code>```

The only caveat is that calculation is performed upon each call to Length even if x and y haven't changed.

You can encapsulate you x and y fields into properties and call length function from setter like

```<code>double X
{
    get { return x; }
    set
    {
        x = value;
        length();
    }
}

double Y
{
    get { return y; }
    set
    {
        y = value;
        length();
    }
}
</code>```

and then change x and y ONLY via X and Y properties.

Title: How a function can be automatically called upon a variable change?

Body:
You can achieve pretty similar behavior using calculated property like

double Length
{
    get { return Math.sqrt(x*x+y*y); }
}

The only caveat is that calculation is performed upon each call to Length even if x and y haven't changed.

You can encapsulate you x and y fields into properties and call length function from setter like

double X
{
    get { return x; }
    set
    {
        x = value;
        length();
    }
}

double Y
{
    get { return y; }
    set
    {
        y = value;
        length();
    }
}

and then change x and y ONLY via X and Y properties.