问:
HTML & CSS - How to place DIVs next to each other on the same line?
I'm building a chat interface, and my task is now to add a date between messages. The date must be centered, and messages must be traditionally on the left and right.

Messages are working correctly, but dates are a problem.

How it looks:

Chat is divided by sections. Each section has a date. Each section can have multiply messages.

Code of section is following:

```<code>        <div>
            <div class="discussionMessageDate">{date here}</div>
            <ul className="noDot">
                <li className="noDot + ..logic to figure out if to apple 'right' class"><span class="discussionMessage">{message}</span></li>
            </ul>
        </div>
</code>```

classes are

```<code>.discussionMessage {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 5px 13px;
  list-style-type: none;
  max-width: 300px;
  float: left;
  clear: both;
}

.discussionMessageDate {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 5px 13px;
  max-width: 300px;
  display: block
}

.noDot {
  list-style-type: none;
  padding: 0;
  margin: 0 0 5px 0;
}

.right {
   float: right;
  clear: both;
}
</code>```

What am I doing wrong?

答:
added a clearfix to the wrapping div, this looks like i think it should work

https://jsfiddle.net/hmtkyz96/

```<code><div class="discussionMessageContainer">
  <div class="discussionMessageDate">{date here}</div>
  <ul class="noDot">
    <li class="right"><span class="discussionMessage">{message}</span></li>
  </ul>
</div>

.discussionMessageContainer::after {
  content:'';
  clear:both;
  display:table;
}
</code>```

Body:
I'm building a chat interface, and my task is now to add a date between messages. The date must be centered, and messages must be traditionally on the left and right.

Messages are working correctly, but dates are a problem.

How it looks:

Chat is divided by sections. Each section has a date. Each section can have multiply messages.

Code of section is following:

{date here}

{message}

classes are

.discussionMessage {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 5px 13px;
  list-style-type: none;
  max-width: 300px;
  float: left;
  clear: both;
}

.discussionMessageDate {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 5px 13px;
  max-width: 300px;
  display: block
}

.noDot {
  list-style-type: none;
  padding: 0;
  margin: 0 0 5px 0;
}

.right {
   float: right;
  clear: both;
}

What am I doing wrong?

Body:
added a clearfix to the wrapping div, this looks like i think it should work

https://jsfiddle.net/hmtkyz96/

<div class="discussionMessageContainer">
  <div class="discussionMessageDate">{date here}</div>
  <ul class="noDot">
    <li class="right"><span class="discussionMessage">{message}</span></li>
  </ul>
</div>

.discussionMessageContainer::after {
  content:'';
  clear:both;
  display:table;
}


来源: stackexchange

问:
Detection of head nod pose from pitch angle
I am making an android application that will detect driver's fatigue from head nod pose.

What I did:

I have detected 68 facial landmarks from image using dlib library.

Used solvePnP to find out rotation matrix and from that matrix I have got roll, pitch and yaw angles.
Now, I have to detect head nod from pitch angle.

My Problem:

How to set a threshold value so that an angle below or above the threshold can be said as a head nod?

It results some negative angles. What does a negative angle mean in 3 dimensional axis?

My code:

```<code> void getEulerAngles(Mat &rotCamerMatrix,Vec3d &eulerAngles)
{
     Mat cameraMatrix,rotMatrix,transVect,rotMatrixX,rotMatrixY,rotMatrixZ;
     double* _r = rotCamerMatrix.ptr<double>();
     double projMatrix[12] = {_r[0],_r[1],_r[2],0,
                  _r[3],_r[4],_r[5],0,
                  _r[6],_r[7],_r[8],0};

      decomposeProjectionMatrix( Mat(3,4,CV_64FC1,projMatrix),
                       cameraMatrix,
                       rotMatrix,
                       transVect,
                       rotMatrixX,
                       rotMatrixY,
                       rotMatrixZ,
                       eulerAngles);

 }
int renderToMat(std::vector<full_object_detection>& dets, Mat& dst)
{
     Scalar color;
     std::vector<cv::Point2d> image_points;
     std::vector<cv::Point3d> model_points;
     string disp;

     int sz = 3,l;
     color = Scalar(0,255,0);
     double p1,p2,p3,leftear,rightear,ear=0,yawn=0.00,yaw=0.00,pitch=0.00,roll=0.00;
     l=dets.size();
     //I am calculating only for one face.. so assuming l=1
     for(unsigned long idx = 0; idx < l; idx++)
     {
          image_points.push_back(
          Point2d(dets[idx].part(30).x(),dets[idx].part(30).x() ) );
          image_points.push_back(Point2d(dets[idx].part(8).x(),dets[idx].part(8).x() ) );
          image_points.push_back(Point2d(dets[idx].part(36).x(),dets[idx].part(36).x() ) );
          image_points.push_back(Point2d(dets[idx].part(45).x(),dets[idx].part(45).x() ) );
          image_points.push_back(Point2d(dets[idx].part(48).x(),dets[idx].part(48).x() ) );
          image_points.push_back(Point2d(dets[idx].part(54).x(),dets[idx].part(54).x() ) );
     }
     double focal_length = dst.cols;
     Point2d center = cv::Point2d(dst.cols/2.00,dst.rows/2.00);
     cv::Mat camera_matrix = (cv::Mat_<double>(3.00,3.00) << focal_length, 0, center.x, 0, focal_length, center.y, 0,
0, 1);
     cv::Mat dist_coeffs = cv::Mat::zeros(4,1,cv::DataType<double>::type);
     cv::Mat rotation_vector; //s Rotation in axis-angle form
     cv::Mat translation_vector;
     cv::Mat rotCamerMatrix1;

     if(l!=0)
     {
          model_points.push_back(cv::Point3d(0.0f, 0.0f, 0.0f));
          model_points.push_back(cv::Point3d(0.0f, -330.0f, -65.0f));
          model_points.push_back(cv::Point3d(-225.0f, 170.0f, -135.0f));
          model_points.push_back(cv::Point3d(225.0f, 170.0f, -135.0f));
          model_points.push_back(cv::Point3d(-150.0f, -150.0f, -125.0f));
          model_points.push_back(cv::Point3d(150.0f, -150.0f, -125.0f));
          cv::solvePnP(model_points, image_points, camera_matrix, dist_coeffs,rotation_vector, translation_vector);
          Rodrigues(rotation_vector,rotCamerMatrix1);
          Vec3d eulerAngles;
          getEulerAngles(rotCamerMatrix1,eulerAngles);

          yaw   = eulerAngles[1];
          pitch = eulerAngles[0];
          roll  = eulerAngles[2];
         /*My problem begins here. I don't know how to set a threshold value for pitch so that I can say a value below or
above the pitch is a head nod!*/

     }
     return 0;
}
</code>```

答:
First you have to understand how are the 3 angles used in a 3D context. Basically they rotate an object in the 3D space with respect to an origin (the origin can change depending on the context), but how are the 3 angles applied?.

This question can be express as: in which order do they rotate the object. If you apply yaw, then pitch and then roll it may give you a different orientation of the object that if you do it in the opposite order. Having said that, you must understand what are those values representing, to understand what to do with them.

Now, you ask what would be a good threshold, well it depends. On what? well, in the order they are applied. For instance if you apply pitch first with 45 degrees so it looks down and then you apply a roll 180 degrees, then it is looking up, so it is a little hard to define a threshold.

Since you have your model points, you can create a 3D rotation matrix and apply it to them with different pitch angles (the rest of the angles will be 0 so the order will not be important here) and visualize them and choose the one that you consider is nodding. This is a little bit subjective, so you should be the one doing it.

Now, to the second question. The answer again is, it depends. On what this time? you may ask. Simple, is your system left handed or right handed? in one this means that the rotation is apply clockwise and the other counter clockwise, the negative sign changes the direction. So, in a left handed system it will be clockwise and with the negative sign will be counterclockwise. The right handed system will be counterclockwise and the negative sign will make it clockwise.

As a suggestion, you can make a vector (0,0,-1) assuming your z axis looks towards the back. Then apply the rotation to it and proyect it to a 2D plane parallel to the z axis, here take the  tip of your vector and see what is the angle here. This way you are sure what are you getting.

ContentLicense: CC BY-SA 3.0

Body:
I am making an android application that will detect driver's fatigue from head nod pose.

What I did:

I have detected 68 facial landmarks from image using dlib library.

Used solvePnP to find out rotation matrix and from that matrix I have got roll, pitch and yaw angles.
Now, I have to detect head nod from pitch angle.

My Problem:

How to set a threshold value so that an angle below or above the threshold can be said as a head nod?

It results some negative angles. What does a negative angle mean in 3 dimensional axis?

My code:

 void getEulerAngles(Mat &rotCamerMatrix,Vec3d &eulerAngles)
{
     Mat cameraMatrix,rotMatrix,transVect,rotMatrixX,rotMatrixY,rotMatrixZ;
     double* _r = rotCamerMatrix.ptr<double>();
     double projMatrix[12] = {_r[0],_r[1],_r[2],0,
                  _r[3],_r[4],_r[5],0,
                  _r[6],_r[7],_r[8],0};

      decomposeProjectionMatrix( Mat(3,4,CV_64FC1,projMatrix),
                       cameraMatrix,
                       rotMatrix,
                       transVect,
                       rotMatrixX,
                       rotMatrixY,
                       rotMatrixZ,
                       eulerAngles);

 }
int renderToMat(std::vector<full_object_detection>& dets, Mat& dst)
{
     Scalar color;
     std::vector<cv::Point2d> image_points;
     std::vector<cv::Point3d> model_points;
     string disp;

     int sz = 3,l;
     color = Scalar(0,255,0);
     double p1,p2,p3,leftear,rightear,ear=0,yawn=0.00,yaw=0.00,pitch=0.00,roll=0.00;
     l=dets.size();
     //I am calculating only for one face.. so assuming l=1
     for(unsigned long idx = 0; idx < l; idx++)
     {
          image_points.push_back(
          Point2d(dets[idx].part(30).x(),dets[idx].part(30).x() ) );
          image_points.push_back(Point2d(dets[idx].part(8).x(),dets[idx].part(8).x() ) );
          image_points.push_back(Point2d(dets[idx].part(36).x(),dets[idx].part(36).x() ) );
          image_points.push_back(Point2d(dets[idx].part(45).x(),dets[idx].part(45).x() ) );
          image_points.push_back(Point2d(dets[idx].part(48).x(),dets[idx].part(48).x() ) );
          image_points.push_back(Point2d(dets[idx].part(54).x(),dets[idx].part(54).x() ) );
     }
     double focal_length = dst.cols;
     Point2d center = cv::Point2d(dst.cols/2.00,dst.rows/2.00);
     cv::Mat camera_matrix = (cv::Mat_<double>(3.00,3.00) << focal_length, 0, center.x, 0, focal_length, center.y, 0,
0, 1);
     cv::Mat dist_coeffs = cv::Mat::zeros(4,1,cv::DataType<double>::type);
     cv::Mat rotation_vector; //s Rotation in axis-angle form
     cv::Mat translation_vector;
     cv::Mat rotCamerMatrix1;

     if(l!=0)
     {
          model_points.push_back(cv::Point3d(0.0f, 0.0f, 0.0f));
          model_points.push_back(cv::Point3d(0.0f, -330.0f, -65.0f));
          model_points.push_back(cv::Point3d(-225.0f, 170.0f, -135.0f));
          model_points.push_back(cv::Point3d(225.0f, 170.0f, -135.0f));
          model_points.push_back(cv::Point3d(-150.0f, -150.0f, -125.0f));
          model_points.push_back(cv::Point3d(150.0f, -150.0f, -125.0f));
          cv::solvePnP(model_points, image_points, camera_matrix, dist_coeffs,rotation_vector, translation_vector);
          Rodrigues(rotation_vector,rotCamerMatrix1);
          Vec3d eulerAngles;
          getEulerAngles(rotCamerMatrix1,eulerAngles);

          yaw   = eulerAngles[1];
          pitch = eulerAngles[0];
          roll  = eulerAngles[2];
         /*My problem begins here. I don't know how to set a threshold value for pitch so that I can say a value below or
above the pitch is a head nod!*/

     }
     return 0;
}


