问:
How to skip tests when using Maven reactor?
I am working on a Maven multi-modules project. I want to build a given module and skip the unit tests to speed the build process up.

I've tried the following:

mvn reactor:make -Dmake.folders=search -Dgoals=package,-DskipTests

mvn reactor:make -Dmake.folders=search -Dgoals=package -Dmaven.test.skip=True

However, this does not have an effect at all. Any clues?

答:
Given the project structure

```<code>/
  A/pom.xml
  B/pom.xml
  C/pom.xml
  D/pom.xml
  E/pom.xml
  pom.xml (parent pom file that includes A,B,C,D,E modules)
</code>```

Similar to your

```<code>mvn reactor:make -Dmake.folders=C,D,E -Dgoals=package -Dmaven.test.skip=True
</code>```

Although I'm not sure if my approach does EXACTLY what the reactor plugin does, but I found the following approach worked well enough for me

```<code>mvn -pl=C,D,E -DskipTests=true package
</code>```

Body:
Given the project structure

/
  A/pom.xml
  B/pom.xml
  C/pom.xml
  D/pom.xml
  E/pom.xml
  pom.xml (parent pom file that includes A,B,C,D,E modules)

Similar to your

mvn reactor:make -Dmake.folders=C,D,E -Dgoals=package -Dmaven.test.skip=True

Although I'm not sure if my approach does EXACTLY what the reactor plugin does, but I found the following approach worked well enough for me

mvn -pl=C,D,E -DskipTests=true package


来源: stackexchange

问:
Mongo Service running but command line functionalities are not working
I am new to mongo. I am following pluralsight's course to mongo's introduction.

I have installed mongo as a service using command

```<code>C:\Windows\system32>"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --config "C:/mongod.conf" --install
</code>```

Config file consists of  :

```<code>dbpath= C:/pluralsight/db

logpath=C:/pluralsight/mongo-server.log

verbose=vvvvv
</code>```

Then I started the service using

```<code>net start mongodb
</code>```

Inspit eof the service running on my machine, i am not able to run the mongo shell on my system. The course on pluralsight shows the tutor running the shell after the installation, but i am not able to do it. Any reasons why?

答:
Form the screenshot it looks like mongo is not in your path.
try executing "C:\Program Files\MongoDB\Server\3.4\bin\mongo.exe"</p>

ContentLicense: CC BY-SA 3.0

Body:
I am new to mongo. I am following pluralsight's course to mongo's introduction.

I have installed mongo as a service using command

C:\Windows\system32>"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --config "C:/mongod.conf" --install

Config file consists of  :

dbpath= C:/pluralsight/db

logpath=C:/pluralsight/mongo-server.log

verbose=vvvvv

Then I started the service using

net start mongodb

Inspit eof the service running on my machine, i am not able to run the mongo shell on my system. The course on pluralsight shows the tutor running the shell after the installation, but i am not able to do it. Any reasons why?


问:
Set selected option if ngModel exists
I have a select field as follows:

```<code><select class="form-control" [(ngModel)]="myClient.address && myClient.address.state" name="state" (ngModelChange)="getCitiesByState($event)">
   <option class="form-control" *ngFor="let state of states"
      [ngValue]="state">
       {{state.name}}</option>
</select>
</code>```

However, as I'm reusing the same component, I would like my option to be set to a value if my ngModel has a value. For example, if myClient.address has myClient.address = {"name":"Texas", "stateId":"2"}, I want Texas to be the selected option.

How do I achieve this?

答:
```<code><select class="form-control" [ngModel]="myClient.address?.name" name="state" (ngModelChange)="getCitiesByState($event)">
   <option class="form-control" *ngFor="let state of states"
      [ngValue]="state">
       {{state.name}}</option>
</select>
</code>```

Now if myClient.address has myClient.address = {"name":"Texas", "stateId":"2"}, I want Texas to be the selected option.

All the changes you need is [ngModel]="myClient.address?.name" add ? , that defines optional behaviour , so if its provided then it will get selected and if not then it will work as there is nothing selected.

But here you have to provide atleast myClient.address with value or without value.

Title: Set selected option if ngModel exists

Body:
I have a select field as follows:

<select class="form-control" [(ngModel)]="myClient.address && myClient.address.state" name="state" (ngModelChange)="getCitiesByState($event)">
   <option class="form-control" *ngFor="let state of states"
      [ngValue]="state">
       {{state.name}}</option>
</select>

However, as I'm reusing the same component, I would like my option to be set to a value if my ngModel has a value. For example, if myClient.address has myClient.address = {"name":"Texas", "stateId":"2"}, I want Texas to be the selected option.

How do I achieve this?

Body:
<select class="form-control" [ngModel]="myClient.address?.name" name="state" (ngModelChange)="getCitiesByState($event)">
   <option class="form-control" *ngFor="let state of states"
      [ngValue]="state">
       {{state.name}}</option>
</select>

Now if myClient.address has myClient.address = {"name":"Texas", "stateId":"2"}, I want Texas to be the selected option.

All the changes you need is [ngModel]="myClient.address?.name" add ? , that defines optional behaviour , so if its provided then it will get selected and if not then it will work as there is nothing selected.

But here you have to provide atleast myClient.address with value or without value.


问:
JQuery game - Make player stay inside a div
I need help making my player stay inside of the my div. My player is a div that can move and it is placed inside of an "arena" div that has an border! Can somone help me make so that the player can't move outside of the div!

Here is a JSfiddle of my project!
Here is my code!

```<code>$(document).ready(function(){

    $("#bana").append("<div id='spelare1'></div>"); //Sätter in spelaren
    $("#bana").append("<div id='obj_poäng'></div>"); //Sätter in poäng obj

    $("#tid").text("Tid: " + tid); //Sätter tid texten
    $("#poäng").text("Poäng: " + poäng) //Sätter poäng texten

    sättSpelareHöjd(); //Kallar på sättSpelareHöjd funktionen vid start
});

var knappTryckt = true;
var tid = 60; //Tiden i spelet
var poäng = 0; //Start poäng

function sättSpelareHöjd() {
    var spelareHöjd = $("#spelare1").width();
    $("#spelare1").css("height", spelareHöjd);
} //Sätter spelarens höjd så att den hela tiden är en kub

//Spelare 1 rörelse
$(document).keydown(function(e){
if(knappTryckt) {
    if(e.keyCode == 37) {
        $("#spelare1").stop().animate({left: "-=" + 100 + "%"},5000);
        //Pil vänster
    }

    else if (e.keyCode == 38) {
        $("#spelare1").stop().animate({top: "-=" + 100 + "vh"},5000);
        //Pil upp
    }

    else if (e.keyCode == 39) {
        $("#spelare1").stop().animate({left: "+=" + 100 + "%"},5000);
        //Pil höger
    }

    else if (e.keyCode == 40) {
        $("#spelare1").stop().animate({top: "+=" + 100 + "vh"},5000);
        //Pil ner
    }

    knappTryckt = false;
}
});
$(document).keyup(function(){
    $("#spelare1").stop();
    knappTryckt = true;
});
</code>```

答:
Use the progress property of animate to get the current postion of the item and position() to get the item position left & top:

```<code>$(document).ready(function() {

  $("#bana").append("<div id='spelare1'></div>"); //Sätter in spelaren
  $("#bana").append("<div id='obj_poäng'></div>"); //Sätter in poäng obj

  $("#tid").text("Tid: " + tid); //Sätter tid texten
  $("#poäng").text("Poäng: " + poäng) //Sätter poäng texten

  sättSpelareHöjd(); //Kallar på sättSpelareHöjd funktionen vid start
  sättPoängHöjd(); //Kallar på sättPoängHöjd funktion vid start
  poängPosition(); //Kallar på poängPosition vid start
});

var knappTryckt = true;
var tid = 60; //Tiden i spelet
var poäng = 0; //Start poäng

function sättSpelareHöjd() {
  var spelareHöjd = $("#spelare1").width();
  $("#spelare1").css("height", spelareHöjd);
} //Sätter spelarens höjd så att den hela tiden är en kub

//Spelare 1 rörelse
$(document).keydown(function(e) {
  if (knappTryckt) {
    if (e.keyCode == 37) {
      $("#spelare1").stop().animate({
        left: "-=" + 100 + "%"
      }, {
        duration: 5000,
        progress: function() {
          var pos = $(this).position();
          if (pos.left < 0) {
            $(this).stop();
          }
        }
      });
      //Pil vänster
    } else if (e.keyCode == 38) {
      $("#spelare1").stop().animate({
        top: "-=" + 100 + "vh"
      },{
        duration: 5000,
        progress: function() {
          var pos = $(this).position();
          if (pos.top < 0) {
            $(this).stop();
          }
        }
      });
      //Pil upp
    } else if (e.keyCode == 39) {
      $("#spelare1").stop().animate({
        left: "+=" + 100 + "%"
      },{
        duration: 5000,
        progress: function() {
          var pos = $(this).position();
          if (pos.left > $('#bana').width()-$("#spelare1").width()) {
            $(this).stop();
          }
        }
      });
      //Pil höger
    } else if (e.keyCode == 40) {
      $("#spelare1").stop().animate({
        top: "+=" + 100 + "vh"
      },{
        duration: 5000,
        progress: function() {
          var pos = $(this).position();
          if (pos.top > $('#bana').height()-$("#spelare1").height()) {
            $(this).stop();
          }
        }
      });
      //Pil ner
    }

    knappTryckt = false;
  }
});
$(document).keyup(function() {
  $("#spelare1").stop();
  knappTryckt = true;
});
</code>```

demo:https://jsfiddle.net/z61wxo9x/2/

Body:
I need help making my player stay inside of the my div. My player is a div that can move and it is placed inside of an "arena" div that has an border! Can somone help me make so that the player can't move outside of the div!

Here is a JSfiddle of my project!
Here is my code!

