问:
Averaging and adding data in an unknown number of identical rows
I have data that essentially looks like this

URL       Pageviews   Unique Pageviews   Avg. Time   Entrances   Bounce Rate   %Exit

AAA          8               1              1.04        8            0.8         0.6
 AAA          5               3              0.80       10            0.9        0.6
 AAA         10               5              1.11        8            1           0.6
 AAA          7               2              0.50        4            0.8         0.6
  BB         12               1              0.37       10            0.75        0.6
  BB          4               2              0.76        3            0.9         0.6

I want to merge all identical urls into one row and sum the Pageviews/Unique Pageviews / Entrances column data, and average the Avg.Time / Bounce Rate / %Exit columns.

The number of identical rows vary throughout the table.

This is the code I have so far. I'm new to vba and tried to solve this with a two-dimensional array, but got the subscript out of range error.

```<code>Sub Data()
 Dim Ws As Worksheet
 Dim tbl As ListObject
 Dim lastRow As Long, k As Long, t As Long
 Dim arr() As Long
   Set Ws = ThisWorkbook.Worksheets("Data")
   Set tbl = Ws.ListObjects("Table9")

   lastRow = Cells(Rows.Count, "A").End(xlUp).Row

 For t = 1 To lastRow

 arr(0, 1) = Ws.Cells(t, 2).Value
   Do Until Ws.Cells(t, 1).Value <> Ws.Cells(t + 1, 1).Value
        k = k + 1
        t = t + 1
          ReDim Preserve arr(k - 1, 5) As Long
        arr(k - 1, 5) = Ws.Cells(k - 1, 5).Value

   Loop
       Cells(t - k, 2) = Application.WorksheetFunction.Sum(arr)
       Cells(t - k, 3) = Application.WorksheetFunction.Sum(arr)
       Cells(t - k, 4) = Application.WorksheetFunction.Average(dataArray)
       Cells(t - k, 5) = Application.WorksheetFunction.Sum(arr)
       Cells(t - k, 6) = Application.WorksheetFunction.Average(dataArray)
       Cells(t - k, 7) = Application.WorksheetFunction.Average(dataArray)
       Rows(t - k + 1 & k - 1, 5).EntireRow.Delete shift:=xlShiftUp

       t = t - k
       k = 0

  Next t

  Set tbl = Nothing

End Sub
</code>```

I'd really appreciate any help on this, I've been stuck for a while.

答:
Okay, I did some research, you're declaring the array okay, but it needs to be re-dimensioned to a multi-dimensional size.</p>

```<code>Dim arr() As Long
Redim arr(1,1)
</code>```

Body:
I have data that essentially looks like this

URL       Pageviews   Unique Pageviews   Avg. Time   Entrances   Bounce Rate   %Exit

AAA          8               1              1.04        8            0.8         0.6
 AAA          5               3              0.80       10            0.9        0.6
 AAA         10               5              1.11        8            1           0.6
 AAA          7               2              0.50        4            0.8         0.6
  BB         12               1              0.37       10            0.75        0.6
  BB          4               2              0.76        3            0.9         0.6

I want to merge all identical urls into one row and sum the Pageviews/Unique Pageviews / Entrances column data, and average the Avg.Time / Bounce Rate / %Exit columns.

The number of identical rows vary throughout the table.

This is the code I have so far. I'm new to vba and tried to solve this with a two-dimensional array, but got the subscript out of range error.

Sub Data()
 Dim Ws As Worksheet
 Dim tbl As ListObject
 Dim lastRow As Long, k As Long, t As Long
 Dim arr() As Long
   Set Ws = ThisWorkbook.Worksheets("Data")
   Set tbl = Ws.ListObjects("Table9")

   lastRow = Cells(Rows.Count, "A").End(xlUp).Row

 For t = 1 To lastRow

 arr(0, 1) = Ws.Cells(t, 2).Value
   Do Until Ws.Cells(t, 1).Value <> Ws.Cells(t + 1, 1).Value
        k = k + 1
        t = t + 1
          ReDim Preserve arr(k - 1, 5) As Long
        arr(k - 1, 5) = Ws.Cells(k - 1, 5).Value

   Loop
       Cells(t - k, 2) = Application.WorksheetFunction.Sum(arr)
       Cells(t - k, 3) = Application.WorksheetFunction.Sum(arr)
       Cells(t - k, 4) = Application.WorksheetFunction.Average(dataArray)
       Cells(t - k, 5) = Application.WorksheetFunction.Sum(arr)
       Cells(t - k, 6) = Application.WorksheetFunction.Average(dataArray)
       Cells(t - k, 7) = Application.WorksheetFunction.Average(dataArray)
       Rows(t - k + 1 & k - 1, 5).EntireRow.Delete shift:=xlShiftUp

       t = t - k
       k = 0

  Next t

  Set tbl = Nothing

End Sub

I'd really appreciate any help on this, I've been stuck for a while.

Body:
Okay, I did some research, you're declaring the array okay, but it needs to be re-dimensioned to a multi-dimensional size.

Dim arr() As Long
Redim arr(1,1)


来源: stackexchange

问:
Error creating bean with name 'sessionFactory' java config based hibernate
I am getting this error:

I don´t know how can I solve this.This is my app folder:

And these are my java based config file:

答:
you this dependency

```<code><dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.2.9.Final</version>
</dependency>
</code>```

for configuration refer bellow link :

http://www.codejava.net/frameworks/spring/spring-4-and-hibernate-4-integration-tutorial-part-2-java-based-configuration

https://dzone.com/articles/springhibernate-application

ContentLicense: CC BY-SA 3.0

Body:
you this dependency

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.2.9.Final</version>
</dependency>

for configuration refer bellow link :

http://www.codejava.net/frameworks/spring/spring-4-and-hibernate-4-integration-tutorial-part-2-java-based-configuration

https://dzone.com/articles/springhibernate-application


问:
Dependency for SMS Retriever API
I am trying to implement SMS Retriever API, but I am unable to find classes like SmsRetrieverClient. I'm not able to import them.

Refer to the following sample code:

```<code> SmsRetrieverClient client = SmsRetriever.getClient(context);
 Task<Void> task = client.startSmsRetriever();
 task.addOnSuccessListener(new OnSuccessListener<Void>() {});
</code>```

I have added following dependency, after which I am able to refer the classes:

```<code>compile 'com.google.android.gms:play-services:11.0.2'
</code>```

But as this include all service API, I want to know the dependency specific to SMS Retriever API

I have referred to this doc for all dependency and added following, but it did not work.

```<code>com.google.android.gms:play-services-auth:11.0.2
com.google.android.gms:play-services-identity:11.0.2
</code>```

Also, is it necessary to have 11.x.x versions?

答:
Try adding the following dependency:

```<code>implementation "com.google.android.gms:play-services-auth-api-phone:$playServicesVersion"
</code>```

replace $playServicesVersion with the play services version you are using.

ContentLicense: CC BY-SA 4.0

Title: Dependency for SMS Retriever API

Body:
I am trying to implement SMS Retriever API, but I am unable to find classes like SmsRetrieverClient. I'm not able to import them.

Refer to the following sample code:

 SmsRetrieverClient client = SmsRetriever.getClient(context);
 Task<Void> task = client.startSmsRetriever();
 task.addOnSuccessListener(new OnSuccessListener<Void>() {});

I have added following dependency, after which I am able to refer the classes:

compile 'com.google.android.gms:play-services:11.0.2'

But as this include all service API, I want to know the dependency specific to SMS Retriever API

I have referred to this doc for all dependency and added following, but it did not work.

com.google.android.gms:play-services-auth:11.0.2
com.google.android.gms:play-services-identity:11.0.2

Also, is it necessary to have 11.x.x versions?

Body:
Try adding the following dependency:

implementation "com.google.android.gms:play-services-auth-api-phone:$playServicesVersion"

replace $playServicesVersion with the play services version you are using.


问:
Why are literal HTML strings being appended to the DOM?
When prepending or appending to an element, it literally puts the text and doesn't compile in HTML:

```<code>var banner ={
    'Format': '90x120cm',
    'Value': 35
};
// var premium = { key: values };

function defineProduct(data) {
        var item = $('span.tooltip')[0];
        console.log($('span.tooltip'));
        for(var keys in data){
            console.log(keys);
            item.append('<div class="item"><div class="left">'+keys+':</div><div class="right ">'+data[keys]+'</div></div>');
        }
    }

defineProduct(banner);
</code>```

HTML:

```<code><div class="three-columns">
        <div class="col">
            <div class="image-holder">
                <a href='' id="premium" class="tooltips">
                <img src="" class="premium-img" width="85px" height="79px">
                <p class="description">Cartão <br><span style="color: #ffc600;" class="different">premium</span></p>
                    <span class="tooltip"></span>
                </a>
            </div>
        <!-- Same thing from above different description -->
        <!-- ditto -->
</div>
</code>```

Output:

What have I tried/used:

.get();

.prepend(string);

.html(string);

.text(string); <– I don't know why, but I did

document.createTextNode(string);

set a variable which contains HTML tags strings and set to one of the previous attempts

And the reason I used .get() is because I have more than one object that are equivalent to the quantity of their elements, in this case, I have 3. So, for every append, I have different information. E.g.: .get(0), .get(1), etc

答: [0] needs to be removed from $('span.tooltip')[0] . It is trying to access first child of ".tooltip" span which is not available in DOM.

Body:
When prepending or appending to an element, it literally puts the text and doesn't compile in HTML:

var banner ={
    'Format': '90x120cm',
    'Value': 35
};
// var premium = { key: values };