问:
Excel Custom Validation when with Like Function
I am trying to enforce some excel validation using like function. IF A1 is not like "YES" then Do not allow the user to enter anything in Cell B1. Any help is appreciated. Thanks!</p>

答:
For case sensitive:

```<code>=ISNUMBER(FIND("YES",A1))
</code>```

For non case sensitive:

```<code>=ISNUMBER(SEARCH("YES",A1))
</code>```

Both will return a number if the word is found and an error if not.  The ISNUMBER will return FALSE if error and TRUE if number.

Body:
For case sensitive:

=ISNUMBER(FIND("YES",A1))

For non case sensitive:

=ISNUMBER(SEARCH("YES",A1))

Both will return a number if the word is found and an error if not.  The ISNUMBER will return FALSE if error and TRUE if number.


问:
Error while applying OOPM in python
First of all I am new to python programming.
Here is my code:-

```<code>class login_ok(object):
    """docstring for instalogin"""
 def __init__(self):
 pass

def open_website(self,websiteName):
print(websiteName)

def login(self,email,password):
print(email)

def search(self,searchVariable):
print(searchVariable)

login1 = login_ok()
web = "a"
email_pass = "c"
password_pass = "b"
search_variable = "d"
login1.open_website(web)
login1.login(email_pass,password_pass)
login1.search(search_variable)
</code>```

I am using sublime and i am getting this error 'login_ok' object has no attribute 'open_website' .

答:
While defining your class, you are defining its methods as unrelated functions outside of its scope. In order for your methods to be within the scope of your class, they would need to be written as follows:

```<code>class login_ok(object):
    """docstring for instalogin"""
    def __init__(self):
        pass

    def open_website(self,websiteName):
        print(websiteName)

    def login(self,email,password):
        print(email)

    def search(self,searchVariable):
        print(searchVariable)
</code>```

You can use either tabs or spaces to indent, but you must be consistent and not mix them. You may want to read further documentation on Variables and Scope and Classes in order to get a better understanding of how to structure your programs. The style in which you write Python is directly related to its functionality as its lack of braces means that scope is defined by indentation.

Title: Error while applying OOPM in python

Body:
First of all I am new to python programming.
Here is my code:-

class login_ok(object):
    """docstring for instalogin"""
 def __init__(self):
 pass

def open_website(self,websiteName):
print(websiteName)

def login(self,email,password):
print(email)

def search(self,searchVariable):
print(searchVariable)

login1 = login_ok()
web = "a"
email_pass = "c"
password_pass = "b"
search_variable = "d"
login1.open_website(web)
login1.login(email_pass,password_pass)
login1.search(search_variable)

I am using sublime and i am getting this error 'login_ok' object has no attribute 'open_website' .

Body:
While defining your class, you are defining its methods as unrelated functions outside of its scope. In order for your methods to be within the scope of your class, they would need to be written as follows:

class login_ok(object):
    """docstring for instalogin"""
    def __init__(self):
        pass

    def open_website(self,websiteName):
        print(websiteName)

    def login(self,email,password):
        print(email)

    def search(self,searchVariable):
        print(searchVariable)

You can use either tabs or spaces to indent, but you must be consistent and not mix them. You may want to read further documentation on Variables and Scope and Classes in order to get a better understanding of how to structure your programs. The style in which you write Python is directly related to its functionality as its lack of braces means that scope is defined by indentation.


问:
Akka HTTP - How to get the raw (not URL decoded) request URL?
I am using Akka HTTP and having the following HTTP request:

```<code>http://www.example.com?p1=1&p2=2&p3=http://www.example.net?a=1&b=2%203
</code>```

Is there a way in Akka HTTP to get the full raw (not URL decoded) request URL? I would like to get the full raw request URL as it is

```<code>http://www.example.com?p1=1&p2=2&p3=http://www.example.net?a=1&b=2%203
</code>```

parse it and get everything after "p3=".

答:
Turn on the akka.http.server.raw-request-uri-header configuration setting, and the raw request URI will be included as the value for a header named Raw-Request-URI.

In other words, in your application.conf, set the following:

```<code>akka.http.server.raw-request-uri-header = on
</code>```

Then obtain the raw request URI from the Raw-Request-URI header.

From the documentation:

Sometimes it may be needed to obtain the “raw” value of an incoming URI, without applying any escaping or parsing to it. While this use case is rare, it comes up every once in a while. It is possible to obtain the “raw” request URI in Akka HTTP Server side by turning on the akka.http.server.raw-request-uri-header flag. When enabled, a Raw-Request-URI header will be added to each request. This header will hold the original raw request’s URI that was used. For an example check the reference configuration.

Body:
I am using Akka HTTP and having the following HTTP request:

http://www.example.com?p1=1&p2=2&p3=http://www.example.net?a=1&b=2%203

Is there a way in Akka HTTP to get the full raw (not URL decoded) request URL? I would like to get the full raw request URL as it is

http://www.example.com?p1=1&p2=2&p3=http://www.example.net?a=1&b=2%203

parse it and get everything after "p3=".

Body:
Turn on the akka.http.server.raw-request-uri-header configuration setting, and the raw request URI will be included as the value for a header named Raw-Request-URI.

In other words, in your application.conf, set the following:

akka.http.server.raw-request-uri-header = on

Then obtain the raw request URI from the Raw-Request-URI header.

From the documentation:

Sometimes it may be needed to obtain the “raw” value of an incoming URI, without applying any escaping or parsing to it. While this use case is rare, it comes up every once in a while. It is possible to obtain the “raw” request URI in Akka HTTP Server side by turning on the akka.http.server.raw-request-uri-header flag. When enabled, a Raw-Request-URI header will be added to each request. This header will hold the original raw request’s URI that was used. For an example check the reference configuration.


问:
Regular grammars
In a regular grammar with the following rules
S->aS/aSbS/ε is it acceptable to do the following steps:
S->aSbS->a{aSbS}bS->aa{aSbS}bSbS->aaa{aSbS}bSbSbS

Do i have to replace every S in each step or i can replace one S out of two for example? In this : aSbS can i do aSb (following the rule S->ε) and if i cannot
should i replace all the S's with the same rule? (aSbS)-> a(aS)b(aS) (following the rule (S->aS) ) or i can do (aSbS->a(aS)b(aSbS)) .

ps. I use the parentheses do indicate which S's i have replaced

答:
In a formal grammar, a derivation step consists of replacing a single instance of the left-hand side of a rule with the right-hand side of that rule. In the case of a context-free grammar, the left-hand side is a single non-terminal, so a derivation step consists of replacing a single instance of a non-terminal with one of the possible corresponding right-hand sides.

You never perform two replacements at the same time, and each derivation step is independent of every other derivation step, so in a context-free grammar, there is no way to express the constraint that two non-terminals need to be replaced with the same right-hand side. (In fact, you cannot directly express this constraint with a context-sensitive grammar either, but you can achieve the effect by using markers.)

Regular grammars are a subset of context-free grammars where either every right-hand side which includes a non-terminal has the form aC or every right-hand side which includes a non-terminal has the form Ba. (This comes straight out of the Wikipedia page which you link.) Your grammar is not a regular grammar, because the rule S → aSbS has two non-terminals on the right-hide side, which is not either of the regular forms.

Title: Regular grammars


问:
How do I restrict context menus to appear only for certain selected text in a Chrome extension?
I made a very simple chrome extension which allows users to highlight a DOI number, right-click and choose "Resolve DOI", and it sends them to the associated web page. Right now, this is done in background.html with:

```<code>chrome.contextMenus.create({
"title" : "Resolve DOI",
"type" : "normal",
"contexts" : ["selection"],
"onclick" : getClickHandler()
});
</code>```

I would like to restrict the context menu option to only appear if the text they highlight begins with "10." Any suggestions on how to do this? Do I need to wait for the Context Menus module to become more advanced?

答:
You would need to control content menu creation from a content script. Dynamic menu creation/deletion should execute pretty fast and the delay will be unnoticeable for a user.

Add mousedown event listener in a content script and check there whether selection satisfies your pattern.

Based on whether or not selection matches the patterrn, send a request to a background page asking to create or delete the menu.

Something along those lines (not tested):

content_script.js:

```<code>document.addEventListener("mousedown", function(event){
    var selection = window.getSelection().toString();
    if(selection.match(/^10\./)) {
        chrome.extension.sendRequest({cmd: "create_menu"});
    } else {
        chrome.extension.sendRequest({cmd: "delete_menu"});
    }
}, true);
</code>```

background.html:

```<code>chrome.extension.onRequest.addListener(function(request) {
    if(request.cmd == "create_menu") {
        chrome.contextMenus.removeAll(function() {
            chrome.contextMenus.create({
                "title" : "Resolve DOI",
                "type" : "normal",
                "contexts" : ["selection"],
                "onclick" : getClickHandler()
            });
        });
    } else if(request.cmd == "delete_menu") {
        chrome.contextMenus.removeAll();
    }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I made a very simple chrome extension which allows users to highlight a DOI number, right-click and choose "Resolve DOI", and it sends them to the associated web page. Right now, this is done in background.html with:

chrome.contextMenus.create({
"title" : "Resolve DOI",
"type" : "normal",
"contexts" : ["selection"],
"onclick" : getClickHandler()
});

I would like to restrict the context menu option to only appear if the text they highlight begins with "10." Any suggestions on how to do this? Do I need to wait for the Context Menus module to become more advanced?

Body:
You would need to control content menu creation from a content script. Dynamic menu creation/deletion should execute pretty fast and the delay will be unnoticeable for a user.

Add mousedown event listener in a content script and check there whether selection satisfies your pattern.

Based on whether or not selection matches the patterrn, send a request to a background page asking to create or delete the menu.

Something along those lines (not tested):

content_script.js:

document.addEventListener("mousedown", function(event){
    var selection = window.getSelection().toString();
    if(selection.match(/^10\./)) {
        chrome.extension.sendRequest({cmd: "create_menu"});
    } else {
        chrome.extension.sendRequest({cmd: "delete_menu"});
    }
}, true);

background.html:

chrome.extension.onRequest.addListener(function(request) {
    if(request.cmd == "create_menu") {
        chrome.contextMenus.removeAll(function() {
            chrome.contextMenus.create({
                "title" : "Resolve DOI",
                "type" : "normal",
                "contexts" : ["selection"],
                "onclick" : getClickHandler()
            });
        });
    } else if(request.cmd == "delete_menu") {
        chrome.contextMenus.removeAll();
    }
});


问:
Doing same action every time document is completed
I've got a problem with GeckoWebBrowser. I try to do the same action multiple times, everytime web document is loaded. I want to wait for the document to load, then click the button, then wait for the document to load, then click the button...

This is what I have so far:

```<code>private void geckoWebBrowser1_DocumentCompleted(object sender, EventArgs e)
{
    GeckoHtmlElement button = (GeckoHtmlElement)geckoWebBrowser1.Document
        .GetElementsByClassName("one-class")[0];

    button.Click();
}
</code>```

But it clicks the button only one time. How can I make the code click the button multiple times everytime the page is loaded?

答:
The DocumentCompleted is called every time the page is loaded. If it clicks only one time then there are several possible ways:

1) The page was loaded only once. 2) There is no button. You better check if it exists on he page:

```<code>var buttons = geckoWebBrowser1.Document.GetElementsByClassName("one-class");
if (buttons.Length > 0)
{
    var button = buttons[0] as GeckoHtmlElement;
    if (button != null)
        button.Click();
}
</code>```

So just put the breakpoint into the DocumentCompleted, and you will find out everything.
If you need to reload the page after clicking the button, call geckoWebBrowser1.Reload();

Body:
I've got a problem with GeckoWebBrowser. I try to do the same action multiple times, everytime web document is loaded. I want to wait for the document to load, then click the button, then wait for the document to load, then click the button...

This is what I have so far:

private void geckoWebBrowser1_DocumentCompleted(object sender, EventArgs e)
{
    GeckoHtmlElement button = (GeckoHtmlElement)geckoWebBrowser1.Document
        .GetElementsByClassName("one-class")[0];

    button.Click();
}

But it clicks the button only one time. How can I make the code click the button multiple times everytime the page is loaded?

Body:
The DocumentCompleted is called every time the page is loaded. If it clicks only one time then there are several possible ways:

1) The page was loaded only once. 2) There is no button. You better check if it exists on he page:

var buttons = geckoWebBrowser1.Document.GetElementsByClassName("one-class");
if (buttons.Length > 0)
{
    var button = buttons[0] as GeckoHtmlElement;
    if (button != null)
        button.Click();
}

So just put the breakpoint into the DocumentCompleted, and you will find out everything.
If you need to reload the page after clicking the button, call geckoWebBrowser1.Reload();


答:
The DictReader tool in the csv library is handy for this sort of thing - it converts the column headings into dictionary keys, and then you can interrogate each row as you would any other dict.

```<code>from csv import DictReader

with open('test2.csv', newline='') as csvfile:
    srcdat = DictReader(csvfile)
    csvdict = [line for line in srcdat]

for row in csvdict:
    if row['Host']:
        current_host = row['Host']
    q = row[' Time OK']
    q = q.split('.')[0]
    if int(q) <100:
        print(f'Host failure for: {current_host}')
        print('Time OK: ', row[' Time OK'])
</code>```

the output isn't quite the format you want but should give you the foundation.

Title: column operation in csv [python]

Body:
I have a scenario where I am extracting a row value from a csv file.

(CSV) test1:

    Host, Time Up, Time Down, Time Unreachable, Time Undetermined
server1.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000
server2.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000
Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000

(CSV) test2:

Host,Service, Time OK, Time Warning, Time Unknown, Time Critical, Time Undetermined
server1.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
server2.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000

This is my code:

df = pd.read_csv('test1.csv',skipfooter=1)
df2 = pd.read_csv('test2.csv',skipfooter=1)
combined = pd.merge(df[['Host',' Time Up']],df2[['Host',' Time OK']], on='Host')
combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])

Here I am trying to get the value of "server_hit_rate" which is 99% & belongs to 3rd row data.
But with this above code I am able to get the data which is in first row only. i.e.

                    Host    Time Up    Time OK
0  server1.test.com:1717  100.000%   100.000%
1  server2.test.com:1717  100.000%   100.000%

The required output should be:

                    Host    Time Up    Time OK
0  server1.test.com:1717  100.000%    99.000%
1  server2.test.com:1717  100.000%    99.000%

Any advice to achieve the following will be helpful.

Edit1:

import pandas as pd
import pandas
import os, shutil, glob
import sys
import datetime
import time
def t1():
    import pandas as pd
    import pandas
    today=datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S %Z %Y")
    print "date :", today
    df = pd.read_csv('t1.csv',skipfooter=1, engine='python')
    df2 = pd.read_csv('t2.csv',skipfooter=1, engine='python')
    temp = df2.ffill()[df2['Service']=='server_hit_rate']
    combined = pd.merge(df[['Host',' Time Up']],temp[['Host',' Time OK']], on='Host')
    combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
    combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])
    combined.to_csv('test.csv',index=False)
t1()

O/P:

Wed Nov 15 10:07:01  2017
Empty DataFrame
Columns: [Host, % Time Up, % Time OK]
Index: []

Body:
The DictReader tool in the csv library is handy for this sort of thing - it converts the column headings into dictionary keys, and then you can interrogate each row as you would any other dict.

from csv import DictReader

with open('test2.csv', newline='') as csvfile:
    srcdat = DictReader(csvfile)
    csvdict = [line for line in srcdat]

for row in csvdict:
    if row['Host']:
        current_host = row['Host']
    q = row[' Time OK']
    q = q.split('.')[0]
    if int(q) <100:
        print(f'Host failure for: {current_host}')
        print('Time OK: ', row[' Time OK'])

the output isn't quite the format you want but should give you the foundation.


问:
Can't be opened because it is from an unidentified developer
I have made a Java game that is a mix between Pacman and Snake.

It works fine on my computer. I have tried sending it to my friend, he has a Mac and I have a Windows. His computer says

can't be opened because it is from an unidentified developer

How would I fix this? I have tried looking it up, but I can not find a fix. (If more information is needed let me know I will add it.)

答: go to finder then application then Hold down the Control key and click the application icon. From the contextual menu choose Open.</p>


问:
XML files having numeric entities doesn't recognize tags
I am working on some XML files to parse some data. In one XML file, the content is like

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dataroot>
    <analyst>
        <id>100</id>
        <name>bob</name>
    </analyst>
    <analyst>
        <id>101</id>
        <name>alice</name>
    </analyst>
</dataroot>
</code>```

and in other, the content is like

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dataroot>
    <analyst>
        <id>100</id>
        <name>bob</name>
    </analyst>
    <analyst>
        <id>101</id>
        <name>alice</name>
    </analyst>
</dataroot>
</code>```

In one file there are numeric charecter entities other than the actual charecter.

But when the files are opened in the browser(IE and Chrome), the files seem different.

The first file is showing like -

The second file is showing like -

Another thing I checked is if in same file we have both numeric entities and the character itself it shows different things.

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dataroot>
    <analyst>
        <id>100</id>
        <name>alice</name>
    </analyst>
    <analyst>
        <id>101</id>
        <name>bob</name>
    </analyst>
</dataroot>
</code>```

This is shown as

It recognizes the tags when written normally and can not recognizes if there are numeric entities. Why is it so?
Why those two are shown differently?

Any help is appreciated.

答:
The contents of the files are actually different based on what you show in the question. The first file shows standard XML. The process that created the second file is actually XML escaping the analyst XML element. This transforms the analyst elements to valid text. This SO question and answer has a good explanation of the reasons for escaping XML.

The fix is to get the processes that create the XML files to produce consistent unescaped XML.

Body:
I am working on some XML files to parse some data. In one XML file, the content is like

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dataroot>
    <analyst>
        <id>100</id>
        <name>bob</name>
    </analyst>
    <analyst>
        <id>101</id>
        <name>alice</name>
    </analyst>
</dataroot>

and in other, the content is like

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dataroot>
    <analyst>
        <id>100</id>
        <name>bob</name>
    </analyst>
    <analyst>
        <id>101</id>
        <name>alice</name>
    </analyst>
</dataroot>

In one file there are numeric charecter entities other than the actual charecter.

But when the files are opened in the browser(IE and Chrome), the files seem different.

The first file is showing like -

The second file is showing like -

Another thing I checked is if in same file we have both numeric entities and the character itself it shows different things.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dataroot>
    <analyst>
        <id>100</id>
        <name>alice</name>
    </analyst>
    <analyst>
        <id>101</id>
        <name>bob</name>
    </analyst>
</dataroot>

This is shown as

It recognizes the tags when written normally and can not recognizes if there are numeric entities. Why is it so?
Why those two are shown differently?

Any help is appreciated.


问:
A way to examine a separate java application's GUI buttons/labels/etc
I'm looking for a program, application, or some way to examine a java application, and be able to view its GUI information. This would include buttons, labels, panels, and list information. Ideally you could examine things by using the mouse pointer, and either hovering over an object or clicking on it. The separate program or application could display things like type of object, object name, and position of object in a console or a window.

I've found some applications that can examine a java application if it's using the Java Access Bridge, but I'm looking for a way that does not require the target java application to have the JAB.

Java Native Interface (JNI) allows you to get mouse clicks, positioning, and keyboard presses, but it does not appear to return information, like button names, inside a java application. Any ideas?

答:
Answers to this question will be highly subjective, depending on the type of GUI technology used and the personal views of the answering person.

That being said, when I do JavaFX development, I use ScenicView. It works really well in my experience and can be loaded a number of different ways. It has most of the features you mentioned and displays a ton of data about the GUI objects, as well as highlighting the selected object's boundaries.


问:
What is the definition of a non-trainable parameter?
What is the definition of non-trainable parameter in a model?

For example, while you are building your own model, its value is 0 as a default, but when you want to use an inception model, it is becoming something else rather than 0. What would be the reason behind it?

答:
In keras, non-trainable parameters (as shown in model.summary()) means the number of weights that are not updated during training with backpropagation.

There are mainly two types of non-trainable weights:

The ones that you have chosen to keep constant when training. This means that keras won't update these weights during training at all.

The ones that work like statistics in BatchNormalization layers. They're updated with mean and variance, but they're not "trained with backpropagation".

Weights are the values inside the network that perform the operations and can be adjusted to result in what we want. The backpropagation algorithm changes the weights towards a lower error at the end.

By default, all weights in a keras model are trainable.

When you create layers, internally it creates its own weights and they're trainable. (The backpropagation algorithm will update these weights)

When you make them untrainable, the algorithm will not update these weights anymore. This is useful, for instance, when you want a convolutional layer with a specific filter, like a Sobel filter, for instance. You don't want the training to change this operation, so these weights/filters should be kept constant.

