问:
What is the difference between the | and || or operators?
I have always used || (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: |. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable?

答:
& - (Condition 1 & Condition 2): checks both cases even if first one is false

&& - (Condition 1 && Condition 2): dosen't bother to check second case if case one
                                   is false

&& - operator will make your code run faster, professionally & is rarely used

| - (Condition 1 | Condition 2): checks both cases even if case 1 is true

|| - (Condition 1 || Condition 2): dosen't  bother to check second case if first
                                   one is true

|| - operator will make your code run faster, professionally | is rarely used

OwnerDisplayName: GloryFish


来源: stackexchange

问:
Set Execution Context Selector in Chrome via console
I'm working with JavaScript and need to refresh the browser a lot.
The Execution Context Selector always jumps back to "top".

Is there a line of code that automatically sets the desired file.

Just to be sure, here is a picture of the
Execution Context Selector

Sorry, it's not possible for me to embed yet.
Longtime lurker, this is the first time I can't find an answer.

答: You can use debugger; statement in your code devtools will break on this line of code and execution context will be automatically set.

ContentLicense: CC BY-SA 3.0


问:
Node Js soap package
I am using node soap package and trying to call a WSDL function by sending request to it. The function is working fine when I tried it through SoapUI client. I want to execute it through my node application. I have used 'soap' node package in the following manner:

```<code>soap.createClient(url, function(err, client) {
        if (err) {
            console.log(err);
        } else {
            client.ProcessOrderRequest(exampleJsonRequest, function(error, processOrderResult, body) {
                console.log(error)
            })
        }
})
</code>```

I saw an example on the package's documentation that we can send json data to the function while in  SoapUI I am sending xml data and it works. The same is not working in node code.

It is giving an error as below:

```<code>Fault:
   { faultcode: 500,
     faultstring: 'Invalid XML',
     detail: 'Error: Non-whitespace before first tag.\nLine: 0\nColumn: 1\nChar: \u001f',
     statusCode: 500 }
</code>```

I tried sending XML string and it is still not working. What can be issue?
Thanks in advance.

答:
Try using client.lastRequest;.  It is a property. It will print the request in xml format. After printing the requested xml; compare it with the xml request in SOAP. There might be the difference in the xml files.
Probably the error might be because of two same xmlns attributes for requested input variables. This might be because of SOAP package (which created the requested xml). There is another approach to add arguments. Use XML String for the args. Go to the link and try creating the argument using xml string.

Later re-verify the requested xml with the new xml string approach.

I think this will be useful for other users who are still facing the same problem. Please add your queries if you are still facing the issue.

Title: Node Js soap package

Body:
I am using node soap package and trying to call a WSDL function by sending request to it. The function is working fine when I tried it through SoapUI client. I want to execute it through my node application. I have used 'soap' node package in the following manner:

soap.createClient(url, function(err, client) {
        if (err) {
            console.log(err);
        } else {
            client.ProcessOrderRequest(exampleJsonRequest, function(error, processOrderResult, body) {
                console.log(error)
            })
        }
})

I saw an example on the package's documentation that we can send json data to the function while in  SoapUI I am sending xml data and it works. The same is not working in node code.

It is giving an error as below:

Fault:
   { faultcode: 500,
     faultstring: 'Invalid XML',
     detail: 'Error: Non-whitespace before first tag.\nLine: 0\nColumn: 1\nChar: \u001f',
     statusCode: 500 }

I tried sending XML string and it is still not working. What can be issue?
Thanks in advance.


问:
Convert Varchar to Float/double
I have column 'Age' (Varchar)
How can I select query and convert it to (float)

Pet_Name         Age(varchar)

John                  2 years 6 months.

Anne                  3 years and 6 months.

output:

Pet_Name         Age(float/double)

John                  2.5

Anne                 3.5

my problem is that the inputs does not follow a specific date/age format and was entered as string.

答:
Assuming the age column always has two numbers, I have used REGEXP_SUBSTR function in Redshift to write below answer:

```<code>create temp table pets (petname varchar(10), age varchar(20));

insert into pets values ('john','2 years 6 mnths');
insert into pets values ('anne','3 Years and 4 months');
insert into pets values ('buddy','4 yrs and 3 Mnths');
insert into pets values ('tommy','9 Years and 5 mnths');
insert into pets values ('alex','5 YEARS and 12 mnts');
insert into pets values ('bob','0 year and 7 Mnts');
insert into pets values ('danny','10 years 11 mnths');
insert into pets values ('sunny','81 years 10 mnths');

select petname,(REGEXP_SUBSTR(AGE,'[0-9]|[0-9][0-9]',1))::integer+(REGEXP_SUBSTR(AGE,'[0-9]|[0-9][0-9]',3))/12 as age from pets;

+--------------------+
|petname   | age     |
+--------------------+
|john      |2.5000   |
|sunny     |81.8333  |
|danny     |10.9166  |
|anne      |3.3333   |
|alex      |6.0000   |
|tommy     |9.4166   |
|bob       |0.5833   |
|buddy     |4.2500   |
+--------------------+
</code>```

Note: The above answer works only when there are two numbers in the age column.

Title: Convert Varchar to Float/double

Body:
Assuming the age column always has two numbers, I have used REGEXP_SUBSTR function in Redshift to write below answer:

create temp table pets (petname varchar(10), age varchar(20));

insert into pets values ('john','2 years 6 mnths');
insert into pets values ('anne','3 Years and 4 months');
insert into pets values ('buddy','4 yrs and 3 Mnths');
insert into pets values ('tommy','9 Years and 5 mnths');
insert into pets values ('alex','5 YEARS and 12 mnts');
insert into pets values ('bob','0 year and 7 Mnts');
insert into pets values ('danny','10 years 11 mnths');
insert into pets values ('sunny','81 years 10 mnths');

select petname,(REGEXP_SUBSTR(AGE,'[0-9]|[0-9][0-9]',1))::integer+(REGEXP_SUBSTR(AGE,'[0-9]|[0-9][0-9]',3))/12 as age from pets;

+--------------------+
|petname   | age     |
+--------------------+
|john      |2.5000   |
|sunny     |81.8333  |
|danny     |10.9166  |
|anne      |3.3333   |
|alex      |6.0000   |
|tommy     |9.4166   |
|bob       |0.5833   |
|buddy     |4.2500   |
+--------------------+

Note: The above answer works only when there are two numbers in the age column.


问:
R :: How to find if any letters exist in an factor variable
I have an factor variable in a data table with values as below :

```<code>TC02345,TC02734,TS3234,34566,79800,.....
</code>```

I need to concatenate "S" only for those records which has no letters at the beginning. (i.e) 34566,79800.

So final expected output needs to be as below :

```<code>TC02345,TC02734,TS3234,S37666,S778800.
</code>```

Kindly guide.

答:
Your data:

```<code>df <- data.frame(my_factor = c('TC02345','TC02734','TS3234','34566','79800'))
</code>```

Using a tidyverse approach, i.e. with the dplyr and stringr packages:

```<code>df %>%
    mutate(my_factor = str_replace(my_factor, '^(?=[0-9])', 'C'))
</code>```

Body:
I have an factor variable in a data table with values as below :

TC02345,TC02734,TS3234,34566,79800,.....

I need to concatenate "S" only for those records which has no letters at the beginning. (i.e) 34566,79800.

So final expected output needs to be as below :

TC02345,TC02734,TS3234,S37666,S778800.

Kindly guide.

Body:
Your data:

df <- data.frame(my_factor = c('TC02345','TC02734','TS3234','34566','79800'))

Using a tidyverse approach, i.e. with the dplyr and stringr packages:

df %>%
    mutate(my_factor = str_replace(my_factor, '^(?=[0-9])', 'C'))


问:
Visual Studio 2015 UWP Error: Microsoft.VCLibs not found
I create a UWP project with Visual Studio 2015 and from from one moment to another I get, when I open my project this error:

The SDK "SQLite.UAP.2015, Version=3.9.2" depends on the following
  SDK(s) "Microsoft.VCLibs, version=14.0", which have not been added to
  the project or were not found. Please ensure that you add these
  dependencies to your project or you may experience runtime issues. You
  can add dependencies to your project through the Reference Manager.

In my Project I use

SQLite.UAP from https://www.sqlite.org/download.html

SQLite.Net-PCL from NuGet

I updated all possible over "Tools->Extensions and Updates"

I don't change anything special on my code only some Buttons and Textlines.

I don't find a solution for this problem.

答:
If you look in your References for the project, you should see under the Universal Windows>>Extensions an option to select for Visual C++ 2015 Runtime for Universal Windows 14.0.

Try adding that reference to your project.

If you do not see that option you will need to add it using the tools get tools and features from the visual studio menu. You can select Individual components and locate the missing SDK that you need.


问:
Perform .join on value in array of objects
If I have an array of strings, I can use the .join() method to get a single string, with each element separated by commas, like so:

```<code>["Joe", "Kevin", "Peter"].join(", ") // => "Joe, Kevin, Peter"
</code>```

I have an array of objects, and I’d like to perform a similar operation on a value held within it; so from

```<code>[
  {name: "Joe", age: 22},
  {name: "Kevin", age: 24},
  {name: "Peter", age: 21}
]
</code>```

perform the join method only on the name attribute, to achieve the same output as before.

Currently I have the following function:

```<code>function joinObj(a, attr){
  var out = [];

  for (var i = 0; i < a.length; i++){
    out.push(a[i][attr]);
  }

  return out.join(", ");
}
</code>```

There’s nothing wrong with that code, it works, but all of a sudden I’ve gone from a simple, succinct line of code to a very imperative function. Is there a more succinct, ideally more functional way of writing this?

答:
On node or ES6+:

const users = [{
    name: "Joe",
    age: 22
  },
  {
    name: "Kevin",
    age: 24
  },
  {
    name: "Peter",
    age: 21
  }
];

console.log(
  users.map(u => u.name).join(', ')
);```

Body:
If I have an array of strings, I can use the .join() method to get a single string, with each element separated by commas, like so:

["Joe", "Kevin", "Peter"].join(", ") // => "Joe, Kevin, Peter"

I have an array of objects, and I’d like to perform a similar operation on a value held within it; so from

[
  {name: "Joe", age: 22},
  {name: "Kevin", age: 24},
  {name: "Peter", age: 21}
]

perform the join method only on the name attribute, to achieve the same output as before.

Currently I have the following function:

function joinObj(a, attr){
  var out = [];

  for (var i = 0; i < a.length; i++){
    out.push(a[i][attr]);
  }

  return out.join(", ");
}

There’s nothing wrong with that code, it works, but all of a sudden I’ve gone from a simple, succinct line of code to a very imperative function. Is there a more succinct, ideally more functional way of writing this?

ContentLicense: CC BY-SA 4.0


问:
AspectJ - pointcut to match a method that has generic parameters
I have a generic method that accepts any type as its parameter.

For example, I would like a pointcut that matches the calls made to the method only with 'String' type as its parameter. Ultimately the requirement is to limit the scope which the advices get executed for to 'String' parameters.

Here is my generic class and method:

```<code>public class Param<T> {
    public T execute(T s){
        return s;
    }
}
</code>```

Main class:  My app makes calls to the method with both Boolean and String as parameters.

```<code>public static void main(String[] args) {
    Param<String> sp = new Param<String>();
    String rs = sp.execute("myString"); //want a joint point

    Param<Boolean> bp = new Param<Boolean>();
    Boolean rb = bp.execute(true); //dont want a joint point
}
</code>```

Below pointcuts are valid for both String and Boolean parameters (work for any type actually). But I would like a pointcut to intercept method calls only when parameter is of type String.

```<code>@Pointcut("call(* com.amazon.auiqa.aspectj.generics.Param.execute(**))")
void param(){}

@Pointcut("execution(Object com.amazon.auiqa.aspectj.generics.Param.execute(Object))")
void param(){}
</code>```

Below ones did not work for me:

```<code> @Pointcut("execution(String com.amazon.auiqa.aspectj.generics.Param.execute(String))")
 @Pointcut("call(String com.amazon.auiqa.aspectj.generics.Param.execute(String))")
</code>```

I was wondering if it is possible to achieve what I want to achieve here. I would like to do the same thing with method return types.

答:
You cannot do that with AspectJ, nor with any other bytecode manipulation library as generic type information is actually erased from the compiled bytecode (as of Java 9), so your generic method becomes public Object execute(Object s), since the type argument T is unbounded. See Type Erasure at the Java Documentation for further info.

While the original method signature is preserved in the form of metadata, the compiler can check whether type bounds are respected or not while compiling against generic code, but this will not help you in any way to determine what generic type argument an instance of that class was instantiated with, because that information is simply not present at all.

Body:
I have a generic method that accepts any type as its parameter.

For example, I would like a pointcut that matches the calls made to the method only with 'String' type as its parameter. Ultimately the requirement is to limit the scope which the advices get executed for to 'String' parameters.

Here is my generic class and method:

public class Param<T> {
    public T execute(T s){
        return s;
    }
}

Main class:  My app makes calls to the method with both Boolean and String as parameters.

public static void main(String[] args) {
    Param<String> sp = new Param<String>();
    String rs = sp.execute("myString"); //want a joint point

    Param<Boolean> bp = new Param<Boolean>();
    Boolean rb = bp.execute(true); //dont want a joint point
}

Below pointcuts are valid for both String and Boolean parameters (work for any type actually). But I would like a pointcut to intercept method calls only when parameter is of type String.

@Pointcut("call(* com.amazon.auiqa.aspectj.generics.Param.execute(**))")
void param(){}

@Pointcut("execution(Object com.amazon.auiqa.aspectj.generics.Param.execute(Object))")
void param(){}

Below ones did not work for me:

 @Pointcut("execution(String com.amazon.auiqa.aspectj.generics.Param.execute(String))")
 @Pointcut("call(String com.amazon.auiqa.aspectj.generics.Param.execute(String))")

I was wondering if it is possible to achieve what I want to achieve here. I would like to do the same thing with method return types.


问:
Jenkins: print a Hyperlink (HyperlinkNote) in console output from a script
When we add a post build action of "Build other project" Jenkins will put a smart link to that build in console output.

I cat the log file of a build (/var/Jenkins/jobs/job1/builds/1/log) and realized that link is in fact a string of bytes.
My question is how can I generate such string from a python script that Jenkins run?

(I know I can print http://myjenkins.com/job1 and Jenkins will turn it to a link. but I want to have a Jenkins-like link)

答:
I think you are after this:

```<code>import hudson.console.*
String getHyperlink(String url, String text) {
    return hudson.console.ModelHyperlinkNote.encodeTo(url, text)
}
println getHyperlink('http://myurl.com', 'linkText')
</code>```

this will generate the encoded string that can be printed in the console

In this case, this generates:

```<code>[8mha:////4NFwoQVOoX5oFqAB5LRT6AEbVT9priUOFDfXahNHEtv7AAAAmh+LCAAAAAAAAP9b85aBtbiIQTGjNKU4P08vOT+vOD8nVc83PyU1x6OyILUoJzMv2y+/JJUBAhiZGBgqihhk0NSjKDWzXb3RdlLBUSYGJk8GtpzUvPSSDB8G5tKinBIGIZ+sxLJE/ZzEvHT94JKizLx0a6BxUmjGOUNodHsLgAyOEgaBjJKSAit9/dxKoJFAPbkAmUKP18UAAAA=[0mlinkText
</code>```

that will be printed in the job console as:

lnikText

Body:
I think you are after this:

import hudson.console.*
String getHyperlink(String url, String text) {
    return hudson.console.ModelHyperlinkNote.encodeTo(url, text)
}
println getHyperlink('http://myurl.com', 'linkText')

this will generate the encoded string that can be printed in the console

In this case, this generates:

[8mha:////4NFwoQVOoX5oFqAB5LRT6AEbVT9priUOFDfXahNHEtv7AAAAmh+LCAAAAAAAAP9b85aBtbiIQTGjNKU4P08vOT+vOD8nVc83PyU1x6OyILUoJzMv2y+/JJUBAhiZGBgqihhk0NSjKDWzXb3RdlLBUSYGJk8GtpzUvPSSDB8G5tKinBIGIZ+sxLJE/ZzEvHT94JKizLx0a6BxUmjGOUNodHsLgAyOEgaBjJKSAit9/dxKoJFAPbkAmUKP18UAAAA=[0mlinkText

that will be printed in the job console as:

lnikText


问:
jQuery get Select option value shows Undefined error
I am generating an Html select in a form that is in a bootstrap 3 modal popup. I am trying to get the selected value and pass it through JQuery to dump to a database.

I have other input fields and a text area field using tinyMCE that I get the value from without any issues at all using $('#id').val();.

My select is super simple and displays in the view source as:

```<code><select id='practitionerID' name='practitionerID' class='form-control'>
    <option value="1">Doctor 1</option>
    <option value="2">Doctor 2</option>
</select>
</code>```

I am have tried many different ways to get the data to display and cannot for the life of me get the option value.

I have tried the following:

```<code>$('#practitionerID').prop('selectedIndex'); // give's me -1 no matter the option selected
$('#practitionerID').val(); // returns null
$('#practitionerID').text(); // returns null, dont want the text anyways
$("#practitionerID option:selected").val(); // returns undefined
$("#practitionerID option:selected" ).text(); //returns undefined, still not what i want.
</code>```

EDIT:
So it tried this and it actually gives me a value now but only ever gives me the first option in the dropdown even though i have chosen something else.
    $('#practitionerID :selected').val();

The only thing i can think of that is tripping this up is the fact that I am loading it in a modal? Maybe it cannot read into it for some reason to see the property?

When I load an existing record and get the data.event.practitionerID it works gives me the value fine. However, I cannot seem to set the value when i get it though. So it appears to be an issue with the ID of this select but I just cant see where or how.

Any help would be greatly appreciated!

答:
Hope this helps....

$( "#select" ).submit(function( event ) {
  var select=$('#practitionerID').val();
  alert( select );
  event.preventDefault();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">

<!-- Button to trigger modal -->
Launch demo modal

  <!-- Modal -->
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
         <form id="select">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
          <h4 class="modal-title">Select!</h4>
        </div>
        <div class="modal-body">

            <select id='practitionerID' name='practitionerID' class='form-control'>
    <option value="1">Doctor 1</option>
    <option value="2">Doctor 2</option>
</select>

        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Submit</button>
        </div>
      </div><!-- /.modal-content -->
    </form>
      </div><!-- /.modal-dialog -->
  </div><!-- /.modal -->

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

Body:
I am generating an Html select in a form that is in a bootstrap 3 modal popup. I am trying to get the selected value and pass it through JQuery to dump to a database.

I have other input fields and a text area field using tinyMCE that I get the value from without any issues at all using $('#id').val();.

My select is super simple and displays in the view source as:

<select id='practitionerID' name='practitionerID' class='form-control'>
    <option value="1">Doctor 1</option>
    <option value="2">Doctor 2</option>
</select>

I am have tried many different ways to get the data to display and cannot for the life of me get the option value.

I have tried the following:

$('#practitionerID').prop('selectedIndex'); // give's me -1 no matter the option selected
$('#practitionerID').val(); // returns null
$('#practitionerID').text(); // returns null, dont want the text anyways
$("#practitionerID option:selected").val(); // returns undefined
$("#practitionerID option:selected" ).text(); //returns undefined, still not what i want.

EDIT:
So it tried this and it actually gives me a value now but only ever gives me the first option in the dropdown even though i have chosen something else.
    $('#practitionerID :selected').val();

The only thing i can think of that is tripping this up is the fact that I am loading it in a modal? Maybe it cannot read into it for some reason to see the property?

When I load an existing record and get the data.event.practitionerID it works gives me the value fine. However, I cannot seem to set the value when i get it though. So it appears to be an issue with the ID of this select but I just cant see where or how.

Any help would be greatly appreciated!

Body:
Hope this helps....

$( "#select" ).submit(function( event ) {
  var select=$('#practitionerID').val();
  alert( select );
  event.preventDefault();
});

<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">

<!-- Button to trigger modal -->
<a href="#myModal" class="btn btn-primary" data-toggle="modal">Launch demo modal</a>

  <!-- Modal -->
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
         <form id="select">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
          <h4 class="modal-title">Select!</h4>
        </div>
        <div class="modal-body">

            <select id='practitionerID' name='practitionerID' class='form-control'>
    <option value="1">Doctor 1</option>
    <option value="2">Doctor 2</option>
</select>

        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Submit</button>
        </div>
      </div><!-- /.modal-content -->
    </form>
      </div><!-- /.modal-dialog -->
  </div><!-- /.modal -->

</div>
</body>
</html>


问:
Characters counting only in one textarea
I have many inputs and one textarea in my page. I want to count the characters from all
these inputs/textarea.

HTML:

```<code><textarea name="texto_envio" class="form-control txtArea" maxlength="160"></textarea>
<input type="text"maxlength=3" class="form-control txtArea" />
<input type="text"maxlength=3" class="form-control txtArea" />
<span class="caracteres">160</span> restantes<br>
</code>```

JS:

```<code>$(document).on("input keyup", ".txtArea", function () {
    var limite = 160;
    var caracteresDigitados = $(this).val().length;
    var caracteresRestantes = limite - caracteresDigitados;
    $(".caracteres").text(caracteresRestantes);
});
</code>```

Like...if I write "abc" in textarea and if I also write "abc" in both inputs, it will show "151 restantes".

I tried this code above but it only count the element that I am writing in. I write "abc" in textarea then span shows me "157 restantes". With "abc" written in textarea, I also write "abc" in one of the inputs. But the span shows me "157 restantes".

Span is reseting when I write in the other element.

What can I do to make it count every element (textarea and inputs)?

答:
The event method will attach event handler for each input separately. So $(this).val().length refers to the specific input that triggered the event.

In the event you'll have to call a method that reads from all inputs.

$(document).on('keyup', 'textarea, input', countChars);

function countChars() {
  var total = 0;
  $('textarea, input').each(function(i, el) {
    total += el.value.length
  });
  var remaining = 160 - total;
  $('span').text(remaining + ' remaining');
}```
<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>
<textarea></textarea>
<input type="text" />
<input type="text" />
<span></span></code>```

Body:
I have many inputs and one textarea in my page. I want to count the characters from all
these inputs/textarea.

HTML:

<textarea name="texto_envio" class="form-control txtArea" maxlength="160"></textarea>
<input type="text"maxlength=3" class="form-control txtArea" />
<input type="text"maxlength=3" class="form-control txtArea" />
160 restantes

JS:

$(document).on("input keyup", ".txtArea", function () {
    var limite = 160;
    var caracteresDigitados = $(this).val().length;
    var caracteresRestantes = limite - caracteresDigitados;
    $(".caracteres").text(caracteresRestantes);
});

Like...if I write "abc" in textarea and if I also write "abc" in both inputs, it will show "151 restantes".

I tried this code above but it only count the element that I am writing in. I write "abc" in textarea then span shows me "157 restantes". With "abc" written in textarea, I also write "abc" in one of the inputs. But the span shows me "157 restantes".

Span is reseting when I write in the other element.

What can I do to make it count every element (textarea and inputs)?

Body:
The event method will attach event handler for each input separately. So $(this).val().length refers to the specific input that triggered the event.

In the event you'll have to call a method that reads from all inputs.

$(document).on('keyup', 'textarea, input', countChars);

function countChars() {
  var total = 0;
  $('textarea, input').each(function(i, el) {
    total += el.value.length
  });
  var remaining = 160 - total;
  $('span').text(remaining + ' remaining');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<input type="text" />
<input type="text" />
<span></span>


问:
Looking for a drop-in replacement for a java.util.Map

Problem

Following up on this question, it seems that a file- or disk-based Map implementation may be the right solution to the problems I mentioned there. Short version:

Right now, I have a Map implemented as a ConcurrentHashMap.

Entries are added to it continually, at a fairly fixed rate. Details on this later.

Eventually, no matter what, this means the JVM runs out of heap space.

At work, it was (strongly) suggested that I solve this problem using SQLite, but after asking that previous question, I don't think that a database is the right tool for this job. So - let me know if this sounds crazy - I think a better solution would be a Map stored on disk.

Bad idea: implement this myself. Better idea: use someone else's library! Which one?

Requirements

Must-haves:

Free.

Persistent. The data needs to stick around between JVM restarts.

Some sort of searchability. Yes, I need the ability to retrieve this darn data as well as put it away. Basic result set filtering is a plus.

Platform-independent. Needs to be production-deployable on Windows or Linux machines.

Purgeable. Disk space is finite, just like heap space. I need to get rid of entries that are n days old. It's not a big deal if I have to do this manually.

Nice-to-haves:

Easy to use. It would be great if I could get this working by the end of the week.

Better still: the end of the day. It would be really, really great if I could add one JAR to my classpath, change new ConcurrentHashMap<Foo, Bar>(); to new SomeDiskStoredMap<Foo, Bar>();

and be done.

Decent scalability and performance. Worst case: new entries are added (on average) 3 times per second, every second, all day long, every day. However, inserts won't always happen that smoothly. It might be (no inserts for an hour) then (insert 10,000 objects at once).

Possible Solutions

Ehcache? I've never used it before. It was a suggested solution to my previous question.

Berkeley DB? Again, I've never used it, and I really don't know anything about it.

Hadoop (and which subproject)? Haven't used it. Based on these docs, its cross-platform-readiness is ambiguous to me. I don't need distributed operation in the foreseeable future.

A SQLite JDBC driver after all?

???

Ehcache and Berkeley DB both look reasonable right now. Any particular recommendations in either direction?

答:
UPDATE (some 4 years after first post...): beware that in newer versions of ehcache, persistence of cache items is available only in the pay product. Thanks @boday for pointing this out.

ehcache is great.  It will give you the flexibility you need to implement the map in memory, disk or memory with spillover to disk.  If you use this very simple wrapper for java.util.Map then using it is blindingly simple:

```<code>import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.apache.log4j.Logger;

import com.google.common.collect.Sets;

public class EhCacheMapAdapter<K,V> implements Map<K,V> {
    @SuppressWarnings("unused")
    private final static Logger logger = Logger
            .getLogger(EhCacheMapAdapter.class);

    public Cache ehCache;

    public EhCacheMapAdapter(Cache ehCache) {
        super();
        this.ehCache = ehCache;
    } // end constructor

    @Override
    public void clear() {
        ehCache.removeAll();
    } // end method

    @Override
    public boolean containsKey(Object key) {
        return ehCache.isKeyInCache(key);
    } // end method

    @Override
    public boolean containsValue(Object value) {
        return ehCache.isValueInCache(value);
    } // end method

    @Override
    public Set<Entry<K, V>> entrySet() {
        throw new UnsupportedOperationException();
    } // end method

    @SuppressWarnings("unchecked")
    @Override
    public V get(Object key) {
        if( key == null ) return null;
        Element element = ehCache.get(key);
        if( element == null ) return null;
        return (V)element.getObjectValue();
    } // end method

    @Override
    public boolean isEmpty() {
        return ehCache.getSize() == 0;
    } // end method

    @SuppressWarnings("unchecked")
    @Override
    public Set<K> keySet() {
        List<K> l = ehCache.getKeys();
        return Sets.newHashSet(l);
    } // end method

    @SuppressWarnings("unchecked")
    @Override
    public V put(K key, V value) {
        Object o = this.get(key);
        if( o != null ) return (V)o;
        Element e = new Element(key,value);
        ehCache.put(e);
        return null;
    } // end method

    @Override
    public V remove(Object key) {
        V retObj = null;
        if( this.containsKey(key) ) {
            retObj = this.get(key);
        } // end if
        ehCache.remove(key);
        return retObj;
    } // end method

    @Override
    public int size() {
        return ehCache.getSize();
    } // end method

    @Override
    public Collection<V> values() {
        throw new UnsupportedOperationException();
    } // end method

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        for( K key : m.keySet() ) {
            this.put(key, m.get(key));
        } // end for
    } // end method
} // end class
</code>```

ContentLicense: CC BY-SA 2.5

Body:
UPDATE (some 4 years after first post...): beware that in newer versions of ehcache, persistence of cache items is available only in the pay product. Thanks @boday for pointing this out.

ehcache is great.  It will give you the flexibility you need to implement the map in memory, disk or memory with spillover to disk.  If you use this very simple wrapper for java.util.Map then using it is blindingly simple:

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.apache.log4j.Logger;

import com.google.common.collect.Sets;

public class EhCacheMapAdapter<K,V> implements Map<K,V> {
    @SuppressWarnings("unused")
    private final static Logger logger = Logger
            .getLogger(EhCacheMapAdapter.class);

    public Cache ehCache;

    public EhCacheMapAdapter(Cache ehCache) {
        super();
        this.ehCache = ehCache;
    } // end constructor

    @Override
    public void clear() {
        ehCache.removeAll();
    } // end method

    @Override
    public boolean containsKey(Object key) {
        return ehCache.isKeyInCache(key);
    } // end method

    @Override
    public boolean containsValue(Object value) {
        return ehCache.isValueInCache(value);
    } // end method

    @Override
    public Set<Entry<K, V>> entrySet() {
        throw new UnsupportedOperationException();
    } // end method

    @SuppressWarnings("unchecked")
    @Override
    public V get(Object key) {
        if( key == null ) return null;
        Element element = ehCache.get(key);
        if( element == null ) return null;
        return (V)element.getObjectValue();
    } // end method

    @Override
    public boolean isEmpty() {
        return ehCache.getSize() == 0;
    } // end method

    @SuppressWarnings("unchecked")
    @Override
    public Set<K> keySet() {
        List<K> l = ehCache.getKeys();
        return Sets.newHashSet(l);
    } // end method

    @SuppressWarnings("unchecked")
    @Override
    public V put(K key, V value) {
        Object o = this.get(key);
        if( o != null ) return (V)o;
        Element e = new Element(key,value);
        ehCache.put(e);
        return null;
    } // end method

    @Override
    public V remove(Object key) {
        V retObj = null;
        if( this.containsKey(key) ) {
            retObj = this.get(key);
        } // end if
        ehCache.remove(key);
        return retObj;
    } // end method

    @Override
    public int size() {
        return ehCache.getSize();
    } // end method

    @Override
    public Collection<V> values() {
        throw new UnsupportedOperationException();
    } // end method

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        for( K key : m.keySet() ) {
            this.put(key, m.get(key));
        } // end for
    } // end method
} // end class


问:
Converting Binary Search Tree to Linked List error
I am trying to convert a bst into a linked list, but am getting an error when trying to recall the list to print on the display.

Here is my code for the main functions,

```<code>ListNodePtr createListnode(int key) {
    ListNodePtr newList = (ListNodePtr)malloc(sizeof(struct ListNode));

    if (newList != NULL) {
            newList->key = key;
            newList->next = NULL;
            return newList;
    } else {
            return NULL;
    }
}

ListNodePtr insertNodeIntoList(ListNodePtr root, const ListNodePtr z) {
    if (root == NULL) {
            root = createListnode(z->key);
    } else {
            root->next = insertNodeIntoList(root->next, z);
    }
    return root;
}

void linkedListINIT(ListNodePtr list, TreeNodePtr root) {
    if (root != NULL) {
            linkedListINIT(list, root->left);
            ListNodePtr current = createListnode(root->key);
            list = insertNodeIntoList(list, current);
            linkedListINIT(list, root->right);
    }
    return;
}

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root) {
    ListNodePtr list = NULL;

    linkedListINIT(list, root);

    return list;
}
</code>```

Here is the initialization for the listNodePtr and the print function.

```<code>struct ListNode {
    int key;
    struct ListNode *next;
};