$(document).ready(function(){

    $("#bana").append("

"); //Sätter in spelaren
    $("#bana").append("

"); //Sätter in poäng obj

    $("#tid").text("Tid: " + tid); //Sätter tid texten
    $("#poäng").text("Poäng: " + poäng) //Sätter poäng texten

    sättSpelareHöjd(); //Kallar på sättSpelareHöjd funktionen vid start
});

var knappTryckt = true;
var tid = 60; //Tiden i spelet
var poäng = 0; //Start poäng

function sättSpelareHöjd() {
    var spelareHöjd = $("#spelare1").width();
    $("#spelare1").css("height", spelareHöjd);
} //Sätter spelarens höjd så att den hela tiden är en kub

//Spelare 1 rörelse
$(document).keydown(function(e){
if(knappTryckt) {
    if(e.keyCode == 37) {
        $("#spelare1").stop().animate({left: "-=" + 100 + "%"},5000);
        //Pil vänster
    }

    else if (e.keyCode == 38) {
        $("#spelare1").stop().animate({top: "-=" + 100 + "vh"},5000);
        //Pil upp
    }

    else if (e.keyCode == 39) {
        $("#spelare1").stop().animate({left: "+=" + 100 + "%"},5000);
        //Pil höger
    }

    else if (e.keyCode == 40) {
        $("#spelare1").stop().animate({top: "+=" + 100 + "vh"},5000);
        //Pil ner
    }

    knappTryckt = false;
}
});
$(document).keyup(function(){
    $("#spelare1").stop();
    knappTryckt = true;
});

Body:
Use the progress property of animate to get the current postion of the item and position() to get the item position left & top:

$(document).ready(function() {

  $("#bana").append("<div id='spelare1'></div>"); //Sätter in spelaren
  $("#bana").append("<div id='obj_poäng'></div>"); //Sätter in poäng obj

  $("#tid").text("Tid: " + tid); //Sätter tid texten
  $("#poäng").text("Poäng: " + poäng) //Sätter poäng texten

  sättSpelareHöjd(); //Kallar på sättSpelareHöjd funktionen vid start
  sättPoängHöjd(); //Kallar på sättPoängHöjd funktion vid start
  poängPosition(); //Kallar på poängPosition vid start
});

var knappTryckt = true;
var tid = 60; //Tiden i spelet
var poäng = 0; //Start poäng

function sättSpelareHöjd() {
  var spelareHöjd = $("#spelare1").width();
  $("#spelare1").css("height", spelareHöjd);
} //Sätter spelarens höjd så att den hela tiden är en kub

//Spelare 1 rörelse
$(document).keydown(function(e) {
  if (knappTryckt) {
    if (e.keyCode == 37) {
      $("#spelare1").stop().animate({
        left: "-=" + 100 + "%"
      }, {
        duration: 5000,
        progress: function() {
          var pos = $(this).position();
          if (pos.left < 0) {
            $(this).stop();
          }
        }
      });
      //Pil vänster
    } else if (e.keyCode == 38) {
      $("#spelare1").stop().animate({
        top: "-=" + 100 + "vh"
      },{
        duration: 5000,
        progress: function() {
          var pos = $(this).position();
          if (pos.top < 0) {
            $(this).stop();
          }
        }
      });
      //Pil upp
    } else if (e.keyCode == 39) {
      $("#spelare1").stop().animate({
        left: "+=" + 100 + "%"
      },{
        duration: 5000,
        progress: function() {
          var pos = $(this).position();
          if (pos.left > $('#bana').width()-$("#spelare1").width()) {
            $(this).stop();
          }
        }
      });
      //Pil höger
    } else if (e.keyCode == 40) {
      $("#spelare1").stop().animate({
        top: "+=" + 100 + "vh"
      },{
        duration: 5000,
        progress: function() {
          var pos = $(this).position();
          if (pos.top > $('#bana').height()-$("#spelare1").height()) {
            $(this).stop();
          }
        }
      });
      //Pil ner
    }

    knappTryckt = false;
  }
});
$(document).keyup(function() {
  $("#spelare1").stop();
  knappTryckt = true;
});

demo:https://jsfiddle.net/z61wxo9x/2/


问:
Don't want to delete object when shared_ptr get out of scope --Closed
I have a situation that I have some code like this. We need to add child objects to a clean up list, which will delete these children later when the class get destroyed. But we wish to use set for internal safety reasons, and obviously the set has longer lifetime.

```<code>//This is will delete twice, if this is called later.
~classX(){
    cleanList.clear();
}

classX::addToCleanList(T* child){
    set<shared_ptr<T> > cleanList;

    shared_ptr<T> p = shared_ptr(child);

    //Set has a customized comparetor
    //If the set already has the object pointer, insert will fail
    //and the shared_ptr will get out of the scope
    cleanList.insert(p);
}
//When it gets out of scope, p will be destroyed.
</code>```

This will cause issue, since the child objects are still needed.

Any solution to this? I don't see unique_ptr or shared_ptr and move semantic
can avoid being deleted when they get out of the scope.

答:
This code has a number of issues that make it really hard to understand what is the actual problem:

cleanList has the scope of addToCleanList function. Judging by the names and by the fact that cleanList does literally nothing this way, I'd say the intention was to make it the classX member.

the set.insert(p) statement - how does it even compile? Don't you mean cleanList.insert(p)?

The whole idea of using std::set here is a bit weird. Seems like you're trying to reinvent the shared_ptr functionality on a grander scale, but then you're still using shared_ptr after that.

Using a vector of shared_ptr would be just as fine, and no need for custom comparators.

All of those kinda indicate possible major design problems here, so further help is somewhat hindered by that; e.g. I have a strong suspiction you won't need shared_ptr at all after you carefully plan the lifetime of your objects.

Body:
I have a situation that I have some code like this. We need to add child objects to a clean up list, which will delete these children later when the class get destroyed. But we wish to use set for internal safety reasons, and obviously the set has longer lifetime.

//This is will delete twice, if this is called later.
~classX(){
    cleanList.clear();
}

classX::addToCleanList(T* child){
    set<shared_ptr<T> > cleanList;

    shared_ptr<T> p = shared_ptr(child);

    //Set has a customized comparetor
    //If the set already has the object pointer, insert will fail
    //and the shared_ptr will get out of the scope
    cleanList.insert(p);
}
//When it gets out of scope, p will be destroyed.

This will cause issue, since the child objects are still needed.

Any solution to this? I don't see unique_ptr or shared_ptr and move semantic
can avoid being deleted when they get out of the scope.


问:
Making a new object, cannot be applied to type (int)
I have a ProcessHeap class that has two fields:

Heap: an array of type Process which represents the heap

Size: the number of elements in the heap

My constructor and attributes look like this:

```<code>private Process[] heap;
private int size;
private static int counter = 0;

//Paramaterized construct
    public ProcessHeap(Process[] heap, int size) {
        this.heap = heap;
        this.size = size;
</code>```

The problem is, we were given a driver and at the start of the driver I am getting an error particularly on (HEAP_SIZE)

This is the line:

```<code>final int HEAP_SIZE = 100;
ProcessHeap heap = new ProcessHeap(HEAP_SIZE); // gives this error:
</code>```

The error upon mouse-over states:

ProcessHeap (Process[], int) in ProcessHeap cannot be applied to (int)

答:
As others have said; your direct problem is that you want only have one constructor taking two arguments, but then you are invoking it with one argument. But beyond that, you are over-complicating things:

```<code>class ProcessHeap {
  private final Process[] heap;

 public ProcessHeap(int size) {
   heap = new Process[size];
 }
</code>```

is all that you need and should use. There is no point in tracking size and array in two places. You can always do heap.length to get the size of your heap. And beyond that: you absolutely do not want that users of this class have to provide an array for your heap - because they could just go and manipulate that array later on.

Your class implements that heap; and that you are using an array to do that is an implementation detail that you should not at all communicate to the outside world.

Body:
I have a ProcessHeap class that has two fields:

Heap: an array of type Process which represents the heap

Size: the number of elements in the heap

My constructor and attributes look like this:

private Process[] heap;
private int size;
private static int counter = 0;

//Paramaterized construct
    public ProcessHeap(Process[] heap, int size) {
        this.heap = heap;
        this.size = size;

The problem is, we were given a driver and at the start of the driver I am getting an error particularly on (HEAP_SIZE)

This is the line:

final int HEAP_SIZE = 100;
ProcessHeap heap = new ProcessHeap(HEAP_SIZE); // gives this error:

The error upon mouse-over states:

ProcessHeap (Process[], int) in ProcessHeap cannot be applied to (int)

Body:
As others have said; your direct problem is that you want only have one constructor taking two arguments, but then you are invoking it with one argument. But beyond that, you are over-complicating things:

class ProcessHeap {
  private final Process[] heap;

 public ProcessHeap(int size) {
   heap = new Process[size];
 }

is all that you need and should use. There is no point in tracking size and array in two places. You can always do heap.length to get the size of your heap. And beyond that: you absolutely do not want that users of this class have to provide an array for your heap - because they could just go and manipulate that array later on.

Your class implements that heap; and that you are using an array to do that is an implementation detail that you should not at all communicate to the outside world.


问:
Regex for complex password validation
I looked around on stackoverflow, etc, but haven't found a good answer for this..Does regex support writing a rule like this? If so is there any regex experts our there who can help me write this, I am a big newb to regex and in a time crunch...

I know I can do this with a manual function in c# using c# char, number methods, but I would like to use regex if I can for this..

Requirement :

At least 8 characters long

2 letters

2 digits

1 Upper case

1 Lower case

1 Symbol

答:
You may try this method.</p>

```<code> private bool ValidatePassword(string password, out string ErrorMessage)
{
    var input = password;
    ErrorMessage = string.Empty;

    if (string.IsNullOrWhiteSpace(input))
    {
        throw new Exception("Password should not be empty");
    }

    var hasNumber = new Regex(@"[0-9]+");
    var hasUpperChar = new Regex(@"[A-Z]+");
    var hasMiniMaxChars = new Regex(@".{8,8}");
    var hasLowerChar = new Regex(@"[a-z]+");
    var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]");

    if (!hasLowerChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one lower case letter";
        return false;
    }
    else if (!hasUpperChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one upper case letter";
        return false;
    }
    else if (!hasMiniMaxChars.IsMatch(input))
    {
        ErrorMessage = "Password should not be less than or greater than 8 characters";
        return false;
    }
    else if (!hasNumber.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one numeric value";
        return false;
    }

    else if (!hasSymbols.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one special case characters";
        return false;
    }
    else
    {
        return true;
    }
}
</code>```

Title: Regex for complex password validation

Body:
You may try this method.

 private bool ValidatePassword(string password, out string ErrorMessage)
{
    var input = password;
    ErrorMessage = string.Empty;

    if (string.IsNullOrWhiteSpace(input))
    {
        throw new Exception("Password should not be empty");
    }

    var hasNumber = new Regex(@"[0-9]+");
    var hasUpperChar = new Regex(@"[A-Z]+");
    var hasMiniMaxChars = new Regex(@".{8,8}");
    var hasLowerChar = new Regex(@"[a-z]+");
    var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]");

    if (!hasLowerChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one lower case letter";
        return false;
    }
    else if (!hasUpperChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one upper case letter";
        return false;
    }
    else if (!hasMiniMaxChars.IsMatch(input))
    {
        ErrorMessage = "Password should not be less than or greater than 8 characters";
        return false;
    }
    else if (!hasNumber.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one numeric value";
        return false;
    }

    else if (!hasSymbols.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one special case characters";
        return false;
    }
    else
    {
        return true;
    }
}


问:
How to extract the host name from a git repo URI?
Given a git repository URI Like

```<code>git@company-name.com:/company-name/repo.git
</code>```

or

```<code>https://company-name.com/company-name/repo.git
</code>```

How can I extract company-name.com from them? I am trying to fetch the hostname so I can pass them to a cookbook called ssk_known_hosts.

答:
Use the proper tools for this. URI parsing is a solved problem.</p>

```<code>require 'uri'

s = 'https://company-name.com/company-name/repo.git'
uri = URI(s)
uri.host # => "company-name.com"
</code>```

Body:
Given a git repository URI Like

git@company-name.com:/company-name/repo.git

or

https://company-name.com/company-name/repo.git

How can I extract company-name.com from them? I am trying to fetch the hostname so I can pass them to a cookbook called ssk_known_hosts.

Body:
Use the proper tools for this. URI parsing is a solved problem.

require 'uri'

s = 'https://company-name.com/company-name/repo.git'
uri = URI(s)
uri.host # => "company-name.com"


问:
Adding selenium webdriver as a python project dependence
Is there a way to install selenium webdriver as a python project dependence.

I need this in such a way, so when this project goes to a os, that doesn't have selenium webdriver installed not to be an issue for this project to run properly on that os.

Thank you in advance.

PS: Please take a look at my own answer to this question.

Stefan

答:
I solved my problem this way:

Installing pip for the current OS I am working on

Installing selenium with the following command:

```<code>pip install --install-option="--prefix=<path_to_dependencies_in_my_python_project>" -U selenium
</code>```

Import selenium module from this dependencies project folder

Also another approach is to check if the new OS has selenium installed and if not - install it via python script. The code looks something like that:

```<code> # windows
 try:
     from selenium import webdriver
 except ModuleNotFoundError:
     os.system("pip install --install-option=\"--prefix={}\" selenium"
               .format(os.path.join(project_main_folder_path, "_depedencies")))
     from selenium import webdriver
</code>```

```<code># Linux
try:
    from selenium import webdriver
except:
    os.system("pip install selenium -t {}"
              .format(os.path.join(project_main_folder_path, "_depedencies", "Lib", "site-packages")))
    from selenium import webdriver
</code>```

Take a look at the difference of the pathing - on Linux it is installed directly in the folder, while on windows it is installed in sub-folder "Lib\site-packages". Also I don't know why, but I had problems with name 'ModuleNotFoundError' is not defined.

Body:
I solved my problem this way:

Installing pip for the current OS I am working on

Installing selenium with the following command:

pip install --install-option="--prefix=<path_to_dependencies_in_my_python_project>" -U selenium

Import selenium module from this dependencies project folder

Also another approach is to check if the new OS has selenium installed and if not - install it via python script. The code looks something like that:

 # windows
 try:
     from selenium import webdriver
 except ModuleNotFoundError:
     os.system("pip install --install-option=\"--prefix={}\" selenium"
               .format(os.path.join(project_main_folder_path, "_depedencies")))
     from selenium import webdriver

# Linux
try:
    from selenium import webdriver
except:
    os.system("pip install selenium -t {}"
              .format(os.path.join(project_main_folder_path, "_depedencies", "Lib", "site-packages")))
    from selenium import webdriver

Take a look at the difference of the pathing - on Linux it is installed directly in the folder, while on windows it is installed in sub-folder "Lib\site-packages". Also I don't know why, but I had problems with name 'ModuleNotFoundError' is not defined.


问:
Imagebutton.setImageURI(uri) doesn't work
now my problem is that:
This is a workaround for Onclcick an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.

```<code>private ImageButton mImageSelect;
private static  final int GALLERY_REQUEST =1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mImageSelect=(ImageButton) findViewById(R.id.imageselect);
    mImageSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent= new Intent(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, GALLERY_REQUEST);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   // super.onActivityResult(requestCode, resultCode, data);

    if(requestCode== GALLERY_REQUEST && resultCode==RESULT_OK){
        Uri selectedImageUri=data.getData();
        if (null != selectedImageUri) {

            mImageSelect.setImageURI(selectedImageUri);
            Toast.makeText(PostActivity.this, "Image Selected", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(PostActivity.this,"Image Not Selected",Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

答:
Imagebutton.setImageURI(uri) doesn't work

You can use Glide to load images more easily

Add this to your build.gradle

```<code>  compile 'com.github.bumptech.glide:glide.3.7.0'
</code>```

Load image uri using glide as follows

```<code> Glide.with(MainActivity.this).load(uri).into(imageView);
</code>```

Body:
now my problem is that:
This is a workaround for Onclcick an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.

private ImageButton mImageSelect;
private static  final int GALLERY_REQUEST =1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mImageSelect=(ImageButton) findViewById(R.id.imageselect);
    mImageSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent= new Intent(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, GALLERY_REQUEST);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   // super.onActivityResult(requestCode, resultCode, data);

    if(requestCode== GALLERY_REQUEST && resultCode==RESULT_OK){
        Uri selectedImageUri=data.getData();
        if (null != selectedImageUri) {

            mImageSelect.setImageURI(selectedImageUri);
            Toast.makeText(PostActivity.this, "Image Selected", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(PostActivity.this,"Image Not Selected",Toast.LENGTH_SHORT).show();
        }
    }
}

Body:
Imagebutton.setImageURI(uri) doesn't work

You can use Glide to load images more easily

Add this to your build.gradle

  compile 'com.github.bumptech.glide:glide.3.7.0'

Load image uri using glide as follows

 Glide.with(MainActivity.this).load(uri).into(imageView);


问:
Windows 10 remote desktop RDP mstsc.exe won't start
I have recently upgraded from win 8.1 to Win 10. Since the upgrade RDP wouldn't work correctly.

I couldn't use a recently used connection. Instead I had to open a new window each time. Today it stopped working completely.

If I tried to run mstsc.exe directly it would appear in task manager for less than a second before dissapearing.

Edit: Issue was traced to "custom scale factors" in display settings. See answer below.

答:
Issue was traced to "custom scale factors" in display settings.

This fix on technet worked for me. I am reposting here for others. (since most links in my search results were way off the mark)

Hit the Windows key and then type "display".

Tap on the "display settings" link that is found.

You should see the following text in red: "A custom scale factor is set"

Click on the text underneath which states "Turn off custom scaling and sign out".

Sign back in.

I would add that if you have it pinned to the task bar it would be worth unpinning and re-pinning it also.


问:
How can I avoid TimeOut exception using Entity Framework with a stored procedure?
I'm using Entity Framework to call a stored procedure which takes 2 minutes to execute. As a result, I get a timeout exception.

Is there any way I can use my stored procedure without getting a timeout exception?

答:
You can control Timeout value using connection string also.

```<code><connectionStrings>

<add name="AdventureWorksEntities"
connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;provider connection string='Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient" />

</connectionStrings>
</code>```

Also you can set it for your DBContext.

```<code>public class MyDatabase : DbContext
{
    public MyDatabase ()
        : base(ContextHelper.CreateConnection("Connection string"), true)
    {
        ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
    }
}
</code>```

Body:
You can control Timeout value using connection string also.

<connectionStrings>

<add name="AdventureWorksEntities"
connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;provider connection string='Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient" />

</connectionStrings>

Also you can set it for your DBContext.

public class MyDatabase : DbContext
{
    public MyDatabase ()
        : base(ContextHelper.CreateConnection("Connection string"), true)
    {
        ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
    }
}


问:
GridView Header Click
I am trying to figure out how to point a Grid View Header Click to my Viewmodel

```<code> <ListView ItemsSource="{Binding UserProfileData}" GridViewColumnHeader.Click="Handle_Click">
       <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="User ID"/>
                    <GridViewColumn DisplayMemberBinding="{Binding LastUsed}" Header="Last Loaded"/>
                    <GridViewColumn DisplayMemberBinding="{Binding IsLoaded}" Header="Logged In"/>
                </GridView>
            </ListView.View>
        </ListView>
</code>```

GridViewColumnHeader.Click="Handle_Click" will push it to my MainWindow.xaml.cs but i want to have the click go to the DataContext of my MainWindow

```<code><Window.DataContext>
    <vm:MainWindowViewModel/>
</Window.DataContext>
</code>```

any ideas?

答:
You need to add reference of 2 assemblies:

```<code>System.Windows.Interactivity
Microsoft.Expression.Interactions
</code>```

Add following namespaces:

```<code>xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
</code>```

Xaml:

```<code><ListView ItemsSource="{Binding UserProfileData}">
        <ListView.View>
            <GridView>
                <GridViewColumn DisplayMemberBinding="{Binding Name}">
                    <GridViewColumnHeader Content="User ID">
                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="Click">
                                <ei:CallMethodAction TargetObject="{Binding}" MethodName="OnClick"/>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>
                    </GridViewColumnHeader>
                </GridViewColumn>

                <GridViewColumn DisplayMemberBinding="{Binding LastUsed}">
                    <GridViewColumnHeader Content="Last Loaded">
                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="Click">
                                <ei:CallMethodAction TargetObject="{Binding}" MethodName="OnClick"/>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>
                    </GridViewColumnHeader>
                </GridViewColumn>

                <GridViewColumn DisplayMemberBinding="{Binding IsLoaded}">
                    <GridViewColumnHeader Content="Logged In">
                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="Click">
                                <ei:CallMethodAction TargetObject="{Binding}" MethodName="OnClick"/>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>
                    </GridViewColumnHeader>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</code>```

In view model, put following method:

```<code>public void OnClick(object sender, RoutedEventArgs e)
    {

    }
</code>```

Title: GridView Header Click

Body:
I am trying to figure out how to point a Grid View Header Click to my Viewmodel

 <ListView ItemsSource="{Binding UserProfileData}" GridViewColumnHeader.Click="Handle_Click">
       <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="User ID"/>
                    <GridViewColumn DisplayMemberBinding="{Binding LastUsed}" Header="Last Loaded"/>
                    <GridViewColumn DisplayMemberBinding="{Binding IsLoaded}" Header="Logged In"/>
                </GridView>
            </ListView.View>
        </ListView>

GridViewColumnHeader.Click="Handle_Click" will push it to my MainWindow.xaml.cs but i want to have the click go to the DataContext of my MainWindow

<Window.DataContext>
    <vm:MainWindowViewModel/>
</Window.DataContext>

any ideas?

Body:
You need to add reference of 2 assemblies:

System.Windows.Interactivity
Microsoft.Expression.Interactions

Add following namespaces:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

Xaml:

<ListView ItemsSource="{Binding UserProfileData}">
        <ListView.View>
            <GridView>
                <GridViewColumn DisplayMemberBinding="{Binding Name}">
                    <GridViewColumnHeader Content="User ID">
                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="Click">
                                <ei:CallMethodAction TargetObject="{Binding}" MethodName="OnClick"/>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>
                    </GridViewColumnHeader>
                </GridViewColumn>

                <GridViewColumn DisplayMemberBinding="{Binding LastUsed}">
                    <GridViewColumnHeader Content="Last Loaded">
                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="Click">
                                <ei:CallMethodAction TargetObject="{Binding}" MethodName="OnClick"/>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>
                    </GridViewColumnHeader>
                </GridViewColumn>

                <GridViewColumn DisplayMemberBinding="{Binding IsLoaded}">
                    <GridViewColumnHeader Content="Logged In">
                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="Click">
                                <ei:CallMethodAction TargetObject="{Binding}" MethodName="OnClick"/>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>
                    </GridViewColumnHeader>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

In view model, put following method:

public void OnClick(object sender, RoutedEventArgs e)
    {

    }


问:
how can i refresh a page on particular time in php?
```<code><?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '<br>';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>
<html>
    <head>
    <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
    </head>
    <body>
    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>
    </body>
</html>
</code>```

<p>// in this code insted of second i wont to pass time like 12.00 then the code execute in above code after 10 second page refresh and generate number on every 10 sec and i also wont to generate 1 random number on particular time   </p>

答:
You can you use this little Javascript snippet to refresh the page.

window.onload = function() {
 setInterval(function() {
  location.reload(true);
 },21 * 1000); //21 is after how much seconds you wanna reload!
};```

Body:
<?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '
';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>

    <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">

    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>

// in this code insted of second i wont to pass time like 12.00 then the code execute in above code after 10 second page refresh and generate number on every 10 sec and i also wont to generate 1 random number on particular time


问:
Can someone tell me how to run a batch file from Notepad++
I thought I could run a batch file from Notepad++ directly using nppexec by (or the built in run command) by typing CMD $(FULL_CURRENT_PATH)

But since notepad++ HAS a CMD command (which open the cmd shell in the npp console) then it is not working.  So running the above command opens cmd shell in the npp console but does not run the batch file.  At that point I can run $(FULL_CURRENT_PATH) AND it will run the batch file.  But then I have to type exit to get our of command shell mode.

Can someone tell me how to run the batch file I am current editing in npp directly in npp.

答:
```<code>cmd /c "$(FULL_CURRENT_PATH)"
</code>```

<p>:)</p>

Body:
cmd /c "$(FULL_CURRENT_PATH)"

:)

ContentLicense: CC BY-SA 2.5


问:
Keras - predict_proba does not add up to 1?
I'm new to Keras, and this is my nn:

```<code>model = Sequential()
model.add(Dense(12, activation="relu", input_dim=12, kernel_initializer="normal"))
model.add(Dense(3, activation="sigmoid", kernel_initializer="normal"))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
</code>```

I have 3 outputs: high, medium, or low.

When I tried to use the predict function, I get the correct classes:

```<code>array(['medium', 'low', 'medium', ..., 'low', 'medium', 'low'], dtype=object)
</code>```

However, when i tried predict_proba function, I would get probabilities that doesn't add up to 1?

```<code>array([[  4.93983855e-04,   2.28181913e-01,   9.70774710e-01],
       [  3.14530940e-03,   9.60477769e-01,   3.79752717e-04],
       [  1.40661141e-03,   5.70683666e-02,   9.96348858e-01],
       ...,
       [  1.29012510e-01,   7.08254218e-01,   2.44960701e-03],
       [  1.69786233e-02,   4.71719205e-02,   9.90665674e-01],
       [  1.28657368e-04,   9.89430904e-01,   9.04915680e-04]], dtype=float32)
</code>```

The first row is 4.93983855e-04 + 2.28181913e-01 + 9.70774710e-01, the sum is 1.199450606855, which is greater than 1.

I thought the 1st row means: probability of 1st column (4.93983855e-04) is medium?

答:
The sigmoid activation is outputing values between 0 and 1 independently from one another.

If you want probabilities outputs that sums up to 1, use the softmax activation on your last layer, it will normalize the output to sum up to 1.

I hope this helps :)