There is a lot of other reasons why you might want to make weights untrainable.

Changing parameters:

For deciding whether weights are trainable or not, you take layers from the model and set trainable:

```<code>model.get_layer(layerName).trainable = False #or True
</code>```

This must be done before compilation.

ContentLicense: CC BY-SA 4.0

Body:
In keras, non-trainable parameters (as shown in model.summary()) means the number of weights that are not updated during training with backpropagation.

There are mainly two types of non-trainable weights:

The ones that you have chosen to keep constant when training. This means that keras won't update these weights during training at all.

The ones that work like statistics in BatchNormalization layers. They're updated with mean and variance, but they're not "trained with backpropagation".

Weights are the values inside the network that perform the operations and can be adjusted to result in what we want. The backpropagation algorithm changes the weights towards a lower error at the end.

By default, all weights in a keras model are trainable.

When you create layers, internally it creates its own weights and they're trainable. (The backpropagation algorithm will update these weights)

When you make them untrainable, the algorithm will not update these weights anymore. This is useful, for instance, when you want a convolutional layer with a specific filter, like a Sobel filter, for instance. You don't want the training to change this operation, so these weights/filters should be kept constant.

There is a lot of other reasons why you might want to make weights untrainable.

Changing parameters:

For deciding whether weights are trainable or not, you take layers from the model and set trainable:

model.get_layer(layerName).trainable = False #or True

This must be done before compilation.


问:
Powershell Code for a birthday cake
My son is a computer science major, and his birthday is coming up. I want to create a code themed cake for him. I have studied PowerShell code and created what I think is something correct and fun. However, I'm unsure and was turned on to this site to get help with it. This is what I have ... JularJ is my son's display name for his video games.</p>

```<code>$day=11/21/2017
$today=Get-Date
if (Today=$day)
{
    echo"Happy 18th Birthday [Jular]"}
else
{
    echo"Eat Cake Anyway"
}
</code>```

答:
I'm sorry if this is terrible.

It could be much worse ;-)

Two things - make sure you prefix variable names with $, and that you use -eq for equality comparison:

```<code>if ($today -eq $day)
</code>```

And then separate your commands from their arguments with white space:

```<code>echo "Happy birthday ..."
</code>```

Finally, imposing a bit of indentation would make it look more professional:

```<code>$day = Get-Date 11/21/2017
$today = Get-Date
if ($today -eq $day) {
    echo "Happy 18th Birthday [Jular]"
}
else {
    echo "Eat Cake Anyways"
}
</code>```

Title: Powershell Code for a birthday cake

Body:
My son is a computer science major, and his birthday is coming up. I want to create a code themed cake for him. I have studied PowerShell code and created what I think is something correct and fun. However, I'm unsure and was turned on to this site to get help with it. This is what I have ... JularJ is my son's display name for his video games.

$day=11/21/2017
$today=Get-Date
if (Today=$day)
{
    echo"Happy 18th Birthday [Jular]"}
else
{
    echo"Eat Cake Anyway"
}

Body:
I'm sorry if this is terrible.

It could be much worse ;-)

Two things - make sure you prefix variable names with $, and that you use -eq for equality comparison:

if ($today -eq $day)

And then separate your commands from their arguments with white space:

echo "Happy birthday ..."

Finally, imposing a bit of indentation would make it look more professional:

$day = Get-Date 11/21/2017
$today = Get-Date
if ($today -eq $day) {
    echo "Happy 18th Birthday [Jular]"
}
else {
    echo "Eat Cake Anyways"
}


问:
Conditional using of CSS framework in Angular 4
I try to integrate a specific CSS framework (material-design) for my Admin module and another one CSS Framework for my User module in the same project application.

If it's possible how can I do.

答:
It's not possible to use conditionnaly a specific bundle script depending to route.

The easiest way is to create one project by module.

Integrate your external component separately into your project.

Then to host your two projects on the same URL, you have to use a reverse proxy (For example : HAProxy). Or declaring one project by domain or sub domain.


问:
Does a detached thread terminate if its owning class destructs
Suppose I have a class like this

```<code>class foo
{
  void foo()
  {
     std::thread t(std::bind(&foo::doSomething,this));
     t.detach();
  }

  void doSomething()
  {
     while(true)
     {
       //Does some stuff here
     }
  }
};
</code>```

My question is in the above scenario if foo class destructs will the detached thread terminate as well ? From my current observation it seems like it does exit.Also I believe the reason for this is because since the thread has access to the member variables of the instance and once the destructor is called those member variables are no longer present so it makes sense to conclude that the thread exits too. Please correct me if my understanding is wrong.Also what if the thread does not access member variables will it still exit if the class destructs ?

答: No, it doesn't necessarily exit. If it access members of the foo that started it after that foo is destroyed, you have undefined behaviour. That may have the symptoms of doSomething exiting and the thread ceasing naturally, or anything else.

Body:
Suppose I have a class like this

class foo
{
  void foo()
  {
     std::thread t(std::bind(&foo::doSomething,this));
     t.detach();
  }

  void doSomething()
  {
     while(true)
     {
       //Does some stuff here
     }
  }
};

My question is in the above scenario if foo class destructs will the detached thread terminate as well ? From my current observation it seems like it does exit.Also I believe the reason for this is because since the thread has access to the member variables of the instance and once the destructor is called those member variables are no longer present so it makes sense to conclude that the thread exits too. Please correct me if my understanding is wrong.Also what if the thread does not access member variables will it still exit if the class destructs ?


问:
how to protect My Programs?
Let's say I have designed s very important system, and this system costs thousands dollars. I want to protect my system with a serial number as I know crackers will try to edit the binary code to bypass the serial number.

I have read about using a checksum function and apply it over my binary code and check the value if changed, but again, we are talking about a condition a cracker can avoid by editing the code.

My question is: what's the most used technique to protect important programs?

答:
I would always recommend to build a custom software protection before applying any kind of commercial protector such as a Packer.
In any case just a serial validation and a checksum check are not going to keep crackers away.
I would recommend you to visit my new blog www.anti-reversing.com and take a quick look at the anti-piracy tips & tricks page just to have an idea about what I am talking about.</p>

Title: how to protect My Programs?


问:
PL/SQL - Creating a trigger that prevents the update/insertion of a value with a date after the current date
I need to figure out a way to create a trigger that prevents an accident from being inserted or updated if that accident has a day/time past the current system date.

Table code:

```<code>create table Accident
(Report_nr  varchar2(4),
 Accident_date  date,
 Location   varchar2(20),
 primary key (Report_nr));
</code>```

My attempt (incomplete obviously) with pseudocode

```<code>CREATE OR REPLACE TRIGGER trigger1
    BEFORE INSERT OR UPDATE ON accident
    FOR EACH ROW
DECLARE
    cur_date DATE := SYSDATE;
    e EXCEPTION;
BEGIN
    IF :new.accident_date <= cur_date THEN
        [allow insertion/update]
    ELSE
        [dont allow]
    END IF;
END;
</code>```

I might not be anywhere close, to be honest this is not my strong suit. Any help or guidance would be appreciated. I'm running this on an Oracle server.

答:
You are making it a bit more complicated than it needs to be. The default is for the insert to happen, so you just need to identify when it should not, and throw an exception at that point that causes the inert to be rejected; something like:

```<code>CREATE OR REPLACE TRIGGER trigger1
    BEFORE INSERT OR UPDATE ON accident
    FOR EACH ROW
BEGIN
    IF :new.accident_date > SYSDATE THEN
        RAISE_APPLICATION_ERROR(-20001, 'Accident date cannot be in the future');
    END IF;
END;
/
</code>```

Today's date works:

```<code>insert into accident values ('0001', date '2017-11-15', 'X');

1 row inserted.
</code>```

Tomorrow's does not:

```<code>insert into accident values ('0002', date '2017-11-16', 'Y');

Error starting at line : 18 in command -
insert into accident values ('0002', date '2017-11-16', 'Y')
Error report -
ORA-20001: Accident date cannot be in the future
ORA-06512: at "MY_SCHEMA.TRIGGER1", line 3
ORA-04088: error during execution of trigger 'MY_SCHEMA.TRIGGER1'
</code>```

Read more about raising exceptions.

Body:
I need to figure out a way to create a trigger that prevents an accident from being inserted or updated if that accident has a day/time past the current system date.

Table code:

create table Accident
(Report_nr  varchar2(4),
 Accident_date  date,
 Location   varchar2(20),
 primary key (Report_nr));

My attempt (incomplete obviously) with pseudocode

CREATE OR REPLACE TRIGGER trigger1
    BEFORE INSERT OR UPDATE ON accident
    FOR EACH ROW
DECLARE
    cur_date DATE := SYSDATE;
    e EXCEPTION;
BEGIN
    IF :new.accident_date <= cur_date THEN
        [allow insertion/update]
    ELSE
        [dont allow]
    END IF;
END;

I might not be anywhere close, to be honest this is not my strong suit. Any help or guidance would be appreciated. I'm running this on an Oracle server.

Body:
You are making it a bit more complicated than it needs to be. The default is for the insert to happen, so you just need to identify when it should not, and throw an exception at that point that causes the inert to be rejected; something like:

CREATE OR REPLACE TRIGGER trigger1
    BEFORE INSERT OR UPDATE ON accident
    FOR EACH ROW
BEGIN
    IF :new.accident_date > SYSDATE THEN
        RAISE_APPLICATION_ERROR(-20001, 'Accident date cannot be in the future');
    END IF;
END;
/

Today's date works:

insert into accident values ('0001', date '2017-11-15', 'X');

1 row inserted.

Tomorrow's does not:

insert into accident values ('0002', date '2017-11-16', 'Y');

Error starting at line : 18 in command -
insert into accident values ('0002', date '2017-11-16', 'Y')
Error report -
ORA-20001: Accident date cannot be in the future
ORA-06512: at "MY_SCHEMA.TRIGGER1", line 3
ORA-04088: error during execution of trigger 'MY_SCHEMA.TRIGGER1'

Read more about raising exceptions.


问:
pd.to_datetime error after saving csv file without doing anything
when I was using pd.to_datetime, my code is like below

```<code>rate = pd.read_csv('P2training.csv', header=0)
rate['Date'] = pd.to_datetime(rate['Date'], format='%Y-%m-%d')
rate.set_index('Date', inplace=True, drop=True)
rate.tail(10)
print(rate)
</code>```

in P2training.csv, first column is 'Date' and this code ran well when I first downloaded P2training dataset. However after I open the csv file and save it without doing anything else, this code started to report errors below. If I put the original downloaded file to replace the 'saved' file, the code can still run properly.