typedef struct ListNode *ListNodePtr;
</code>```

and

```<code>void printList(ListNodePtr head) {
    if (head != NULL) {
            printf("%d ", head->key);
            printList(head->next);
    }
    return;
}
</code>```

The issue is, when i try to print the final list, there is no output even though the 'current' variable outputs properly if I check it with print statements. I'm not really sure where it goes wrong, the main function just calls convertBSTtoLinkedList and printList. Any help would be appreciated!

答:
In the function call linkedListINIT (list, root) the function linkedListINIT() cannot possibly modify the variable list. It doesn't matter how it's defined; it simply cannot possibly modify the variables passed as arguments because the C language is strictly pass-by-value.

So without reading anything more than the definition of convertBSTtoLinkedList() I know that it always returns NULL.

Body:
I am trying to convert a bst into a linked list, but am getting an error when trying to recall the list to print on the display.

Here is my code for the main functions,

ListNodePtr createListnode(int key) {
    ListNodePtr newList = (ListNodePtr)malloc(sizeof(struct ListNode));

    if (newList != NULL) {
            newList->key = key;
            newList->next = NULL;
            return newList;
    } else {
            return NULL;
    }
}

ListNodePtr insertNodeIntoList(ListNodePtr root, const ListNodePtr z) {
    if (root == NULL) {
            root = createListnode(z->key);
    } else {
            root->next = insertNodeIntoList(root->next, z);
    }
    return root;
}

void linkedListINIT(ListNodePtr list, TreeNodePtr root) {
    if (root != NULL) {
            linkedListINIT(list, root->left);
            ListNodePtr current = createListnode(root->key);
            list = insertNodeIntoList(list, current);
            linkedListINIT(list, root->right);
    }
    return;
}

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root) {
    ListNodePtr list = NULL;

    linkedListINIT(list, root);

    return list;
}

Here is the initialization for the listNodePtr and the print function.

struct ListNode {
    int key;
    struct ListNode *next;
};

typedef struct ListNode *ListNodePtr;

and

void printList(ListNodePtr head) {
    if (head != NULL) {
            printf("%d ", head->key);
            printList(head->next);
    }
    return;
}

The issue is, when i try to print the final list, there is no output even though the 'current' variable outputs properly if I check it with print statements. I'm not really sure where it goes wrong, the main function just calls convertBSTtoLinkedList and printList. Any help would be appreciated!


问:
How to list all resources without know the package name or filesystem path for jar files in Java 9
in Java 7 & 8 I use to be able to do

```<code>URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
for (URL u : urlLoader.getURLs()) {
    System.out.println("*************** url=" + url);
}
</code>```

But in Java 9 the above gives an error

```<code>java.lang.ClassCastException: java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLClass
Loader
</code>```

So how do I list all resources without knowing the package prefix or the filesystem path of the jar files?

答:
Best answer I found is to provide an argument to getResources, of course means you know prefix of the path the resources are located</p>

```<code>  ArrayList<URL> resources = new ArrayList<URL>();
  ClassLoader urlLoader = ClassLoader.getSystemClassLoader();
  Enumeration<URL> eU = urlLoader.getResources("com");
  while (eU.hasMoreElements()) {
     URL u = eU.nextElement();
     JarFile jarFile = new JarFile(u.getFile().replace("file:/", "").replaceAll("!.*$", ""));
     Enumeration<JarEntry> e = jarFile.entries();
     while (e.hasMoreElements()) {
        JarEntry jarEntry = e.nextElement();
        resources.add(urlLoader.getResource(jarEntry.getName()));
     }
  }