Body:
I'm new to Keras, and this is my nn:

model = Sequential()
model.add(Dense(12, activation="relu", input_dim=12, kernel_initializer="normal"))
model.add(Dense(3, activation="sigmoid", kernel_initializer="normal"))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

I have 3 outputs: high, medium, or low.

When I tried to use the predict function, I get the correct classes:

array(['medium', 'low', 'medium', ..., 'low', 'medium', 'low'], dtype=object)

However, when i tried predict_proba function, I would get probabilities that doesn't add up to 1?

array([[  4.93983855e-04,   2.28181913e-01,   9.70774710e-01],
       [  3.14530940e-03,   9.60477769e-01,   3.79752717e-04],
       [  1.40661141e-03,   5.70683666e-02,   9.96348858e-01],
       ...,
       [  1.29012510e-01,   7.08254218e-01,   2.44960701e-03],
       [  1.69786233e-02,   4.71719205e-02,   9.90665674e-01],
       [  1.28657368e-04,   9.89430904e-01,   9.04915680e-04]], dtype=float32)

The first row is 4.93983855e-04 + 2.28181913e-01 + 9.70774710e-01, the sum is 1.199450606855, which is greater than 1.

I thought the 1st row means: probability of 1st column (4.93983855e-04) is medium?


问:
Heap size issue on migrating from Solr 5.0.0 to Solr 5.1.0
I have a Solr 5.0.0 in production with a custom heap size like this