C:\Users\yaojia\AppData\Local\Continuum\Anaconda3\lib\site-packages\statsmodels\compat\pandas.py:56:
  FutureWarning: The pandas.core.datetools module is deprecated and will
  be removed in a future version.  Please use the pandas.tseries module
  instead.   from pandas.core import datetools Traceback (most recent
  call last):   File
  "C:\Users\yaojia\AppData\Roaming\Python\Python36\site-packages\pandas\core\tools\datetimes.py",
  line 444, in _convert_listlike
      values, tz = tslib.datetime_to_datetime64(arg)   File "pandas_libs\tslib.pyx", line 1810, in
  pandas._libs.tslib.datetime_to_datetime64 (pandas_libs\tslib.c:33275)
  TypeError: Unrecognized value type:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File
  "C:/Users/yaojia/.PyCharmEdu4.0/config/scratches/scratch_7.py", line
  23, in
      rate['Date'] = pd.to_datetime(rate['Date'], format='%Y-%m-%d')   File
  "C:\Users\yaojia\AppData\Roaming\Python\Python36\site-packages\pandas\core\tools\datetimes.py",
  line 509, in to_datetime
      values = _convert_listlike(arg._values, False, format)   File "C:\Users\yaojia\AppData\Roaming\Python\Python36\site-packages\pandas\core\tools\datetimes.py",
  line 447, in _convert_listlike
      raise e   File "C:\Users\yaojia\AppData\Roaming\Python\Python36\site-packages\pandas\core\tools\datetimes.py",
  line 435, in _convert_listlike
      require_iso8601=require_iso8601   File "pandas_libs\tslib.pyx", line 2355, in pandas._libs.tslib.array_to_datetime
  (pandas_libs\tslib.c:46617)   File "pandas_libs\tslib.pyx", line
  2484, in pandas._libs.tslib.array_to_datetime
  (pandas_libs\tslib.c:44616) ValueError: time data '12/31/1979'
  doesn't match format specified

Process finished with exit code 1

Could anyone give any hint what's going wrong?

答:
I guess you open the csv with excel? If yes, excel recognize that column 'Date' are indeed dates and parse the column in it's own date format (in your case 'day/month/year') and save it this way while you are expecting 'year-month-day'.

I suggest you to open/save your csv with a text editor or change the default excel date format...

Body:
when I was using pd.to_datetime, my code is like below

rate = pd.read_csv('P2training.csv', header=0)
rate['Date'] = pd.to_datetime(rate['Date'], format='%Y-%m-%d')
rate.set_index('Date', inplace=True, drop=True)
rate.tail(10)
print(rate)

in P2training.csv, first column is 'Date' and this code ran well when I first downloaded P2training dataset. However after I open the csv file and save it without doing anything else, this code started to report errors below. If I put the original downloaded file to replace the 'saved' file, the code can still run properly.

C:\Users\yaojia\AppData\Local\Continuum\Anaconda3\lib\site-packages\statsmodels\compat\pandas.py:56:
  FutureWarning: The pandas.core.datetools module is deprecated and will
  be removed in a future version.  Please use the pandas.tseries module
  instead.   from pandas.core import datetools Traceback (most recent
  call last):   File
  "C:\Users\yaojia\AppData\Roaming\Python\Python36\site-packages\pandas\core\tools\datetimes.py",
  line 444, in _convert_listlike
      values, tz = tslib.datetime_to_datetime64(arg)   File "pandas_libs\tslib.pyx", line 1810, in
  pandas._libs.tslib.datetime_to_datetime64 (pandas_libs\tslib.c:33275)
  TypeError: Unrecognized value type:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File
  "C:/Users/yaojia/.PyCharmEdu4.0/config/scratches/scratch_7.py", line
  23, in
      rate['Date'] = pd.to_datetime(rate['Date'], format='%Y-%m-%d')   File
  "C:\Users\yaojia\AppData\Roaming\Python\Python36\site-packages\pandas\core\tools\datetimes.py",
  line 509, in to_datetime
      values = _convert_listlike(arg._values, False, format)   File "C:\Users\yaojia\AppData\Roaming\Python\Python36\site-packages\pandas\core\tools\datetimes.py",
  line 447, in _convert_listlike
      raise e   File "C:\Users\yaojia\AppData\Roaming\Python\Python36\site-packages\pandas\core\tools\datetimes.py",
  line 435, in _convert_listlike
      require_iso8601=require_iso8601   File "pandas_libs\tslib.pyx", line 2355, in pandas._libs.tslib.array_to_datetime
  (pandas_libs\tslib.c:46617)   File "pandas_libs\tslib.pyx", line
  2484, in pandas._libs.tslib.array_to_datetime
  (pandas_libs\tslib.c:44616) ValueError: time data '12/31/1979'
  doesn't match format specified

Process finished with exit code 1

Could anyone give any hint what's going wrong?


问:
Configure the firestore security rules to allow users to only access their own data - efficiently
Using firestore with angularfire2 rc 2.

All is working very nicely in development with no effective security rules.

These are the no security rules - where the client code will create, update and delete collections below the $COLLECTION_NAME/document without issue.

```<code>service cloud.firestore {
    match /databases/{database}/documents {
        match /collectionA/{userId=**} {
            allow read, write: if true;
        }
        match /collectionB/{userId=**}  {
            allow read, write: if true;
        }
        match /collectionC/{userId=**}  {
            allow read, write: if true;
        }
        match /collectionD/{userId=**}  {
            allow read, write: if true;
        }
    }
}
</code>```

Where I want to get to is to only allow users to access their own data.

I started out with the following rules:

```<code>service cloud.firestore {
    match /databases/{database}/documents {
        match /collectionA/{userId=**} {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionB/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionC/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionD/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
    }
}
</code>```

However, as soon as I add any sort of restrictive rule including even just validating the request is authorised.

```<code>match /databases/{database}/documents {
    match /collectionA/{userId=**} {
       allow read, write: if request.auth;
    }
    match /collectionB/{userId=**}  {
        allow read, write: if request.auth;
    }
    match /collectionC/{userId=**}  {
        allow read, write: if request.auth;
    }
    match /collectionD/{userId=**}  {
         allow read, write: if request.auth;
    }
}
</code>```

I get code permission errors.

[code=permission-denied]: Missing or insufficient permissions.

FirebaseError: Missing or insufficient permissions.

Each {userId} document contains a collection which in turn contains documents so a full path might be something like

```<code>const entryCollection: AngularFirestoreCollection<Entry> = this.angularfirestore.collection('collectionC/' + user.uid + '/records' + '/2017-40' + '/entries');
</code>```

The requests should be authenticated as the access is only granted in the client following authentication using firebase authentication. Logging indicates the uid is present and indeed when creating the document below collectionA or B or C or D the user.uid document is named using the uid.

答:
The following setup worked for me (I've used allChildren as opposed to allSubcollection):

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/{allChildren=**} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}
</code>```

allChildren will allow to read/write in any subcollections of a user document.

More information on this wildcard matching is here

Body:
Using firestore with angularfire2 rc 2.

All is working very nicely in development with no effective security rules.

These are the no security rules - where the client code will create, update and delete collections below the $COLLECTION_NAME/document without issue.

service cloud.firestore {
    match /databases/{database}/documents {
        match /collectionA/{userId=**} {
            allow read, write: if true;
        }
        match /collectionB/{userId=**}  {
            allow read, write: if true;
        }
        match /collectionC/{userId=**}  {
            allow read, write: if true;
        }
        match /collectionD/{userId=**}  {
            allow read, write: if true;
        }
    }
}

Where I want to get to is to only allow users to access their own data.

I started out with the following rules:

service cloud.firestore {
    match /databases/{database}/documents {
        match /collectionA/{userId=**} {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionB/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionC/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
        match /collectionD/{userId=**}  {
            allow read, write: if request.auth.uid == userId;
        }
    }
}

However, as soon as I add any sort of restrictive rule including even just validating the request is authorised.

match /databases/{database}/documents {
    match /collectionA/{userId=**} {
       allow read, write: if request.auth;
    }
    match /collectionB/{userId=**}  {
        allow read, write: if request.auth;
    }
    match /collectionC/{userId=**}  {
        allow read, write: if request.auth;
    }
    match /collectionD/{userId=**}  {
         allow read, write: if request.auth;
    }
}

I get code permission errors.

[code=permission-denied]: Missing or insufficient permissions.

FirebaseError: Missing or insufficient permissions.

Each {userId} document contains a collection which in turn contains documents so a full path might be something like

const entryCollection: AngularFirestoreCollection<Entry> = this.angularfirestore.collection('collectionC/' + user.uid + '/records' + '/2017-40' + '/entries');

The requests should be authenticated as the access is only granted in the client following authentication using firebase authentication. Logging indicates the uid is present and indeed when creating the document below collectionA or B or C or D the user.uid document is named using the uid.

Body:
The following setup worked for me (I've used allChildren as opposed to allSubcollection):

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/{allChildren=**} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}

allChildren will allow to read/write in any subcollections of a user document.

More information on this wildcard matching is here


问:
json in flashvars
I want to use josn in my flashvars and I'm having trouble

here is my json

```<code>var flashvars = {
                xmlFile: '<?php echo $preface.$xmlpath; ?>',
                preface: '<?php echo $preface; ?>',
                "preload": {
                    "url": "flash/someflash.swf",
                    "x": "375",
                    "y": "237"
                }
                };
</code>```

here is what I have been trying

```<code>    var jsondata:String  = this.loaderInfo.parameters.preload;
    if(jsondata){
        //var jsonData:Object = JSON.decode(jsondata.toString()) ;

     error_txt.text = jsondata.toString();
    }
</code>```

error_txt returns "object Object" but I can't access any part of the json object

答:
Where do you actually use/need JSON?...</p>

```<code>var flashvars = {
            xmlFile: '<?php echo $preface.$xmlpath; ?>',
            preface: '<?php echo $preface; ?>',
            preload: {
                       url: "flash/someflash.swf",
                       x: "375",
                       y: "237"
                      }
            };

//in AS3
var params:Object  = this.loaderInfo.parameters;

if(params != null)
{
  var preload:Object = params.preload;

  for( var name:String in preload )
      trace( preload[name] );
}
</code>```

Title: json in flashvars

Body:
I want to use josn in my flashvars and I'm having trouble

here is my json

var flashvars = {
                xmlFile: '<?php echo $preface.$xmlpath; ?>',
                preface: '<?php echo $preface; ?>',
                "preload": {
                    "url": "flash/someflash.swf",
                    "x": "375",
                    "y": "237"
                }
                };

here is what I have been trying

    var jsondata:String  = this.loaderInfo.parameters.preload;
    if(jsondata){
        //var jsonData:Object = JSON.decode(jsondata.toString()) ;

     error_txt.text = jsondata.toString();
    }

error_txt returns "object Object" but I can't access any part of the json object

Body:
Where do you actually use/need JSON?...

var flashvars = {
            xmlFile: '<?php echo $preface.$xmlpath; ?>',
            preface: '<?php echo $preface; ?>',
            preload: {
                       url: "flash/someflash.swf",
                       x: "375",
                       y: "237"
                      }
            };

//in AS3
var params:Object  = this.loaderInfo.parameters;

if(params != null)
{
  var preload:Object = params.preload;

  for( var name:String in preload )
      trace( preload[name] );
}


问:
Appending from a csv file for each time a function is called
How would I append something to a variable on a list each iteration?
I need to be able to add a number based on the amount of times the function has been called.  For instance if the function was called 3 times, then a certain row from a csv list would be called and that number would be appended to the list.  For example personlist here would look like ['john', '1', 'HERE WOULD BE WHERE THE NUMBER IS ADDED IN'.

```<code>personList = []