</code>```

Body:
in Java 7 & 8 I use to be able to do

URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
for (URL u : urlLoader.getURLs()) {
    System.out.println("*************** url=" + url);
}

But in Java 9 the above gives an error

java.lang.ClassCastException: java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLClass
Loader

So how do I list all resources without knowing the package prefix or the filesystem path of the jar files?

Body:
Best answer I found is to provide an argument to getResources, of course means you know prefix of the path the resources are located

  ArrayList<URL> resources = new ArrayList<URL>();
  ClassLoader urlLoader = ClassLoader.getSystemClassLoader();
  Enumeration<URL> eU = urlLoader.getResources("com");
  while (eU.hasMoreElements()) {
     URL u = eU.nextElement();
     JarFile jarFile = new JarFile(u.getFile().replace("file:/", "").replaceAll("!.*$", ""));
     Enumeration<JarEntry> e = jarFile.entries();
     while (e.hasMoreElements()) {
        JarEntry jarEntry = e.nextElement();
        resources.add(urlLoader.getResource(jarEntry.getName()));
     }
  }


问:
ConstraintLayout make cell items fit screen viewport
I am trying to create a screen which should look like this

But when I create the view using the XML code as per below

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fb_constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="me.buddy.buddy.ui.BenefitsActivity$BenefitsFragment">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_animals"
        android:src="@drawable/animal_love"

        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_meal_data"
        app:layout_constraintBottom_toTopOf="@id/fb_environment"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_meal_data"
        android:src="@drawable/food"

        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toRightOf="@id/fb_animals"
        app:layout_constraintBottom_toTopOf="@id/fb_health"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_environment"
        android:src="@drawable/environment"

        app:layout_constraintTop_toBottomOf="@id/fb_animals"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_health"
        app:layout_constraintBottom_toTopOf="@id/fb_hunger"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_health"
        android:src="@drawable/health"

        app:layout_constraintTop_toBottomOf="@id/fb_meal_data"
        app:layout_constraintBottom_toTopOf="@id/fb_section_label"
        app:layout_constraintLeft_toRightOf="@id/fb_environment"
        app:layout_constraintRight_toRightOf="parent"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_hunger"
        android:src="@drawable/bowl"

        app:layout_constraintTop_toBottomOf="@id/fb_environment"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_section_label"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_section_label"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"

        app:layout_constraintTop_toBottomOf="@id/fb_health"
        app:layout_constraintLeft_toRightOf="@id/fb_hunger"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</android.support.constraint.ConstraintLayout>
</code>```