```<code>SOLR_JAVA_MEM="-Xms2g -Xmx2g"
</code>```

When I tried to migrate to Solr 5.1.0 with the same configuration and start the server it returned a OutOfMemoryError. Looking to the Solr API I saw that the heap size was set to 512m. My custom heap configuration is not working in Solr 5.1.0 and the server is starting with the default heap size value.

答:
In my case, with the same SOLR version (v.5.0), I changed it in bin\solr.in.sh file.

There are other files that has "-Xms512m -Xmx512m", just be aware that those won't update the JVM Memory such as:

bin\solr

bin\solr.in.cmd

bin\solr.cmd

Body:
I have a Solr 5.0.0 in production with a custom heap size like this

SOLR_JAVA_MEM="-Xms2g -Xmx2g"

When I tried to migrate to Solr 5.1.0 with the same configuration and start the server it returned a OutOfMemoryError. Looking to the Solr API I saw that the heap size was set to 512m. My custom heap configuration is not working in Solr 5.1.0 and the server is starting with the default heap size value.


问:
Function returns -nan
I have this code. Why does it produce -nan upon returning a value in main program?

```<code>#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace::std;

float f(float x)
{
    float result = -5 * x * x - 2 * x + 1;
    return powf(result, (float)1/(float)3);
}
int main()
{
    cout<<f(-1)<<endl;
    getchar();
    return 0;
}
</code>```

This confuses me. As I far as I know, I use suitable data type.

答:
As others have mentioned, the desired functionality is not available with std::pow. Instead you could use std::cbrt or simply do like so:

```<code>#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cmath>

using namespace::std;

float f(float x)
{
    float result = -5 * x * x - 2 * x + 1;
    float intermediate = powf(std::abs(result),(float)1/(float)3);
    if (std::signbit(result))
        return -intermediate; // Negate if 'result' is negative
    return intermediate;
}
int main()
{
    cout<<f(-1)<<endl;
    getchar();
    return 0;
}
</code>```

You can also just use one of the overloads of std::pow instead of powf

```<code>#include<iostream> // std::cout, std::endl
#include<cstdio>   // getchar
#include<cmath>    // std::pow, std::abs, std::signbit

float f(float x)
{
    float result = -5.0f * x * x - 2.0f * x + 1.0f;
    float intermediate = std::pow(std::abs(result),1.0f/3.0f);
    if (std::signbit(result))
        return -intermediate; // Negate if 'result' is negative
    return intermediate;
}

int main()
{
    std::cout << f(-1) << std::endl;
    getchar();
}
</code>```

Online here

Title: Function returns -nan

Body:
I have this code. Why does it produce -nan upon returning a value in main program?

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace::std;

float f(float x)
{
    float result = -5 * x * x - 2 * x + 1;
    return powf(result, (float)1/(float)3);
}
int main()
{
    cout<<f(-1)<<endl;
    getchar();
    return 0;
}

This confuses me. As I far as I know, I use suitable data type.

Body:
As others have mentioned, the desired functionality is not available with std::pow. Instead you could use std::cbrt or simply do like so:

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cmath>

using namespace::std;

float f(float x)
{
    float result = -5 * x * x - 2 * x + 1;
    float intermediate = powf(std::abs(result),(float)1/(float)3);
    if (std::signbit(result))
        return -intermediate; // Negate if 'result' is negative
    return intermediate;
}
int main()
{
    cout<<f(-1)<<endl;
    getchar();
    return 0;
}

You can also just use one of the overloads of std::pow instead of powf

#include<iostream> // std::cout, std::endl
#include<cstdio>   // getchar
#include<cmath>    // std::pow, std::abs, std::signbit

float f(float x)
{
    float result = -5.0f * x * x - 2.0f * x + 1.0f;
    float intermediate = std::pow(std::abs(result),1.0f/3.0f);
    if (std::signbit(result))
        return -intermediate; // Negate if 'result' is negative
    return intermediate;
}

int main()
{
    std::cout << f(-1) << std::endl;
    getchar();
}

Online here


问:
Inserting txt file info into docx
I am using python 3.5, python-docx, and TKinter.  Is there any way to be able to type a .txt file name into an entry box and have python insert the contents of that .txt file into a specific place in docx?  I know how to get information from Entry boxes in tkinter and how to convert them into a string.

I want to be able to enter someones name (which would also be the name of the text file) into the entry box and have python insert the content of the .txt file.

Thanks

Update here is my code that I'm trying

```<code>from tkinter import *
from tkinter import ttk
import tkinter as tk
from docx import Document
root=Tk()

def make_document():
    testbox=ProjectEngineerEntry.get()
    TestBox=str(testbox)

    def projectengineer():
        with open(+TestBox+'.txt') as f:
            for line in f:
                document.add_paragraph(line)
    document=Document()

    h1=document.add_heading('engineer test',level=1)
    h1a=document.add_heading('Project Engineer',level=2)
    projectengineer()

    document.save('test.docx')

notebook=ttk.Notebook()
notebook.pack(fill=BOTH)
frame1=ttk.Frame(notebook)
notebook.add(frame1,text='Tester',sticky=W)
tester1=Label(frame1,text='Test1')
ProjectEngineerEntry=Entry(frame1)
tester1.pack()
ProjectEngineerEntry.pack()
save=Button(frame1,text='Save',command=make_document).pack()
</code>```