def number(peopleList):
    personList.append(peopleList[:])
    return personList
</code>```

Massive apologies if this doesn't really make sense !  Finding it fairly hard to articulate what I was trying to achieve here.  But thanks for looking :)

答:
If I understood your question correctly, you want to append an incremental counter to each peopleList object being added to personList.

Going with your code example, a good solution would be for you to declare a global variable and increment it every time your function is called, while also appending it to peopleList:

```<code>personList = []
functionCalls = 0

def number(peopleList):
    global functionCalls
    functionCalls += 1

    # if peopleList is ['john', '1'] then ['john', '1', NUMBER_OF_CALLS] will be appended here.
    personList.append(peopleList[:] + [functionCalls])
    return personList
</code>```

Body:
How would I append something to a variable on a list each iteration?
I need to be able to add a number based on the amount of times the function has been called.  For instance if the function was called 3 times, then a certain row from a csv list would be called and that number would be appended to the list.  For example personlist here would look like ['john', '1', 'HERE WOULD BE WHERE THE NUMBER IS ADDED IN'.

personList = []

def number(peopleList):
    personList.append(peopleList[:])
    return personList

Massive apologies if this doesn't really make sense !  Finding it fairly hard to articulate what I was trying to achieve here.  But thanks for looking :)

Body:
If I understood your question correctly, you want to append an incremental counter to each peopleList object being added to personList.

Going with your code example, a good solution would be for you to declare a global variable and increment it every time your function is called, while also appending it to peopleList:

personList = []
functionCalls = 0

def number(peopleList):
    global functionCalls
    functionCalls += 1

    # if peopleList is ['john', '1'] then ['john', '1', NUMBER_OF_CALLS] will be appended here.
    personList.append(peopleList[:] + [functionCalls])
    return personList


问:
@HostBinding disabling class from child component Angular 4
I have an angular app which has user login and logout. I am showing up a welcome page as the home page before a user logs in. I want to enable a background image only on the welcome page. Once the user logs in, the background image must disappear. When the user logs out, he will be redirected to welcome page which must show up the background image again.

I have tried using @HostBinding in the app.component.ts by renaming the selector to 'body'.

```<code>app.component.ts

import {Component, HostBinding, Input} from '@angular/core';
import {InputMask} from "primeng/primeng";

@Component({
  selector: 'body',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  path = '../assets/img/AvayaHome.jpg';
  title = 'app';
  toggleClass = true;
  @HostBinding('class.bodyClass') isWelcomePage = this.toggleClass;
}
</code>```

Here is my CSS.

```<code>app.component.css

.bodyClass  {
    background-image: url("../assets/img/AvayaHome.jpg");
}
</code>```

Here is my index.html

```<code><!doctype html>
<html lang="en">
<head>
 <title> Something </title>
</head>
<body class="bodyClass">

    <app-welcome-page></app-welcome-page>

</body>
</html>
</code>```

I am enabling the css style for bodyClass by assigning toggleClass as true. Once the user logs in, I am changing the value of toggleClass (which is in the app.component.ts) from the child component.

Here is my login.component.ts

```<code>onLogin() {
    console.log('onLogin() invoked:', this._email, ':' , this.password);
    if (this._email == null || this.password == null) {
      this.errorMessage = 'All fields are required';
      return;
    }
    this.errorMessage = null;
    this.loginservice.authenticate(this._email, this.password);
    this.appComponent.toggleClass = true;
    this.router.navigate(['/dashboard']);
  }
</code>```

The value of the toggleClass changes when the user logs in to FALSE. But I am still seeing the background image. Not sure what I am doing wrong. Any help will be appreciated.

答:
Make a function with if and else;

```<code>if (user is login) {
  document.body.classList.add('bodyClass');
} else {
  document.body.classList.remove('bodyClass');
}
</code>```

Than call that function when ever you need, logIn logOut etc

Body:
I have an angular app which has user login and logout. I am showing up a welcome page as the home page before a user logs in. I want to enable a background image only on the welcome page. Once the user logs in, the background image must disappear. When the user logs out, he will be redirected to welcome page which must show up the background image again.

I have tried using @HostBinding in the app.component.ts by renaming the selector to 'body'.

app.component.ts

import {Component, HostBinding, Input} from '@angular/core';
import {InputMask} from "primeng/primeng";

@Component({
  selector: 'body',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  path = '../assets/img/AvayaHome.jpg';
  title = 'app';
  toggleClass = true;
  @HostBinding('class.bodyClass') isWelcomePage = this.toggleClass;
}

Here is my CSS.

app.component.css

.bodyClass  {
    background-image: url("../assets/img/AvayaHome.jpg");
}

Here is my index.html

<!doctype html>

 <title> Something </title>

    <app-welcome-page></app-welcome-page>

I am enabling the css style for bodyClass by assigning toggleClass as true. Once the user logs in, I am changing the value of toggleClass (which is in the app.component.ts) from the child component.

Here is my login.component.ts

onLogin() {
    console.log('onLogin() invoked:', this._email, ':' , this.password);
    if (this._email == null || this.password == null) {
      this.errorMessage = 'All fields are required';
      return;
    }
    this.errorMessage = null;
    this.loginservice.authenticate(this._email, this.password);
    this.appComponent.toggleClass = true;
    this.router.navigate(['/dashboard']);
  }

The value of the toggleClass changes when the user logs in to FALSE. But I am still seeing the background image. Not sure what I am doing wrong. Any help will be appreciated.

Body:
Make a function with if and else;

if (user is login) {
  document.body.classList.add('bodyClass');
} else {
  document.body.classList.remove('bodyClass');
}

Than call that function when ever you need, logIn logOut etc


问:
VS2012: Access to path is denied when executing publish
When trying to publish an application (a WCF Service specifically) in VS2012, I get an error stating: "Exception in executing publishing: Access to the path [path] is denied." The file referenced is the publish profile I'm trying to execute and is type ".pubxml"

I've used SysInternals Process Explorer to check if another process has the file locked, I've closed VS2012 and reopened it with administrator rights, and have rebooted my PC.

This is the same issue described here: VS2012 Error when creating publish package: Exception in Executing Publishing Access to path is denied and I'd rather comment on that question asking if he ever found a solution but unfortunately I don't have comment rights yet.

EDIT ------

I'm using Visual Studio 2012 Ultimate with Update 2 (11.0.60315.01 Update 2)

答:
on Visual Studio for MAC:
sudo "Applications/Visual Studio.app/Contents/MacOS/VisualStudio" ~/.bash_profile


问:
Why do objects of the same class have access to each other's private data?
Why do objects of the same class have access to each other's private data?

```<code>class TrivialClass {
public:
  TrivialClass(const std::string& data) :
    mData(data) {};

  const std::string& getData(const TrivialClass& rhs) const {
    return rhs.mData;
  };

private:
  std::string mData;
};

int main() {
  TrivialClass a("fish");
  TrivialClass b("heads");

  std::cout << "b via a = " << a.getData(b) << std::endl;
  return 0;
}
</code>```

This code works.  It is perfectly possible for object a to access private data from object b and return it.  Why should this be so?  I would think that private data is private.  (I started out by trying to understand copy constructors in the pimpl idiom, but then I discovered that I didn't even understand this simple situation.)

答: In addition to all the answers above, consider custom copy constructors, assignment operators and all the other functions you would write for a class which operate on other instances. You would need accessor functions for all those data members.

Body:
Why do objects of the same class have access to each other's private data?

class TrivialClass {
public:
  TrivialClass(const std::string& data) :
    mData(data) {};

  const std::string& getData(const TrivialClass& rhs) const {
    return rhs.mData;
  };

private:
  std::string mData;
};

int main() {
  TrivialClass a("fish");
  TrivialClass b("heads");

  std::cout << "b via a = " << a.getData(b) << std::endl;
  return 0;
}

This code works.  It is perfectly possible for object a to access private data from object b and return it.  Why should this be so?  I would think that private data is private.  (I started out by trying to understand copy constructors in the pimpl idiom, but then I discovered that I didn't even understand this simple situation.)


问:
Subset dataframe based on duplicate values in multiple rows
How can I subset the dataframe below to show only the rows were columns AAA:CCC all have the same value and retain the IndID field?

```<code>Dat <- data.frame(IndID = LETTERS[seq(1,10)],
                  AAA = c(1,5,3,2,3,1,5,4,6,2),
                  BBB = c(1,8,5,2,5,4,8,4,4,5),
                  CCC = c(1,5,3,2,3,5,5,4,6,5))

> Dat
   IndID AAA BBB CCC
1      A   1   1   1
2      B   5   8   5
3      C   3   5   3
4      D   2   2   2
5      E   3   5   3
6      F   1   4   5
7      G   5   8   5
8      H   4   4   4
9      I   6   4   6
10     J   2   5   5
</code>```

I would like to return the following result.

```<code>Result <- data.frame(IndID = c("A", "D", "H"),
                  AAA = c(1,2,4),
                  BBB = c(1,2,4),
                  CCC = c(1,2,4))

> Result
  IndID AAA BBB CCC
1     A   1   1   1
2     D   2   2   2
3     H   4   4   4
</code>```

I have found a number of related posts including Find duplicated rows (based on 2 columns) in Data Frame in R and Find duplicated elements with dplyr, among others, but have not been able to reproduce the desired result with three columns. For example, while close the code below shows all distinct rows, but with the undesired result of including rows were only two of the values are equal.

```<code>Dat %>% distinct(AAA, BBB, CCC)
</code>```

I suspect the solution involves filter but an not sure how to obtain the desired result from the example mentioned above. A dplyr solution is preferred.

Addition
I also wonder if this could be applied to multiple factors. For example with the data below, which contains an IndID and three dates stored as factors, can a similar result be produced by either allowing factors or changing the factors to numeric values?

```<code>Dat <- structure(list(GenIndID = structure(c(1L, 2L, 6L, 7L, 3L, 4L,
8L, 5L), .Label = c("BHS_601", "BHS_603", "BHS_604", "BHS_605",
"BHS_631", "BHS_635", "BHS_636", "BHS_637"), class = "factor"),
    CptrDate = structure(c(1L, 2L, 3L, 3L, 2L, 2L, 3L, 4L), .Label = c("2016-02-01",
    "2016-02-02", "2016-02-04", "2016-12-11"), class = "factor"),
    DtLastAlive = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04",
    "2017-07-13", "2017-08-27"), class = "factor"), DtFnlFate = structure(c(2L,
    2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04", "2017-07-13",
    "2017-08-27"), class = "factor")), .Names = c("GenIndID",
"CptrDate", "DtLastAlive", "DtFnlFate"), row.names = c(82L, 83L,
224L, 225L, 84L, 85L, 226L, 360L), class = "data.frame")