I am getting a screen like below in my app

Do note that this layout is inside a fragment of an activity as depicted in the tools tag in the xml. Hence the additional floating action button and the back arrow in the actual layout.

However what I am not able to understand is why is icon of the food bowl getting pushed below the visible screen space in the actual layout.

Any resolution to this issue? I would like to avoid using Scrollview as much as possible.

For reference, XML Code of parent activity is attached below

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="me.buddy.buddy.ui.BenefitsActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/ab_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/ab_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_weight="1"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="@string/app_name">

        </android.support.v7.widget.Toolbar>

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

    <android.support.v4.view.ViewPager
        android:id="@+id/ab_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/ab_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_menu_share" />
</android.support.design.widget.CoordinatorLayout>
</code>```

Java code for adding fragment to main activity as per below:

First the parent class:

```<code>setContentView(R.layout.activity_benefits);
Toolbar toolbar = (Toolbar) findViewById(R.id.ab_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.ab_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
</code>```

Then inside Fragment class:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_benefits_dashboard, container, false);
return rootView;}
</code>```

答:
The Toolbar in your Main Activity pushes down the ViewPager. The AppBarLayout is mainly used in a Tabbed Layout for using a TabLayout. If you are using a TabLayout inside the AppBarLayout, the Toolbar will hide automatically after launching the activity and your ViewPager will occupy the full window.

The Solution:
Remove the whole AppBarLayout with Toolbar from your Activity and also remove the NoActionBar theme from Activity manifest

Or, don't use CoordinatorLayout for your parent activity.

Body:
I am trying to create a screen which should look like this

But when I create the view using the XML code as per below

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fb_constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="me.buddy.buddy.ui.BenefitsActivity$BenefitsFragment">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_animals"
        android:src="@drawable/animal_love"

        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_meal_data"
        app:layout_constraintBottom_toTopOf="@id/fb_environment"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_meal_data"
        android:src="@drawable/food"

        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toRightOf="@id/fb_animals"
        app:layout_constraintBottom_toTopOf="@id/fb_health"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_environment"
        android:src="@drawable/environment"

        app:layout_constraintTop_toBottomOf="@id/fb_animals"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_health"
        app:layout_constraintBottom_toTopOf="@id/fb_hunger"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_health"
        android:src="@drawable/health"

        app:layout_constraintTop_toBottomOf="@id/fb_meal_data"
        app:layout_constraintBottom_toTopOf="@id/fb_section_label"
        app:layout_constraintLeft_toRightOf="@id/fb_environment"
        app:layout_constraintRight_toRightOf="parent"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_hunger"
        android:src="@drawable/bowl"

        app:layout_constraintTop_toBottomOf="@id/fb_environment"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/fb_section_label"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fb_section_label"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"

        app:layout_constraintTop_toBottomOf="@id/fb_health"
        app:layout_constraintLeft_toRightOf="@id/fb_hunger"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</android.support.constraint.ConstraintLayout>

I am getting a screen like below in my app

Do note that this layout is inside a fragment of an activity as depicted in the tools tag in the xml. Hence the additional floating action button and the back arrow in the actual layout.

However what I am not able to understand is why is icon of the food bowl getting pushed below the visible screen space in the actual layout.

Any resolution to this issue? I would like to avoid using Scrollview as much as possible.

For reference, XML Code of parent activity is attached below

    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="me.buddy.buddy.ui.BenefitsActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/ab_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/ab_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_weight="1"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="@string/app_name">

        </android.support.v7.widget.Toolbar>

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

    <android.support.v4.view.ViewPager
        android:id="@+id/ab_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/ab_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_menu_share" />
</android.support.design.widget.CoordinatorLayout>

Java code for adding fragment to main activity as per below:

First the parent class:

setContentView(R.layout.activity_benefits);
Toolbar toolbar = (Toolbar) findViewById(R.id.ab_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.ab_container);
mViewPager.setAdapter(mSectionsPagerAdapter);

Then inside Fragment class:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_benefits_dashboard, container, false);
return rootView;}