As you can see I am trying to take the information from the entry box, convert it to a string and then use that string to open a text file with that specific name.  However I keep getting

a TypeError: bad operand type for unary +: 'str'

I don't understand whats going on here.  In the actual document I used the ++ method when saving the file (saves it as the current date and time).

答:
python-docx doesn't have this functionality and it's unlikely it ever will. Typically this sort of thing is done to suit by the script or application using python-docx. Something like this:

```<code>from docx import Document

document = Document()
with open('textfile.txt') as f:
    for line in f:
        document.add_paragraph(line)
document.save('wordfile.docx')
</code>```

You'll need to deal with the particulars, like how a paragraph is separated (perhaps a blank line) and so on, but the code doesn't need to be much longer than this.

Title: Inserting txt file info into docx

Body:
I am using python 3.5, python-docx, and TKinter.  Is there any way to be able to type a .txt file name into an entry box and have python insert the contents of that .txt file into a specific place in docx?  I know how to get information from Entry boxes in tkinter and how to convert them into a string.

I want to be able to enter someones name (which would also be the name of the text file) into the entry box and have python insert the content of the .txt file.

Thanks

Update here is my code that I'm trying

from tkinter import *
from tkinter import ttk
import tkinter as tk
from docx import Document
root=Tk()

def make_document():
    testbox=ProjectEngineerEntry.get()
    TestBox=str(testbox)

    def projectengineer():
        with open(+TestBox+'.txt') as f:
            for line in f:
                document.add_paragraph(line)
    document=Document()

    h1=document.add_heading('engineer test',level=1)
    h1a=document.add_heading('Project Engineer',level=2)
    projectengineer()

    document.save('test.docx')

notebook=ttk.Notebook()
notebook.pack(fill=BOTH)
frame1=ttk.Frame(notebook)
notebook.add(frame1,text='Tester',sticky=W)
tester1=Label(frame1,text='Test1')
ProjectEngineerEntry=Entry(frame1)
tester1.pack()
ProjectEngineerEntry.pack()
save=Button(frame1,text='Save',command=make_document).pack()

As you can see I am trying to take the information from the entry box, convert it to a string and then use that string to open a text file with that specific name.  However I keep getting

a TypeError: bad operand type for unary +: 'str'

I don't understand whats going on here.  In the actual document I used the ++ method when saving the file (saves it as the current date and time).

Body:
python-docx doesn't have this functionality and it's unlikely it ever will. Typically this sort of thing is done to suit by the script or application using python-docx. Something like this:

from docx import Document

document = Document()
with open('textfile.txt') as f:
    for line in f:
        document.add_paragraph(line)
document.save('wordfile.docx')

You'll need to deal with the particulars, like how a paragraph is separated (perhaps a blank line) and so on, but the code doesn't need to be much longer than this.


问:
how to write a custom panel displaying categories in magento
I have a category called "Top Products". I wish to display this in a panel on my home page. What is the best way to do this in magento.

** edit **

Thanks sdek, i now have the following. In Home Page / Design.

```<code><block type="catalog/product_list" category_id="13"  template="catalog/product/featured.phtml"/>
</code>```

And it is displaying products. However i have the following issues.
- it's not displaying products from category_id 13, It seems like this value is not being passed thru
- it's only display 2 products. I wish to display all.

featured.phtml

```<code><?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<h2>Featured Products </h2>
    <?php $_collectionSize = $_productCollection->count() ?>
    <?php $_columnCount = $this->getColumnCount(); ?>
    <?php $i=0; foreach ($_productCollection as $_product): ?>
        <?php if ($i++%$_columnCount==0): ?>
        <ul class="product-grid">
        <?php endif ?>
            <li class="<?php if(($i-1)%$_columnCount==0): ?> first<?php else: ?> last<?php endif; ?>">
            <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" >
            <img src="<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail')->resize(85); ?>" class="product-img" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" style="padding-bottom:20px; margin-bottom:20px;" />
            </a>
           <p><strong><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></strong>
           <?php echo $_product->getShortDescription(); ?></p>

            <?php echo $this->getPriceHtml($_product, true) ?>
            <a href="<?php echo $_product->getProductUrl() ?>" class="more">More details</a>
            </li>
        <?php if ($i%$_columnCount==0 || $i==$_collectionSize): ?>
        </ul>
        <?php endif ?>
        <?php endforeach ?>
    <?php endif; ?
</code>```

答:
I wouldn't even use a category but this extension instead:

Featured Products

Body:
I have a category called "Top Products". I wish to display this in a panel on my home page. What is the best way to do this in magento.

** edit **

Thanks sdek, i now have the following. In Home Page / Design.

<block type="catalog/product_list" category_id="13"  template="catalog/product/featured.phtml"/>

And it is displaying products. However i have the following issues.
- it's not displaying products from category_id 13, It seems like this value is not being passed thru
- it's only display 2 products. I wish to display all.

featured.phtml

<?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>
<?php if(!$_productCollection->count()): ?>

<?php echo $this->__('There are no products matching the selection.') ?>

<?php else: ?>

Featured Products

    <?php $_collectionSize = $_productCollection->count() ?>
    <?php $_columnCount = $this->getColumnCount(); ?>
    <?php $i=0; foreach ($_productCollection as $_product): ?>
        <?php if ($i++%$_columnCount==0): ?>

        <?php endif ?>
            <li class="<?php if(($i-1)%$_columnCount==0): ?> first<?php else: ?> last<?php endif; ?>">
            <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" >
            <img src="<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail')->resize(85); ?>" class="product-img" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" style="padding-bottom:20px; margin-bottom:20px;" />

<?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?>
           <?php echo $_product->getShortDescription(); ?>

            <?php echo $this->getPriceHtml($_product, true) ?>
            <a href="<?php echo $_product->getProductUrl() ?>" class="more">More details

        <?php if ($i%$_columnCount==0 || $i==$_collectionSize): ?>

        <?php endif ?>
        <?php endforeach ?>
    <?php endif; ?


答:
You need to define one parameter constructor also because you are passing only singleInteger value. At the time of Instantiate the ProcessHeap class.

```<code>    private Process[] heap;
    private int size;
    private static int counter = 0;

    //One Paramaterized construct
     public ProcessHeap( int size) {
            this.size = size;
     }

    //Two Paramaterized construct
     public ProcessHeap(Process[] heap, int size) {
            this.heap = heap;
            this.size = size;
     }
</code>```

Now you cal call your Constructor As you desired.

Like  This

```<code>final int HEAP_SIZE = 100;

final Process[] processHeap = new Process[HEAP_SIZE];

ProcessHeap heap = new ProcessHeap(HEAP_SIZE);
ProcessHeap heap1 = new ProcessHeap(processHeap , HEAP_SIZE);
</code>```

Title: Making a new object, cannot be applied to type (int)

Body:
I have a ProcessHeap class that has two fields:

Heap: an array of type Process which represents the heap

Size: the number of elements in the heap

My constructor and attributes look like this:

private Process[] heap;
private int size;
private static int counter = 0;