> Dat
    GenIndID   CptrDate DtLastAlive  DtFnlFate
82   BHS_601 2016-02-01  2017-07-13 2017-07-13
83   BHS_603 2016-02-02  2017-07-13 2017-07-13
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
84   BHS_604 2016-02-02  2017-07-13 2017-07-13
85   BHS_605 2016-02-02  2017-07-13 2017-07-13
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
360  BHS_631 2016-12-11  2017-08-27 2017-08-27
</code>```

with the desired result being

```<code>> Dat[c(3, 4, 7),]
    GenIndID   CptrDate DtLastAlive  DtFnlFate
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
</code>```

答:
If all you need is a subset of 3 columns you can use the DF[,] operator. </p>

```<code># DF[where rows have a value, select columns]
# [where rows where AAA==BBB==CCC, select all columns with ""]
temp <- Dat[Dat$AAA == Dat$BBB & Dat$BBB == Dat$CCC,]
</code>```

Body:
How can I subset the dataframe below to show only the rows were columns AAA:CCC all have the same value and retain the IndID field?

Dat <- data.frame(IndID = LETTERS[seq(1,10)],
                  AAA = c(1,5,3,2,3,1,5,4,6,2),
                  BBB = c(1,8,5,2,5,4,8,4,4,5),
                  CCC = c(1,5,3,2,3,5,5,4,6,5))

> Dat
   IndID AAA BBB CCC
1      A   1   1   1
2      B   5   8   5
3      C   3   5   3
4      D   2   2   2
5      E   3   5   3
6      F   1   4   5
7      G   5   8   5
8      H   4   4   4
9      I   6   4   6
10     J   2   5   5

I would like to return the following result.

Result <- data.frame(IndID = c("A", "D", "H"),
                  AAA = c(1,2,4),
                  BBB = c(1,2,4),
                  CCC = c(1,2,4))

> Result
  IndID AAA BBB CCC
1     A   1   1   1
2     D   2   2   2
3     H   4   4   4

I have found a number of related posts including Find duplicated rows (based on 2 columns) in Data Frame in R and Find duplicated elements with dplyr, among others, but have not been able to reproduce the desired result with three columns. For example, while close the code below shows all distinct rows, but with the undesired result of including rows were only two of the values are equal.

Dat %>% distinct(AAA, BBB, CCC)

I suspect the solution involves filter but an not sure how to obtain the desired result from the example mentioned above. A dplyr solution is preferred.

Addition
I also wonder if this could be applied to multiple factors. For example with the data below, which contains an IndID and three dates stored as factors, can a similar result be produced by either allowing factors or changing the factors to numeric values?

Dat <- structure(list(GenIndID = structure(c(1L, 2L, 6L, 7L, 3L, 4L,
8L, 5L), .Label = c("BHS_601", "BHS_603", "BHS_604", "BHS_605",
"BHS_631", "BHS_635", "BHS_636", "BHS_637"), class = "factor"),
    CptrDate = structure(c(1L, 2L, 3L, 3L, 2L, 2L, 3L, 4L), .Label = c("2016-02-01",
    "2016-02-02", "2016-02-04", "2016-12-11"), class = "factor"),
    DtLastAlive = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04",
    "2017-07-13", "2017-08-27"), class = "factor"), DtFnlFate = structure(c(2L,
    2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04", "2017-07-13",
    "2017-08-27"), class = "factor")), .Names = c("GenIndID",
"CptrDate", "DtLastAlive", "DtFnlFate"), row.names = c(82L, 83L,
224L, 225L, 84L, 85L, 226L, 360L), class = "data.frame")

> Dat
    GenIndID   CptrDate DtLastAlive  DtFnlFate
82   BHS_601 2016-02-01  2017-07-13 2017-07-13
83   BHS_603 2016-02-02  2017-07-13 2017-07-13
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
84   BHS_604 2016-02-02  2017-07-13 2017-07-13
85   BHS_605 2016-02-02  2017-07-13 2017-07-13
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
360  BHS_631 2016-12-11  2017-08-27 2017-08-27

with the desired result being

> Dat[c(3, 4, 7),]
    GenIndID   CptrDate DtLastAlive  DtFnlFate
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
226  BHS_637 2016-02-04  2016-02-04 2016-02-04

Body:
If all you need is a subset of 3 columns you can use the DF[,] operator.

# DF[where rows have a value, select columns]
# [where rows where AAA==BBB==CCC, select all columns with ""]
temp <- Dat[Dat$AAA == Dat$BBB & Dat$BBB == Dat$CCC,]


问:
How to make VBA do the same actions while changing criteria until it hits an empty cell?
I am trying to create a simple VBA macro that would help me with some work that I am currently doing manually.

The idea is that there is a given list, of that list column "A" will contain data that I will need to filter on on another sheet, copy the result to another sheet and move on with the next cell below.

```<code>Sheets("Sheet4").Select
ActiveSheet.Range("$A$1:$R$25239").AutoFilter Field:=5, Criteria1:= _
    Sheets("Sheet3").Range("A3").Value
Range("A1").Select
ActiveCell.CurrentRegion.Select
Selection.Copy
Sheets("Sheet5").Select
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveSheet.Paste
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "+"
</code>```

I need VBA to repeat this step until the it hits the bottom of the list, however I also need the range to change to the cell one below at the Filter criteria.

I would really appreciate some help as I am a beginner.

答:
as and example </p>

```<code>dim myRng as range, cell as range

set myRng = ThisWorkbook.Sheets("Sheet4").Range("Your Range here" eg "A1:A20")

For each cell in myRng
      if "//your condition" eg cell.value = "1" Then
         "What you want to do with it here"
               "you can also nest another for each loop here to copy to your destination"
      End If
Next Cell
</code>```

Body:
I am trying to create a simple VBA macro that would help me with some work that I am currently doing manually.

The idea is that there is a given list, of that list column "A" will contain data that I will need to filter on on another sheet, copy the result to another sheet and move on with the next cell below.

Sheets("Sheet4").Select
ActiveSheet.Range("$A$1:$R$25239").AutoFilter Field:=5, Criteria1:= _
    Sheets("Sheet3").Range("A3").Value
Range("A1").Select
ActiveCell.CurrentRegion.Select
Selection.Copy
Sheets("Sheet5").Select
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveSheet.Paste
Range("A1").Select
ActiveCell.End(xlDown).Select
Selection.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "+"

I need VBA to repeat this step until the it hits the bottom of the list, however I also need the range to change to the cell one below at the Filter criteria.

I would really appreciate some help as I am a beginner.

Body:
as and example

dim myRng as range, cell as range

set myRng = ThisWorkbook.Sheets("Sheet4").Range("Your Range here" eg "A1:A20")

For each cell in myRng
      if "//your condition" eg cell.value = "1" Then
         "What you want to do with it here"
               "you can also nest another for each loop here to copy to your destination"
      End If
Next Cell


答:
Definitely a cool idea for your son! Here is how I would write your code in PowerShell

```<code>$day = 11/21/2017

$today = Get-Date -Format MM/dd/yyyy

if ($today -eq $day){
    Write-Host "Happy 18th Birthday [Jular]"
}else{
    Write-Host "Eat Cake Anyway"
}
</code>```

The -Format parameter is important for the Get-Date function. Otherwise it will always say "Eat Cake Anyway".

Title: Powershell Code for a birthday cake

Body:
My son is a computer science major, and his birthday is coming up. I want to create a code themed cake for him. I have studied PowerShell code and created what I think is something correct and fun. However, I'm unsure and was turned on to this site to get help with it. This is what I have ... JularJ is my son's display name for his video games.

$day=11/21/2017
$today=Get-Date
if (Today=$day)
{
    echo"Happy 18th Birthday [Jular]"}
else
{
    echo"Eat Cake Anyway"
}

Body:
Definitely a cool idea for your son! Here is how I would write your code in PowerShell

$day = 11/21/2017

$today = Get-Date -Format MM/dd/yyyy

if ($today -eq $day){
    Write-Host "Happy 18th Birthday [Jular]"
}else{
    Write-Host "Eat Cake Anyway"
}

The -Format parameter is important for the Get-Date function. Otherwise it will always say "Eat Cake Anyway".


问:
Change record field in each loop iteration
I have to generate a report which shows sales for each country, per year. (Fixed amount of years)

I managed to create this query:

```<code>SELECT sum(dwfactsales.amount) as "2009" INTO v_dwrecord."2009"
        FROM dwfactsales
        JOIN dwdimcustomer ON dwdimcustomer.customerkey = dwfactsales.customerkey
        JOIN dwdimdate ON dwdimdate.datekey = dwfactsales.datekey
        WHERE dwdimcustomer.country = 'Australia' and dwdimdate.calenderyear = 2009;
        v_dwreport(1) := v_dwrecord;
</code>```

This query works perfectly to gather the amount of sales for the year 2009 in Australia. However, I want to use this query for each year and each country. I can iterate the countries, but I can't seem to iterate the years.

My record and table is declared as:

```<code>TYPE t_DWRECORD IS RECORD(
    COUNTRY     dwdimcustomer.country%TYPE,
    "2009"      NUMBER,
    "2010"      NUMBER,
    "2011"      NUMBER,
    "2012"      NUMBER,
    "2013"      NUMBER,
    "2014"      NUMBER,
    TOTAL       NUMBER
    );
TYPE t_DWTABLE IS TABLE OF t_DWRECORD INDEX BY BINARY_INTEGER;
</code>```

I created the following snippet:

```<code>v_count := 0;
FOR country_rec IN (SELECT DISTINCT country FROM dwdimcustomer order by country asc) LOOP
    FOR year_rec IN (SELECT DISTINCT calenderyear FROM dwdimdate order by calenderyear asc) LOOP
        SELECT sum(dwfactsales.amount) as "2009" INTO v_dwrecord."2009"
        FROM dwfactsales
        JOIN dwdimcustomer ON dwdimcustomer.customerkey = dwfactsales.customerkey
        JOIN dwdimdate ON dwdimdate.datekey = dwfactsales.datekey
        WHERE dwdimcustomer.country = country_rec.country and dwdimdate.calenderyear = year_rec.calenderyear;
        v_dwreport(v_count) := v_dwrecord;
        v_count := v_count+1;
    END LOOP;