function defineProduct(data) {
        var item = $('span.tooltip')[0];
        console.log($('span.tooltip'));
        for(var keys in data){
            console.log(keys);
            item.append('

'+keys+':

'+data[keys]+'

');
        }
    }

defineProduct(banner);

HTML:

Cartão
premium

Output:

What have I tried/used:

.get();

.prepend(string);

.html(string);

.text(string); <– I don't know why, but I did

document.createTextNode(string);

set a variable which contains HTML tags strings and set to one of the previous attempts

And the reason I used .get() is because I have more than one object that are equivalent to the quantity of their elements, in this case, I have 3. So, for every append, I have different information. E.g.: .get(0), .get(1), etc


问:
Why are "smoke tests" called "smoke tests"?

Possible Duplicate:

  What is a smoke testing and what will it do for me?

Why are "smoke tests" called "smoke tests"?  I don't get this at all.  What does smoke have to do with it?

答:
See also answer to What is a smoke testing and what will it do for me?:

The term originates in hardware repair
  and has been applied to software. It's
  intended to be a quick test to see if
  the application "catches on fire" when
  run for the first time. As stated
  above it's just to make sure you don't
  waste a bunch of folks time by setting
  them loose on something that's
  obviously broken.

ContentLicense: CC BY-SA 2.5


问:
Removing quotes of string in jsp page
```<code><%
    String val = request.getParameter("name");
%>
</code>```

Above val contains a value like { "name":"a"}. I need to escape the quotes in order to place it inside a text field like below.

```<code><input type="text" name="firstVal" value="<%=val%>"/>
</code>```

I have tried jstl function but this did not help.

答:
How about replace it first before displaying it on your jsp like

```<code>String val = request.getParameter("name").replace("\"", "\\\"");
</code>```

Then replace it again if you need it as a json format.

Title: Removing quotes of string in jsp page

Body:
<%
    String val = request.getParameter("name");
%>

Above val contains a value like { "name":"a"}. I need to escape the quotes in order to place it inside a text field like below.

<input type="text" name="firstVal" value="<%=val%>"/>

I have tried jstl function but this did not help.

Body:
How about replace it first before displaying it on your jsp like

String val = request.getParameter("name").replace("\"", "\\\"");

Then replace it again if you need it as a json format.


问:
difference between global and static variable in c
I want to know the difference between a static and a global variable. Suppose in my case below

```<code>int globvar;
static int statvariable;

int main(void)
{ }
</code>```

I have defined two variables one is static and other global.Both the variables have their scope throughout the file.

So my another question is then what is the benefit of static variable in general and over global variables.

答:
Both variables are "global". They both have the static storage duration. The difference is that the first has external linkage and the second has internal linkage that is it is invisible outside the compilation unit where it is declared. If the declaration of a variable with internal linkage is included in several compilation units then each of them has its own unique variable with this name.

From the C Standard (6.2.2 Linkages of identifiers)

2 In the set of translation units and libraries that constitutes an
entire program, each declaration of a particular identifier with
external linkage denotes the same object or function. Within one
translation unit, each declaration of an identifier with internal
linkage denotes the same object or function. Each declaration of an
identifier with no linkage denotes a unique entity.

and

3 If the declaration of a file scope identifier for an object or a
function contains the storage class specifier static, the identifier
has internal linkage.

Using a variable with internal linkage hides implementation and prevents a conflict with a variable with the same name with external linkage.

Body:
I want to know the difference between a static and a global variable. Suppose in my case below

int globvar;
static int statvariable;

int main(void)
{ }

I have defined two variables one is static and other global.Both the variables have their scope throughout the file.

So my another question is then what is the benefit of static variable in general and over global variables.


问:
Nested arrays in Firebase Database
I'm trying to work with angulafire2 to use my data stored in Firebase Database in my Angular app and I'm having some trouble with nested arrays.

I have an structure that looks like this:

```<code>items{
    item1{
        name: item1,
        subitems{
            subitem1{
                name: subitem1
            },
            subitem2{
                name: subitem2
            }
        }
    }
}
</code>```

I'm using a FirebaseListObservable to get the items array.

```<code>items: FirebaseListObservable<any>;
[...]
this.items = this.af.database.list('/items');
</code>```

And the problem appears when I try to display the data.

```<code><div *ngFor="let item of items | async">
    <span>{{(item)?.name}}</span>

    <div *ngFor="let subitem of (item)?.subitems">
        <span>{{(subitem)?.name}}</span>
    </div>

</div>
</code>```

I get an error because item.subitems is not recognized as an array.

Error: Cannot find a differ supporting object '[object Object]' of
  type 'object'. NgFor only supports binding to Iterables such as
  Arrays.

EDIT: I made a plunker that uses a test database in Firebase as the example above. HERE

答:
Firebase structures should generally avoid being deeply nested. The deeper your structure is the more complicated they are.

But you can map over the structure and convert an object to an array using something like Object.keys(obj) or the experimental Object.value(obj) or write you own function as further on below

For example to convert the keys for a level

```<code>this.items = db.list('/items').map(items => {
  return items.map(item => {
    return {
       item: Object.keys(item.subitem)
    }
  });
});
</code>```

You can also do something like this using a function in the ngFor loop found in this stack question

```<code><li *ngFor="let o of obj">
   <p *ngFor="let item of generateArray(o)">{{item.key}}: {{item.value}}  </p>
</li>
</code>```

using this function

```<code>generateArray(obj){
    return Object.keys(obj).map((key)=>{ return {key:key, value:obj[key]}});
}
</code>```

Which should give you the keys and the values

Title: Nested arrays in Firebase Database

Body:
I'm trying to work with angulafire2 to use my data stored in Firebase Database in my Angular app and I'm having some trouble with nested arrays.

I have an structure that looks like this:

items{
    item1{
        name: item1,
        subitems{
            subitem1{
                name: subitem1
            },
            subitem2{
                name: subitem2
            }
        }
    }
}

I'm using a FirebaseListObservable to get the items array.

items: FirebaseListObservable<any>;
[...]
this.items = this.af.database.list('/items');

And the problem appears when I try to display the data.

    {{(item)?.name}}

        {{(subitem)?.name}}

I get an error because item.subitems is not recognized as an array.

Error: Cannot find a differ supporting object '[object Object]' of
  type 'object'. NgFor only supports binding to Iterables such as
  Arrays.

EDIT: I made a plunker that uses a test database in Firebase as the example above. HERE

Body:
Firebase structures should generally avoid being deeply nested. The deeper your structure is the more complicated they are.

But you can map over the structure and convert an object to an array using something like Object.keys(obj) or the experimental Object.value(obj) or write you own function as further on below

For example to convert the keys for a level

this.items = db.list('/items').map(items => {
  return items.map(item => {
    return {
       item: Object.keys(item.subitem)
    }
  });
});

You can also do something like this using a function in the ngFor loop found in this stack question

<li *ngFor="let o of obj">
   <p *ngFor="let item of generateArray(o)">{{item.key}}: {{item.value}}  </p>
</li>

using this function

generateArray(obj){
    return Object.keys(obj).map((key)=>{ return {key:key, value:obj[key]}});
}

Which should give you the keys and the values


问:
jQuery daterangepicker: executes alert twice?
I want it to alert "ok" when you change/make a date. But i get two alerts instead of one?

How can i fix this?

here's the code:

```<code>$(document).ready(function(){
       $('#datePicking').daterangepicker({
           arrows:true,
           onChange: function(){
               alert('ok');
           }
       });
});
</code>```

I am using jquery 1.3.2 and UI 1.7.2

答:
In my case, I am using daterangepicker with angular. My purpose is to watch any change in the model that stores the date range value and save it for an AJAX call later. I face the same issue as it hits the event twice whenever the date is change even if it is only 'Today': Once it is object with startDate and endDate properties, and the other time it is a string.

It can be made use of as an advantage.

```<code> $scope.$watch(
    'rangeOfDate',
    function (newValue) {
        // Due to a known bug of open source library daterangepicker, the event is hit twice
        //upon change. Once it is an object, and once it is a string. So, use appropriately.
        var selectedDateRange = new Object();
        if (typeof (newValue) == 'object') {
            selectedDateRange.startDate = new Date(newValue.startDate).toLocaleDateString();
            selectedDateRange.endDate = new Date(newValue.endDate).toLocaleDateString();
            //Do as you wish with this custom object
        }
        else if (typeof (newValue) == 'string') {
            alert("string");
        }
    },
    false);
</code>```

Body:
I want it to alert "ok" when you change/make a date. But i get two alerts instead of one?

How can i fix this?

here's the code:

$(document).ready(function(){
       $('#datePicking').daterangepicker({
           arrows:true,
           onChange: function(){
               alert('ok');
           }
       });
});

I am using jquery 1.3.2 and UI 1.7.2

Body:
In my case, I am using daterangepicker with angular. My purpose is to watch any change in the model that stores the date range value and save it for an AJAX call later. I face the same issue as it hits the event twice whenever the date is change even if it is only 'Today': Once it is object with startDate and endDate properties, and the other time it is a string.

It can be made use of as an advantage.

 $scope.$watch(
    'rangeOfDate',
    function (newValue) {
        // Due to a known bug of open source library daterangepicker, the event is hit twice
        //upon change. Once it is an object, and once it is a string. So, use appropriately.
        var selectedDateRange = new Object();
        if (typeof (newValue) == 'object') {
            selectedDateRange.startDate = new Date(newValue.startDate).toLocaleDateString();
            selectedDateRange.endDate = new Date(newValue.endDate).toLocaleDateString();
            //Do as you wish with this custom object
        }
        else if (typeof (newValue) == 'string') {
            alert("string");
        }
    },
    false);


问:
default R personal library location is null
I updated my Ubuntu 16.04 machine to R 3.4.1.  When installing the first non-required package (eg, lubridate), I received the message:

would you like to create a personal library 'null' to install packages into?

This occurred in both RStudio and the command-line R.  I uninstalled r-base-core & reinstalled r-base and r-base-dev through apt-get, and still had problems.

I noticed that the /etc/R/ directory contained four fleeting files that existed temporarily during the installation process, but had vanished by the time  apt-get install r-base r-base-dev completed.  I reinstalled again to quickly grab and paste those files to the desktop.  After re-installing again, I copied them into /etc/R/ with:

```<code>~/Desktop/temp$ sudo cp repositories.dpkg-new /etc/R/repositories
~/Desktop/temp$ sudo cp Rprofile.site.dpkg-new /etc/R/Rprofile.site
~/Desktop/temp$ sudo cp ldpaths.dpkg-new /etc/R/ldpaths
~/Desktop/temp$ sudo cp Makeconf.dpkg-new /etc/R/Makeconf
</code>```

The second step was to uncomment the second like below, found in /etc/R/Renviron.  Apparently this is a recent change in the r-base packaging by @dirk-eddelbuettel.

```<code># edd Jun 2017  Comment-out R_LIBS_USER
#R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}
##R_LIBS_USER=${R_LIBS_USER-'~/Library/R/3.4/library'}
</code>```

I have a two-part question:

Is the process above recommended, or should I have done something differently? (eg, along the lines of Setting R_LIBS & avoiding "Would you like to use a personal library instead?".)

Are these two steps likely required for future R upgrades on this machine?

答:
I found that for me the most suitable solution was to edit /etc/R/Renviron.site:

# nano /etc/R/Renviron

And uncomment the line where it sets R_LIBS_USER environment variable.

Et voilà!

I can again use library(), require(), and install.packages() within R.

Body:
I updated my Ubuntu 16.04 machine to R 3.4.1.  When installing the first non-required package (eg, lubridate), I received the message:

would you like to create a personal library 'null' to install packages into?

This occurred in both RStudio and the command-line R.  I uninstalled r-base-core & reinstalled r-base and r-base-dev through apt-get, and still had problems.

I noticed that the /etc/R/ directory contained four fleeting files that existed temporarily during the installation process, but had vanished by the time  apt-get install r-base r-base-dev completed.  I reinstalled again to quickly grab and paste those files to the desktop.  After re-installing again, I copied them into /etc/R/ with:

~/Desktop/temp$ sudo cp repositories.dpkg-new /etc/R/repositories
~/Desktop/temp$ sudo cp Rprofile.site.dpkg-new /etc/R/Rprofile.site
~/Desktop/temp$ sudo cp ldpaths.dpkg-new /etc/R/ldpaths
~/Desktop/temp$ sudo cp Makeconf.dpkg-new /etc/R/Makeconf

The second step was to uncomment the second like below, found in /etc/R/Renviron.  Apparently this is a recent change in the r-base packaging by @dirk-eddelbuettel.

# edd Jun 2017  Comment-out R_LIBS_USER
#R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}
##R_LIBS_USER=${R_LIBS_USER-'~/Library/R/3.4/library'}

I have a two-part question:

Is the process above recommended, or should I have done something differently? (eg, along the lines of Setting R_LIBS & avoiding "Would you like to use a personal library instead?".)

Are these two steps likely required for future R upgrades on this machine?


问:
Debug Lists in Eclipse
Now I like to use IntelliJ over Eclipse, mainly because the debugging comes to me much easier. When I debug LinkedList for example I can see all the items the list contains, which is what I want to debug. Is there any simple way to debug in a similar way in Eclipse?

Right now all I see is the begin and end Object and all the next references. And for lists larger than, lets say 5 items, it's a real pain to click through all those references. I really don't want to print all the items every step.

答: You could set up a Detail Formatter (in the preferences dialog) for the LinkedList type, outputting each of its contained Node's items as you go. Doing that by default would be hazardous depending on the contained object's type. I suspect most cases use an ArrayList, though, which is already easier to debug with.</p>

Title: Debug Lists in Eclipse


问:
Something do not work with background on website
I'm trying do someting like that (background image cover full page)
https://www.w3schools.com/howto/tryhow_css_fullpage_demo.htm
I have no idea why my code do not work. Maybe it is something with html, thats why I deleted most of code to check it, what did not work. That why I thought that was a problem with css. But i do not know. Here is my code</p>

```<code><!doctype html>
<html lang = "pl">
<head>
<meta charset = "utf-8" />

<meta http-equiv = "X-UA-Compatible" content = "IE=edge,chrome=1" />

<!--<link rel = "stylesheet" type = "text/css" href = "style.css" /> -->

<style>
body {
margin: 0;
padding: 0;
height: 100%;
}

.clear{
clear:both;
}
#head{
/*https://pixabay.com/pl/users/Tama66-1032521/*/
background-image:url("railway.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height:100%;
}

#space1{
width:20%;
float:left;
}

</style>
</head>
<body>
<div id = "container">
<header>
<div id = "head">
<div id = "menu">

<div id = "space1">
</div>

<div id = "menulist">
<ol id = list>
<li><a href = "#"></a></li>
<li><a href = "#"></a></li>
<li><a href = "#"></a></li>
<li><a href = "#"></a></li>
</ol>
</div>

<div class = "clear">
</div>

</div>
</div>
</header>

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

答:
In addition to setting height:100% on the body, you also need to add this

```<code>html{height:100%}
</code>```

When you set height:100% on any element, it means you are asking the element to take up as much height as the parent element's height. The parent element needs to have some height explicitly specified. Only then will it work(with the exception of a position:absolute or position:fixed on the element). Here, you didn't specify height on the body's parent, html. You might ask that whose height should html base it's own height on. That, I don't have an answer to. Perhaps someone looking at this question will have an answer.

Body:
I'm trying do someting like that (background image cover full page)
https://www.w3schools.com/howto/tryhow_css_fullpage_demo.htm
I have no idea why my code do not work. Maybe it is something with html, thats why I deleted most of code to check it, what did not work. That why I thought that was a problem with css. But i do not know. Here is my code

<!doctype html>

<meta charset = "utf-8" />

<meta http-equiv = "X-UA-Compatible" content = "IE=edge,chrome=1" />

Body:
In addition to setting height:100% on the body, you also need to add this

html{height:100%}

When you set height:100% on any element, it means you are asking the element to take up as much height as the parent element's height. The parent element needs to have some height explicitly specified. Only then will it work(with the exception of a position:absolute or position:fixed on the element). Here, you didn't specify height on the body's parent, html. You might ask that whose height should html base it's own height on. That, I don't have an answer to. Perhaps someone looking at this question will have an answer.


问:
Mocking php POST input
I have a script that is getting POST data using

```<code>$payload = file_get_contents("php://input");
</code>```

I want to use phpunit and mock the POST data. Is there a way I can do this? Maybe with the $_POST variable? I am fine with changing the way the script gets the POST data - im just not sure how I can change it so I can mock POST data for testing.

答:
For Google Chrome, there is an extension called Modify Headers, which will allow you to intercept a page before it reaches it's destination...

Once you have intercepted, you can modify Request & Response Headers data.

Title: Mocking php POST input

Body:
I have a script that is getting POST data using

$payload = file_get_contents("php://input");

I want to use phpunit and mock the POST data. Is there a way I can do this? Maybe with the $_POST variable? I am fine with changing the way the script gets the POST data - im just not sure how I can change it so I can mock POST data for testing.


问:
Add a cloned github project to eclipse, setup push/pull to github
I'm a small bit confused with git/github. I've git setup on my desktop and I'm able to push changes to github fine.

I want to be able to also work on my project from my laptop. I've cloned my project using

```<code>git clone url project
</code>```

So I now have it on my PC. I want to add this project to eclipse and I also want to be able to push and pull changes to github but I'm not sure how to do this.

Do I need to init a new .git file and re add all the files?

答:
If the project is already configured to be used in Eclipse, you can just open it directly. There is nothing more you need to do.

Once you already have a repo, there is no reason to go through all the work again. This is one of the points of using version control. You only need to clone the repo to another machine to continue working on it. To get the project on your laptop, do the same thing as you did on the PC:

```<code>$ git clone <URL to GitHub repo> <project directory>
</code>```

When you make changes on the PC, commit them:

```<code>$ cd <project directory>
$ git add .
$ git commit
</code>```

And push them to the GitHub repo:

```<code>$ git push origin master
</code>```

Now you can update the code on your laptop:

```<code>$ git pull origin master
</code>```

You can also do these in reverse: make changes on the laptop, push them to GitHub and pull them to your PC. The commands are the exact same.

Body:
I'm a small bit confused with git/github. I've git setup on my desktop and I'm able to push changes to github fine.

I want to be able to also work on my project from my laptop. I've cloned my project using

git clone url project

So I now have it on my PC. I want to add this project to eclipse and I also want to be able to push and pull changes to github but I'm not sure how to do this.

Do I need to init a new .git file and re add all the files?

Body:
If the project is already configured to be used in Eclipse, you can just open it directly. There is nothing more you need to do.

Once you already have a repo, there is no reason to go through all the work again. This is one of the points of using version control. You only need to clone the repo to another machine to continue working on it. To get the project on your laptop, do the same thing as you did on the PC:

$ git clone <URL to GitHub repo> <project directory>

When you make changes on the PC, commit them:

$ cd <project directory>
$ git add .
$ git commit

And push them to the GitHub repo:

$ git push origin master

Now you can update the code on your laptop:

$ git pull origin master

You can also do these in reverse: make changes on the laptop, push them to GitHub and pull them to your PC. The commands are the exact same.


答:
It comes from hardware. After you've assembled/soldered/wired everything together, you connect it to mains and turn it on.

If you don't see or smell smoke, test is successful. :)

If there is smoke, disconnect power immediately! (and figure out the problem before re-test...)

Body:
Possible Duplicate:

  What is a smoke testing and what will it do for me?

Why are "smoke tests" called "smoke tests"?  I don't get this at all.  What does smoke have to do with it?


答: static is only visible in the current file scope. Another ones are viisble in the program wide scope (for example you can use them in the other files linked together)</p>

Title: difference between global and static variable in c


问:
does node js mysql needs apache
I have recently wanted to use a MySQL database with my node.js server. And after doing some digging, I found the following github page for mysql to be used via node.js:

https://github.com/mysqljs/mysql

However what I wasn't sure is if this is an API that allows for node.js to communicate with a MySQL database, or if this is a full implementation of a MySQL database (hence I wouldn't need to install apache). Since I tried implementing this without an apache server, it gave me an error:

code run (after having doing npm install mysql)

```<code>var mysql = require('mysql');

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'articles'
});