答:
Try this solution,
This will read all the elements with class txtArea and count the characters from each. in this way you will get the total character count.

```<code><textarea name="texto_envio" class="form-control txtArea" maxlength="160"></textarea>
<input type="text" maxlength="3" class="form-control txtArea" />
<input type="text" maxlength="3" class="form-control txtArea" />
</code>```

JS

```<code>$(document).on("input keyup", ".txtArea", function () {
var limit = 160;
   var count = 0;
   var inputElements = $(".txtArea").each(function(){
       count += $(this).val().length;
   });
 $(".caracteres").text(limit - count);
});
</code>```

Title: Characters counting only in one textarea

Body:
Try this solution,
This will read all the elements with class txtArea and count the characters from each. in this way you will get the total character count.

<textarea name="texto_envio" class="form-control txtArea" maxlength="160"></textarea>
<input type="text" maxlength="3" class="form-control txtArea" />
<input type="text" maxlength="3" class="form-control txtArea" />

JS

$(document).on("input keyup", ".txtArea", function () {
var limit = 160;
   var count = 0;
   var inputElements = $(".txtArea").each(function(){
       count += $(this).val().length;
   });
 $(".caracteres").text(limit - count);
});


问:
Matplotlib: how to plot a line with categorical data on the x-axis?
I am trying to plot a few lines (not a bar plot, as in this case). My y values are float, whereas x values are categorical data. How to do this in matplotlib?