END LOOP;
</code>```

As you can see there's still the part INTO v_dwrecord."2009", I want to change it to the year_rec.calenderyear in each iteration. How can I do this? I tried using the EXECUTE IMMEDIATE with a VARCHAR2(500) variable, which contained a dynamic query. It looked like this: INTO v_dwrecord." || year_rec.calenderyear ||".

Working with the EXECUTE IMMEDIATE gave me the following errors:

00000 -  "SQL command not properly ended"
  *Cause:

  *Action:

00000 -  "%s: invalid identifier"
  *Cause:

  *Action:

ORA-00911: invalid character

Everything seems to break when I try out creating a dynamic query. How do I tackle this problem? Should I continue with dynamic queries or is there an easier way to change v_dwrecord."2009"?

Sample output:

答:
You can use a PIVOT technique to do what you want without the need of the FOR and the RECORD. It would be like this:</p>

```<code>select dwdimcustomer.country,
       sum(case when dwdimdate.calenderyear = 2009
                  then dwfactsales.amount else 0 end) as "2009",
       sum(case when dwdimdate.calenderyear = 2010
                  then dwfactsales.amount else 0 end) as "2010",
       ....
       sum(case when dwdimdate.calenderyear = 2014
                  then dwfactsales.amount else 0 end) as "2014",
       sum(dwfactsales.amount) as total
  FROM dwfactsales
      JOIN dwdimcustomer
             ON dwdimcustomer.customerkey = dwfactsales.customerkey
      JOIN dwdimdate
             ON dwdimdate.datekey = dwfactsales.datekey
 GROUP BY dwdimcustomer.country
 ORDER BY <what ever you want here>;
</code>```

Body:
I have to generate a report which shows sales for each country, per year. (Fixed amount of years)

I managed to create this query:

SELECT sum(dwfactsales.amount) as "2009" INTO v_dwrecord."2009"
        FROM dwfactsales
        JOIN dwdimcustomer ON dwdimcustomer.customerkey = dwfactsales.customerkey
        JOIN dwdimdate ON dwdimdate.datekey = dwfactsales.datekey
        WHERE dwdimcustomer.country = 'Australia' and dwdimdate.calenderyear = 2009;
        v_dwreport(1) := v_dwrecord;

This query works perfectly to gather the amount of sales for the year 2009 in Australia. However, I want to use this query for each year and each country. I can iterate the countries, but I can't seem to iterate the years.

My record and table is declared as:

TYPE t_DWRECORD IS RECORD(
    COUNTRY     dwdimcustomer.country%TYPE,
    "2009"      NUMBER,
    "2010"      NUMBER,
    "2011"      NUMBER,
    "2012"      NUMBER,
    "2013"      NUMBER,
    "2014"      NUMBER,
    TOTAL       NUMBER
    );
TYPE t_DWTABLE IS TABLE OF t_DWRECORD INDEX BY BINARY_INTEGER;

I created the following snippet:

v_count := 0;
FOR country_rec IN (SELECT DISTINCT country FROM dwdimcustomer order by country asc) LOOP
    FOR year_rec IN (SELECT DISTINCT calenderyear FROM dwdimdate order by calenderyear asc) LOOP
        SELECT sum(dwfactsales.amount) as "2009" INTO v_dwrecord."2009"
        FROM dwfactsales
        JOIN dwdimcustomer ON dwdimcustomer.customerkey = dwfactsales.customerkey
        JOIN dwdimdate ON dwdimdate.datekey = dwfactsales.datekey
        WHERE dwdimcustomer.country = country_rec.country and dwdimdate.calenderyear = year_rec.calenderyear;
        v_dwreport(v_count) := v_dwrecord;
        v_count := v_count+1;
    END LOOP;
END LOOP;

As you can see there's still the part INTO v_dwrecord."2009", I want to change it to the year_rec.calenderyear in each iteration. How can I do this? I tried using the EXECUTE IMMEDIATE with a VARCHAR2(500) variable, which contained a dynamic query. It looked like this: INTO v_dwrecord." || year_rec.calenderyear ||".

Working with the EXECUTE IMMEDIATE gave me the following errors:

00000 -  "SQL command not properly ended"
  *Cause:

  *Action:

00000 -  "%s: invalid identifier"
  *Cause:

  *Action:

ORA-00911: invalid character

Everything seems to break when I try out creating a dynamic query. How do I tackle this problem? Should I continue with dynamic queries or is there an easier way to change v_dwrecord."2009"?

Sample output:

Body:
You can use a PIVOT technique to do what you want without the need of the FOR and the RECORD. It would be like this:

select dwdimcustomer.country,
       sum(case when dwdimdate.calenderyear = 2009
                  then dwfactsales.amount else 0 end) as "2009",
       sum(case when dwdimdate.calenderyear = 2010
                  then dwfactsales.amount else 0 end) as "2010",
       ....
       sum(case when dwdimdate.calenderyear = 2014
                  then dwfactsales.amount else 0 end) as "2014",
       sum(dwfactsales.amount) as total
  FROM dwfactsales
      JOIN dwdimcustomer
             ON dwdimcustomer.customerkey = dwfactsales.customerkey
      JOIN dwdimdate
             ON dwdimdate.datekey = dwfactsales.datekey
 GROUP BY dwdimcustomer.country
 ORDER BY <what ever you want here>;


问:
MySQL Insert - How to prevent two foreign IDs in the same table from being identical?
Trying to make a forum database where a user can follow other user(s) and vice versa. For this I have two tables "user" and "follow_user".

This works just fine:

INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 13, 14);
INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 13, 15);
INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 14, 13);
INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 14, 15);
INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 15, 13);
INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 15, 14);

The problem: A user shouldn't be able to follow himself (currently my DB allows it):

INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 13, 13);

```<code>CREATE TABLE `forum`.`user` (
`user_id` SMALLINT(5) NOT NULL,
`user_name` VARCHAR(45) NOT NULL,
`user_email` VARCHAR(65) NOT NULL,
`user_signature` VARCHAR(240) NULL,
`user_created` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
`user_updated` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`));

CREATE TABLE `follow_user` (
`follower_id` smallint(5) NOT NULL,
`being_followed_id` smallint(5) NOT NULL,
PRIMARY KEY (`follower_id`,`being_followed_id`),
UNIQUE KEY `unique_index` (`follower_id`,`being_followed_id`),
KEY `follower_id_fk_idx` (`follower_id`),
KEY `being_followed_id_fk_idx` (`being_followed_id`),
CONSTRAINT `being_followed_id_fk`
FOREIGN KEY (`being_followed_id`)
REFERENCES `user` (`user_id`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `follower_id_fk` FOREIGN KEY (`follower_id`) REFERENCES `user`(`user_id`)
ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='   ';
</code>```

答:
You can use a trigger to execute before insert, to make sure the two columns don't have the same value.

```<code>CREATE TABLE `follow_user` (
    `follower_id` smallint(5) NOT NULL,
    `being_followed_id` smallint(5) NOT NULL,
    PRIMARY KEY (`follower_id`,`being_followed_id`),
    UNIQUE KEY `unique_index` (`follower_id`,`being_followed_id`),
    KEY `follower_id_fk_idx` (`follower_id`),
    KEY `being_followed_id_fk_idx` (`being_followed_id`),
    CONSTRAINT `being_followed_id_fk`
    FOREIGN KEY (`being_followed_id`)
    REFERENCES `user` (`user_id`)
    ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT `follower_id_fk` FOREIGN KEY (`follower_id`) REFERENCES `user`(`user_id`)
    ON DELETE NO ACTION ON UPDATE NO ACTION
)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='   ';

CREATE TRIGGER follow_user_before_insert
BEFORE INSERT ON follow_user FOR EACH ROW
BEGIN
    IF NEW.follower_id = NEW.being_followed_id
    THEN
        SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'Cannot add or update row: follower_id must be different from being_followed_id'
    END IF
END
/
</code>```

However, as @ADyson mentionned in the comments, it may be simpler to do at the application level, with a simple if else statement.

```<code>if(followerId != beingFollowedId) {
    // insert
}
else {
    // throw exception or return error code/message
}
</code>```

Body:
Trying to make a forum database where a user can follow other user(s) and vice versa. For this I have two tables "user" and "follow_user".

This works just fine:

INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 13, 14);
INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 13, 15);
INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 14, 13);
INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 14, 15);
INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 15, 13);
INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 15, 14);

The problem: A user shouldn't be able to follow himself (currently my DB allows it):

INSERT INTO forum.follow_user ( follower_id, being_followed_id ) VALUES ( 13, 13);

CREATE TABLE `forum`.`user` (
`user_id` SMALLINT(5) NOT NULL,
`user_name` VARCHAR(45) NOT NULL,
`user_email` VARCHAR(65) NOT NULL,
`user_signature` VARCHAR(240) NULL,
`user_created` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
`user_updated` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`));

CREATE TABLE `follow_user` (
`follower_id` smallint(5) NOT NULL,
`being_followed_id` smallint(5) NOT NULL,
PRIMARY KEY (`follower_id`,`being_followed_id`),
UNIQUE KEY `unique_index` (`follower_id`,`being_followed_id`),
KEY `follower_id_fk_idx` (`follower_id`),
KEY `being_followed_id_fk_idx` (`being_followed_id`),
CONSTRAINT `being_followed_id_fk`
FOREIGN KEY (`being_followed_id`)
REFERENCES `user` (`user_id`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `follower_id_fk` FOREIGN KEY (`follower_id`) REFERENCES `user`(`user_id`)
ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='   ';

Body:
You can use a trigger to execute before insert, to make sure the two columns don't have the same value.

CREATE TABLE `follow_user` (
    `follower_id` smallint(5) NOT NULL,
    `being_followed_id` smallint(5) NOT NULL,
    PRIMARY KEY (`follower_id`,`being_followed_id`),
    UNIQUE KEY `unique_index` (`follower_id`,`being_followed_id`),
    KEY `follower_id_fk_idx` (`follower_id`),
    KEY `being_followed_id_fk_idx` (`being_followed_id`),
    CONSTRAINT `being_followed_id_fk`
    FOREIGN KEY (`being_followed_id`)
    REFERENCES `user` (`user_id`)
    ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT `follower_id_fk` FOREIGN KEY (`follower_id`) REFERENCES `user`(`user_id`)
    ON DELETE NO ACTION ON UPDATE NO ACTION
)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='   ';

CREATE TRIGGER follow_user_before_insert
BEFORE INSERT ON follow_user FOR EACH ROW
BEGIN
    IF NEW.follower_id = NEW.being_followed_id
    THEN
        SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'Cannot add or update row: follower_id must be different from being_followed_id'
    END IF
END
/

However, as @ADyson mentionned in the comments, it may be simpler to do at the application level, with a simple if else statement.

if(followerId != beingFollowedId) {
    // insert
}
else {
    // throw exception or return error code/message
}


问:
Wordpress: cloaking links
I am cloaking my affiliate link in wordpress and I don't want my user to see it in the status bar or something so is there a way for me to go to a page like www.mysite.com/my-redirect.php?p=foo without me having to create a page or post? or is there a better way?

My redirect.php file will do the redirection after the user lands to this file.

I am using the latest version.

答:
The best way is to create a masked link, which is a unique link that appear to be embedded into your internal link structure, but really is an offsite redirect.  A masked link looks something like http://www.myblog.com/recommendeds/wp-traffic-tools/

There are a couple of commercial solutions including:

WP Traffic Tools

Eclipse Link Cloaker

WP Link Engine

And I believe there are some free tools around but due to all the starch in the topic they are not available in the Wordpress Plugin Database, but are available elsewhere. PlanetOzh I believe has a free one floating around.

Title: Wordpress: cloaking links