connection.connect();
</code>```

error:

[Error: connect ECONNREFUSED 127.0.0.1:3306]

答: Node.js MySQL does not require Apache; however, make sure that you are running a MySQL server on your local machine.</p>

Title: does node js mysql needs apache

Body:
I have recently wanted to use a MySQL database with my node.js server. And after doing some digging, I found the following github page for mysql to be used via node.js:

https://github.com/mysqljs/mysql

However what I wasn't sure is if this is an API that allows for node.js to communicate with a MySQL database, or if this is a full implementation of a MySQL database (hence I wouldn't need to install apache). Since I tried implementing this without an apache server, it gave me an error:

code run (after having doing npm install mysql)

var mysql = require('mysql');

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'articles'
});

connection.connect();

error:

[Error: connect ECONNREFUSED 127.0.0.1:3306]


问:
Howto Since I can connect from multiple devices, we store each connection instance separately
I wanted to ask about the Firebase Detecting Connection State, specifically the Sample Presence App code on that page. What happens if the same user signs in/out from multiple devices?

I could not see any explanation about the below quote in the documentation:

"since I can connect from multiple devices, we store each connection
  instance separately"

In the sample code on that page it really never explains the situation where the same user is signed in/out from multiple devices.

The docs seem to assume the reader could figure this out by themselves.

I'm looking for an additional explanation about this "make-believe" scenario,  where a user's presence is handled in a chat app, for example the user is signed in/out on multiple devices, and how in the chat app to detect the correct user's presence

答:
The connection state tracked by the .info/connected node indicates whether or not the app has an open connection to the database.  It doesn't know anything about the authenticated user that might be using the app, nor does it know anything about that user with respect to multiple devices.  It's just the connection state of the local device that it's tracking.

If you want to track the same authenticated user across multiple devices, you'll need to find a way to manage that yourself.  The SDK isn't going to give you an easy solution.


问:
EXCEL: COUNTIFS with multiple criteria and or logic
Attempting to count a named range "STATUS" if the value of the cells equals Reserved, Blocked, Pending OR Archive with multiple other countif criteria.

Everything else works, but the array formula I used for counting the status is only returning a count if the cell value = Reserved.

Here is the formula I'm using:

=(COUNTIFS(DATES,">="&A3,DATES,"<"&EDATE(A3,1),AGENT,"TEST",COMPANY,"TEST",STATUS,{"Reserved","Blocked","Pending","Archive"}))

Any help would be greatly appreciated. Thank you in advance.

答:
=SUMPRODUCT((DATES>=A3)*(DATES<EDATE(A3,1))*(AGENT="TEST")*(COMPANY="TEST")*((STATUS="Reserved")+(STATUS="Blocked")+(STATUS="Pending")+(STATUS="Archive")))

It would be great if you could provide some sample data or even a screenshot of your sheet.


问:
Redux: Generic update action
I'm working with Redux and my state is a normalized one with a lot of different models. Now I was wondering myself if it was better to have specific actions like:

```<code>{type: CHANGE_MODEL_NAME, modelId, name}
</code>```

vs

```<code>{type: UPDATE_MODEL, modelId, {name}}
</code>```

I did a bit of searching and I found this question:

Is it ok to create generic redux update action

Now what I'm wondering is that no one is adressing the fact that having specific action types allow for different reducers to 'react' to an action in a cleaner way.

IE: I have a model that is copied from another model like so:

```<code>{
  name: 'foo',
  originalModel: id_0
}
</code>```

It then becomes easier to react to specific actions in my reducer of copied models if I only want to react to the name change action.

Is it wrong for 2 reducers to react to the same actions? Is that why nobody adressed this issue in the original question?

答:
This is perfectly valid. This pattern even has a name. "Applying a change set"

Your message becomes the following:

```<code>{type: APPLY_CHANGSET, data: {id: idOfThingToApplyTo, propOne: '1', propTwo: '2'}}
</code>```

Your reducers can then look like this:

```<code>const propOneReducer = (value = 'default', {type, {data: {propOne}}) => {
  return type === APPLY_CHANGSET && propOne !== undefined ? propOne : value;
}
</code>```

This makes it a lot easier to add new properties (attributes) to your objects in your store. Adding a reducer, and sending the data from your react views to the actionCreator. In simple cases, you might not even need to change the actionCreator.

In these simple cases you can even build a reducer creator, basically creating the reducer for you.

Pro's

Less actions in the system

Simple sweet actionCreators

Not Pro's

Actions don't describe exactly what is happening. It's also harder to parse exactly what happens to the store after a actionCreator is invoked. This because the reducers now take the shape of the data into account.

Slightly more complex reducers

Title: Redux: Generic update action

Body:
I'm working with Redux and my state is a normalized one with a lot of different models. Now I was wondering myself if it was better to have specific actions like:

{type: CHANGE_MODEL_NAME, modelId, name}

vs

{type: UPDATE_MODEL, modelId, {name}}

I did a bit of searching and I found this question:

Is it ok to create generic redux update action

Now what I'm wondering is that no one is adressing the fact that having specific action types allow for different reducers to 'react' to an action in a cleaner way.

IE: I have a model that is copied from another model like so:

{
  name: 'foo',
  originalModel: id_0
}

It then becomes easier to react to specific actions in my reducer of copied models if I only want to react to the name change action.

Is it wrong for 2 reducers to react to the same actions? Is that why nobody adressed this issue in the original question?

Body:
This is perfectly valid. This pattern even has a name. "Applying a change set"

Your message becomes the following:

{type: APPLY_CHANGSET, data: {id: idOfThingToApplyTo, propOne: '1', propTwo: '2'}}

Your reducers can then look like this:

const propOneReducer = (value = 'default', {type, {data: {propOne}}) => {
  return type === APPLY_CHANGSET && propOne !== undefined ? propOne : value;
}

This makes it a lot easier to add new properties (attributes) to your objects in your store. Adding a reducer, and sending the data from your react views to the actionCreator. In simple cases, you might not even need to change the actionCreator.

In these simple cases you can even build a reducer creator, basically creating the reducer for you.

Pro's

Less actions in the system

Simple sweet actionCreators

Not Pro's

Actions don't describe exactly what is happening. It's also harder to parse exactly what happens to the store after a actionCreator is invoked. This because the reducers now take the shape of the data into account.

Slightly more complex reducers


问:
inner join after insert into temp table
I can run two separate SQL statement where the first INSERT INTO a temp table and the second SQL statement runs an INNER JOIN between the temp table and another table.

I was trying to run the two statements in a single SQL statement but I am getting syntax error (using access).

first statement:

```<code>INSERT INTO temp SELECT id from t1 where a_column='Yes'
</code>```

second statement:

```<code>SELECT * from t2 INNER JOIN t2.id = temp.id
</code>```

Is there a way to run the two in a single statement?

答:
These are two very different operations. You can't insert and output data all at once (at least not in Access).

If you are doing this through queries you'll need to make a second query. Each query in Access can only execute one statement.

You also need to specify the two tables you are joining together. Each statement is independent and has not bearing of reference for what came before.

```<code>SELECT *
FROM t2
INNER JOIN temp on t2.id = temp.id
</code>```

Though depending on what you wish to accomplish (I'm not sure why you need a temp table) you might get away with this

```<code>SELECT *
FROM t2
INNER JOIN t1 ON t2.id = t1.id
WHEREt1.a_column='Yes'
</code>```

Title: inner join after insert into temp table

Body:
I can run two separate SQL statement where the first INSERT INTO a temp table and the second SQL statement runs an INNER JOIN between the temp table and another table.

I was trying to run the two statements in a single SQL statement but I am getting syntax error (using access).

first statement:

INSERT INTO temp SELECT id from t1 where a_column='Yes'

second statement:

SELECT * from t2 INNER JOIN t2.id = temp.id

Is there a way to run the two in a single statement?

Body:
These are two very different operations. You can't insert and output data all at once (at least not in Access).

If you are doing this through queries you'll need to make a second query. Each query in Access can only execute one statement.

You also need to specify the two tables you are joining together. Each statement is independent and has not bearing of reference for what came before.

SELECT *
FROM t2
INNER JOIN temp on t2.id = temp.id

Though depending on what you wish to accomplish (I'm not sure why you need a temp table) you might get away with this

SELECT *
FROM t2
INNER JOIN t1 ON t2.id = t1.id
WHEREt1.a_column='Yes'


问:
Is it worth pooling byte[] and char[] arrays or is it better to just create
My code does a lot of Input/Output and this often involves the creation of temporary arrays to hold bytes or chars of some size - i often use 4096. Im starting to wonder - without actual tests - to verify if it would be better to pool these arrays. My code would change to something like this

```<code>take array from pool
try {
   read from one inputStream
   write to another outputstream using array
} finally {
   return array to pool
}
</code>```

it is quicker to take or simply create a byte with 4096 which means some work is required to alloc mem on the heap, clear the 4096 bytes etc.

a pool seems simpler after all its probably just checking a list taking from the list and returning the array.

UPDATE
I wrote a small program that did two things, created arrays and used an apache commons pool. Both looped a lot of times (100*100*100) and created/took, filled array, then released. I added a few goes in the beginning to warm up the jit and ignored the results of those. Each run ran the create and pool forms a dozen times, alternating between the two.

There was little difference between the pool and create forms. However if i added a clear array to the callback that is fired by apache commons pool when an instance is returned to a pool, the pool became that much slower thanthe created form.

答: The answer is yes.  If you have to do a lot of these input/output tasks, pooling will improve performance and keep the memory footprint smaller.</p>

Body:
My code does a lot of Input/Output and this often involves the creation of temporary arrays to hold bytes or chars of some size - i often use 4096. Im starting to wonder - without actual tests - to verify if it would be better to pool these arrays. My code would change to something like this

take array from pool
try {
   read from one inputStream
   write to another outputstream using array
} finally {
   return array to pool
}

it is quicker to take or simply create a byte with 4096 which means some work is required to alloc mem on the heap, clear the 4096 bytes etc.

a pool seems simpler after all its probably just checking a list taking from the list and returning the array.

UPDATE
I wrote a small program that did two things, created arrays and used an apache commons pool. Both looped a lot of times (100*100*100) and created/took, filled array, then released. I added a few goes in the beginning to warm up the jit and ignored the results of those. Each run ran the create and pool forms a dozen times, alternating between the two.

There was little difference between the pool and create forms. However if i added a clear array to the callback that is fired by apache commons pool when an instance is returned to a pool, the pool became that much slower thanthe created form.


问:
Jquery post multiple parameters
I am very new to HTML and jQuery (and also AJAX).

I used this code to post 1 object, but I want to post multiple objects (when I click button "submit"(id=analsis) it takes xyz object id's content and posts it to 127.0.0.1:5002).

$(function() {
  $('#analysis').bind('click', function() {
    $.post('http://127.0.0.1:5002/', {
      contract: $('textarea[name="text"]').val()
    }, function(data) {
      var parsed = JSON.parse(data)
      $("#xyz").text(parsed['abc']);
    });
    return false;
  });
});
```

My form looks like this and (also has 6 dropdowns):

So I want to post all of them to http://127.0.0.1:5002/.

答:
Actually your code doesn't quite do what you described: instead of posting xyz's value it looks up a textarea with name="text" and posts its value to the server. The server result is parsed as json and one of the result properties ("abc") is assigned to your "xyz" (form) element.

You could do the same thing for multiple values adding properties to the object in the second post parameter:

```<code>$(function() {
    $('#analysis').bind('click', function() {
        $.post(
            'http://127.0.0.1:5002/',
            {
                'contract': $('textarea[name="text"]').val(),
                'slider1':  $('#slider1').val(),
                'slider2':  $('#slider2').val(),
                'slider3':  $('#slider3').val(),
                'slider4':  $('#slider4').val(),
                'dropdown1':  $('#dropdown1').val(),
                'dropdown2':  $('#dropdown2').val(),
                'dropdown3':  $('#dropdown3').val(),
                'dropdown4':  $('#dropdown4').val(),
                'dropdown5':  $('#dropdown5').val(),
                'dropdown6':  $('#dropdown6').val(),

            },
            function(data) {
                var parsed = JSON.parse(data);
                $("#xyz").text(parsed['abc']);
            });
         return false;
     });
 });
</code>```

Title: Jquery post multiple parameters

Body:
I am very new to HTML and jQuery (and also AJAX).

I used this code to post 1 object, but I want to post multiple objects (when I click button "submit"(id=analsis) it takes xyz object id's content and posts it to 127.0.0.1:5002).

$(function() {
  $('#analysis').bind('click', function() {
    $.post('http://127.0.0.1:5002/', {
      contract: $('textarea[name="text"]').val()
    }, function(data) {
      var parsed = JSON.parse(data)
      $("#xyz").text(parsed['abc']);
    });
    return false;
  });
});

My form looks like this and (also has 6 dropdowns):

So I want to post all of them to http://127.0.0.1:5002/.

Body:
Actually your code doesn't quite do what you described: instead of posting xyz's value it looks up a textarea with name="text" and posts its value to the server. The server result is parsed as json and one of the result properties ("abc") is assigned to your "xyz" (form) element.

You could do the same thing for multiple values adding properties to the object in the second post parameter:

$(function() {
    $('#analysis').bind('click', function() {
        $.post(
            'http://127.0.0.1:5002/',
            {
                'contract': $('textarea[name="text"]').val(),
                'slider1':  $('#slider1').val(),
                'slider2':  $('#slider2').val(),
                'slider3':  $('#slider3').val(),
                'slider4':  $('#slider4').val(),
                'dropdown1':  $('#dropdown1').val(),
                'dropdown2':  $('#dropdown2').val(),
                'dropdown3':  $('#dropdown3').val(),
                'dropdown4':  $('#dropdown4').val(),
                'dropdown5':  $('#dropdown5').val(),
                'dropdown6':  $('#dropdown6').val(),

            },
            function(data) {
                var parsed = JSON.parse(data);
                $("#xyz").text(parsed['abc']);
            });
         return false;
     });
 });


问:
MEMSql user defined variable
I have found that MEMSql does not support user defined variables (source).

Is there any workaround of this? Is it going to be in future releases?

I want to do SQL injection protection via user defined variables. Is there any other good way of doing this?

答:
In the future 6.0 release, you can define stored procedures etc and use variables within those - see the documentation. A beta is available now here.

As for SQL injection protection, most client drivers support running queries with parameters in a way that is not vulnerable to SQL injection. Usually there is a function like query("select * from t where a = ?", 5) which places your params in the query in a safe way.

Title: MEMSql user defined variable


问:
How do I make my image stay on one page and not repeat itself?
I would like to add an image to the home screen of my practice app.  The image is perfect on the home screen but whenever I click SignUp the app toggles to the next screen and brings along the image with it and causes a repeated pattern of the same image horizontally across the screen.

Here's Login.js:

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ScrollView, Image, Text, TextInput, View, Button, StyleSheet } from 'react-native';
import { login } from '../redux/actions/auth';
import {AuthenticationDetails, CognitoUser, CognitoUserAttribute, CognitoUserPool} from '../lib/aws-cognito-identity';

const awsCognitoSettings = {
    UserPoolId: '',
    ClientId: ''
};

class Login extends Component {
    constructor (props) {
        super(props);
        this.state = {
            page: 'Login',
            username: '',
            password: ''
        };
    }

    get alt () { return (this.state.page === 'Login') ? 'SignUp' : 'Login'; }

    handleClick (e) {
        e.preventDefault();
        const userPool = new CognitoUserPool(awsCognitoSettings);

        // Sign up
        if (this.state.page === 'SignUp') {
            const attributeList = [
                new CognitoUserAttribute({ Name: 'email', Value: this.state.username })
            ];
            userPool.signUp(
                this.state.username,
                this.state.password,
                attributeList,
                null,
                (err, result) => {
                    if (err) {
                        alert(err);
                        this.setState({ username: '', password: '' });
                        return;
                    }
                    console.log(`result = ${JSON.stringify(result)}`);
                    this.props.onLogin(this.state.username, this.state.password);
                }
            );
        } else {
            const authDetails = new AuthenticationDetails({
                Username: this.state.username,
                Password: this.state.password
            });
            const cognitoUser = new CognitoUser({
                Username: this.state.username,
                Pool: userPool
            });
            cognitoUser.authenticateUser(authDetails, {
                onSuccess: (result) => {
                    console.log(`access token = ${result.getAccessToken().getJwtToken()}`);
                    this.props.onLogin(this.state.username, this.state.password);
                },
                onFailure: (err) => {
                    alert(err);
                    this.setState({ username: '', password: '' });
                    return;
                }
            });
        }
    }

    togglePage (e) {
        this.setState({ page: this.alt });
        e.preventDefault();
    }

    render() {
        return (
            <ScrollView style={{padding: 20}}>
                <View>
                    <Image
                        source={require('../pictures/icon.png')}
                    />
                </View>

                <TextInput
                    style={styles.pw}
                    placeholder=' Email Address'
                    autoCapitalize='none'
                    autoCorrect={false}
                    autoFocus={true}
                    keyboardType='email-address'
                    value={this.state.username}
                    onChangeText={(text) => this.setState({ username: text })} />

                <TextInput
                    style={styles.pw}
                    placeholder=' Password'
                    autoCapitalize='none'
                    autoCorrect={false}
                    secureTextEntry={true}
                    value={this.state.password}
                    onChangeText={(text) => this.setState({ password: text })} />

                <View style={{margin: 7}}/>
                    <Button onPress={(e) => this.handleClick(e)} title={this.state.page}/>
                    <View style={{margin: 7, flexDirection: 'row', justifyContent: 'center'}}>
                        <Text onPress={(e) => this.togglePage(e)} style={styles.buttons}>
                            {this.alt}
                        </Text>
                </View>

            </ScrollView>
        );
    }
}

const styles = StyleSheet.create({
    title: {
        fontSize: 27,
        textAlign: 'center'
    },

    pw: {
        paddingRight: 90,
        justifyContent: 'flex-end',
        marginBottom: 20,
        backgroundColor: '#9b42f4',
        height: 40,
        borderWidth: 1,
        borderRadius: 5
    },

    buttons: {
        fontFamily: 'AvenirNext-Heavy'
    }
});

const mapStateToProps = (state, ownProps) => {
    return {
        isLoggedIn: state.auth.isLoggedIn
    };
}

const mapDispatchToProps = (dispatch) => {
    return {
        onLogin: (username, password) => { dispatch(login(username, password)); }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);
</code>```

答:
Probably because your render function is used for 2 page states, I think you would need to create a SignUp class (I'm not familiar with react).

So what you will get is a Login class and a SignUp class, also means you don't need the if else structures, and cleaner code.

Body:
I would like to add an image to the home screen of my practice app.  The image is perfect on the home screen but whenever I click SignUp the app toggles to the next screen and brings along the image with it and causes a repeated pattern of the same image horizontally across the screen.

Here's Login.js:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ScrollView, Image, Text, TextInput, View, Button, StyleSheet } from 'react-native';
import { login } from '../redux/actions/auth';
import {AuthenticationDetails, CognitoUser, CognitoUserAttribute, CognitoUserPool} from '../lib/aws-cognito-identity';

const awsCognitoSettings = {
    UserPoolId: '',
    ClientId: ''
};

class Login extends Component {
    constructor (props) {
        super(props);
        this.state = {
            page: 'Login',
            username: '',
            password: ''
        };
    }

    get alt () { return (this.state.page === 'Login') ? 'SignUp' : 'Login'; }

    handleClick (e) {
        e.preventDefault();
        const userPool = new CognitoUserPool(awsCognitoSettings);

        // Sign up
        if (this.state.page === 'SignUp') {
            const attributeList = [
                new CognitoUserAttribute({ Name: 'email', Value: this.state.username })
            ];
            userPool.signUp(
                this.state.username,
                this.state.password,
                attributeList,
                null,
                (err, result) => {
                    if (err) {
                        alert(err);
                        this.setState({ username: '', password: '' });
                        return;
                    }
                    console.log(`result = ${JSON.stringify(result)}`);
                    this.props.onLogin(this.state.username, this.state.password);
                }
            );
        } else {
            const authDetails = new AuthenticationDetails({
                Username: this.state.username,
                Password: this.state.password
            });
            const cognitoUser = new CognitoUser({
                Username: this.state.username,
                Pool: userPool
            });
            cognitoUser.authenticateUser(authDetails, {
                onSuccess: (result) => {
                    console.log(`access token = ${result.getAccessToken().getJwtToken()}`);
                    this.props.onLogin(this.state.username, this.state.password);
                },
                onFailure: (err) => {
                    alert(err);
                    this.setState({ username: '', password: '' });
                    return;
                }
            });
        }
    }

    togglePage (e) {
        this.setState({ page: this.alt });
        e.preventDefault();
    }

    render() {
        return (
            <ScrollView style={{padding: 20}}>
                <View>
                    <Image
                        source={require('../pictures/icon.png')}
                    />
                </View>

                <TextInput
                    style={styles.pw}
                    placeholder=' Email Address'
                    autoCapitalize='none'
                    autoCorrect={false}
                    autoFocus={true}
                    keyboardType='email-address'
                    value={this.state.username}
                    onChangeText={(text) => this.setState({ username: text })} />

                <TextInput
                    style={styles.pw}
                    placeholder=' Password'
                    autoCapitalize='none'
                    autoCorrect={false}
                    secureTextEntry={true}
                    value={this.state.password}
                    onChangeText={(text) => this.setState({ password: text })} />

                <View style={{margin: 7}}/>
                    <Button onPress={(e) => this.handleClick(e)} title={this.state.page}/>
                    <View style={{margin: 7, flexDirection: 'row', justifyContent: 'center'}}>
                        <Text onPress={(e) => this.togglePage(e)} style={styles.buttons}>
                            {this.alt}
                        </Text>
                </View>

            </ScrollView>
        );
    }
}

const styles = StyleSheet.create({
    title: {
        fontSize: 27,
        textAlign: 'center'
    },

    pw: {
        paddingRight: 90,
        justifyContent: 'flex-end',
        marginBottom: 20,
        backgroundColor: '#9b42f4',
        height: 40,
        borderWidth: 1,
        borderRadius: 5
    },

    buttons: {
        fontFamily: 'AvenirNext-Heavy'
    }
});

const mapStateToProps = (state, ownProps) => {
    return {
        isLoggedIn: state.auth.isLoggedIn
    };
}

const mapDispatchToProps = (dispatch) => {
    return {
        onLogin: (username, password) => { dispatch(login(username, password)); }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);


问:
Encounter order friendly/unfriendly terminal operations vs parallel/sequential vs ordered/unordered streams
Inspired by this question, I started to play with ordered vs unordered streams, parallel vs sequential streams and terminal operations that respect encounter order vs terminal operations that don't respect it.

In one answer to the linked question, a code similar to this one is shown:

```<code>List<Integer> ordered = Arrays.asList(
    1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4);
List<Integer> result = new CopyOnWriteArrayList<>();

ordered.parallelStream().forEach(result::add);

System.out.println(ordered);
System.out.println(result);
</code>```

And the lists are indeed different. The unordered list even changes from one run to another, showing that the result is actually non-deterministic.

So I created this other example:

```<code>CopyOnWriteArrayList<Integer> result2 = ordered.parallelStream()
        .unordered()
        .collect(Collectors.toCollection(CopyOnWriteArrayList::new));

System.out.println(ordered);
System.out.println(result2);
</code>```

And I expected to see similar results, as the stream is both parallel and unordered (maybe unordered() is redundant, since it's already parallel). However, the resulting list is ordered, i.e. it's equal to the source list.

So my question is why the collected list is ordered? Does collect always respect encounter-order, even for parallel, unordered streams? Is it the specific Collectors.toCollection(...) collector the one that forces encounter-order?

答:
Collectors.toCollection returns a Collector which lacks the Collector.Characteristics.UNORDERED characteristic.  Another collector which specified Collector.Characteristics.UNORDERED might behave differently.

That said: "unordered" means no guarantees, not guaranteed to vary.  If the library finds it easiest to treat an unordered collection as ordered, it is allowed to do so, and that behavior is allowed to change release to release, on Tuesdays, or if there is a full moon.

(Note also that Collectors.toCollection does not require you to use a concurrent collection implementation if you're going to use parallel streams; toCollection(ArrayList::new) would work fine.  That's because the collector doesn't have the Collector.Characteristics.CONCURRENT characteristic, so it uses a collection strategy that works for non-concurrent collections even with parallel streams.)

If you use an unordered stream but a collector that isn't UNORDERED, or vice versa, I doubt you get any guarantees from the framework.  If there were a table, it would say "HERE BE DRAGONS UNDEFINED BEHAVIOR."  I'd also expect some differences for different kinds of chained operations here, e.g. Eugene mentions findFirst varies here, even though findFirst is inherently an ordered operation -- unordered().findFirst() becomes equivalent to findAny().

For Stream.collect, I believe the current implementation has three strategies it chooses between:

Sequential: starts one accumulator, accumulates elements into it (in encounter order, because why would you bother doing work to shuffle the elements? just accept them in the order you get them), calls the finisher.

Parallel execution, concurrent collector, and the stream or the collector are unordered: one accumulator, shards the input, worker threads process the elements from each shard and add elements to the accumulator when they're ready, calls the finisher.

Parallel execution, anything else: shards the input into N shards, each shard gets sequentially accumulated into its own distinct accumulator, the accumulators get combined with the combiner function, calls the finisher.

Body:
Inspired by this question, I started to play with ordered vs unordered streams, parallel vs sequential streams and terminal operations that respect encounter order vs terminal operations that don't respect it.

In one answer to the linked question, a code similar to this one is shown:

List<Integer> ordered = Arrays.asList(
    1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4);
List<Integer> result = new CopyOnWriteArrayList<>();

ordered.parallelStream().forEach(result::add);

System.out.println(ordered);
System.out.println(result);

And the lists are indeed different. The unordered list even changes from one run to another, showing that the result is actually non-deterministic.

So I created this other example:

CopyOnWriteArrayList<Integer> result2 = ordered.parallelStream()
        .unordered()
        .collect(Collectors.toCollection(CopyOnWriteArrayList::new));

System.out.println(ordered);
System.out.println(result2);

And I expected to see similar results, as the stream is both parallel and unordered (maybe unordered() is redundant, since it's already parallel). However, the resulting list is ordered, i.e. it's equal to the source list.

So my question is why the collected list is ordered? Does collect always respect encounter-order, even for parallel, unordered streams? Is it the specific Collectors.toCollection(...) collector the one that forces encounter-order?


问:
Using an input how do I copy certain data from a row on one sheet and display it in another sheet
When I try this code an error comes up saying "Run Time Error '424': Object Required"
I can see that it finds the inputted number, but doesn't copy any number in the row. It also pastes "0" in the wrong sheet.
Here's my code:

```<code>Dim x As Integer
Dim a As Integer
Dim b As Integer
x = InputBox(("Input palletizer pattern."), ("Pattern"), (0))
Application.Goto ThisWorkbook.Sheets("Palletizer 2").Range("A:A").Cells(Application.Match(x, ThisWorkbook.Sheets("Palletizer 2").Range("A:A")))
With Selection
ActiveCell.Offset(0, 3) = a
Set ThisWorkbook.Sheets("Palletizer Changeover App").Range("I6") = a
End With
</code>```

Any help would be much appreciated.

答:
You are getting the error because you use a set statement to assign the integer a to the range I6. You can only use set statements to assign objects.

The error will go away if you remove the Set in the second last line. However, please note that it would be more obvious what you are trying to achieve if you explicitly assigned to the Value property of the range, which its default property.

With why the number does not appear at the right spot I cannot help you because your exact intentions are not clear to me from your question.

Body:
When I try this code an error comes up saying "Run Time Error '424': Object Required"
I can see that it finds the inputted number, but doesn't copy any number in the row. It also pastes "0" in the wrong sheet.
Here's my code:

Dim x As Integer
Dim a As Integer
Dim b As Integer
x = InputBox(("Input palletizer pattern."), ("Pattern"), (0))
Application.Goto ThisWorkbook.Sheets("Palletizer 2").Range("A:A").Cells(Application.Match(x, ThisWorkbook.Sheets("Palletizer 2").Range("A:A")))
With Selection
ActiveCell.Offset(0, 3) = a
Set ThisWorkbook.Sheets("Palletizer Changeover App").Range("I6") = a
End With

Any help would be much appreciated.


问:
sbt using multiple classloaders
Sbt seems to be using different classloaders, making some tests failing when run more than once in an sbt session, with the following error:

```<code>[info]   java.lang.ClassCastException: net.i2p.crypto.eddsa.EdDSAPublicKey cannot be cast to net.i2p.crypto.eddsa.EdDSAPublicKey
[info]   at com.advancedtelematic.libtuf.crypt.EdcKeyPair$.generate(RsaKeyPair.scala:120)
</code>```

I tried equivalent code using pattern matching instead of asInstanceOf and I get the same result.

How can I make sure sbt uses the same class loader for all test executions in the same session?

答:
I think it's related to this: Do security providers cause ClassLoader leaks in Java?. Basically Security is re-using providers from old class-loaders. So this could happen in any multi-classpath environment (like OSGi), not just SBT.

Fix for your build.sbt (without forking):

```<code>testOptions in Test += Tests.Cleanup(() =>
  java.security.Security.removeProvider("BC"))
</code>```

Experiment:

```<code>sbt-classloader-issue$ sbt
> test
[success] Total time: 1 s, completed Jul 6, 2017 11:43:53 PM
> test
[success] Total time: 0 s, completed Jul 6, 2017 11:43:55 PM
</code>```

Explanation:

As I can see from your code (published here):

```<code>Security.addProvider(new BouncyCastleProvider)
</code>```

you're reusing the same BouncyCastleProvider provider every-time you run a test, as your Security.addProvider works only first time. As sbt creates new class-loader for every "test" run, but re-uses the same JVM - Security is kind-of JVM-scoped singleton as it was loaded by JVM-bootstrap, so classOf[java.security.Security].getClassLoader() == null and sbt cannot reload/reinitialize this class.

And you can easily check that

```<code>classOf[org.bouncycastle.jce.spec.ECParameterSpec].getClassLoader()
res30: ClassLoader = URLClassLoader with NativeCopyLoader with RawResources
</code>```

org.bouncycastle classes are loaded with custom classloader (from sbt) which changes every-time you run test.

So this code:

```<code>val generator = KeyPairGenerator.getInstance("ECDSA", "BC")
</code>```

gets instance of class loaded from old classloader (the one used for first "test" run) and you're trying to initialize it with spec from new classloader:

```<code>generator.initialize(ecSpec)
</code>```

That's why you're getting "parameter object not a ECParameterSpec" exception. The reasoning around "net.i2p.crypto.eddsa.EdDSAPublicKey cannot be cast to net.i2p.crypto.eddsa.EdDSAPublicKey" is basically same.

Title: sbt using multiple classloaders

Body:
Sbt seems to be using different classloaders, making some tests failing when run more than once in an sbt session, with the following error:

[info]   java.lang.ClassCastException: net.i2p.crypto.eddsa.EdDSAPublicKey cannot be cast to net.i2p.crypto.eddsa.EdDSAPublicKey
[info]   at com.advancedtelematic.libtuf.crypt.EdcKeyPair$.generate(RsaKeyPair.scala:120)

I tried equivalent code using pattern matching instead of asInstanceOf and I get the same result.

How can I make sure sbt uses the same class loader for all test executions in the same session?

Body:
I think it's related to this: Do security providers cause ClassLoader leaks in Java?. Basically Security is re-using providers from old class-loaders. So this could happen in any multi-classpath environment (like OSGi), not just SBT.

Fix for your build.sbt (without forking):

testOptions in Test += Tests.Cleanup(() =>
  java.security.Security.removeProvider("BC"))

Experiment:

sbt-classloader-issue$ sbt
> test
[success] Total time: 1 s, completed Jul 6, 2017 11:43:53 PM
> test
[success] Total time: 0 s, completed Jul 6, 2017 11:43:55 PM

Explanation:

As I can see from your code (published here):

Security.addProvider(new BouncyCastleProvider)

you're reusing the same BouncyCastleProvider provider every-time you run a test, as your Security.addProvider works only first time. As sbt creates new class-loader for every "test" run, but re-uses the same JVM - Security is kind-of JVM-scoped singleton as it was loaded by JVM-bootstrap, so classOf[java.security.Security].getClassLoader() == null and sbt cannot reload/reinitialize this class.

And you can easily check that

classOf[org.bouncycastle.jce.spec.ECParameterSpec].getClassLoader()
res30: ClassLoader = URLClassLoader with NativeCopyLoader with RawResources

org.bouncycastle classes are loaded with custom classloader (from sbt) which changes every-time you run test.

So this code:

val generator = KeyPairGenerator.getInstance("ECDSA", "BC")

gets instance of class loaded from old classloader (the one used for first "test" run) and you're trying to initialize it with spec from new classloader:

generator.initialize(ecSpec)

That's why you're getting "parameter object not a ECParameterSpec" exception. The reasoning around "net.i2p.crypto.eddsa.EdDSAPublicKey cannot be cast to net.i2p.crypto.eddsa.EdDSAPublicKey" is basically same.


问:
Performance difference between table collations in MySQL
I know that having a different column collation impacts table performance, but I haven't been able to find any information on performance difference between table collations.

Also, what if I don't have any varchar/etc. type columns in my table, in that case does it even matter what collation is my table set to? If so what's the most robust collation to have for a table that contains only number column types?

答:
The table character set and collation are used as default values for
  column definitions if the column character set and collation are not
  specified in individual column definitions.
  from the documentation

This suggests the choice would have absolutely no impact on the performance of a table lacking columns that have collation.
...and my guess is that even in tables that have fields with collation, the general performance impact on the table is minimal in queries not filtering/joining/grouping/etc... on those fields.


问:
error reading X.509 key or certificate file: Error in parsing
I'm setting certificate auth to my nifi server.

I have used nifi-tools/tls-toolkit from nifi project to generate a keystore, truststore, client certificate and so on.

I have added the client certificate generated by tls-toolkit in p12 format to my browser and configured my nifi server property. All works fine.

Now I want to use the client certificate within ruby script.

To do that I have converted the certificate from p12 format to pem format like that...

openssl pkcs12 -in CN=admin_DC=nifi_DC=com.p12 -passin pass:26V+Hs1qupglToDlVqO+oKW0yWR2jG3uXjuFTUus76o -out a.pem
MAC verified OK
Enter PEM pass phrase:

PEM pass phrase in blank.

To test it I tried

curl --insecure --cert-type pem --cert "a.pem" "https://127.0.0.1:9443/nifi"
curl: (35) error reading X.509 key or certificate file: Error in parsing.

Error in parsing? I haven't found any info about it.

Let's to verify...

openssl verify a.pem
a.pem: DC = com, DC = nifi, CN = admin
error 20 at 0 depth lookup:unable to get local issuer certificate

Verify with tha CA file...

openssl verify -verbose -x509_strict -issuer_checks -CAfile nifi-cert.pem a.pem
a.pem: OK

With my ruby script fails too (obviously)

require 'rest_client'

a = RestClient::Resource.new(
  'https://127.0.0.1:9443/nifi',
  :ssl_client_cert  => OpenSSL::X509::Certificate.new(File.read("a.pem")),
  :verify_ssl       =>  OpenSSL::SSL::VERIFY_NONE
).get

pp a
```

<p>`</p>

<p>I get...</p>

<pre class="lang-sh prettyprint-override"><code>/usr/lib/ruby/2.3.0/net/http.rb:933:in `connect_nonblock': SSL_connect returned=1 errno=0 state=unknown state: sslv3 alert bad certificate (OpenSSL::SSL::SSLError)
from /usr/lib/ruby/2.3.0/net/http.rb:933:in `connect'
from /usr/lib/ruby/2.3.0/net/http.rb:863:in `do_start'
from /usr/lib/ruby/2.3.0/net/http.rb:852:in `start'
from /var/lib/gems/2.3.0/gems/rest-client-2.0.2/lib/restclient/request.rb:715:in `transmit'
from /var/lib/gems/2.3.0/gems/rest-client-2.0.2/lib/restclient/request.rb:145:in `execute'
from /var/lib/gems/2.3.0/gems/rest-client-2.0.2/lib/restclient/request.rb:52:in `execute'
from /var/lib/gems/2.3.0/gems/rest-client-2.0.2/lib/restclient/resource.rb:51:in `get'
from test.rb:8:in `<main>'
</code>```

Whats wrong?

Thanks.

答:
My hunch is that the issuer certificate (the Apache NiFi CA public certificate which signed the client certificate) is not bundled in the exported PEM file. In addition, the NiFi CA is generated on the system, and it is imported into the NiFi truststore, but it is not imported into the OpenSSL truststore, JRE cacerts, or any browser truststore automatically, so those tools will report that it is an unverified CA.

Can you verify that the exported PEM is in the expected format? A simple more or xxd command will output it in raw form, and you can examine the file structure. It should look like this:

```<code>hw12203:/Users/alopresto/Workspace/nifi (master) alopresto
 1s @ 09:32:18 $ more ..//scratch/secure_nifi/client.pem
Bag Attributes
    friendlyName: nifi-key
    localKeyID: 4D A3 BA 01 40 32 60 6F 84 0B 1B B7 7F 1E 50 81 C7 DF 45 96
Key Attributes: <No Attributes>
Removed private key
Bag Attributes
    friendlyName: nifi-key
    localKeyID: 4D A3 BA 01 40 32 60 6F 84 0B 1B B7 7F 1E 50 81 C7 DF 45 96
subject=/OU=Apache NiFi/CN=alopresto
issuer=/OU=NIFI/CN=localhost
-----BEGIN CERTIFICATE-----
MIIDTTCCAjWgAwIBAgIKAVpj404fAAAAADANBgkqhkiG9w0BAQsFADAjMQ0wCwYD
... lines removed ...
WLvUHa29207v8ZQ6eFuTwM4OTISQIBRahxFqaluCvdQ8
-----END CERTIFICATE-----
Bag Attributes: <Empty Attributes>
subject=/OU=NIFI/CN=localhost
issuer=/OU=NIFI/CN=localhost
-----BEGIN CERTIFICATE-----
MIIDSTCCAjGgAwIBAgIKAVpj40jcAAAAADANBgkqhkiG9w0BAQsFADAjMQ0wCwYD
... lines removed ...
T7q7PHuhxvvdG4ckFMNpntxdTGIUoioZYzeijY4=
-----END CERTIFICATE-----
</code>```

You can see that two certificates are included there -- the first is my client certificate and the second is the certificate of the CA that signed it.

In addition, you may need to export the private key from PKCS12 to PEM using the -nodes flag. Rather than meaning "node(s)", this flag indicates "no DES encryption", aka "no password required". You can see more about using the flag in this StackOverflow answer.

Body:
I'm setting certificate auth to my nifi server.

I have used nifi-tools/tls-toolkit from nifi project to generate a keystore, truststore, client certificate and so on.

I have added the client certificate generated by tls-toolkit in p12 format to my browser and configured my nifi server property. All works fine.

Now I want to use the client certificate within ruby script.

To do that I have converted the certificate from p12 format to pem format like that...

openssl pkcs12 -in CN=admin_DC=nifi_DC=com.p12 -passin pass:26V+Hs1qupglToDlVqO+oKW0yWR2jG3uXjuFTUus76o -out a.pem
MAC verified OK
Enter PEM pass phrase:

PEM pass phrase in blank.

To test it I tried

curl --insecure --cert-type pem --cert "a.pem" "https://127.0.0.1:9443/nifi"
curl: (35) error reading X.509 key or certificate file: Error in parsing.

Error in parsing? I haven't found any info about it.

Let's to verify...

openssl verify a.pem
a.pem: DC = com, DC = nifi, CN = admin
error 20 at 0 depth lookup:unable to get local issuer certificate

Verify with tha CA file...

openssl verify -verbose -x509_strict -issuer_checks -CAfile nifi-cert.pem a.pem
a.pem: OK

With my ruby script fails too (obviously)

require 'rest_client'

a = RestClient::Resource.new(
  'https://127.0.0.1:9443/nifi',
  :ssl_client_cert  => OpenSSL::X509::Certificate.new(File.read("a.pem")),
  :verify_ssl       =>  OpenSSL::SSL::VERIFY_NONE
).get

pp a

`

I get...

/usr/lib/ruby/2.3.0/net/http.rb:933:in `connect_nonblock': SSL_connect returned=1 errno=0 state=unknown state: sslv3 alert bad certificate (OpenSSL::SSL::SSLError)
from /usr/lib/ruby/2.3.0/net/http.rb:933:in `connect'
from /usr/lib/ruby/2.3.0/net/http.rb:863:in `do_start'
from /usr/lib/ruby/2.3.0/net/http.rb:852:in `start'
from /var/lib/gems/2.3.0/gems/rest-client-2.0.2/lib/restclient/request.rb:715:in `transmit'
from /var/lib/gems/2.3.0/gems/rest-client-2.0.2/lib/restclient/request.rb:145:in `execute'
from /var/lib/gems/2.3.0/gems/rest-client-2.0.2/lib/restclient/request.rb:52:in `execute'
from /var/lib/gems/2.3.0/gems/rest-client-2.0.2/lib/restclient/resource.rb:51:in `get'
from test.rb:8:in `'

Whats wrong?

Thanks.

Body:
My hunch is that the issuer certificate (the Apache NiFi CA public certificate which signed the client certificate) is not bundled in the exported PEM file. In addition, the NiFi CA is generated on the system, and it is imported into the NiFi truststore, but it is not imported into the OpenSSL truststore, JRE cacerts, or any browser truststore automatically, so those tools will report that it is an unverified CA.

Can you verify that the exported PEM is in the expected format? A simple more or xxd command will output it in raw form, and you can examine the file structure. It should look like this:

hw12203:/Users/alopresto/Workspace/nifi (master) alopresto
 1s @ 09:32:18 $ more ..//scratch/secure_nifi/client.pem
Bag Attributes
    friendlyName: nifi-key
    localKeyID: 4D A3 BA 01 40 32 60 6F 84 0B 1B B7 7F 1E 50 81 C7 DF 45 96
Key Attributes: <No Attributes>
Removed private key
Bag Attributes
    friendlyName: nifi-key
    localKeyID: 4D A3 BA 01 40 32 60 6F 84 0B 1B B7 7F 1E 50 81 C7 DF 45 96
subject=/OU=Apache NiFi/CN=alopresto
issuer=/OU=NIFI/CN=localhost
-----BEGIN CERTIFICATE-----
MIIDTTCCAjWgAwIBAgIKAVpj404fAAAAADANBgkqhkiG9w0BAQsFADAjMQ0wCwYD
... lines removed ...
WLvUHa29207v8ZQ6eFuTwM4OTISQIBRahxFqaluCvdQ8
-----END CERTIFICATE-----
Bag Attributes: <Empty Attributes>
subject=/OU=NIFI/CN=localhost
issuer=/OU=NIFI/CN=localhost
-----BEGIN CERTIFICATE-----
MIIDSTCCAjGgAwIBAgIKAVpj40jcAAAAADANBgkqhkiG9w0BAQsFADAjMQ0wCwYD
... lines removed ...
T7q7PHuhxvvdG4ckFMNpntxdTGIUoioZYzeijY4=
-----END CERTIFICATE-----

You can see that two certificates are included there -- the first is my client certificate and the second is the certificate of the CA that signed it.

In addition, you may need to export the private key from PKCS12 to PEM using the -nodes flag. Rather than meaning "node(s)", this flag indicates "no DES encryption", aka "no password required". You can see more about using the flag in this StackOverflow answer.


问:
Is this reducer compliant with the Redux rules?
I'm confused because I don't return state here, only action.payload (code snippet):

```<code>case HISTORY_SELECTED:
  return action.payload;
</code>```

All that reducer code:

```<code>import { HISTORY_SELECTED } from '../actions/index';

export default function (state = null, action) {
  switch (action.type) {
    case HISTORY_SELECTED:
      return action.payload;
    default:
      return state;
  }
}
</code>```

EDIT: Added 3 more cases.

If I understood answer in the right way, also CASE 2, CASE 3 and CASE 4 are ok, yes?

CASE 2 (reducer_note_selected.js)

```<code>import { NOTE_SELECTED, DEL_NOTE_SUCCESS } from '../actions/actions';

export default function (state = null, action) {
  switch (action.type) {
    case NOTE_SELECTED:
      return action.payload;
    case DEL_NOTE_SUCCESS:
      return null;
    default:
      return state;
  }
}
</code>```

CASE 3 (reducer_notes_status_fetch.js - here I'm returning just strings)

```<code> import {
 FETCH_ALL_NOTES_STARTED,
 FETCH_ALL_NOTES_ERROR,
 FETCH_ALL_NOTES_SUCCESS
} from '../actions/actions';

    export default function (state = {}, action) {
      switch (action.type) {
        case FETCH_ALL_NOTES_STARTED:
          return 'fetching_started';
        case FETCH_ALL_NOTES_ERROR:
          return 'error';
        case FETCH_ALL_NOTES_SUCCESS:
          return 'fetch_all_notes_success';
        default:
          return state;
      }
    }
</code>```

CASE 4 (reducer_notes_general.js)

```<code>import _ from 'lodash';
import { FETCH_ALL_NOTES_SUCCESS, DEL_NOTE_SUCCESS } from '../actions/actions';

export default function (state = {}, action) {
  switch (action.type) {
    case FETCH_ALL_NOTES_SUCCESS:
      return _.mapKeys(action.payload.data, '_id');
    case DEL_NOTE_SUCCESS:
      return _.omit(state, action.payload);
    default:
      return state;
  }
}
</code>```

答:
Yes, that reducer is absolutely fine conceptually.  That simply means that you want to replace whatever the existing state was with the contents of action.payload.  Here's a similar example to illustrate the principle:

```<code>function todosReducer(todos = [], action) {
    switch(action.type) {
        case LOAD_TODOS: {
            return action.payload.loadedTodos;
        }
        default: return state;
    }
}
</code>```

So, in this case, the "new state" that the reducer is returning is the data from the action, as opposed to something that's calculated based on the old state.

The only thing to be careful with is that if your action creator grabbed an existing value from the Redux state and included it in the action, you might wind up not actually changing anything.  I helped debug an issue like that in a recent SO question about a reducer "updating while just returning state".

Body:
I'm confused because I don't return state here, only action.payload (code snippet):

case HISTORY_SELECTED:
  return action.payload;

All that reducer code:

import { HISTORY_SELECTED } from '../actions/index';

export default function (state = null, action) {
  switch (action.type) {
    case HISTORY_SELECTED:
      return action.payload;
    default:
      return state;
  }
}

EDIT: Added 3 more cases.

If I understood answer in the right way, also CASE 2, CASE 3 and CASE 4 are ok, yes?

CASE 2 (reducer_note_selected.js)

import { NOTE_SELECTED, DEL_NOTE_SUCCESS } from '../actions/actions';

export default function (state = null, action) {
  switch (action.type) {
    case NOTE_SELECTED:
      return action.payload;
    case DEL_NOTE_SUCCESS:
      return null;
    default:
      return state;
  }
}

CASE 3 (reducer_notes_status_fetch.js - here I'm returning just strings)

 import {
 FETCH_ALL_NOTES_STARTED,
 FETCH_ALL_NOTES_ERROR,
 FETCH_ALL_NOTES_SUCCESS
} from '../actions/actions';

    export default function (state = {}, action) {
      switch (action.type) {
        case FETCH_ALL_NOTES_STARTED:
          return 'fetching_started';
        case FETCH_ALL_NOTES_ERROR:
          return 'error';
        case FETCH_ALL_NOTES_SUCCESS:
          return 'fetch_all_notes_success';
        default:
          return state;
      }
    }

CASE 4 (reducer_notes_general.js)

import _ from 'lodash';
import { FETCH_ALL_NOTES_SUCCESS, DEL_NOTE_SUCCESS } from '../actions/actions';

export default function (state = {}, action) {
  switch (action.type) {
    case FETCH_ALL_NOTES_SUCCESS:
      return _.mapKeys(action.payload.data, '_id');
    case DEL_NOTE_SUCCESS:
      return _.omit(state, action.payload);
    default:
      return state;
  }
}

Body:
Yes, that reducer is absolutely fine conceptually.  That simply means that you want to replace whatever the existing state was with the contents of action.payload.  Here's a similar example to illustrate the principle:

function todosReducer(todos = [], action) {
    switch(action.type) {
        case LOAD_TODOS: {
            return action.payload.loadedTodos;
        }
        default: return state;
    }
}

So, in this case, the "new state" that the reducer is returning is the data from the action, as opposed to something that's calculated based on the old state.

The only thing to be careful with is that if your action creator grabbed an existing value from the Redux state and included it in the action, you might wind up not actually changing anything.  I helped debug an issue like that in a recent SO question about a reducer "updating while just returning state".


问:
Why are literal HTML strings being appended to the DOM?
When prepending or appending to an element, it literally puts the text and doesn't compile in HTML:

```<code>var banner ={
    'Format': '90x120cm',
    'Value': 35
};
// var premium = { key: values };

function defineProduct(data) {
        var item = $('span.tooltip')[0];
        console.log($('span.tooltip'));
        for(var keys in data){
            console.log(keys);
            item.append('<div class="item"><div class="left">'+keys+':</div><div class="right ">'+data[keys]+'</div></div>');
        }
    }

defineProduct(banner);
</code>```

HTML:

```<code><div class="three-columns">
        <div class="col">
            <div class="image-holder">
                <a href='' id="premium" class="tooltips">
                <img src="" class="premium-img" width="85px" height="79px">
                <p class="description">Cartão <br><span style="color: #ffc600;" class="different">premium</span></p>
                    <span class="tooltip"></span>
                </a>
            </div>
        <!-- Same thing from above different description -->
        <!-- ditto -->
</div>
</code>```

Output:

What have I tried/used:

.get();

.prepend(string);

.html(string);

.text(string); <– I don't know why, but I did

document.createTextNode(string);

set a variable which contains HTML tags strings and set to one of the previous attempts

And the reason I used .get() is because I have more than one object that are equivalent to the quantity of their elements, in this case, I have 3. So, for every append, I have different information. E.g.: .get(0), .get(1), etc

答:
Instead of

```<code>item.append....
</code>```

you can use:

```<code>item.insertAdjacentHTML('beforeend',....
</code>```

insertAdjacentHTML: parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.

var banner = {
      'Format': '90x120cm',
      'Value': 35
  };

  function defineProduct(data) {
      var item = $('span.tooltip')[0];
      //console.log($('span.tooltip'));
      for (var keys in data) {
          //console.log(keys);
          item.insertAdjacentHTML('beforeend', '

' + keys + ':

' + data[keys] + '

');
      }
  }

  defineProduct(banner);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="three-columns">
    <div class="col">
        <div class="image-holder">

                <img src="" class="premium-img" width="85px" height="79px">

                <p class="description">Cartão <br><span style="color: #ffc600;" class="different">premium</span></p>
                <span class="tooltip"></span>

        </div>
        <!-- Same thing from above different description -->
        <!-- ditto -->
    </div>
</div></code>```

Body:
When prepending or appending to an element, it literally puts the text and doesn't compile in HTML:

var banner ={
    'Format': '90x120cm',
    'Value': 35
};
// var premium = { key: values };

function defineProduct(data) {
        var item = $('span.tooltip')[0];
        console.log($('span.tooltip'));
        for(var keys in data){
            console.log(keys);
            item.append('

'+keys+':

'+data[keys]+'

');
        }
    }

defineProduct(banner);

HTML:

Cartão
premium

Output:

What have I tried/used:

.get();

.prepend(string);

.html(string);

.text(string); <– I don't know why, but I did

document.createTextNode(string);

set a variable which contains HTML tags strings and set to one of the previous attempts

And the reason I used .get() is because I have more than one object that are equivalent to the quantity of their elements, in this case, I have 3. So, for every append, I have different information. E.g.: .get(0), .get(1), etc

Body:
Instead of

item.append....

you can use:

item.insertAdjacentHTML('beforeend',....

insertAdjacentHTML: parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.

var banner = {
      'Format': '90x120cm',
      'Value': 35
  };

  function defineProduct(data) {
      var item = $('span.tooltip')[0];
      //console.log($('span.tooltip'));
      for (var keys in data) {
          //console.log(keys);
          item.insertAdjacentHTML('beforeend', '<div class="item"><div class="left">' + keys + ':</div><div class="right ">' + data[keys] + '</div></div>');
      }
  }

  defineProduct(banner);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="three-columns">
    <div class="col">
        <div class="image-holder">
            <a href='' id="premium" class="tooltips">
                <img src="" class="premium-img" width="85px" height="79px">

                <p class="description">Cartão <br><span style="color: #ffc600;" class="different">premium</span></p>
                <span class="tooltip"></span>
            </a>
        </div>
        <!-- Same thing from above different description -->
        <!-- ditto -->
    </div>
</div>


问:
Trying to upload file to remote machine getting exception " (530) Not logged in"
I am trying to upload file to remote machine getting exception

(530) Not logged in

```<code>using (WebClient webClient = new WebClient())
{
string filePath = "D:/CLIENT/12345.txt";
webClient.UploadFile("ftp://10.10.10.21/var/www/webdav/12345.txt","STOR",     filePath);
}
</code>```

Can anyone help ?

答:
@Mainak, you need to provide a credential to the FTP server, so it can validate if you're allowed to access it. Try this:</p>

```<code>using (WebClient webClient = new WebClient())
{
string filePath = "D:/CLIENT/12345.txt";
webClient.Credentials = new NetworkCredential("ftpusername", "ftpuserpassword");
webClient.UploadFile("ftp://10.10.10.21/var/www/webdav/12345.txt","STOR",     filePath);
}
</code>```

Body:
I am trying to upload file to remote machine getting exception

(530) Not logged in

using (WebClient webClient = new WebClient())
{
string filePath = "D:/CLIENT/12345.txt";
webClient.UploadFile("ftp://10.10.10.21/var/www/webdav/12345.txt","STOR",     filePath);
}

Can anyone help ?

Body:
@Mainak, you need to provide a credential to the FTP server, so it can validate if you're allowed to access it. Try this:

using (WebClient webClient = new WebClient())
{
string filePath = "D:/CLIENT/12345.txt";
webClient.Credentials = new NetworkCredential("ftpusername", "ftpuserpassword");
webClient.UploadFile("ftp://10.10.10.21/var/www/webdav/12345.txt","STOR",     filePath);
}


问:
Python pymssql - Connecting to Named Instance
I'm trying to connect to a SQL Server named instance from python 3.4 on a remote server, and get an error.

File "C:\Scripts\Backups Integrity Report\Backup Integrity Reports.py", line 269, in

  conn = pymssql.connect(host=r'hwcvcs01\HDPS', user='My-office\romano', password='PASS', database='CommServ')

  File "pymssql.pyx", line 636, in pymssql.connect (pymssql.c:10178)

  pymssql.OperationalError: (20002, b'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed\n')

Other SQLs are connected without a problem. Also I manage to connect to the SQL using the Management Studio, from the same remote server.

Tried different ports, tried to connect to the host itself rather than the instance, and also tried pypyodbc.
What might be the problem?

答:
For a named instance that looks like this:

```<code>myhost\myinstance,1435
</code>```

You can connect via pymssql with the following:

```<code>pymssql.connect(host='myhost', server='myinstance', port='1435', user='user', password='pw')
</code>```

Body:
For a named instance that looks like this:

myhost\myinstance,1435

You can connect via pymssql with the following:

pymssql.connect(host='myhost', server='myinstance', port='1435', user='user', password='pw')


问:
Using MySQL's COUNT with two tables
I have the following MySQL table called tbl_pet_owners:

```<code>+--------+----------+--------+
| name   | pet      | city   |
+========+==========+========+
| jane   | cat      | Boston |
+--------+----------+--------+
| jane   | dog      | Boston |
+--------+----------+--------+
| jack   | cat      | Boston |
+--------+----------+--------+
| jim    | snake    | Boston |
+--------+----------+--------+
| jim    | goldfish | Boston |
+--------+----------+--------+
| joseph | cat      | NYC    |
+--------+----------+--------+
</code>```

I want to use COUNT to get the number of pets per city, BUT if an individual owns two or more pets of the same type, then those pets are counted as one. The pet types are listed in another MySQL table called tbl_pet_types:

```<code>+----------+---------+
| pet      | type    |
+==========+=========+
| cat      | mammal  |
+----------+---------+
| dog      | mammal  |
+----------+---------+
| snake    | reptile |
+----------+---------+
| goldfish | fish    |
+----------+---------+
</code>```

So since jane's cat and dog are of the same type, they're considered one pet.
In this example, the result would be:

```<code>Boston 4
NYC    1
</code>```

Any tips on how to achieve this?

答:
See if this works.</p>

```<code>SELECT PO.city, COUNT(DISTINCT PO.name, PT.type)
FROM tbl_pet_owners PO
JOIN tbl_pet_types PT ON PO.pet = PT.pet
GROUP BY PO.city
</code>```

Title: Using MySQL's COUNT with two tables

Body:
I have the following MySQL table called tbl_pet_owners:

+--------+----------+--------+
| name   | pet      | city   |
+========+==========+========+
| jane   | cat      | Boston |
+--------+----------+--------+
| jane   | dog      | Boston |
+--------+----------+--------+
| jack   | cat      | Boston |
+--------+----------+--------+
| jim    | snake    | Boston |
+--------+----------+--------+
| jim    | goldfish | Boston |
+--------+----------+--------+
| joseph | cat      | NYC    |
+--------+----------+--------+

I want to use COUNT to get the number of pets per city, BUT if an individual owns two or more pets of the same type, then those pets are counted as one. The pet types are listed in another MySQL table called tbl_pet_types:

+----------+---------+
| pet      | type    |
+==========+=========+
| cat      | mammal  |
+----------+---------+
| dog      | mammal  |
+----------+---------+
| snake    | reptile |
+----------+---------+
| goldfish | fish    |
+----------+---------+

So since jane's cat and dog are of the same type, they're considered one pet.
In this example, the result would be:

Boston 4
NYC    1

Any tips on how to achieve this?

Body:
See if this works.

SELECT PO.city, COUNT(DISTINCT PO.name, PT.type)
FROM tbl_pet_owners PO
JOIN tbl_pet_types PT ON PO.pet = PT.pet
GROUP BY PO.city