My values:

```<code>data1=[5.65,7.61,8.17,7.60,9.54]
data2=[7.61,16.17,16.18,19.54,19.81]
data3=[29.55,30.24,31.51,36.40,35.47]
</code>```

My categories:

```<code>x_axis=['A','B','C','D','E']
</code>```

The code I am using, which does not give me what I want:

```<code>import matplotlib.pyplot as plt
fig=plt.figure() #Creates a new figure
ax1=fig.add_subplot(111) #Plot with: 1 row, 1 column, first subplot.
line1 = ax1.plot(str(x_axis), data1,'ko-',label='line1') #Plotting data1
line2 = ax1.plot(str(x_axis), data2,'ro-',label='line2') #Plotting data2
line3 = ax1.plot(str(x_axis), data3,'mo-',label='line3') #Plotting data3
plt.xticks(range(len(data3)), x_axis, size='small')
ax1.set_ylim(0,51)
ax1.set_ylabel('y values',fontsize=12)
#Assigning labels
lines = line1+line2+line3
labels = [l.get_label() for l in lines]
ax1.legend(lines,labels,loc='upper center', prop={'size':10}, bbox_to_anchor=(0.5, -0.13), fancybox=True, shadow=True, ncol=5)
ax1.set_xlabel('Categories',fontsize=14)
plt.setp(ax2.get_xticklabels(), visible=True)
title_string=('Plotting categories vs y values in matplotlib')
plt.suptitle(title_string, y=1.0, fontsize=17)
fig.tight_layout()
fig.subplots_adjust(top=0.92,bottom=0.2)
plt.show()
plt.savefig('myplot.jpg',bbox_inches='tight')
plt.close()
</code>```

答:
Matplotlib version 2.1.0 allows plotting categorical variables directly, just calling plt.plot(x,y) as usual, without the need to use range or get_xticklabels().

```<code>line1 = plt.plot(x_axis, data1,'ko-',label='line1')
line2 = plt.plot(x_axis, data2,'ro-',label='line2')
line3 = plt.plot(x_axis, data3,'mo-',label='line3')
</code>```

Body:
I am trying to plot a few lines (not a bar plot, as in this case). My y values are float, whereas x values are categorical data. How to do this in matplotlib?

My values:

data1=[5.65,7.61,8.17,7.60,9.54]
data2=[7.61,16.17,16.18,19.54,19.81]
data3=[29.55,30.24,31.51,36.40,35.47]

My categories:

x_axis=['A','B','C','D','E']

The code I am using, which does not give me what I want:

import matplotlib.pyplot as plt
fig=plt.figure() #Creates a new figure
ax1=fig.add_subplot(111) #Plot with: 1 row, 1 column, first subplot.
line1 = ax1.plot(str(x_axis), data1,'ko-',label='line1') #Plotting data1
line2 = ax1.plot(str(x_axis), data2,'ro-',label='line2') #Plotting data2
line3 = ax1.plot(str(x_axis), data3,'mo-',label='line3') #Plotting data3
plt.xticks(range(len(data3)), x_axis, size='small')
ax1.set_ylim(0,51)
ax1.set_ylabel('y values',fontsize=12)
#Assigning labels
lines = line1+line2+line3
labels = [l.get_label() for l in lines]
ax1.legend(lines,labels,loc='upper center', prop={'size':10}, bbox_to_anchor=(0.5, -0.13), fancybox=True, shadow=True, ncol=5)
ax1.set_xlabel('Categories',fontsize=14)
plt.setp(ax2.get_xticklabels(), visible=True)
title_string=('Plotting categories vs y values in matplotlib')
plt.suptitle(title_string, y=1.0, fontsize=17)
fig.tight_layout()
fig.subplots_adjust(top=0.92,bottom=0.2)
plt.show()
plt.savefig('myplot.jpg',bbox_inches='tight')
plt.close()

Body:
Matplotlib version 2.1.0 allows plotting categorical variables directly, just calling plt.plot(x,y) as usual, without the need to use range or get_xticklabels().

line1 = plt.plot(x_axis, data1,'ko-',label='line1')
line2 = plt.plot(x_axis, data2,'ro-',label='line2')
line3 = plt.plot(x_axis, data3,'mo-',label='line3')


问:
Expanding a list to include all possible pairwise combinations within a group
I am currently running a randomization where individuals of a given population are sampled and placed into groups of defined size. The result is a data frame seen below:

```<code>Ind Group
Sally   1
Bob 1
Sue 1
Joe 2
Jeff    2
Jess    2
Mary    2
Jim 3
James   3
</code>```

Is there a function which will allow me to expand the data set to show every possible within group pairing? (Desired output below). The pairings do not need to be reciprocal.

```<code>Group   Ind1    Ind2
1   Sally   Bob
1   Sally   Sue
1   Sue Bob
2   Joe Jeff
2   Joe Jess
2   Joe Mary
2   Jeff    Jess
2   Jess    Mary
2   Jeff    Mary
3   Jim James
</code>```

I feel like there must be a way to do this in dplyr, but for the life of me I can't seem to sort it out.

答:
An alternative dplyr & tidyr approach: The pipeline is a little longer, but the wrangling feels more straightforward to me. Start with combining all records in each group together. Next, pool and alphabetize all the names together to be able to eliminate the reciprocal/duplicates. Then finally separate the results back apart again.

```<code>left_join(dt, dt, by = "Group") %>%
    filter(Ind.x != Ind.y) %>%
    rowwise %>%
    mutate(name = toString(sort(c(Ind.x,Ind.y)))) %>%
    select(Group, name) %>%
    distinct %>%
    separate(name, into = c("Ind1", "Ind2")) %>%
    arrange(Group, Ind1, Ind2)
</code>```

start off with a weak cross join of all records in each group

filter out the self joins

collect up all the names in each row, sort them, and set them down together in the name column.

now that the names are alphabetized, remove the alphabetized reciprocals

pull the data apart back into separate columns.

```<code># A tibble: 10 x 3
   Group  Ind1  Ind2
 * <int> <chr> <chr>
 1     1   Bob Sally
 2     1 Sally   Sue
 3     1   Bob   Sue
 4     2  Jeff   Joe
 5     2  Jess   Joe
 6     2   Joe  Mary
 7     2  Jeff  Jess
 8     2  Jeff  Mary
 9     2  Jess  Mary
10     3 James   Jim
</code>```

Body:
I am currently running a randomization where individuals of a given population are sampled and placed into groups of defined size. The result is a data frame seen below:

Ind Group
Sally   1
Bob 1
Sue 1
Joe 2
Jeff    2
Jess    2
Mary    2
Jim 3
James   3

Is there a function which will allow me to expand the data set to show every possible within group pairing? (Desired output below). The pairings do not need to be reciprocal.

Group   Ind1    Ind2
1   Sally   Bob
1   Sally   Sue
1   Sue Bob
2   Joe Jeff
2   Joe Jess
2   Joe Mary
2   Jeff    Jess
2   Jess    Mary
2   Jeff    Mary
3   Jim James

I feel like there must be a way to do this in dplyr, but for the life of me I can't seem to sort it out.

Body:
An alternative dplyr & tidyr approach: The pipeline is a little longer, but the wrangling feels more straightforward to me. Start with combining all records in each group together. Next, pool and alphabetize all the names together to be able to eliminate the reciprocal/duplicates. Then finally separate the results back apart again.

left_join(dt, dt, by = "Group") %>%
    filter(Ind.x != Ind.y) %>%
    rowwise %>%
    mutate(name = toString(sort(c(Ind.x,Ind.y)))) %>%
    select(Group, name) %>%
    distinct %>%
    separate(name, into = c("Ind1", "Ind2")) %>%
    arrange(Group, Ind1, Ind2)

start off with a weak cross join of all records in each group

filter out the self joins

collect up all the names in each row, sort them, and set them down together in the name column.

now that the names are alphabetized, remove the alphabetized reciprocals

pull the data apart back into separate columns.