//Paramaterized construct
    public ProcessHeap(Process[] heap, int size) {
        this.heap = heap;
        this.size = size;

The problem is, we were given a driver and at the start of the driver I am getting an error particularly on (HEAP_SIZE)

This is the line:

final int HEAP_SIZE = 100;
ProcessHeap heap = new ProcessHeap(HEAP_SIZE); // gives this error:

The error upon mouse-over states:

ProcessHeap (Process[], int) in ProcessHeap cannot be applied to (int)

Body:
You need to define one parameter constructor also because you are passing only singleInteger value. At the time of Instantiate the ProcessHeap class.

    private Process[] heap;
    private int size;
    private static int counter = 0;

    //One Paramaterized construct
     public ProcessHeap( int size) {
            this.size = size;
     }

    //Two Paramaterized construct
     public ProcessHeap(Process[] heap, int size) {
            this.heap = heap;
            this.size = size;
     }

Now you cal call your Constructor As you desired.

Like  This

final int HEAP_SIZE = 100;

final Process[] processHeap = new Process[HEAP_SIZE];

ProcessHeap heap = new ProcessHeap(HEAP_SIZE);
ProcessHeap heap1 = new ProcessHeap(processHeap , HEAP_SIZE);


问:
Operand should contain only 1 column Mysql Query
I am using the following query to fetch multiple column values based on the condition specified in the case statement and encountered the following error operand should contain only 1 column mysql query.I just can't figure out what the problem is.Is there a simple fix to this, or another way to write my query?</p>

```<code>SELECT id,
          CASE
             WHEN id='' THEN (select * where name='abc')
             ELSE (select * from sample)
          END
    FROM sample WHERE name='abc' and status='xyz'
</code>```

答:
You could use a union query that combines three different queries:

```<code>select * from samples
where name='abc' and status='xyz'

union all

select * from samples
where
  name='abc' and not exists (
    select * from samples
    where name='abc' and status='xyz'
  )

union all

select * from samples
where
  not exists (
    select * from samples
    where name='abc'
  )
</code>```

the first part will return all records from samples that match the name and status condition

the second part will return all records from sample that match the name condition, but only if the first query doesn't return anything

the thirds part will return all records from sample whenever both the first and second query don't return anything

(those three queries can be combined together with ORs but the union query is easier to read and clearer)

Body:
I am using the following query to fetch multiple column values based on the condition specified in the case statement and encountered the following error operand should contain only 1 column mysql query.I just can't figure out what the problem is.Is there a simple fix to this, or another way to write my query?

SELECT id,
          CASE
             WHEN id='' THEN (select * where name='abc')
             ELSE (select * from sample)
          END
    FROM sample WHERE name='abc' and status='xyz'

Body:
You could use a union query that combines three different queries:

select * from samples
where name='abc' and status='xyz'

union all

select * from samples
where
  name='abc' and not exists (
    select * from samples
    where name='abc' and status='xyz'
  )

union all

select * from samples
where
  not exists (
    select * from samples
    where name='abc'
  )

the first part will return all records from samples that match the name and status condition

the second part will return all records from sample that match the name condition, but only if the first query doesn't return anything

the thirds part will return all records from sample whenever both the first and second query don't return anything

(those three queries can be combined together with ORs but the union query is easier to read and clearer)


问:
Angular way to capture Id if child being clicked
I'm new to Angular 1.0 and I'm coming from jQuery backgroud.

Let's say I have following HTML :

```<code><div id="filters">
    <div id="filter1">Filter 1</div>
    <div id="filter2">Filter 2</div>
    <div id="filter3">Filter 3</div>
    <div id="filter4">Filter 4</div>
</div>
</code>```

Now I want to have a function which will return id of child element being clicked.
What could be the Angular way to best implement the following jQuery code :

```<code>$('#filters div').on('click', function() {
  alert($(this).attr("id"));
});
</code>```

答: Create a custome directive on your parent div. This directive will give you the access to the DOM element. This is recommended angular way for accessing DOM elements.

Body:
I'm new to Angular 1.0 and I'm coming from jQuery backgroud.

Let's say I have following HTML :

Filter 1

Filter 2

Filter 3

Filter 4

Now I want to have a function which will return id of child element being clicked.
What could be the Angular way to best implement the following jQuery code :

$('#filters div').on('click', function() {
  alert($(this).attr("id"));
});


问:
Kentico: How to access searched string from inside search transformation?
How to access searched string from inside search transformation? Couldn't find it in the docs or forums. Tried <%#SearchedText()%> but of course, it doesn't exist.

Any help would be appreciated. Thanks.

答:
Search string is typically available in querystring so you can use query string macro like

```<code>{%QueryString.name|(encode)%}
{%QueryString.name%}
{%HTMLEncode(QueryString.name)%}
</code>```

where querystring is (probably) in your case 'searchtext'.

If you need more complex search transformation you can inspire yourself in example on Corporate Site:

```<code><div style="margin-bottom: 30px;">
<%-- Search result image --%>
    <div style="float: left; border: solid 1px #eeeeee; height:90px; width:90px; margin-right: 5px;text-align:center;">
       <img src="<%# GetSearchImageUrl("/CMSModules/CMS_SmartSearch/no_image.gif",90) %>" alt="" />
    </div>
    <div style="margin-left: 108px;">
        <%-- Search result title --%>
        <div>
            <a style="font-weight: bold" href='<%# SearchResultUrl(true) %>'>
                <%#SearchHighlight(HTMLHelper.HTMLEncode(CMS.Base.Web.UI.ControlsHelper.RemoveDynamicControls(DataHelper.GetNotEmpty(Eval("Title"), "/"))), "<span style='font-weight:bold;'>", "</span>")%>
            </a>
        </div>
        <%-- Search result content --%>
        <div style="margin-top: 5px; min-height:40px">
            <%#SearchHighlight(HTMLHelper.HTMLEncode(TextHelper.LimitLength(HttpUtility.HtmlDecode(HTMLHelper.StripTags(CMS.Base.Web.UI.ControlsHelper.RemoveDynamicControls(GetSearchedContent(DataHelper.GetNotEmpty(Eval("Content"), ""))), false, " ")), 280, "...")), "<span style='background-color: #FEFF8F'>", "</span>")%><br />
        </div>
        <%-- Relevance, URL, Creattion --%>
        <div style="margin-top: 5px;">
            <%-- Relevance --%>
            <div title="Relevance: <%# Convert.ToInt32(ValidationHelper.GetDouble(Eval("Score"), 0) * 100) %>%"
                style="width: 50px; border: solid 1px #aaaaaa; margin-top: 7px; margin-right: 6px;
                float: left; color: #0000ff; font-size: 2pt; line-height: 4px; height: 4px;">
                <div style="<%# "background-color:#a7d3a7;width:" + Convert.ToString(Convert.ToInt32(ValidationHelper.GetDouble(Eval("Score"), 0) * 50)) + "px;height:4px;line-height: 4px;"%>">
                </div>
            </div>
            <%-- URL --%>
            <span style="color: #008000">
                <%# TextHelper.BreakLine(SearchHighlight(SearchResultUrl(true),"<strong>","</strong>"),100,"<br />") %>
            </span>
            <%-- Creation --%>
            <span style="padding-left:5px;;color: #888888; font-size: 9pt">
                (<%# GetDateTimeString(ValidationHelper.GetDateTime(Eval("Created"), DateTimeHelper.ZERO_TIME), true) %>)
            </span>
        </div>
    </div>
    <div style="clear: both">
    </div>
</div>
</code>```

Body:
Search string is typically available in querystring so you can use query string macro like

{%QueryString.name|(encode)%}
{%QueryString.name%}
{%HTMLEncode(QueryString.name)%}

where querystring is (probably) in your case 'searchtext'.

If you need more complex search transformation you can inspire yourself in example on Corporate Site:

<div style="margin-bottom: 30px;">
<%-- Search result image --%>
    <div style="float: left; border: solid 1px #eeeeee; height:90px; width:90px; margin-right: 5px;text-align:center;">
       <img src="<%# GetSearchImageUrl("/CMSModules/CMS_SmartSearch/no_image.gif",90) %>" alt="" />
    </div>
    <div style="margin-left: 108px;">
        <%-- Search result title --%>
        <div>
            <a style="font-weight: bold" href='<%# SearchResultUrl(true) %>'>
                <%#SearchHighlight(HTMLHelper.HTMLEncode(CMS.Base.Web.UI.ControlsHelper.RemoveDynamicControls(DataHelper.GetNotEmpty(Eval("Title"), "/"))), "<span style='font-weight:bold;'>", "</span>")%>
            </a>
        </div>
        <%-- Search result content --%>
        <div style="margin-top: 5px; min-height:40px">
            <%#SearchHighlight(HTMLHelper.HTMLEncode(TextHelper.LimitLength(HttpUtility.HtmlDecode(HTMLHelper.StripTags(CMS.Base.Web.UI.ControlsHelper.RemoveDynamicControls(GetSearchedContent(DataHelper.GetNotEmpty(Eval("Content"), ""))), false, " ")), 280, "...")), "<span style='background-color: #FEFF8F'>", "</span>")%><br />
        </div>
        <%-- Relevance, URL, Creattion --%>
        <div style="margin-top: 5px;">
            <%-- Relevance --%>
            <div title="Relevance: <%# Convert.ToInt32(ValidationHelper.GetDouble(Eval("Score"), 0) * 100) %>%"
                style="width: 50px; border: solid 1px #aaaaaa; margin-top: 7px; margin-right: 6px;
                float: left; color: #0000ff; font-size: 2pt; line-height: 4px; height: 4px;">
                <div style="<%# "background-color:#a7d3a7;width:" + Convert.ToString(Convert.ToInt32(ValidationHelper.GetDouble(Eval("Score"), 0) * 50)) + "px;height:4px;line-height: 4px;"%>">
                </div>
            </div>
            <%-- URL --%>
            <span style="color: #008000">
                <%# TextHelper.BreakLine(SearchHighlight(SearchResultUrl(true),"<strong>","</strong>"),100,"<br />") %>
            </span>
            <%-- Creation --%>
            <span style="padding-left:5px;;color: #888888; font-size: 9pt">
                (<%# GetDateTimeString(ValidationHelper.GetDateTime(Eval("Created"), DateTimeHelper.ZERO_TIME), true) %>)
            </span>
        </div>
    </div>
    <div style="clear: both">
    </div>
</div>


问:
Is "message" a reserved word in Django or Python?
I seem to get a TypeError ('message' is an invalid keyword argument for this function) every time I try adding something in the DB via the Django admin interface. The object is added but this exception is raised. Could be this linked to the fact that I have a model named "Message"?</p>

答: Seems I was missing the directives for the Django messages framework in my settings.py. Thanks anyway for the answers.</p>


问:
React Flux Get Api data from remote service
I am trying to follow the flux architecture from the facebook sample found at
https://github.com/facebook/flux/tree/master/examples/flux-todomvc

Where is this architecture would you call your api to get data from a remote service?

The AppContainer has a getState method which gets the get initial state of the store. This would be null since the database call hasn't happened yet. I could make the api call in the Action creator. But where do i trigger this action?

AppContainer.js

```<code>function getStores() {
    return [
        TodoStore
    ];
}

function getState() {
  return {
    todos: TodoStore.getState()
  };
}
</code>```

答: You should create an action dispatcher, that fires the fetch request and dispatches the action with the fetch result as payload. Handle this action dispatcher over via mapDispatchToProps and call it inside your component via componentDidMount cycle method.

Body:
I am trying to follow the flux architecture from the facebook sample found at
https://github.com/facebook/flux/tree/master/examples/flux-todomvc

Where is this architecture would you call your api to get data from a remote service?

The AppContainer has a getState method which gets the get initial state of the store. This would be null since the database call hasn't happened yet. I could make the api call in the Action creator. But where do i trigger this action?

AppContainer.js

function getStores() {
    return [
        TodoStore
    ];
}

function getState() {
  return {
    todos: TodoStore.getState()
  };
}


答:
You can use ng-click directive to pass event. Like this

```<code><div id="filters" ng-click="myFunction($event)">
   <div id="filter1">Filter 1</div>
   <div id="filter2">Filter 2</div>
   <div id="filter3">Filter 3</div>
   <div id="filter4">Filter 4</div>
</div>
</code>```

Title: Angular way to capture Id if child being clicked

Body:
You can use ng-click directive to pass event. Like this

<div id="filters" ng-click="myFunction($event)">
   <div id="filter1">Filter 1</div>
   <div id="filter2">Filter 2</div>
   <div id="filter3">Filter 3</div>
   <div id="filter4">Filter 4</div>
</div>


问:
How to reduce the font size according to the length of the header in php?
I've created a form which displays header in the starting of the page.if the length of the header is larger it displays two lines and it looks bad, so please tell me is there any way to reduce the font size according to the length of the header.</p>

答: I think you can use "em" (font-size: 1.1em) or percentage(font-size: 20%) in font-size. But I think you should share your screenshot to give more clear idea of problem</p>


问:
Delphi SOAP Server - Document/Literal - Possible?
We're using Delphi2005 with Delphi2007 patches, also experimenting with DelphiXE SOAP libraries.  But I've hit a snag...
We've got an internal service that our app has been consuming for a year now. The service uses document/literal convention, and is used by several systems on several platforms (java, .Net, and ours - Delphi2005).  Now we need to become a publisher and not just a consumer.  So we're building a server service.  And the WSDL is coming out wrong.  I consume the "official" WSDL as document/literal, and when I try to serve it back as a service, it comes out as RPC style.  Even though I've set the options of the HTTPSoapPascalInvoker.Converter to be [soLiteralParams, soDocument].
Now that I do some more searching, I find statements like this:
"Delphi for Win32 does not support creating Document Literal Soap Servers."
[ http://www.experts-exchange.com/Programming/Languages/Pascal/Delphi/Q_22664248.html ]

That quote is a few years old. Does anyone know if it still applies?

I AM in a position to move this portion of the project to Delphi2010 or XE if necessary, but I'd rather not (throws a wrench into our automated build process).  Including the SOAP libs is ok, and we already do that.

So, if anyone knows whether it's possible to write a Win32 Delphi web service in 2005, 2010 or XE that will produce a WSDL that conforms to document/literal, I'd be very, very happy.

答:
AFAIK, last time I checked, the stock Delphi SOAP Server was limited to RPC and the "official" motto was that you could use Delphi Prism to build your server (i.e. we won't add Doc|Lit in Delphi).

However, you can use the latest RemObjects SDK (not free) to build a Doc|lit SOAP Server, or use IndySOAP (open Source), but I don't know if there is a version compatible with D2009 and up (Unicode/Indy 10)...


问:
Uncaught SyntaxError: Invalid or unexpected token one element works but other one does not
When I run this code it works fine, but if I add another select box it does not work - actually 'Select Project Team Member Role' does not work at all but 'Select Project Team Member' works really fine.

When I run code for 'Select Project Team Member Role' it gives error 'uncaught SyntaxError: Invalid or unexpected token'

I need both select box and when I run both none works. I cant find what is the error; please help me out.

HTML

```<code><form name="add_name" id="add_name">
  <div class="table-responsive">
    <table class="table table-bordered" id="dynamic_field">
      <tr>
        <td>
          <select name="projteam[]" id="projmem_id" class="form-control">
            <option> Select Project Team Member</option>
            <?php foreach($this->memdata as $pc){ ?>
              <option value="<?php echo $pc->id ?>"><?php echo $pc->name ?></option>
            <?php } ?>
          </select>
         </td>
        <td>
          <select name="keyrole[]" id="role_id" class="form-control">
            <option> Select Project Team Member Role</option>
            <?php foreach($this->roldata as $mr){ ?>
              <option value="<?php echo $mr->id ?>"><?php echo $mr->key_role ?></option>
            <?php } ?>
          </select>
        </td>
        <td>
          <button type="button" name="add" id="add" class="btn btn-success">Add More</button>
        </td>
      </tr>
    </table>
  </div>
</form>
</code>```

JavaScript

```<code><script>
  $(document).ready(function(){
    var i=1;
    $('#add').click(function(){
      i++;
      $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><select name="projteam[]" id="projmem_id" class="form-control"><option> Select Project Team Member</option> <?php foreach($this->memdata as $pc){ ?> <option value="<?php echo $pc->id ?>"><?php echo $pc->name ?></option> <?php } ?> </select></td><td><select name="keyrole[]" id="role_id" class="form-control"><option> Select Project Team Member Role</option> <?php foreach($this->roldata as $mr){ ?> <option value="<?php echo $mr->id ?>"><?php echo $mr->key_role ?></option> <?php } ?> </select></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
    });
    $(document).on('click', '.btn_remove', function(){
      var button_id = $(this).attr("id");
      $('#row'+button_id+'').remove();
    });
  });
</script>
</code>```

答:
You might use an ajax request to load the content of your option tags, like Srikant Sahu said, the php content is returned before the event occurs.. Here an example of an Ajax Request:</p>

```<code>$(document).ready(function () {
$('#yourid').click(function (event) {
   $.ajax({
            type: 'POST',
            url: 'yourfile.php',
            data: '',
            dataType:'json',
            success: function(data) {
                //create the new select
            }
        });
     });
});
</code>```

Body:
When I run this code it works fine, but if I add another select box it does not work - actually 'Select Project Team Member Role' does not work at all but 'Select Project Team Member' works really fine.

When I run code for 'Select Project Team Member Role' it gives error 'uncaught SyntaxError: Invalid or unexpected token'

I need both select box and when I run both none works. I cant find what is the error; please help me out.

HTML

<form name="add_name" id="add_name">

          <select name="projteam[]" id="projmem_id" class="form-control">
            <option> Select Project Team Member</option>
            <?php foreach($this->memdata as $pc){ ?>
              <option value="<?php echo $pc->id ?>"><?php echo $pc->name ?></option>
            <?php } ?>
          </select>

          <select name="keyrole[]" id="role_id" class="form-control">
            <option> Select Project Team Member Role</option>
            <?php foreach($this->roldata as $mr){ ?>
              <option value="<?php echo $mr->id ?>"><?php echo $mr->key_role ?></option>
            <?php } ?>
          </select>

          <button type="button" name="add" id="add" class="btn btn-success">Add More</button>

</form>

JavaScript

Body:
You might use an ajax request to load the content of your option tags, like Srikant Sahu said, the php content is returned before the event occurs.. Here an example of an Ajax Request:

$(document).ready(function () {
$('#yourid').click(function (event) {
   $.ajax({
            type: 'POST',
            url: 'yourfile.php',
            data: '',
            dataType:'json',
            success: function(data) {
                //create the new select
            }
        });
     });
});


问:
Can't change permissions on a folder on HDFS. Nothing is printed as a reason why.
We cannot change permissions of a single folder on HDFS.  We can change permissions of all the other folders no problem.  Except this one folder.  Current permissions are:

```<code>drwxrwx--x   - app app          0 2017-03-28 14:29 /app/drops
</code>```

None of these work to change the permission and nothing is printed, not even a permission denied is printed:

```<code>root@ss01nn01 # hdfs dfs -setfacl -m other::r-x /app/drops
root@ss01nn01 # hdfs dfs -chmod 775 /app/drops
</code>```

We're using the Cloudera line of products.  I've enabled more debugging in HDFS via Cloudera Manager, but still nothing.  How could I debug this further?

Cheers,

答:
Did you try this?

sudo -u hdfs hdfs dfs -chmod 775 /app/drops

Body:
We cannot change permissions of a single folder on HDFS.  We can change permissions of all the other folders no problem.  Except this one folder.  Current permissions are:

drwxrwx--x   - app app          0 2017-03-28 14:29 /app/drops

None of these work to change the permission and nothing is printed, not even a permission denied is printed:

root@ss01nn01 # hdfs dfs -setfacl -m other::r-x /app/drops
root@ss01nn01 # hdfs dfs -chmod 775 /app/drops

We're using the Cloudera line of products.  I've enabled more debugging in HDFS via Cloudera Manager, but still nothing.  How could I debug this further?

Cheers,


问:
Zeppelin: How to add python files in PYTHONPATH
I am running zeppelin with Spark on yarn.
Option --py-files(SPARK_SUBMIT_OPTIONS) does not work in zeppelin. Is there any alternative to --py-files in zeppelin.

NOTE: I can upload files using option: --files but then it does not add those files in PYTHONPATH. Hence I need an alternative to --py-files in zeppelin.

答: I'm not familiar with Zeppelin, but you can achieve the equivalent of --py-files by using the addPyFile method on the context (See https://spark.apache.org/docs/1.6.1/api/python/pyspark.html). HTH


问:
Cannot drag and drop using harmon.ie addin in Outlook

I am a newbie here, and this is my first post here so please don't judge :)

I need help with outlook addin for sharepoint called "harmon.ie". We have been using it (with sharepoint 2010) for years, but suddenly it stopped working with drag and drop function. This only happens in one sharepoint site (where this addin is used mainly). When i drag and drop file to any of the folders in that site - nothing happens (list just refresh). Connections working fine, permissions are set up properly, even given "all rights" as i thought this was the problem. No avail. When I tried in other sites and folders - everything is working fine, files uploading and I am able to see it.
The "harmon.ie" logs it shows one error:

09:15:15,956 ERROR [eclipse-CLR] com.mainsoft.sharepoint.sidebar.SideBarViewPart - External tabs provider was not found

Sharepoint logs doesn't show any bad behaviour comparing to logs when files are uploaded fine. I am not a big coder, just a beginner so any help would be gold worth!

答:
Please list the exact version in use.

If this issue only occurs with a specific SharePoint site it means the problem stems from your server.
Do you reproduce on top of our demo SharePoint site at:
http://ravenwood-corp.com/sandbox   username:sandbox password: sandbox

Gather the communication information between client (harmon.ie) and SharePoint server – we usually rely on Fiddler network tracing tool http://www.fiddler2.com/fiddler2/ Please download and install it. If your Sharepoint site uses HTTPS secure protocol – after installing Fiddler, please go under ‘Tools -> Fiddler Options’, select ‘HTTPS’ tab and enable the checkboxes (Capture HTTPS Traffic, Decrypt HTTPS Traffic, Ignore Server Certificate Errors).
If installed and configured successfully – restart Outlook, and reproduce the problem i.e. D&D inside the problematic SharePoint site. You should see requests being registered in fiddler. Once the trace log is generated, save it via File -> Save All Sessions… and send me the generated .saz file

---- jean


问:
How to change the border color of a single cell using dynamic table
I am creating a dynamic table and I want to change the border color of a specific cell e.g (0,1).I cannot figure out on how will access the specific cell? Any idea?</p>

```<code>protected void cmdCreate_Click(object sender, EventArgs e)
{
    //clear the table
    tbl.Controls.Clear();

    int rows = Int32.Parse(txtRows.Text);
    int cols = Int32.Parse(txtCols.Text);

    for (int row = 0; row < rows; row++)
    {
        TableRow rowNew = new TableRow();

        tbl.Controls.Add(rowNew);

        tbl.Rows.AddAt(0, TableRow row);

        for (int col = 0; col < cols; col++)
        {
            //create a new tablecell object
            TableCell cellNew = new TableCell();

            cellNew.Text = "Example Cell (" + row.ToString() + "," + col.ToString() + ")";

            cellNew.BorderColor = System.Drawing.Color.Red;

            //     cellNew.Text += col.ToString() + ")";

            if (chkBorder.Checked)
            {
                cellNew.BorderStyle = BorderStyle.Inset;
                cellNew.BorderWidth = Unit.Pixel(1);
            }

            rowNew.Controls.Add(cellNew);
        }
    }
}
</code>```

答:
You can check which at which cell you are by checking row and col. And you need to specify the BorderStyle also, not just the color.

```<code>if (row == 0 && col == 1)
{
    cellNew.BorderColor = System.Drawing.Color.Red;
    cellNew.BorderStyle = BorderStyle.Solid;
}
</code>```

Body:
I am creating a dynamic table and I want to change the border color of a specific cell e.g (0,1).I cannot figure out on how will access the specific cell? Any idea?

protected void cmdCreate_Click(object sender, EventArgs e)
{
    //clear the table
    tbl.Controls.Clear();

    int rows = Int32.Parse(txtRows.Text);
    int cols = Int32.Parse(txtCols.Text);

    for (int row = 0; row < rows; row++)
    {
        TableRow rowNew = new TableRow();

        tbl.Controls.Add(rowNew);

        tbl.Rows.AddAt(0, TableRow row);

        for (int col = 0; col < cols; col++)
        {
            //create a new tablecell object
            TableCell cellNew = new TableCell();

            cellNew.Text = "Example Cell (" + row.ToString() + "," + col.ToString() + ")";

            cellNew.BorderColor = System.Drawing.Color.Red;

            //     cellNew.Text += col.ToString() + ")";

            if (chkBorder.Checked)
            {
                cellNew.BorderStyle = BorderStyle.Inset;
                cellNew.BorderWidth = Unit.Pixel(1);
            }

            rowNew.Controls.Add(cellNew);
        }
    }
}

Body:
You can check which at which cell you are by checking row and col. And you need to specify the BorderStyle also, not just the color.

if (row == 0 && col == 1)
{
    cellNew.BorderColor = System.Drawing.Color.Red;
    cellNew.BorderStyle = BorderStyle.Solid;
}


问:
Align image in center without getting space
I want to align the logo at the center in the navigation bar of the page.

This is my code:

```<code><div class="nav">
    <ul>
        <li id="center">
           <a href="home.php"><img src="images/w_logo.gif"></a>
        </li>
    </ul>
</div>
</code>```

I have found this solution online:

```<code>#center img{
    display: block;
    margin: auto;
}
</code>```

But the problem is that by using display:block property I am getting space around the image which is increasing the height of my navigation bar and I am not being able to remove that space.

Help would be appreciated.

答:
Check this fiddle.
https://jsfiddle.net/5huhpxuk/

#center img {
  display: block;
  margin: auto;
}

.nav {
  background-color: black;
  line-height: 0%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">
  <ul>
    <li id="center">
      <img src="http://zdnet3.cbsistatic.com/hub/i/2015/09/01/cb834e24-18e7-4f0a-a9bf-4c2917187d3f/83bb139aac01023dbf3e55a3d1789ad8/google-new-logo.png">
    </li>
  </ul>
</div></code>```

Body:
I want to align the logo at the center in the navigation bar of the page.

This is my code:

I have found this solution online:

#center img{
    display: block;
    margin: auto;
}

But the problem is that by using display:block property I am getting space around the image which is increasing the height of my navigation bar and I am not being able to remove that space.

Help would be appreciated.

Body:
Check this fiddle.
https://jsfiddle.net/5huhpxuk/

#center img {
  display: block;
  margin: auto;
}

.nav {
  background-color: black;
  line-height: 0%
}

<div class="nav">
  <ul>
    <li id="center">
      <a href="home.php"><img src="http://zdnet3.cbsistatic.com/hub/i/2015/09/01/cb834e24-18e7-4f0a-a9bf-4c2917187d3f/83bb139aac01023dbf3e55a3d1789ad8/google-new-logo.png"></a>
    </li>
  </ul>
</div>


问:
Need to Execute test in both parallel and in Sequence
I got 4 test cases in protractor of which I need to run 2 in parallel and 2 in sequence. I want to run the first 2 test in sequence and the next two test in parallel. Can any one please suggest me how to do this? I don't know how to do it. My conf.js looks like this:

```<code>module.exports = {
    framework: 'jasmine',

 specs: [
         './test/supplier-portal-partner.js',// Sequence
        './test/supplier-portal-admin.js',// Sequence
        './test/supplier-portal-Language-PT.js',// Parallel
        './test/supplier-portal-Language-ES.js',// Parallel

        ],
    capabilities:[ {
        browserName: 'chrome',
        shardTestFiles: true,
        maxInstances: 1,

        'platform': 'ANY',
        'version': 'ANY',
        'chromeOptions': {

            prefs: {
                download: {
                    'prompt_for_download': false,
                    'directory_upgrade': true,
                    'default_directory': 'C:/Users/jasharma/gitrepo/supplier-portal/download'
                }
            }
        }

    }],
 http://qaswarm.community.nw.ops.here.com:4444/wd/hub",

    // Options to be passed to Jasmine.
    jasmineNodeOpts: {
        defaultTimeoutInterval: 10000 * 250 //250 Seconds
    }
};
</code>```

Thanks in adavance

答:
Can you try the below multicapabilities configuration,

```<code>multiCapabilities: [
    {
        sequential: true,
        browserName: 'chrome',
        specs: ['./test/supplier-portal-partner.js',
                './test/supplier-portal-admin.js']
    },
    {
        shardTestFiles: true,
        maxInstances: 2,
        browserName: 'chrome',
        specs: './test/supplier-portal-Language-PT.js',
               './test/supplier-portal-Language-ES.js']
    }
]
</code>```

Above configuration will launch 3 browser instances and executes 1st set of specs in sequence and 2nd set of specs in two different browsers simultaneously.

Body:
I got 4 test cases in protractor of which I need to run 2 in parallel and 2 in sequence. I want to run the first 2 test in sequence and the next two test in parallel. Can any one please suggest me how to do this? I don't know how to do it. My conf.js looks like this:

module.exports = {
    framework: 'jasmine',

 specs: [
         './test/supplier-portal-partner.js',// Sequence
        './test/supplier-portal-admin.js',// Sequence
        './test/supplier-portal-Language-PT.js',// Parallel
        './test/supplier-portal-Language-ES.js',// Parallel

        ],
    capabilities:[ {
        browserName: 'chrome',
        shardTestFiles: true,
        maxInstances: 1,

        'platform': 'ANY',
        'version': 'ANY',
        'chromeOptions': {

            prefs: {
                download: {
                    'prompt_for_download': false,
                    'directory_upgrade': true,
                    'default_directory': 'C:/Users/jasharma/gitrepo/supplier-portal/download'
                }
            }
        }

    }],
 http://qaswarm.community.nw.ops.here.com:4444/wd/hub",

    // Options to be passed to Jasmine.
    jasmineNodeOpts: {
        defaultTimeoutInterval: 10000 * 250 //250 Seconds
    }
};

Thanks in adavance

Body:
Can you try the below multicapabilities configuration,

multiCapabilities: [
    {
        sequential: true,
        browserName: 'chrome',
        specs: ['./test/supplier-portal-partner.js',
                './test/supplier-portal-admin.js']
    },
    {
        shardTestFiles: true,
        maxInstances: 2,
        browserName: 'chrome',
        specs: './test/supplier-portal-Language-PT.js',
               './test/supplier-portal-Language-ES.js']
    }
]

Above configuration will launch 3 browser instances and executes 1st set of specs in sequence and 2nd set of specs in two different browsers simultaneously.


答:
You could create a directive which you attach to the parent and this directive could bind to the onClick event for all the children.

function getChildrenid() {
  return {
    restrict: 'A',
    link: function(scope, element, attributes) {
      var children = element[0].querySelectorAll('div'); //get all child div's
      angular.forEach(children, function(child) { //loop over all the child
        var ngElement = angular.element(child); //create an angular element of the child
        ngElement.on('click', function() { //bind to the click event
          console.log(ngElement.attr('id'));
        });
      });
    }
  };
}

function MainController() {
  //
}

angular.module('app', []);
angular.module('app')
  .controller('MainController', MainController)
  .directive('getChildrenid', getChildrenid);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="MainController as ctrl">
    <div id="filters" get-childrenid>
        <div id="filter1">Filter 1</div>
        <div id="filter2">Filter 2</div>
        <div id="filter3">Filter 3</div>
        <div id="filter4">Filter 4</div>
    </div>
  </div>
</div></code>```

You could use an ngRepeat to render the children instead of listing them all separately and on the repeated children you could add an ngClick.

You could add an ngClick to each child element separately.

Body:
You could create a directive which you attach to the parent and this directive could bind to the onClick event for all the children.

function getChildrenid() {
  return {
    restrict: 'A',
    link: function(scope, element, attributes) {
      var children = element[0].querySelectorAll('div'); //get all child div's
      angular.forEach(children, function(child) { //loop over all the child
        var ngElement = angular.element(child); //create an angular element of the child
        ngElement.on('click', function() { //bind to the click event
          console.log(ngElement.attr('id'));
        });
      });
    }
  };
}

function MainController() {
  //
}

angular.module('app', []);
angular.module('app')
  .controller('MainController', MainController)
  .directive('getChildrenid', getChildrenid);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="MainController as ctrl">
    <div id="filters" get-childrenid>
        <div id="filter1">Filter 1</div>
        <div id="filter2">Filter 2</div>
        <div id="filter3">Filter 3</div>
        <div id="filter4">Filter 4</div>
    </div>
  </div>
</div>

You could use an ngRepeat to render the children instead of listing them all separately and on the repeated children you could add an ngClick.

You could add an ngClick to each child element separately.


问:
Shell errors and unwanted "master" in prompt after installing git
I installed Git and now when I open Terminal I get the following:

```<code>-bash: /Users/Lior/.bash_profile: line 21: unexpected EOF while looking for matching `"'
-bash: /Users/Lior/.bash_profile: line 23: syntax error: unexpected end of file
</code>```

I found this solution and tried the following

```<code>Lior (master #) ~ $ echo $PS1
\[\033[0;35m\]\u\[\033[0;32m\]$(__git_ps1)\[\033[0;34m\] \W $ \[\033[0m\]

Lior (master #) ~ $ zsh
\[\033[0;35m\]\u\[\033[0;32m\]$(__git_ps1)\[\033[0;34m\] \W $ \[\033[0m\]bash

bash: __git_ps1: command not found

Lior ~ $
</code>```

There is no (master #) anymore but when I restart the shell (master #) shows again.

How can I get rid of master permanently?

答:
When you installed Git you (apparently) also configured it to display your Git branch in your prompt. That's what the $(__git_ps1) is doing, it's invoking the __git_ps1 function and including its output in your prompt.

Like the error message says, it appears something (either you, or something you installed) has mangled or malformed /Users/Lior/.bash_profile. Take a look at the contents and see if you can fix the mis-quoting, otherwise share the contents of the file in the question.

Now you just need to remove __git_ps1 from your prompt. As the installation instructions note, this is done by either including it in your PS1 or setting your PROMPT_COMMAND to invoke it. Take a look in your .bash_profile for any mention of __git_ps1 and remove / fix it. Remember to back up the file if you're uncertain what you're doing, so you can restore it if it doesn't work.

Body:
I installed Git and now when I open Terminal I get the following:

-bash: /Users/Lior/.bash_profile: line 21: unexpected EOF while looking for matching `"'
-bash: /Users/Lior/.bash_profile: line 23: syntax error: unexpected end of file

I found this solution and tried the following

Lior (master #) ~ $ echo $PS1
\[\033[0;35m\]\u\[\033[0;32m\]$(__git_ps1)\[\033[0;34m\] \W $ \[\033[0m\]

Lior (master #) ~ $ zsh
\[\033[0;35m\]\u\[\033[0;32m\]$(__git_ps1)\[\033[0;34m\] \W $ \[\033[0m\]bash

bash: __git_ps1: command not found

Lior ~ $

There is no (master #) anymore but when I restart the shell (master #) shows again.

How can I get rid of master permanently?