# A tibble: 10 x 3
   Group  Ind1  Ind2
 * <int> <chr> <chr>
 1     1   Bob Sally
 2     1 Sally   Sue
 3     1   Bob   Sue
 4     2  Jeff   Joe
 5     2  Jess   Joe
 6     2   Joe  Mary
 7     2  Jeff  Jess
 8     2  Jeff  Mary
 9     2  Jess  Mary
10     3 James   Jim


问:
How to use error_messages_for in a multi-model form?
I have two models: Album and Track. Album has many tracks, and Track belongs to album.

I'd like to have the ability to create as many tracks as needed while creating the album, similailiy to railscasts episode 197. Unlike the railscasts episode, though, the Track form contains both a title and a description - both are required.

Right now, the form looks like this:

```<code>Create New Album

Name: [      ]

    Track (remove link)
          Name:        [      ]
          Description: [      ]

    Track (remove link)
          Name:        [      ]
          Description: [      ]

(add track link)
</code>```

If I decide to submit the form blank, I get the following error messages on top of the form:

```<code>Description can't be blank
Title can't be blank
Title can't be blank
</code>```

These error messages are not specific to the model, all located at the top of the page, and appear only once for each model (note that I left the fields for both blank and the error messages appear only once - not specific to which track).

To generate the initial track fields, I added the following line in the new action of my album_controller: 2.times { @album.tracks.build }

The gist of what my form looks like is this:

```<code><% form_for @album do |f| %>
<%= f.error_messages %>

<%= f.label :title %><br />
<%= f.text_field :title %>

<% f.fields_for :tracks do |f, track| %>
  <%= render :partial => 'tracks/fields', :locals => {:f => f} %>
<% end %>

<%= f.submit "Submit" %>
<% end %>
</code>```

I tried replacing the top <%= f.error_messages %> with <%= error_messages_for @album %> (to only display the messages for the album), and adding a <%= error_messages_for track %> (to display the error messages specific to each track) - but this does not do the trick.
Does anybody know how to approach this?

Thanks!

答:
Similar to above, but, with the code below, I can test any object or array of objects for errors:

```<code><%= show_errors( [@company, @estabs], :header_ref => 'Company' ) %>
</code>```

```<code>def show_errors(objarray, opt)

    return '' if objarray.blank?

    err = [ ]
    html  = ""

    objarray.each { |obj|
            if obj.is_a?(Array)
                obj.each { |oo| html << show_errors([oo], opt) }
            elsif (obj.errors.count > 0 )
                err << obj.errors.full_messages #didnt worked with gem i18n 0.5.0
            end
              }

    return '' if (err.count==0) and (html.blank?)

    if err.count > 0
        err.flatten!            #remove sub-arrays
        err.each { |x| x.strip! }   #strip:remove espaces
        err.uniq!               #remove duplicated messages
        err.sort!

        header_ref = opt[:header_ref].nil?  ?  ""  :  opt[:header_ref]

        erro_str = (err.count == 1) ? 'erro' : 'erros'
        erro_verb = (err.count == 1) ? 'ocorreu' : 'ocorreram'

        html << '<div class="erros"  id="erros"> '
        html <<  "<b> #{header_ref}: #{err.count.to_s}  #{erro_str} #{erro_verb}: </b> "
        html << '<ul> '

        err.each  { |e| html << '<li> ' + e + ' </li>' }

        html << '</ul> </div>'
    end
    return html
end
</code>```

Body:
I have two models: Album and Track. Album has many tracks, and Track belongs to album.

I'd like to have the ability to create as many tracks as needed while creating the album, similailiy to railscasts episode 197. Unlike the railscasts episode, though, the Track form contains both a title and a description - both are required.

Right now, the form looks like this:

Create New Album

Name: [      ]

    Track (remove link)
          Name:        [      ]
          Description: [      ]

    Track (remove link)
          Name:        [      ]
          Description: [      ]

(add track link)

If I decide to submit the form blank, I get the following error messages on top of the form:

Description can't be blank
Title can't be blank
Title can't be blank

These error messages are not specific to the model, all located at the top of the page, and appear only once for each model (note that I left the fields for both blank and the error messages appear only once - not specific to which track).

To generate the initial track fields, I added the following line in the new action of my album_controller: 2.times { @album.tracks.build }

The gist of what my form looks like is this:

<% form_for @album do |f| %>
<%= f.error_messages %>

<%= f.label :title %>

<%= f.text_field :title %>

<% f.fields_for :tracks do |f, track| %>
  <%= render :partial => 'tracks/fields', :locals => {:f => f} %>
<% end %>

<%= f.submit "Submit" %>
<% end %>

I tried replacing the top <%= f.error_messages %> with <%= error_messages_for @album %> (to only display the messages for the album), and adding a <%= error_messages_for track %> (to display the error messages specific to each track) - but this does not do the trick.
Does anybody know how to approach this?

Thanks!

Body:
Similar to above, but, with the code below, I can test any object or array of objects for errors:

<%= show_errors( [@company, @estabs], :header_ref => 'Company' ) %>

def show_errors(objarray, opt)

    return '' if objarray.blank?

    err = [ ]
    html  = ""

    objarray.each { |obj|
            if obj.is_a?(Array)
                obj.each { |oo| html << show_errors([oo], opt) }
            elsif (obj.errors.count > 0 )
                err << obj.errors.full_messages #didnt worked with gem i18n 0.5.0
            end
              }

    return '' if (err.count==0) and (html.blank?)

    if err.count > 0
        err.flatten!            #remove sub-arrays
        err.each { |x| x.strip! }   #strip:remove espaces
        err.uniq!               #remove duplicated messages
        err.sort!

        header_ref = opt[:header_ref].nil?  ?  ""  :  opt[:header_ref]

        erro_str = (err.count == 1) ? 'erro' : 'erros'
        erro_verb = (err.count == 1) ? 'ocorreu' : 'ocorreram'

        html << '<div class="erros"  id="erros"> '
        html <<  "<b> #{header_ref}: #{err.count.to_s}  #{erro_str} #{erro_verb}: </b> "
        html << '<ul> '

        err.each  { |e| html << '<li> ' + e + ' </li>' }

        html << '</ul> </div>'
    end
    return html
end


答:
This is quite tricky.  I think you need to use lag() to see where the value changes and then do a cumulative sum:

```<code>select df.*,
       sum(case when prev_amount = amount then 0 else 1 end) over
           (partition by id1, id2 order by date desc) as rank
from (select df.*,
             lag(amount) over (partition by id1, id2 order by date desc) as prev_amount
      from df
     ) df;
</code>```

Title: SQL - Window Functions with dense_rank()

Body:
I have a dataset structured such as the one below stored in Hive, call it df:

+-----+-----+----------+--------+
| id1 | id2 |   date   | amount |
+-----+-----+----------+--------+
|   1 |   2 | 11-07-17 | 0.93   |
|   2 |   2 | 11-11-17 | 1.94   |
|   2 |   2 | 11-09-17 | 1.90   |
|   1 |   1 | 11-10-17 | 0.33   |
|   2 |   2 | 11-10-17 | 1.93   |
|   1 |   1 | 11-07-17 | 0.25   |
|   1 |   1 | 11-09-17 | 0.33   |
|   1 |   1 | 11-12-17 | 0.33   |
|   2 |   2 | 11-08-17 | 1.90   |
|   1 |   1 | 11-08-17 | 0.30   |
|   2 |   2 | 11-12-17 | 2.01   |
|   1 |   2 | 11-12-17 | 1.00   |
|   1 |   2 | 11-09-17 | 0.94   |
|   2 |   2 | 11-07-17 | 1.94   |
|   1 |   2 | 11-11-17 | 1.92   |
|   1 |   1 | 11-11-17 | 0.33   |
|   1 |   2 | 11-10-17 | 1.92   |
|   1 |   2 | 11-08-17 | 0.94   |
+-----+-----+----------+--------+

I wish to partition by id1 and id2, and then order by date descending within each grouping of id1 and id2, and then rank "amount" within that, where the same "amount" on consecutive days would receive the same rank. The ordered and ranked output I'd hope to see is shown here:

+-----+-----+------------+--------+------+
| id1 | id2 |    date    | amount | rank |
+-----+-----+------------+--------+------+
|   1 |   1 | 2017-11-12 | 0.33   |    1 |
|   1 |   1 | 2017-11-11 | 0.33   |    1 |
|   1 |   1 | 2017-11-10 | 0.33   |    1 |
|   1 |   1 | 2017-11-09 | 0.33   |    1 |
|   1 |   1 | 2017-11-08 | 0.30   |    2 |
|   1 |   1 | 2017-11-07 | 0.25   |    3 |
|   1 |   2 | 2017-11-12 | 1.00   |    1 |
|   1 |   2 | 2017-11-11 | 1.92   |    2 |
|   1 |   2 | 2017-11-10 | 1.92   |    2 |
|   1 |   2 | 2017-11-09 | 0.94   |    3 |
|   1 |   2 | 2017-11-08 | 0.94   |    3 |
|   1 |   2 | 2017-11-07 | 0.93   |    4 |
|   2 |   2 | 2017-11-12 | 2.01   |    1 |
|   2 |   2 | 2017-11-11 | 1.94   |    2 |
|   2 |   2 | 2017-11-10 | 1.93   |    3 |
|   2 |   2 | 2017-11-09 | 1.90   |    4 |
|   2 |   2 | 2017-11-08 | 1.90   |    4 |
|   2 |   2 | 2017-11-07 | 1.94   |    5 |
+-----+-----+------------+--------+------+

I attempted this with the following SQL query:

SELECT
    id1,
    id2,
    date,
    amount,
    dense_rank() OVER (PARTITION BY id1, id2 ORDER BY date DESC) AS rank
FROM
    df
GROUP BY
    id1,
    id2,
    date,
    amount

But that query doesn't seem to be doing what I'd like it to as I'm not receiving the output I'm looking for.

It seems like a window function using dense_rank, partition by and order by is what I need but I can't quite seem to get it to give me that sample output that I desire. Any help would be much appreciated! Thanks!

Body:
This is quite tricky.  I think you need to use lag() to see where the value changes and then do a cumulative sum:

select df.*,
       sum(case when prev_amount = amount then 0 else 1 end) over
           (partition by id1, id2 order by date desc) as rank
from (select df.*,
             lag(amount) over (partition by id1, id2 order by date desc) as prev_amount
      from df
     ) df;


问:
How do I find out, which user is running the current php script?
How do we determine which user the php script is running under when I run the script on server? Is it running under the same user as apache or phpmyadmin by chance? My question maybe wrongly framed but I want to know which user so that I set appropriate permission for different folders in /var</p>

答: Do not use "whoami". When you execute a process the user will not necessarily be the same as the effective user during running of a script. But in any case "id" would provide much more useful information. Instead call get_current_user(). So simple!</p>


问:
Python - For loop through dictionary with value as findall regular expression
I have a csv file with information on weather everyday, by year. I've created a dictionary where the keys are the year and the value is a regular expression to collect all dates within a year, like so

```<code>import csv, re

with open('weather_data.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')

csvfile = csvfile.read()

years = {'year_92': re.findall(r'\d+/\d+/1992', csvfile), 'year_93': re.findall(r'\d+/\d+/1993', csvfile),
     'year_94': re.findall(r'\d+/\d+/1994', csvfile), 'year_95': re.findall(r'\d+/\d+/1995', csvfile)}
</code>```

The CSVs first column is the date in mm/dd/yyyy format and the second is temperatures. What I'd like to do is use the best method to take all the temperatures in a single year and find their average.

Currently, I am trying to loop through the dictionary to append (ie.) every temperature in 1992, to a list so I could then average that list.

```<code>temps = csvfile[1]
temp_92 = []
 for line in years.items(), temps:
     temp_92.append(line)
     print(temp_92)
</code>```

However, obviously something is wrong with this. The code does run, except it's giving back mm/dd/yy. I tried switching up the csvfile[] but no results.

Here is what my output looks like

```<code>[dict_items([('year_95', ['1/1/1995', '1/2/1995', '1/3/1995', '1/4/1995', '1/5/1995', '1/6/1995', '1/7/1995', '1/8/1995', '1/9/1995', '1/10/1995', '1/11/1995', '1/12/1995', '1/13/1995', '1/14/1995', '1/15/1995', '1/16/1995', '1/17/1995', '1/18/1995', '1/19/1995', '1/20/1995', '1/21/1995', '1/22/1995', '1/23/1995', '1/24/1995', '1/25/1995', '1/26/1995', '1/27/1995', '1/28/1995', '1/30/1995', '1/31/1995' ...and so on
</code>```

EDIT: Here is some example data from the CSV per request! Tried to format best I can.

A1: Date            B1: Temp

A2: 10/1/1992    B2: 53

A3: 10/2/1992    B3: 58

A4: 10/3/1992    B4: 62

答:
I think that your regex and csv reader are overkill for this. I've made an assumtion about you input format, but the following uses all standard libarary.

Input file example

```<code>A1: Date B1: Temp
A2: 10/1/1992 B2: 53
A3: 10/2/1992 B3: 58
A4: 10/3/1992 B4: 62
</code>```

Example average calculator per year:

```<code>from itertools import groupby
from functools import reduce

csv_file = '/tmp/temp_example.txt'

with open(csv_file, 'r') as csv_fh:
    next(csv_fh)  # skip header
    split_lines = [line.strip('\n').split(' ')[1::2] for line in csv_fh]
    split_lines.sort(key=lambda x: x[0])  # sort by date first
    # group by year
    year_temps = {}
    for key, group in groupby(split_lines, lambda x: x[0].split('/')[-1]):
        year_temps[key] = [int(row[1]) for row in group]
    yearly_averages = {year: (reduce(lambda x, y: x + y, temps) / len(temps))
                       for year, temps in year_temps.items()}
    print(yearly_averages)
</code>```

The strategy here is read in your lines and split them into their columns to start with, then use groupby to create your dict of year: [temps]. The average can be calculated however you most prefer.

Your data is pretty structured to start with and really doesn't need the complexity of regex's to extract the years.

Body:
I have a csv file with information on weather everyday, by year. I've created a dictionary where the keys are the year and the value is a regular expression to collect all dates within a year, like so

import csv, re

with open('weather_data.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')

csvfile = csvfile.read()

years = {'year_92': re.findall(r'\d+/\d+/1992', csvfile), 'year_93': re.findall(r'\d+/\d+/1993', csvfile),
     'year_94': re.findall(r'\d+/\d+/1994', csvfile), 'year_95': re.findall(r'\d+/\d+/1995', csvfile)}

The CSVs first column is the date in mm/dd/yyyy format and the second is temperatures. What I'd like to do is use the best method to take all the temperatures in a single year and find their average.

Currently, I am trying to loop through the dictionary to append (ie.) every temperature in 1992, to a list so I could then average that list.

temps = csvfile[1]
temp_92 = []
 for line in years.items(), temps:
     temp_92.append(line)
     print(temp_92)

However, obviously something is wrong with this. The code does run, except it's giving back mm/dd/yy. I tried switching up the csvfile[] but no results.

Here is what my output looks like

[dict_items([('year_95', ['1/1/1995', '1/2/1995', '1/3/1995', '1/4/1995', '1/5/1995', '1/6/1995', '1/7/1995', '1/8/1995', '1/9/1995', '1/10/1995', '1/11/1995', '1/12/1995', '1/13/1995', '1/14/1995', '1/15/1995', '1/16/1995', '1/17/1995', '1/18/1995', '1/19/1995', '1/20/1995', '1/21/1995', '1/22/1995', '1/23/1995', '1/24/1995', '1/25/1995', '1/26/1995', '1/27/1995', '1/28/1995', '1/30/1995', '1/31/1995' ...and so on

EDIT: Here is some example data from the CSV per request! Tried to format best I can.

A1: Date            B1: Temp

A2: 10/1/1992    B2: 53

A3: 10/2/1992    B3: 58

A4: 10/3/1992    B4: 62

Body:
I think that your regex and csv reader are overkill for this. I've made an assumtion about you input format, but the following uses all standard libarary.

Input file example

A1: Date B1: Temp
A2: 10/1/1992 B2: 53
A3: 10/2/1992 B3: 58
A4: 10/3/1992 B4: 62

Example average calculator per year:

from itertools import groupby
from functools import reduce

csv_file = '/tmp/temp_example.txt'

with open(csv_file, 'r') as csv_fh:
    next(csv_fh)  # skip header
    split_lines = [line.strip('\n').split(' ')[1::2] for line in csv_fh]
    split_lines.sort(key=lambda x: x[0])  # sort by date first
    # group by year
    year_temps = {}
    for key, group in groupby(split_lines, lambda x: x[0].split('/')[-1]):
        year_temps[key] = [int(row[1]) for row in group]
    yearly_averages = {year: (reduce(lambda x, y: x + y, temps) / len(temps))
                       for year, temps in year_temps.items()}
    print(yearly_averages)

The strategy here is read in your lines and split them into their columns to start with, then use groupby to create your dict of year: [temps]. The average can be calculated however you most prefer.

Your data is pretty structured to start with and really doesn't need the complexity of regex's to extract the years.