问:
Mono + named/optional parameters = compiler bug?
I have encountered some unforeseen consequences of porting to mono 2.8.1. Problem can be boiled down to a sample program (I have been unable to reduce it further, after cutting several classes and ~1000 lines of code to the file quoted below)

```<code>public class Person
{
    public Person(int age, string name = null){}
    public Person(double income, string name = null){}
    public Person(double income, int age, string name = null){}
}

class Program
{
    static void Main()
    {
        Person p = new Person(1.0, name: "John Doe");
    }
}
</code>```

Compilation of above code with mcs gives output:

```<code>test.cs(22,24): error CS0584: Internal compiler error: Internal error
test.cs(22,20): error CS0266: Cannot implicitly convert type `object' to `NamedParams.Person'.
An explicit conversion exists (are you missing a cast?)
Compilation failed: 2 error(s), 0 warnings
</code>```

Removing use of optional/named parameter (i.e. calling new Person(1.0, null, "John Doe") or new Person(1.0, null, name:"John Doe"), or new Person(1.0, "John Doe") ) leads to flawless compilation. Also, under VS2010 the file (and whole solution with which I started with) compiles fine. Casting removes error CS0266, but not CS0584 -- so no surprise there.

My question: is it me doing something wrong, or mcs (i.e. bug in mcs is obvious to me -- what else ,,internal error'' would mean, but perhaps it's ok such program won't compile), or maybe Microsoft compiler in VS2010 should not let such code to compile?

I bet it's mcs who's wrong (unable to guess right constructor), but perhaps it's otherwise and I shouldn't know better?

PS. I tried searching for a known bug like this in both Google and Novell's Bugzilla, but was unable to find anything relevant. Again, I may be blind ;)

答:
Okay, here goes. The crash is indeed due to the third overload, Person(double income, int age, string name = null).
The compiler sees you are trying to pass less arguments than what are listed in the signature so it goes looking for optional arguments. It happily notices that name is optional and assumes you are not passing that argument. It does this by appending a placeholder at the end of the supplied arguments. Next, it goes to reorder the named arguments in the list so they end up in their right position. This means John Doe is now correctly at the last position for name, but the placeholder gets into the age position. The compiler then tries to fill in the default values, but is shocked to find a placeholder at a location which has no default value. It thinks this can not happen, since the placeholder was only added for an optional argument and now suddenly it is not optional anymore. Not knowing what to do, it throws an exception.

The following patch seems to fix the issue (however it may break something else, so no warranty):

```<code>--- mono-2.6.7.orig/mcs/mcs/ecore.cs    2009-10-02 12:51:12.000000000 +0200
+++ mono-2.6.7/mcs/mcs/ecore.cs 2010-12-21 02:26:44.000000000 +0100
@@ -3803,6 +3803,15 @@

                                int args_gap = Math.Abs (arg_count - param_count);
                                if (optional_count != 0) {
+                                       // readjust for optional arguments passed as named arguments
+                                       for (int i = 0; i < arguments.Count; i++) {
+                                               NamedArgument na = arguments[i] as NamedArgument;
+                                               if (na == null)
+                                                       continue;
+                                               int index = pd.GetParameterIndexByName (na.Name.Value);
+                                               if (pd.FixedParameters[index].HasDefaultValue)
+                                                       optional_count--;
+                                       }
                                        if (args_gap > optional_count)
                                                return int.MaxValue - 10000 + args_gap - optional_count;
</code>```

Body:
I have encountered some unforeseen consequences of porting to mono 2.8.1. Problem can be boiled down to a sample program (I have been unable to reduce it further, after cutting several classes and ~1000 lines of code to the file quoted below)

public class Person
{
    public Person(int age, string name = null){}
    public Person(double income, string name = null){}
    public Person(double income, int age, string name = null){}
}

class Program
{
    static void Main()
    {
        Person p = new Person(1.0, name: "John Doe");
    }
}

Compilation of above code with mcs gives output:

test.cs(22,24): error CS0584: Internal compiler error: Internal error
test.cs(22,20): error CS0266: Cannot implicitly convert type `object' to `NamedParams.Person'.
An explicit conversion exists (are you missing a cast?)
Compilation failed: 2 error(s), 0 warnings

Removing use of optional/named parameter (i.e. calling new Person(1.0, null, "John Doe") or new Person(1.0, null, name:"John Doe"), or new Person(1.0, "John Doe") ) leads to flawless compilation. Also, under VS2010 the file (and whole solution with which I started with) compiles fine. Casting removes error CS0266, but not CS0584 -- so no surprise there.

My question: is it me doing something wrong, or mcs (i.e. bug in mcs is obvious to me -- what else ,,internal error'' would mean, but perhaps it's ok such program won't compile), or maybe Microsoft compiler in VS2010 should not let such code to compile?

I bet it's mcs who's wrong (unable to guess right constructor), but perhaps it's otherwise and I shouldn't know better?

PS. I tried searching for a known bug like this in both Google and Novell's Bugzilla, but was unable to find anything relevant. Again, I may be blind ;)

Body:
Okay, here goes. The crash is indeed due to the third overload, Person(double income, int age, string name = null).
The compiler sees you are trying to pass less arguments than what are listed in the signature so it goes looking for optional arguments. It happily notices that name is optional and assumes you are not passing that argument. It does this by appending a placeholder at the end of the supplied arguments. Next, it goes to reorder the named arguments in the list so they end up in their right position. This means John Doe is now correctly at the last position for name, but the placeholder gets into the age position. The compiler then tries to fill in the default values, but is shocked to find a placeholder at a location which has no default value. It thinks this can not happen, since the placeholder was only added for an optional argument and now suddenly it is not optional anymore. Not knowing what to do, it throws an exception.

The following patch seems to fix the issue (however it may break something else, so no warranty):

--- mono-2.6.7.orig/mcs/mcs/ecore.cs    2009-10-02 12:51:12.000000000 +0200
+++ mono-2.6.7/mcs/mcs/ecore.cs 2010-12-21 02:26:44.000000000 +0100
@@ -3803,6 +3803,15 @@

                                int args_gap = Math.Abs (arg_count - param_count);
                                if (optional_count != 0) {
+                                       // readjust for optional arguments passed as named arguments
+                                       for (int i = 0; i < arguments.Count; i++) {
+                                               NamedArgument na = arguments[i] as NamedArgument;
+                                               if (na == null)
+                                                       continue;
+                                               int index = pd.GetParameterIndexByName (na.Name.Value);
+                                               if (pd.FixedParameters[index].HasDefaultValue)
+                                                       optional_count--;
+                                       }
                                        if (args_gap > optional_count)
                                                return int.MaxValue - 10000 + args_gap - optional_count;


来源: stackexchange

问:
Print column names only once in shell script
Here is my shell script and It is working fine without any errors. But i want to get output differently.

Script:

```<code>#!/bin/bash
DB_USER='root'
DB_PASSWD='123456'
DB_NAME='job'
Table_Name='status_table'
#sql=select job_name, date,status from $DB_NAME.$Table_Name where job_name='$f1' and date=CURDATE()
file="/root/jobs.txt"
while read -r f1
do
    mysql -N -u$DB_USER -p$DB_PASSWD  <<EOF
select job_name, date,status from $DB_NAME.$Table_Name where job_name='$f1' and date=CURDATE()

EOF
done <"$file"
</code>```

Source Table:

```<code>mysql> select * from job.status_table
+---------+----------+------------+-----------+
| Job_id  | Job Name |     date   |   status  |
+---------+----------+--------+---------------+
|   111   |    AA    | 2016-12-01 | completed |
|   112   |    BB    | 2016-12-01 | completed |
|   113   |    CC    | 2016-12-02 | completed |
|   112   |    BB    | 2016-12-01 | completed |
|   114   |    DD    | 2016-12-02 | completed |
|   201   |    X     | 2016-12-03 | completed |
|   202   |    y     | 2016-12-04 | completed |
|   203   |    z     | 2016-12-03 | completed |
|   111   |    A     | 2016-12-04 | completed |
+---------+----------+------------+-----------+
</code>```

Input text file

```<code>[rteja@server0 ~]# more jobs.txt
AA
BB
CC
DD
X
Y
Z
A
ABC
XYZ
</code>```

Output - Supressed coumn names

```<code>(mysql -N -u$DB_USER -p$DB_PASSWD  <<EOF)
[rteja@server0 ~]# ./script.sh
  AA       2016-12-01   completed
  BB       2016-12-01   completed
</code>```

Output - without Suppressed column names, output printing the columns names for every loop iteration.

```<code>(mysql -u$DB_USER -p$DB_PASSWD  <<EOF)

    [rteja@server0 ~]# ./script.sh
    job_name      date        status
      AA       2016-12-01   completed
    job_name      date        status
      BB       2016-12-01   completed
</code>```

Challenges:

1. Want to print column names only once in output and the result i want to store in CSV file.

2. I don't want to expose password & username in code to everyone. Is there way to hide like i heard we can create environmental variables and call it in the script. And we can set the permissions for the environmental variable file to prevent everyone to access it, and only our should be able to access it.

答:
Rather than executing a select query multiple times you can run a single query as:

```<code>job_name in ('AA','BB','CC'...)
</code>```

To do that first read complete file in an array using mapfile:

```<code>mapfile -t arr < jobs.txt
</code>```

Then format the array values into a list of values suited for IN operator:

```<code>printf -v cols "'%s'," "${arr[@]}"
cols="(${cols%,})"
</code>```

Display your values:

```<code>echo "$cols"
('AA','BB','CC','DD','X','Y','Z','A','ABC','XYZ')
</code>```

Finally run your SQL query as:

```<code>mysql -N -u$DB_USER -p$DB_PASSWD <<EOF
select job_name, date,status from $DB_NAME.$Table_Name
where job_name IN "$cols" and date=CURDATE();
EOF
</code>```

To securely connecting to MySQL use login-paths (.mylogin.cnf)

As per MySQL manual:

The best way to specify server connection information is with your .mylogin.cnf file. Not only is this file encrypted, but any logging of the utility execution does not expose the connection information.

ContentLicense: CC BY-SA 3.0

Body:
Here is my shell script and It is working fine without any errors. But i want to get output differently.

Script:

#!/bin/bash
DB_USER='root'
DB_PASSWD='123456'
DB_NAME='job'
Table_Name='status_table'
#sql=select job_name, date,status from $DB_NAME.$Table_Name where job_name='$f1' and date=CURDATE()
file="/root/jobs.txt"
while read -r f1
do
    mysql -N -u$DB_USER -p$DB_PASSWD  <<EOF
select job_name, date,status from $DB_NAME.$Table_Name where job_name='$f1' and date=CURDATE()

EOF
done <"$file"

Source Table:

mysql> select * from job.status_table
+---------+----------+------------+-----------+
| Job_id  | Job Name |     date   |   status  |
+---------+----------+--------+---------------+
|   111   |    AA    | 2016-12-01 | completed |
|   112   |    BB    | 2016-12-01 | completed |
|   113   |    CC    | 2016-12-02 | completed |
|   112   |    BB    | 2016-12-01 | completed |
|   114   |    DD    | 2016-12-02 | completed |
|   201   |    X     | 2016-12-03 | completed |
|   202   |    y     | 2016-12-04 | completed |
|   203   |    z     | 2016-12-03 | completed |
|   111   |    A     | 2016-12-04 | completed |
+---------+----------+------------+-----------+

Input text file

[rteja@server0 ~]# more jobs.txt
AA
BB
CC
DD
X
Y
Z
A
ABC
XYZ

Output - Supressed coumn names

(mysql -N -u$DB_USER -p$DB_PASSWD  <<EOF)
[rteja@server0 ~]# ./script.sh
  AA       2016-12-01   completed
  BB       2016-12-01   completed

Output - without Suppressed column names, output printing the columns names for every loop iteration.

(mysql -u$DB_USER -p$DB_PASSWD  <<EOF)

    [rteja@server0 ~]# ./script.sh
    job_name      date        status
      AA       2016-12-01   completed
    job_name      date        status
      BB       2016-12-01   completed

Challenges:

1. Want to print column names only once in output and the result i want to store in CSV file.

2. I don't want to expose password & username in code to everyone. Is there way to hide like i heard we can create environmental variables and call it in the script. And we can set the permissions for the environmental variable file to prevent everyone to access it, and only our should be able to access it.

Body:
Rather than executing a select query multiple times you can run a single query as:

job_name in ('AA','BB','CC'...)

To do that first read complete file in an array using mapfile:

mapfile -t arr < jobs.txt

Then format the array values into a list of values suited for IN operator:

printf -v cols "'%s'," "${arr[@]}"
cols="(${cols%,})"

Display your values:

echo "$cols"
('AA','BB','CC','DD','X','Y','Z','A','ABC','XYZ')

Finally run your SQL query as:

mysql -N -u$DB_USER -p$DB_PASSWD <<EOF
select job_name, date,status from $DB_NAME.$Table_Name
where job_name IN "$cols" and date=CURDATE();
EOF

To securely connecting to MySQL use login-paths (.mylogin.cnf)

As per MySQL manual:

The best way to specify server connection information is with your .mylogin.cnf file. Not only is this file encrypted, but any logging of the utility execution does not expose the connection information.


问:
My responsive menu gets gliched
I am working on my responsive menu that will be on desktop view a normal horizontal menu, but when the screen is smaller than 992px a hamburger style button will appear which will toggle a push-in side menu.

The problem i am facing is that the menu glitches when resizing the window aka switching between desktop and mobile view.

Here is my code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<title>Menu</title>
<meta charset="utf-8">
<!-- 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>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

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

<body>

<div class="container">
</code>```

my css:

```<code>@media screen and (min-width: 992px) {

}
</code>```

and my js:

```<code>$(document).ready(function(){
    $('#mobile-icon').click(function(){
        $(this).toggleClass('closed');
    });

    $('.expander-icon').click(function(){
        $(this).parent().toggleClass('active-menu');

    });

});

$(window).on('load resize', function () {
    var screenWidth = $( window ).width();
    if(screenWidth < 992){
        $('.u').addClass('isMobile');

        $('#icon').click(function(){
            $(this).toggleClass("open closed");
            if($( "#con" ).hasClass( "open" )){
                $('.gation').css('margin-left',"0");

            }
            else{
                $('.asdn').css('margin-left',"-70%");
            }
        });

    }
});
</code>```

答:
Simplify your JS, move everything you can to CSS. Instead of modifying margin left in JS do it in CSS, and whenever you toggle class open on mr-mobile-icon, toggle it also on mr-navigation. Your $(window).on('load resize', ... ); is unnecessary. Just remove it, let CSS do everything for you.

CSS:

```<code>@media screen and (max-width: 991px) {
    .mr-navigation {
        // style
        margin-left: -70%;
    }
    .mr-navigation.opened {
        margin-left: 0;
    }
}
</code>```

JS:

```<code>$('#mr-mobile-icon').click(function(){
    $(this).toggleClass('open');
    $('.mr-navigation').toggleClass('open');
});
</code>```

Title: My responsive menu gets gliched

Body:
I am working on my responsive menu that will be on desktop view a normal horizontal menu, but when the screen is smaller than 992px a hamburger style button will appear which will toggle a push-in side menu.

The problem i am facing is that the menu glitches when resizing the window aka switching between desktop and mobile view.

Here is my code:

<!DOCTYPE html>

<title>Menu</title>
<meta charset="utf-8">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

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

my css:

@media screen and (min-width: 992px) {

}

and my js:

$(document).ready(function(){
    $('#mobile-icon').click(function(){
        $(this).toggleClass('closed');
    });

    $('.expander-icon').click(function(){
        $(this).parent().toggleClass('active-menu');

    });

});

$(window).on('load resize', function () {
    var screenWidth = $( window ).width();
    if(screenWidth < 992){
        $('.u').addClass('isMobile');

        $('#icon').click(function(){
            $(this).toggleClass("open closed");
            if($( "#con" ).hasClass( "open" )){
                $('.gation').css('margin-left',"0");

            }
            else{
                $('.asdn').css('margin-left',"-70%");
            }
        });

    }
});

Body:
Simplify your JS, move everything you can to CSS. Instead of modifying margin left in JS do it in CSS, and whenever you toggle class open on mr-mobile-icon, toggle it also on mr-navigation. Your $(window).on('load resize', ... ); is unnecessary. Just remove it, let CSS do everything for you.

CSS:

@media screen and (max-width: 991px) {
    .mr-navigation {
        // style
        margin-left: -70%;
    }
    .mr-navigation.opened {
        margin-left: 0;
    }
}

JS:

$('#mr-mobile-icon').click(function(){
    $(this).toggleClass('open');
    $('.mr-navigation').toggleClass('open');
});


问:
Minus in w3c specification grammar
What does the minus sign mean?

```<code>[14]    CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
</code>```

From the w3c XML 1.0 specification

Also, where can I find information related to the syntax grammar?  I'm having troubling finding the specification about the specification, if that makes any sense.

答:
Minus  (-) is part of the Extended Backus-Naur Form (EBNF) notation used by the W3C XML Recommendation to define the formal grammar of XML:

Minus (-) in A - B matches any string that matches A but does
not match B.

How to interpret the CharData production

[14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)

[^<&]* is a string of any characters except the markup start characters, < and &.

']]>' is a literal string that is used to mark the end of CDATA.

([^<&]* ']]>' [^<&]*) is any string without < and & that
doesn't contain the end marker for a CDATA section.

Therefore, altogether, CharData can be any string that doesn't contain the markup start characters, < and &, and doesn't contain the CDATA end marker, ]]>.

See also

Understanding XML CharData EBNF

Title: Minus in w3c specification grammar

Body:
What does the minus sign mean?

[14]    CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)

From the w3c XML 1.0 specification

Also, where can I find information related to the syntax grammar?  I'm having troubling finding the specification about the specification, if that makes any sense.

ContentLicense: CC BY-SA 4.0


问:
Spring Batch -@BeforeStep not getting invoked in Partitioner
We are trying to implement a batch job using spring batch partitioning.In this in "step 2" is a partitioned step where I need some data from step 1 for processing.I used StepExecutionContext which will be promoted to job Execution Context at step1 to store this data.

I tried to use @BeforeStep annotation in partitioner class to get  the stepExecutionContext
from which I can extract the data stored previously and put it in ExecutionContext of the partitioner .But the method with @BeforeStep annotation is not getting invoked in the partitioner.

Is there any other way to achieve this.

Partitioner Implementation

```<code>public class NtfnPartitioner implements Partitioner {

    private int index = 0;
    String prev_job_time  = null;
    String curr_job_time  = null;

    private StepExecution stepExecution ;
    ExecutionContext executionContext ;

    @Override
    public Map<String, ExecutionContext> partition(int gridSize)
    {

           System.out.println("Entered Partitioner");
           List<Integer> referencIds = new ArrayList<Integer>();
           for (int i = 0; i < gridSize;i++) {
            referencIds.add(index++);
           }
           Map<String, ExecutionContext> results = new LinkedHashMap<String,ExecutionContext>();
          for (int referencId : referencIds) {
            ExecutionContext context = new ExecutionContext();
            context.put("referenceId", referencId);
            context.put(NtfnConstants.PREVIOUS_JOB_TIME, prev_job_time);
            context.put(NtfnConstants.JOB_START_TIME, curr_job_time);
            results.put("partition." + referencId, context);
          }
            return results;
        }

    @BeforeStep
    public void beforeStep(StepExecution stepExecution) {
        // TODO Auto-generated method stub
          System.out.println("Entered Before step in partion");
          JobExecution jobExecution = stepExecution.getJobExecution();
          ExecutionContext jobContext = jobExecution.getExecutionContext();
          System.out.println("ExecutionContext"+jobContext);
          String prev_job_time  = (String) jobContext.get(NtfnConstants.PREVIOUS_JOB_TIME);
          String curr_job_time  = (String) jobContext.get(NtfnConstants.JOB_START_TIME);

    }
</code>```

答:
The bean should be step scoped.

Java, annotate class:

```<code>@StepScope
</code>```

XML, in bean definition:

```<code>scope="step"
</code>```

Also look at this answer regarding proxied bean (not sure if this applies to you since no other code than the partitioner was provided). In this case you can still add your partitioner as a listener explicitly during step building:

```<code>@Autowired
private NtfnPartitioner partitioner;

...

final Step masterStep = stepBuilderFactory.get("master")
                    .listener(partitioner)
                    .partitioner("slave", partitioner)
                    .step(slave)
                    ...
</code>```

Or if your partitioner is not bean (e.g. you are creating it based on something dynamic), you can still add it as a listener:

```<code>final NtfnPartitioner partitioner = new NtfnPartitioner();
final Step masterStep = stepBuilderFactory.get("master")
                    .listener(partitioner)
                    .partitioner("slave", partitioner)
                    .step(slave)
                    ...
</code>```

Body:
We are trying to implement a batch job using spring batch partitioning.In this in "step 2" is a partitioned step where I need some data from step 1 for processing.I used StepExecutionContext which will be promoted to job Execution Context at step1 to store this data.

I tried to use @BeforeStep annotation in partitioner class to get  the stepExecutionContext
from which I can extract the data stored previously and put it in ExecutionContext of the partitioner .But the method with @BeforeStep annotation is not getting invoked in the partitioner.

Is there any other way to achieve this.

Partitioner Implementation

public class NtfnPartitioner implements Partitioner {

    private int index = 0;
    String prev_job_time  = null;
    String curr_job_time  = null;

    private StepExecution stepExecution ;
    ExecutionContext executionContext ;

    @Override
    public Map<String, ExecutionContext> partition(int gridSize)
    {

           System.out.println("Entered Partitioner");
           List<Integer> referencIds = new ArrayList<Integer>();
           for (int i = 0; i < gridSize;i++) {
            referencIds.add(index++);
           }
           Map<String, ExecutionContext> results = new LinkedHashMap<String,ExecutionContext>();
          for (int referencId : referencIds) {
            ExecutionContext context = new ExecutionContext();
            context.put("referenceId", referencId);
            context.put(NtfnConstants.PREVIOUS_JOB_TIME, prev_job_time);
            context.put(NtfnConstants.JOB_START_TIME, curr_job_time);
            results.put("partition." + referencId, context);
          }
            return results;
        }

    @BeforeStep
    public void beforeStep(StepExecution stepExecution) {
        // TODO Auto-generated method stub
          System.out.println("Entered Before step in partion");
          JobExecution jobExecution = stepExecution.getJobExecution();
          ExecutionContext jobContext = jobExecution.getExecutionContext();
          System.out.println("ExecutionContext"+jobContext);
          String prev_job_time  = (String) jobContext.get(NtfnConstants.PREVIOUS_JOB_TIME);
          String curr_job_time  = (String) jobContext.get(NtfnConstants.JOB_START_TIME);

    }

Body:
The bean should be step scoped.

Java, annotate class:

@StepScope

XML, in bean definition:

scope="step"

Also look at this answer regarding proxied bean (not sure if this applies to you since no other code than the partitioner was provided). In this case you can still add your partitioner as a listener explicitly during step building:

@Autowired
private NtfnPartitioner partitioner;

...

final Step masterStep = stepBuilderFactory.get("master")
                    .listener(partitioner)
                    .partitioner("slave", partitioner)
                    .step(slave)
                    ...

Or if your partitioner is not bean (e.g. you are creating it based on something dynamic), you can still add it as a listener:

final NtfnPartitioner partitioner = new NtfnPartitioner();
final Step masterStep = stepBuilderFactory.get("master")
                    .listener(partitioner)
                    .partitioner("slave", partitioner)
                    .step(slave)
                    ...


问:
How can I add scrolling functionality to my navigation bar?
I'm trying to get my navigation buttons to scroll to parts of the page as needed on click. How can I do this?

.topnav {
  background-color: #333;
  overflow: hidden;
}

.topnav a {
  float: right;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.topnav a.active {
  background-color: #4CAF50;
  color: white;
}

.profile-id {
  position: center;
}

form {
  display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href='//fonts.googleapis.com/css?family=Bungee Inline' rel='stylesheet'>

<div class="topnav" id="myTopnav">
  Home
  Projects
  Contact
  About
</div>

<header>
  <p style="text-align: center; font-size: 48pt; margin-top: 3%;"> New Wave Design Studios</p>
</header>

<style>
  body {
    margin: 0;
    padding: 0;
    position: absolute;
    font-family: 'Bungee Inline';
    background-image: url(https://arielle.com.au/wp-content/uploads/2016/04/wave-photography-dark-2.jpg), url(http://imageshack.com/a/img922/4958/Ca6YSO.jpg), url(http://imageshack.com/a/img923/1588/duLIdx.png);
    background-repeat: no-repeat;
    background-position: center top, 100% 300px, 0% 870px;
    background-size: 100% 380px, 40%, 42%;
  }
</style>

<p style="margin: 10% 50% 10% 5%; font-size: 14pt; text-align: justified;"> NWDS set up shop in sunny So-Flo. The company was set up with the intention of coding an array of projects to prepare a strong, diverse portfolio for it's founder: Armando F III. With the knowledge from the FreeCodeCamp curriculum and a degree in software
  development, Armando hopes to build NWDS and make a breakout appearence in the software scene.
  <br></br>
  @JadeCoder
</p>

<p style="margin: 10% 5% 10% 50%; font-size: 14pt; text-align: justified;"> You can contact Armando through his freelance portfolio on Upwork by clicking
  Here.
</p>

<p style="text-align: center; font-size: 14pt;"> <u>Projects</u> </p>

  <img src="https://imagizer.imageshack.us/v2/424x283q90/922/l43R2Y.jpg" alt="Nuclear Plant" align="left" style="margin-left: 150px; margin-top: 25px" height="300px" width="400px">

  <img src="https://imagizer.imageshack.us/v2/1020x680q90/924/2VMA4f.jpg" alt="SpaceX Launch" align: "center" style="margin-left: 150px; margin-top: 25px" height="300px" width="500px">

  <img src="https://imagizer.imageshack.us/v2/275x183q90/923/KfsrjN.jpg" alt="Code" align: "right" style="margin-left: 150px; margin-top: 25px" height="300px" width="400px">
</code>```

答:
I always use my own script, I hope this works for you.

Make sure to include jQuery in your  tag like this:

HTML:

```<code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</code>```

JavaScript:

```<code>$(function() {
    $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: target.offset().top - $('.header').outerHeight(true)
                }, 1000);
            }
        }
        return false;
    });
});
</code>```

Doing it this way, you can still control what happens if a user (let's say) scrolls:

```<code>$(function() {

    // previous code

    $(window).on('touchmove wheel mousewheel', function(e) {
        if ( e.type == "wheel" || e.type == "touchmove") {
            $('html, body').stop();
        }
    });
});
</code>```

This way, the animation will stop whenever the user starts scrolling manually (while the animation is still running).

Body:
I'm trying to get my navigation buttons to scroll to parts of the page as needed on click. How can I do this?

.topnav {
  background-color: #333;
  overflow: hidden;
}

.topnav a {
  float: right;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.topnav a.active {
  background-color: #4CAF50;
  color: white;
}

.profile-id {
  position: center;
}

form {
  display: inline;
}

<link href='//fonts.googleapis.com/css?family=Bungee Inline' rel='stylesheet'>

  Home
  Projects
  Contact
  About

 New Wave Design Studios

 NWDS set up shop in sunny So-Flo. The company was set up with the intention of coding an array of projects to prepare a strong, diverse portfolio for it's founder: Armando F III. With the knowledge from the FreeCodeCamp curriculum and a degree in software
  development, Armando hopes to build NWDS and make a breakout appearence in the software scene.

  @JadeCoder

 You can contact Armando through his freelance portfolio on Upwork by clicking
  Here.

 Projects

Body:
I always use my own script, I hope this works for you.

Make sure to include jQuery in your <head> tag like this:

HTML:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

JavaScript:

$(function() {
    $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: target.offset().top - $('.header').outerHeight(true)
                }, 1000);
            }
        }
        return false;
    });
});

Doing it this way, you can still control what happens if a user (let's say) scrolls:

$(function() {

    // previous code

    $(window).on('touchmove wheel mousewheel', function(e) {
        if ( e.type == "wheel" || e.type == "touchmove") {
            $('html, body').stop();
        }
    });
});

This way, the animation will stop whenever the user starts scrolling manually (while the animation is still running).


问:
Retrieving values using the key from parsed json using jquery/javascript
using a function(below), i'm trying to get the average house price from my JSON data(below), using the passed in region and house type parameters.
I'm ok itterating over and matching on the passed in 'regionName', however I'm then struggling to itterate over the house types (which i believe are the keys in the data) in order to match it against the passed in variable 'literalHouseType', with the aim of then getting that house types price.
As you maybe able to tell, the function works up until the point it matches on the region in the first loop, after that I'm stuck.
I'm not an avid programmer, so any type of help would be great. Thanks in advance.

```<code>var jSonData = JSON.stringify([ {
 "Region_Name": "England",
 "Detached_Average_Price": "357425.4953",
 "Semi_Detached_Average_Price": "219615.157",
 "Terraced_Average_Price": "190095.3402",
 "Flat_Average_Price": "222355.8556" },

 {"Region_Name": "Scotland",
 "Detached_Average_Price": "252491.6457",
 "Semi_Detached_Average_Price": "152351.671",
 "Terraced_Average_Price": "121237.8809",
 "Flat_Average_Price": "104417.6462" }
</code>```

Function used:

```<code>var jSondata = jQuery.parseJSON(jSonData);

$( document ).ready(function() {
GetAveragePriceByHouseTypeAndRegion("Detached_Average_Price", "England");
});

function GetAveragePriceByHouseTypeAndRegion(literalHouseType, regionName) {

for (var i = 0; i < jSondata.length; i++) {
    if (jSondata[i].Region_Name === regionName) {

        for (var j = 0; j < Object.keys(jSondata[i]).length; j++) {
            if (Object.keys(jSondata[i]).value === literalHouseType) {
             //stuck here..
            }
        }
    };
}
</code>```

答:
Assuming literalHouseType will look like "Detached" or "Semi_Detached":

var data = [{
    "Region_Name": "England",
    "Detached_Average_Price": "357425.4953",
    "Semi_Detached_Average_Price": "219615.157",
    "Terraced_Average_Price": "190095.3402",
    "Flat_Average_Price": "222355.8556"
  },

  {
    "Region_Name": "Scotland",
    "Detached_Average_Price": "252491.6457",
    "Semi_Detached_Average_Price": "152351.671",
    "Terraced_Average_Price": "121237.8809",
    "Flat_Average_Price": "104417.6462"
  }
];

function getAveragePriceByHouseTypeAndRegion(literalHouseType, regionName) {
  for (var i = 0; i < data.length; i++) {
    if (data[i].Region_Name === regionName) {
      return data[i][literalHouseType + "_Average_Price"];
    }
  }
}

console.log(getAveragePriceByHouseTypeAndRegion("Semi_Detached", "Scotland"));  // 152351.671```
</div>
</div>
</p>

<p><strong>EDIT</strong></p>

<p>Based on the question edit, it looks like a string like <code>Detached_Average_Price</code> is being passed in as <code>literalHouseType</code>, so the code is slightly simpler:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [{
    "Region_Name": "England",
    "Detached_Average_Price": "357425.4953",
    "Semi_Detached_Average_Price": "219615.157",
    "Terraced_Average_Price": "190095.3402",
    "Flat_Average_Price": "222355.8556"
  },

  {
    "Region_Name": "Scotland",
    "Detached_Average_Price": "252491.6457",
    "Semi_Detached_Average_Price": "152351.671",
    "Terraced_Average_Price": "121237.8809",
    "Flat_Average_Price": "104417.6462"
  }
];

function getAveragePriceByHouseTypeAndRegion(literalHouseType, regionName) {
  for (var i = 0; i < data.length; i++) {
    if (data[i].Region_Name === regionName) {
      return data[i][literalHouseType];
    }
  }
}

console.log(getAveragePriceByHouseTypeAndRegion("Semi_Detached_Average_Price", "Scotland"));  // 152351.671</code>```

EDIT 2

Of course, if you can reshape your data, this is even easier:

var data = {
  "England": {
    "Detached_Average_Price": "357425.4953",
    "Semi_Detached_Average_Price": "219615.157",
    "Terraced_Average_Price": "190095.3402",
    "Flat_Average_Price": "222355.8556"
  },
  "Scotland": {
    "Detached_Average_Price": "252491.6457",
    "Semi_Detached_Average_Price": "152351.671",
    "Terraced_Average_Price": "121237.8809",
    "Flat_Average_Price": "104417.6462"
  }
};

function getAveragePriceByHouseTypeAndRegion(literalHouseType, regionName) {
  return data[regionName][literalHouseType];
}

console.log(getAveragePriceByHouseTypeAndRegion("Semi_Detached_Average_Price", "Scotland")); // 152351.671```

Body:
using a function(below), i'm trying to get the average house price from my JSON data(below), using the passed in region and house type parameters.
I'm ok itterating over and matching on the passed in 'regionName', however I'm then struggling to itterate over the house types (which i believe are the keys in the data) in order to match it against the passed in variable 'literalHouseType', with the aim of then getting that house types price.
As you maybe able to tell, the function works up until the point it matches on the region in the first loop, after that I'm stuck.
I'm not an avid programmer, so any type of help would be great. Thanks in advance.

var jSonData = JSON.stringify([ {
 "Region_Name": "England",
 "Detached_Average_Price": "357425.4953",
 "Semi_Detached_Average_Price": "219615.157",
 "Terraced_Average_Price": "190095.3402",
 "Flat_Average_Price": "222355.8556" },

 {"Region_Name": "Scotland",
 "Detached_Average_Price": "252491.6457",
 "Semi_Detached_Average_Price": "152351.671",
 "Terraced_Average_Price": "121237.8809",
 "Flat_Average_Price": "104417.6462" }

Function used:

var jSondata = jQuery.parseJSON(jSonData);

$( document ).ready(function() {
GetAveragePriceByHouseTypeAndRegion("Detached_Average_Price", "England");
});

function GetAveragePriceByHouseTypeAndRegion(literalHouseType, regionName) {

for (var i = 0; i < jSondata.length; i++) {
    if (jSondata[i].Region_Name === regionName) {

        for (var j = 0; j < Object.keys(jSondata[i]).length; j++) {
            if (Object.keys(jSondata[i]).value === literalHouseType) {
             //stuck here..
            }
        }
    };
}

Body:
Assuming literalHouseType will look like "Detached" or "Semi_Detached":

var data = [{
    "Region_Name": "England",
    "Detached_Average_Price": "357425.4953",
    "Semi_Detached_Average_Price": "219615.157",
    "Terraced_Average_Price": "190095.3402",
    "Flat_Average_Price": "222355.8556"
  },

  {
    "Region_Name": "Scotland",
    "Detached_Average_Price": "252491.6457",
    "Semi_Detached_Average_Price": "152351.671",
    "Terraced_Average_Price": "121237.8809",
    "Flat_Average_Price": "104417.6462"
  }
];

function getAveragePriceByHouseTypeAndRegion(literalHouseType, regionName) {
  for (var i = 0; i < data.length; i++) {
    if (data[i].Region_Name === regionName) {
      return data[i][literalHouseType + "_Average_Price"];
    }
  }
}

console.log(getAveragePriceByHouseTypeAndRegion("Semi_Detached", "Scotland"));  // 152351.671

EDIT

Based on the question edit, it looks like a string like Detached_Average_Price is being passed in as literalHouseType, so the code is slightly simpler:

var data = [{
    "Region_Name": "England",
    "Detached_Average_Price": "357425.4953",
    "Semi_Detached_Average_Price": "219615.157",
    "Terraced_Average_Price": "190095.3402",
    "Flat_Average_Price": "222355.8556"
  },

  {
    "Region_Name": "Scotland",
    "Detached_Average_Price": "252491.6457",
    "Semi_Detached_Average_Price": "152351.671",
    "Terraced_Average_Price": "121237.8809",
    "Flat_Average_Price": "104417.6462"
  }
];

function getAveragePriceByHouseTypeAndRegion(literalHouseType, regionName) {
  for (var i = 0; i < data.length; i++) {
    if (data[i].Region_Name === regionName) {
      return data[i][literalHouseType];
    }
  }
}

console.log(getAveragePriceByHouseTypeAndRegion("Semi_Detached_Average_Price", "Scotland"));  // 152351.671

EDIT 2

Of course, if you can reshape your data, this is even easier:

var data = {
  "England": {
    "Detached_Average_Price": "357425.4953",
    "Semi_Detached_Average_Price": "219615.157",
    "Terraced_Average_Price": "190095.3402",
    "Flat_Average_Price": "222355.8556"
  },
  "Scotland": {
    "Detached_Average_Price": "252491.6457",
    "Semi_Detached_Average_Price": "152351.671",
    "Terraced_Average_Price": "121237.8809",
    "Flat_Average_Price": "104417.6462"
  }
};

function getAveragePriceByHouseTypeAndRegion(literalHouseType, regionName) {
  return data[regionName][literalHouseType];
}

console.log(getAveragePriceByHouseTypeAndRegion("Semi_Detached_Average_Price", "Scotland")); // 152351.671


问:
What are my options for navigating through subroutines?
Suppose I want a program Foo.py which has some arbitrary routines Bar(), Quux(), and Fizz(). Let's say that the usual order of execution from a procedural perspective should be Bar() -> Quux() -> Fizz(). However, Fizz() should conditionally call a function Buzz() depending on some runtime action, and calling Buzz() at any time during Fizz() should return the process back to Quux().

I have a fair understanding of how concurrent processes can be implemented in assembly using system calls depending on the architecture, but what options are available to me in Python, where I can't – and frankly would prefer not to – use lots of jumps and directly move an instruction pointer around? When searching for an answer, I found loops and recursion as a suggestion for going back in a program. I don't think a loop would work without stopping the Fizz() process to wait for the condition check for Buzz(), and I'm not sure how recursion could be implemented in this scenario either. (My Buzz() would be like a "Back" button on a GUI).

答:
Perhaps flow like the below.  Fizz loops until some condition evokes a call to Buzz.  The same check that triggers the call breaks the loop.

```<code>import random

def Buzz():
    print ("Buzz")

def Fizz():
    print ("Fizz")
    while True:
        flip = random.random()
        print ("  ", flip)
        if flip <= 0.5:
            Buzz()
            break

def Quux():
    print ("Quux")
    Fizz()
    print ("Back in Quux")

def Bar():
    print ("Bar")
    Quux()

Bar()
</code>```

Output:

```<code>Bar
Quux
Fizz
   0.88313135192614
   0.9782005471906149
   0.6899740417799126
   0.724911154764598
   0.6193573809551899
   0.3713918176393549
Buzz
Back in Quux
</code>```

Body:
Perhaps flow like the below.  Fizz loops until some condition evokes a call to Buzz.  The same check that triggers the call breaks the loop.

import random

def Buzz():
    print ("Buzz")

def Fizz():
    print ("Fizz")
    while True:
        flip = random.random()
        print ("  ", flip)
        if flip <= 0.5:
            Buzz()
            break

def Quux():
    print ("Quux")
    Fizz()
    print ("Back in Quux")

def Bar():
    print ("Bar")
    Quux()

Bar()

Output:

Bar
Quux
Fizz
   0.88313135192614
   0.9782005471906149
   0.6899740417799126
   0.724911154764598
   0.6193573809551899
   0.3713918176393549
Buzz
Back in Quux


问:
Python filter list to remove certain links from html source code
I have html source code which I want to filter out one or more links and keep the others.

I have set up my filter with "*" as the wildcard:

```<code><a*>Link1</a>‚ <a*>Link2</a>‚ or <a*>Link3</a>
<a*>A bad link*</a>
some text* <a*>update*</a>
other text right before link <a*>click here</a>
</code>```

I would like to filter out every instance of the link from the html source code using python. I'm ok with loading the list into an array.  I need some help with the filter.  Each line break would signify a separate filter and I only want to remove the link(s) and not the text

I am still very new to python and regex/beautifulsoup.  Even if you could point me in the right direction, it would be greatly appreciated.

答:
Parsing it with the only purose of reassembling the whole document discarding just a part of the information would yield a lot of uneeded code.

So, I think this is better as a job for regular expressions. Python's regular expressions can have a callback function that allows one to customize the substitution string. In this case, it is a simple matter of creating a regexp that matches the "bad link", the text in between, and the end link mark-up, and preserves only the text in between.

```<code>import re

markup = """<a*>Link1</a>‚ <a*>Link2</a>‚ or <a*>Link3</a>
<a*>A bad link*</a>
some text* <a*>update*</a>
other text right before link <a*>click here</a>"""

filtered = re.sub (r"(\<a.*?>)(.*?)(\</a\s*\>)",lambda match: match.groups()[1] , markup)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have html source code which I want to filter out one or more links and keep the others.

I have set up my filter with "*" as the wildcard:

Link1‚ Link2‚ or Link3
A bad link*
some text* update*
other text right before link click here

I would like to filter out every instance of the link from the html source code using python. I'm ok with loading the list into an array.  I need some help with the filter.  Each line break would signify a separate filter and I only want to remove the link(s) and not the text

I am still very new to python and regex/beautifulsoup.  Even if you could point me in the right direction, it would be greatly appreciated.

Body:
Parsing it with the only purose of reassembling the whole document discarding just a part of the information would yield a lot of uneeded code.

So, I think this is better as a job for regular expressions. Python's regular expressions can have a callback function that allows one to customize the substitution string. In this case, it is a simple matter of creating a regexp that matches the "bad link", the text in between, and the end link mark-up, and preserves only the text in between.

import re

markup = """<a*>Link1</a>‚ <a*>Link2</a>‚ or <a*>Link3</a>
<a*>A bad link*</a>
some text* <a*>update*</a>
other text right before link <a*>click here</a>"""

filtered = re.sub (r"(\<a.*?>)(.*?)(\</a\s*\>)",lambda match: match.groups()[1] , markup)


问:
Efficient way to conditionally populate elements in a pandas groupby object (possibly by applying a function)
I'm having a problem about performance when trying to apply a function to a groupby object derived from a dataframe that has about 150,000 rows.

For simplicity, let's work on the dummy dataframe a

```<code>arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'one','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)
a[1] = pd.date_range('2017-07-02', periods=10, freq='5min')

a
Out[24]:
                     0                   1
first second
bar   one     0.821371 2017-07-02 00:00:00
      one     0.312364 2017-07-02 00:05:00
      two     0.104821 2017-07-02 00:10:00
baz   one     0.839370 2017-07-02 00:15:00
      two     0.307262 2017-07-02 00:20:00
foo   one     0.719300 2017-07-02 00:25:00
      two     0.371118 2017-07-02 00:30:00
      two     0.765483 2017-07-02 00:35:00
qux   one     0.794236 2017-07-02 00:40:00
      two     0.571231 2017-07-02 00:45:00
</code>```

I want to conditionally populate the bottom element of the 0th column in each first-second group according to the logic described in this function

```<code>def myfunc(g):

if( len(g) >= 2): # if each group's length is greater than or equal to 2, then:

    if ((g.loc[g.index[-1], 0] > 0.5)): # If the last element of the 0th column of the group > 0.5, then:

        time_gap = g.loc[g.index[-1], 1] - g.loc[g.index[-2], 1] # Find the time difference between the last two records in 1st column

        g.loc[g.index[-1], 0] = time_gap # and assign it to the last element in the 0th column of that group

    else:
        g.loc[g.index[-1], 0] = 'ELSE' # Assign ELSE to the last element of the 0th column of the group

return g
</code>```

Applying this function yields,

```<code>a.reset_index().groupby(['first', 'second']).apply(myfunc)
Out[23]:
  first second                0                   1
0   bar    one         0.821371 2017-07-02 00:00:00
1   bar    one             ELSE 2017-07-02 00:05:00  correct
2   bar    two         0.104821 2017-07-02 00:10:00
3   baz    one          0.83937 2017-07-02 00:15:00
4   baz    two         0.307262 2017-07-02 00:20:00
5   foo    one           0.7193 2017-07-02 00:25:00
6   foo    two         0.371118 2017-07-02 00:30:00
7   foo    two  0 days 00:05:00 2017-07-02 00:35:00  correct
8   qux    one         0.794236 2017-07-02 00:40:00
9   qux    two         0.571231 2017-07-02 00:45:00
</code>```

The above result is exactly what I wanted. The problem is that this approach is freezing my 16GB/i5-6200U CPU @ 2.3GHz computer when applied to the dataframe where I have about 150,000 rows.

What is the most efficient way to conditionally populate such elements where (possibly) I need to write a function?

NB: I ran this in a jupyter notebook on windows 10 - if that is important

答:
There are several issues here.

You are editing a dataframe from within a group by apply.  This is bound for lot's of debugging.

When you use apply within a groupby, you create a new dataframe for every group.  We can improve performance by just manipulating the indices of the groups.

You don't need to reset your index in order to group by the index levels

To start, please make a copy of a just in case something gets lost in translation, I don't want you messing up a... just yet.

```<code>a_ = a.copy()
</code>```

Ok, to make it quicker

```<code>g = a.groupby(level=['first', 'second'])
</code>```

I'm going to use a lot of get_value and set_value where takeable=True.  The takeable option allows me to use the other arguments as positional references.  As, such, I'll want to make sure that I've got the correct positions.

```<code>j0 = a.columns.get_loc(0)
j1 = a.columns.get_loc(1)
</code>```

Conveniently, g has an indices attribute that tells me the positions of all my rows for each named group.  I'll create a dictionary of names and indices that pass the first hurdle of being of length 2 or more using a comprehension.

```<code>g_ = {n: i for n, i in g.indices.items() if i.size > 1}
</code>```

You are placing different kinds of things into column 0 and since I'm going to be using set_value, I'd better cast the column as object ahead of time.

```<code>a[0] = a[0].astype(object)
</code>```

Now, I can loop over the groups that passed the length hurdle above.

```<code>for n, i in g_.items():
    i0, i1 = i[-2:]
    cond = a.get_value(i1, j0, takeable=True) > 0.5
    if cond:
        tgap = a.get_value(i1, j1, takeable=True) - a.get_value(i0, j1, takeable=True)
        a.set_value(i1, j0, tgap, takeable=True)
    else:
        a.set_value(i1, j0, 'ELSE', takeable=True)
</code>```

All Together

```<code>g = a.groupby(level=['first', 'second'])

j0 = a.columns.get_loc(0)
j1 = a.columns.get_loc(1)
g_ = {n: i for n, i in g.indices.items() if i.size > 1}

a[0] = a[0].astype(object)

for n, i in g_.items():
    i0, i1 = i[-2:]
    cond = a.get_value(i1, j0, takeable=True) > 0.5
    if cond:
        tgap = a.get_value(i1, j1, takeable=True) - a.get_value(i0, j1, takeable=True)
        a.set_value(i1, j0, tgap, takeable=True)
    else:
        a.set_value(i1, j0, 'ELSE', takeable=True)
</code>```

Timing

```<code>%timeit a.reset_index().groupby(['first', 'second']).apply(myfunc)
100 loops, best of 3: 7.14 ms per loop

%%timeit
a = b.copy()
g = a.groupby(level=['first', 'second'])

j0 = a.columns.get_loc(0)
j1 = a.columns.get_loc(1)
g_ = {n: i for n, i in g.indices.items() if i.size > 1}

a[0] = a[0].astype(object)

for n, i in g_.items():
    i0, i1 = i[-2:]
    cond = a.get_value(i1, j0, takeable=True) > 0.5
    if cond:
        tgap = a.get_value(i1, j1, takeable=True) - a.get_value(i0, j1, takeable=True)
        a.set_value(i1, j0, tgap, takeable=True)
    else:
        a.set_value(i1, j0, 'ELSE', takeable=True)

1000 loops, best of 3: 1.01 ms per loop
</code>```

Body:
I'm having a problem about performance when trying to apply a function to a groupby object derived from a dataframe that has about 150,000 rows.

For simplicity, let's work on the dummy dataframe a

arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'one','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)
a[1] = pd.date_range('2017-07-02', periods=10, freq='5min')

a
Out[24]:
                     0                   1
first second
bar   one     0.821371 2017-07-02 00:00:00
      one     0.312364 2017-07-02 00:05:00
      two     0.104821 2017-07-02 00:10:00
baz   one     0.839370 2017-07-02 00:15:00
      two     0.307262 2017-07-02 00:20:00
foo   one     0.719300 2017-07-02 00:25:00
      two     0.371118 2017-07-02 00:30:00
      two     0.765483 2017-07-02 00:35:00
qux   one     0.794236 2017-07-02 00:40:00
      two     0.571231 2017-07-02 00:45:00

I want to conditionally populate the bottom element of the 0th column in each first-second group according to the logic described in this function

def myfunc(g):

if( len(g) >= 2): # if each group's length is greater than or equal to 2, then:

    if ((g.loc[g.index[-1], 0] > 0.5)): # If the last element of the 0th column of the group > 0.5, then:

        time_gap = g.loc[g.index[-1], 1] - g.loc[g.index[-2], 1] # Find the time difference between the last two records in 1st column

        g.loc[g.index[-1], 0] = time_gap # and assign it to the last element in the 0th column of that group

    else:
        g.loc[g.index[-1], 0] = 'ELSE' # Assign ELSE to the last element of the 0th column of the group

return g

Applying this function yields,

a.reset_index().groupby(['first', 'second']).apply(myfunc)
Out[23]:
  first second                0                   1
0   bar    one         0.821371 2017-07-02 00:00:00
1   bar    one             ELSE 2017-07-02 00:05:00  correct
2   bar    two         0.104821 2017-07-02 00:10:00
3   baz    one          0.83937 2017-07-02 00:15:00
4   baz    two         0.307262 2017-07-02 00:20:00
5   foo    one           0.7193 2017-07-02 00:25:00
6   foo    two         0.371118 2017-07-02 00:30:00
7   foo    two  0 days 00:05:00 2017-07-02 00:35:00  correct
8   qux    one         0.794236 2017-07-02 00:40:00
9   qux    two         0.571231 2017-07-02 00:45:00

The above result is exactly what I wanted. The problem is that this approach is freezing my 16GB/i5-6200U CPU @ 2.3GHz computer when applied to the dataframe where I have about 150,000 rows.

What is the most efficient way to conditionally populate such elements where (possibly) I need to write a function?

NB: I ran this in a jupyter notebook on windows 10 - if that is important

Body:
There are several issues here.

You are editing a dataframe from within a group by apply.  This is bound for lot's of debugging.

When you use apply within a groupby, you create a new dataframe for every group.  We can improve performance by just manipulating the indices of the groups.

You don't need to reset your index in order to group by the index levels

To start, please make a copy of a just in case something gets lost in translation, I don't want you messing up a... just yet.

a_ = a.copy()

Ok, to make it quicker

g = a.groupby(level=['first', 'second'])

I'm going to use a lot of get_value and set_value where takeable=True.  The takeable option allows me to use the other arguments as positional references.  As, such, I'll want to make sure that I've got the correct positions.

j0 = a.columns.get_loc(0)
j1 = a.columns.get_loc(1)

Conveniently, g has an indices attribute that tells me the positions of all my rows for each named group.  I'll create a dictionary of names and indices that pass the first hurdle of being of length 2 or more using a comprehension.

g_ = {n: i for n, i in g.indices.items() if i.size > 1}

You are placing different kinds of things into column 0 and since I'm going to be using set_value, I'd better cast the column as object ahead of time.

a[0] = a[0].astype(object)

Now, I can loop over the groups that passed the length hurdle above.

for n, i in g_.items():
    i0, i1 = i[-2:]
    cond = a.get_value(i1, j0, takeable=True) > 0.5
    if cond:
        tgap = a.get_value(i1, j1, takeable=True) - a.get_value(i0, j1, takeable=True)
        a.set_value(i1, j0, tgap, takeable=True)
    else:
        a.set_value(i1, j0, 'ELSE', takeable=True)

All Together

g = a.groupby(level=['first', 'second'])

j0 = a.columns.get_loc(0)
j1 = a.columns.get_loc(1)
g_ = {n: i for n, i in g.indices.items() if i.size > 1}

a[0] = a[0].astype(object)

for n, i in g_.items():
    i0, i1 = i[-2:]
    cond = a.get_value(i1, j0, takeable=True) > 0.5
    if cond:
        tgap = a.get_value(i1, j1, takeable=True) - a.get_value(i0, j1, takeable=True)
        a.set_value(i1, j0, tgap, takeable=True)
    else:
        a.set_value(i1, j0, 'ELSE', takeable=True)

Timing

%timeit a.reset_index().groupby(['first', 'second']).apply(myfunc)
100 loops, best of 3: 7.14 ms per loop

%%timeit
a = b.copy()
g = a.groupby(level=['first', 'second'])

j0 = a.columns.get_loc(0)
j1 = a.columns.get_loc(1)
g_ = {n: i for n, i in g.indices.items() if i.size > 1}

a[0] = a[0].astype(object)

for n, i in g_.items():
    i0, i1 = i[-2:]
    cond = a.get_value(i1, j0, takeable=True) > 0.5
    if cond:
        tgap = a.get_value(i1, j1, takeable=True) - a.get_value(i0, j1, takeable=True)
        a.set_value(i1, j0, tgap, takeable=True)
    else:
        a.set_value(i1, j0, 'ELSE', takeable=True)

1000 loops, best of 3: 1.01 ms per loop


问:
How to display data in smarty when using PDO with prepared statement and executing inside foreach?
```<code>$dbh = new PDO($dsn, $user, $password, array(
 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));

$selectNumberTitle = $dbh->prepare("SELECT AdvertNumber, AdvertTitle FROM `adverts` WHERE AdvertNumber = ? ");

foreach ($advertnumber as $i => $number) {
    $selectNumberTitle->execute(array($number));
    foreach ($selectNumberTitle as $row) {
        echo $row['AdvertNumber'] . ') ' . $row['AdvertTitle'] . "<br/>";
    }
}
</code>```

Above code works nicely. I need the same output in smarty.

答:
You save the data you want to display in a variable like an array. After that you assign this variable to smarty. So, you split this problem into two:

Read the data from the database in an array.

Display the variable (array) in your smarty template.

Body:
$dbh = new PDO($dsn, $user, $password, array(
 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));

$selectNumberTitle = $dbh->prepare("SELECT AdvertNumber, AdvertTitle FROM `adverts` WHERE AdvertNumber = ? ");

foreach ($advertnumber as $i => $number) {
    $selectNumberTitle->execute(array($number));
    foreach ($selectNumberTitle as $row) {
        echo $row['AdvertNumber'] . ') ' . $row['AdvertTitle'] . "
";
    }
}

Above code works nicely. I need the same output in smarty.


问:
Angular Translate Unit Test - Can't inject $translateProvider
I'm using ES6, AngularJS, Karma/Jasmine, and angular-translate. Can't seem to get my unit test to pass. Not really too sure how to work with 3rd party modules, like angular-translate, when it comes to unit testing. The code and the error I'm getting are below. $translateProvider is not loading.

```<code>import CatalogueModule from './catalogue.module'
import CatalogueService from './catalogue.service'

let service,
    _$translateProvider;

describe('CatalogueService', () => {
  beforeEach(angular.mock.module(CatalogueModule));

  beforeEach(() => {
    angular.mock.module({
      $translateProvider: jasmine.createSpyObj('$translateProvider',
        ['translations', 'preferredLanguage']
      ),
      $translate: jasmine.createSpyObj('$translate',
        ['use']
      )
    });
  })

  beforeEach(inject(($translateProvider) => {
    _$translateProvider = $translateProvider;

    _$translateProvider.translations('en', {});
    _$translateProvider.preferredLanguage('en');

    // service = new CatalogueService();
  }));

  it('should set the config object after initialization', inject(($translateProvider, CatalogueService) => {
    // $translateProvider.use.and.returnValue();
    // expect(service.config.headers).to.equal(null);
  }));
});
</code>```

This is the error:

```<code>✖ "before each" hook: WorkFn for "should set the config object after initialization"
      Chrome 59.0.3071 (Mac OS X 10.12.3)
    Error: [$injector:unpr] Unknown provider: $translateProviderProvider <- $translateProvider
</code>```

UPDATE - Adding catalogue.service.js

```<code>class CatalogueService {
  constructor($http, $q, $translate) {
    'ngInject';

    this._$http      = $http;
    this._$q         = $q;
    this._$translate = $translate;

    this.config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '******',
        'P3-APP-ID': '*****',
        'P3-Date': '*****'
      }
    };

    this.catalogue = this.getCatalogue();
  }

  getCatalogue() {
    const lang = this._$translate.use();
    const url = `https://somedomain.com/catalog?language_code=${lang}`;
    const deferred = this._$q.defer();

    this._$http
      .get(url, this.config)
      .then(
        (res) => deferred.resolve(res.data.characters),
        (err) => deferred.reject(err)
      );

    return deferred.promise;
  };

  getCharacterByCharId(charId) {
    return this.catalogue
      .then((res) => {
        return res.find((character) => {
          return character.link_name === charId;
        });
      });
  };
}

export default CatalogueService;
</code>```

答:
I've accomplished this using a custom loader for $translateProvider before. This example is in typescript but something like this should work for you as well:

```<code>angular.mock.module(($provide: angular.auto.IProvideService, translateProvider: angular.translate.ITranslateProvider) => {
    $provide.factory('customLoader', ($q: angular.IQService) =>
        () => {
            const deferred = $q.defer();
            deferred.resolve({});
            return deferred.promise;
    });

    $translateProvider.useLoader('customLoader');
});
</code>```

Body:
I'm using ES6, AngularJS, Karma/Jasmine, and angular-translate. Can't seem to get my unit test to pass. Not really too sure how to work with 3rd party modules, like angular-translate, when it comes to unit testing. The code and the error I'm getting are below. $translateProvider is not loading.

import CatalogueModule from './catalogue.module'
import CatalogueService from './catalogue.service'

let service,
    _$translateProvider;

describe('CatalogueService', () => {
  beforeEach(angular.mock.module(CatalogueModule));

  beforeEach(() => {
    angular.mock.module({
      $translateProvider: jasmine.createSpyObj('$translateProvider',
        ['translations', 'preferredLanguage']
      ),
      $translate: jasmine.createSpyObj('$translate',
        ['use']
      )
    });
  })

  beforeEach(inject(($translateProvider) => {
    _$translateProvider = $translateProvider;

    _$translateProvider.translations('en', {});
    _$translateProvider.preferredLanguage('en');

    // service = new CatalogueService();
  }));

  it('should set the config object after initialization', inject(($translateProvider, CatalogueService) => {
    // $translateProvider.use.and.returnValue();
    // expect(service.config.headers).to.equal(null);
  }));
});

This is the error:

✖ "before each" hook: WorkFn for "should set the config object after initialization"
      Chrome 59.0.3071 (Mac OS X 10.12.3)
    Error: [$injector:unpr] Unknown provider: $translateProviderProvider <- $translateProvider

UPDATE - Adding catalogue.service.js

class CatalogueService {
  constructor($http, $q, $translate) {
    'ngInject';

    this._$http      = $http;
    this._$q         = $q;
    this._$translate = $translate;

    this.config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '******',
        'P3-APP-ID': '*****',
        'P3-Date': '*****'
      }
    };

    this.catalogue = this.getCatalogue();
  }

  getCatalogue() {
    const lang = this._$translate.use();
    const url = `https://somedomain.com/catalog?language_code=${lang}`;
    const deferred = this._$q.defer();

    this._$http
      .get(url, this.config)
      .then(
        (res) => deferred.resolve(res.data.characters),
        (err) => deferred.reject(err)
      );

    return deferred.promise;
  };

  getCharacterByCharId(charId) {
    return this.catalogue
      .then((res) => {
        return res.find((character) => {
          return character.link_name === charId;
        });
      });
  };
}

export default CatalogueService;

Body:
I've accomplished this using a custom loader for $translateProvider before. This example is in typescript but something like this should work for you as well:

angular.mock.module(($provide: angular.auto.IProvideService, translateProvider: angular.translate.ITranslateProvider) => {
    $provide.factory('customLoader', ($q: angular.IQService) =>
        () => {
            const deferred = $q.defer();
            deferred.resolve({});
            return deferred.promise;
    });

    $translateProvider.useLoader('customLoader');
});


问:
Python starter program : Moving files
Looking to make some use out of Python! I wanted to write a script to move all those carelessly placed .jpg files from my desktop.

Thing, is the script I'm using doesn't seem to be finding anything.

thoughts?

```<code>import os, shutil, glob

dst_fldr = "~/path/Desktop/newfolder";

for jpg_file in glob.glob("~/path/Desktop"+"\\*.jpg"):
    print jpg_file + "will be moved to " + dst_fldr
    shutil.move(jpg_file, dst_fldr);
</code>```

答:
~ is not a character that glob understands (it's a character that bash understands and expands). You'll have to provide a full path.

```<code>dst_fldr = "/path/to/Desktop/newfolder";
</code>```

In addition, you'd want to modify the wildcard search, to something like this:

```<code>glob.glob("/path/to/Desktop/*.jpg"):
</code>```

If your python script resides in Desktop, you can drop the /path/to/Desktop part of the path in both cases.

With these changes in place, I believe you're good to go.

Title: Python starter program : Moving files

Body:
Looking to make some use out of Python! I wanted to write a script to move all those carelessly placed .jpg files from my desktop.

Thing, is the script I'm using doesn't seem to be finding anything.

thoughts?

import os, shutil, glob

dst_fldr = "~/path/Desktop/newfolder";

for jpg_file in glob.glob("~/path/Desktop"+"\\*.jpg"):
    print jpg_file + "will be moved to " + dst_fldr
    shutil.move(jpg_file, dst_fldr);

Body:
~ is not a character that glob understands (it's a character that bash understands and expands). You'll have to provide a full path.

dst_fldr = "/path/to/Desktop/newfolder";

In addition, you'd want to modify the wildcard search, to something like this:

glob.glob("/path/to/Desktop/*.jpg"):

If your python script resides in Desktop, you can drop the /path/to/Desktop part of the path in both cases.

With these changes in place, I believe you're good to go.


问:
Is it possible to define a one-off user control in the ASPX codebehind?
One of my big beefs with ASP.NET is that it makes it difficult to organize the controls of a page beyond excessive amounts of prefixing IDs. I have gone to great and complicated lengths in the past to try to alleviate this, but I would like a solution that is easier to implement. So, I'm wondering:

Is it possible to define a user control in the codebehind of a .aspx, and then use it in the .aspx? I'm thinking probably not... I can't get it to work.

答:
There has to be an existing ASP.NET user control defined, and you can dynamically load it.  That's about as much as dynamic capabilities with user controls that you have.  You can also leverage custom controls, which really gives you the complete control over the rendered UI.  However, not rendering complete ID's can have subsequent issues with the client/server integration, depending on what you are trying to do.

Also, to customize the ID, you can leverage ASP.NET 4.0's ClientIDMode property: http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx


问:
Asp.net web form "The wait operation timed out"
I have a web form built to retrieve data from a reporting server. I don't have rights to create an index on the table I'm querying in that server, and the query is very, very slow on the text lookup. I've tried optimizing what I can in the query, but it's just going to be slow. So I need to find a way to avoid getting the timeout in the webpage itself. I have reviewed several similar questions, I set a crazy high connection timeout, but I'm still getting the wait operation timeout on the button click. The timeout happens after 30 seconds, even though I have set such a high connection timeout. I don't know if it's the web config, but I'm not using the connection string defined in my webconfig, just this one here in the codebehind. The query does not time out in SSMS, only when accessing the data from the webform (which technically is using my login credentials in the connection string, so there is no sort of permissions issues, other portions run fine). Is there any where else I need to increase the timeout for the page?

Connection string (un/pw x'ed out for privacy):

```<code>server=lxxxxxx.resources.xxx; Initial Catalog=pxxxxxxxx;User ID=mfeXXXXX;Password=XXXXXX;Trusted_Connection=False; Connection Timeout=10000"
</code>```

query that times out, if that helps:

```<code> protected void btnSearchFeedback_Click(object sender, EventArgs e)
    {
        con.Open();
        SqlDataAdapter sdaFeedBack = new SqlDataAdapter("SELECT CTIR.portion_ID, IB.Item_ID as [Item ID], CTIR.Item_DBkey as [Item DB Key], CTIR.Feedback as [Feedback], CTA.date as [Date],CTA.Candidate_ID as [Candidate ID] FROM Canxxxxxxx CTIR WITH (NOLOCK) left join Ixxxxx IB WITH (NOLOCK) ON CTIR.xxxxx = IB.xxxxx left join Cxxxxxx CTA WITH (NOLOCK) ON CTxxxxxx = CTxxxxxxx where (ctir.portion_id in (" + portionIDTextBox.Text + ") ) AND (len(CTIR.Feedback) > 0) and CTA.Date  > '2015-02-01 00:00:00.000' order by [Date]", con);
        DataSet dtFeedBack = new DataSet();
        sdaFeedBack.Fill(dtFeedBack);
        ViewState["dtFeedback"] = dtFeedBack;
        rptFeedBack.DataSource = dtFeedBack;
        rptFeedBack.DataBind();
        con.Close();
    }
</code>```

Again, x'ed out table names for security. So I am trying to see if there is another location I need to set the connection timeout to a higher number to avoid the "Server Error in '/' Application. The wait operation timed out", or is this something that needs to be handled on the server side?

This is the exact error:

Server Error in '/' Application.

The wait operation timed out
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: The wait operation timed out

stack trace:
[Win32Exception (0x80004005): The wait operation timed out]

[SqlException (0x80131904): Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +2434922
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5736592
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +3731
   System.Data.SqlClient.SqlDataReader.TrySetMetaData(_SqlMetaDataSet metaData, Boolean moreInfo) +198
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +2852
   System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
   System.Data.SqlClient.SqlDataReader.get_MetaData() +89
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +379
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +2026
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +375
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
   System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +12
   System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +139
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +136
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +88
   FeedBackForm.btnSearchFeedback_Click(Object sender, EventArgs e) in C:\Users\mfelchlin\Documents\Visual Studio 2015\WebSites\devFormsSite\FeedBackForm.aspx.cs:27
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9696694
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639

答:
```<code>sdaFeedBack.SelectCommand.CommandTimeout=120; //or some other number of seconds.
</code>```

Setting the timeout on the connection determines how long to wait for the connection to open, not for the command to execute.

Body:
I have a web form built to retrieve data from a reporting server. I don't have rights to create an index on the table I'm querying in that server, and the query is very, very slow on the text lookup. I've tried optimizing what I can in the query, but it's just going to be slow. So I need to find a way to avoid getting the timeout in the webpage itself. I have reviewed several similar questions, I set a crazy high connection timeout, but I'm still getting the wait operation timeout on the button click. The timeout happens after 30 seconds, even though I have set such a high connection timeout. I don't know if it's the web config, but I'm not using the connection string defined in my webconfig, just this one here in the codebehind. The query does not time out in SSMS, only when accessing the data from the webform (which technically is using my login credentials in the connection string, so there is no sort of permissions issues, other portions run fine). Is there any where else I need to increase the timeout for the page?

Connection string (un/pw x'ed out for privacy):

server=lxxxxxx.resources.xxx; Initial Catalog=pxxxxxxxx;User ID=mfeXXXXX;Password=XXXXXX;Trusted_Connection=False; Connection Timeout=10000"

query that times out, if that helps:

 protected void btnSearchFeedback_Click(object sender, EventArgs e)
    {
        con.Open();
        SqlDataAdapter sdaFeedBack = new SqlDataAdapter("SELECT CTIR.portion_ID, IB.Item_ID as [Item ID], CTIR.Item_DBkey as [Item DB Key], CTIR.Feedback as [Feedback], CTA.date as [Date],CTA.Candidate_ID as [Candidate ID] FROM Canxxxxxxx CTIR WITH (NOLOCK) left join Ixxxxx IB WITH (NOLOCK) ON CTIR.xxxxx = IB.xxxxx left join Cxxxxxx CTA WITH (NOLOCK) ON CTxxxxxx = CTxxxxxxx where (ctir.portion_id in (" + portionIDTextBox.Text + ") ) AND (len(CTIR.Feedback) > 0) and CTA.Date  > '2015-02-01 00:00:00.000' order by [Date]", con);
        DataSet dtFeedBack = new DataSet();
        sdaFeedBack.Fill(dtFeedBack);
        ViewState["dtFeedback"] = dtFeedBack;
        rptFeedBack.DataSource = dtFeedBack;
        rptFeedBack.DataBind();
        con.Close();
    }

Again, x'ed out table names for security. So I am trying to see if there is another location I need to set the connection timeout to a higher number to avoid the "Server Error in '/' Application. The wait operation timed out", or is this something that needs to be handled on the server side?

This is the exact error:

Server Error in '/' Application.

The wait operation timed out
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: The wait operation timed out

stack trace:
[Win32Exception (0x80004005): The wait operation timed out]

[SqlException (0x80131904): Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +2434922
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5736592
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +3731
   System.Data.SqlClient.SqlDataReader.TrySetMetaData(_SqlMetaDataSet metaData, Boolean moreInfo) +198
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +2852
   System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
   System.Data.SqlClient.SqlDataReader.get_MetaData() +89
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +379
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +2026
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +375
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
   System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +12
   System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +139
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +136
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +88
   FeedBackForm.btnSearchFeedback_Click(Object sender, EventArgs e) in C:\Users\mfelchlin\Documents\Visual Studio 2015\WebSites\devFormsSite\FeedBackForm.aspx.cs:27
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9696694
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639

Body:
sdaFeedBack.SelectCommand.CommandTimeout=120; //or some other number of seconds.

Setting the timeout on the connection determines how long to wait for the connection to open, not for the command to execute.


问:
vba - setting a numeric array and comparing it to a cell
I have this code:

```<code>Sub PipelineStatusConvert()

Dim rng1 As Range
Dim tgt As Range
Dim ws As Worksheet
Dim cell As Object
Dim myarray As Variant
myarray = Array("1", "2", "3")  '4, 5, 6, 7, 8, 9)

Set ws = ActiveWorkbook.ActiveSheet
Set rng1 = ws.Range("K13:K1000")

'    If Intersect(ActiveCell, rng1) Is Nothing Then
'
'        MsgBox "The active cell does NOT Intersect " & rng1.Address
'
'    Else
'
'        MsgBox "The active cell does Intersect " & rng1.Address
'
'    End If

For Each cell In rng1

 'evaluate something

    If cell <> myarray Then
    MsgBox "no intersection"
'   MsgBox cell.Address
    End If

 '   Select Case
  '  Case 1

Next cell

End Sub
</code>```

I am trying to run a check on each cell in the range selected and say that if the cell's value is not in the array (1-3), then

'do something..

I keep running into the "Type Mismatch error". I know it has to do with the array declaration as I think it's trying to compare a cell value to an array (which won't work).

How would I re-strcuture this?

Thanks

答:
You will need to write a function to search an array for a value.  Modifying your code a little, I came up with the following:</p>

```<code>Sub PipelineStatusConvert()
   Dim rng1 As Range
   Dim tgt As Range
   Dim ws As Worksheet
   Dim cell As Range
   Dim myarray As Variant

   myarray = Array("1", "2", "3")  '4, 5, 6, 7, 8, 9)

   Set ws = ActiveWorkbook.ActiveSheet
   Set rng1 = ws.Range("K13:K1000")

   For Each cell In rng1
       If Not isInArray(cell.Value, myarray) Then
          MsgBox "no intersection"
       End If
   Next
End Sub

Function isInArray(Match As String, SourceArray As Variant) As Boolean
   isInArray = (UBound(Filter(SourceArray, Match)) > -1)
End Function
</code>```

Body:
I have this code:

Sub PipelineStatusConvert()

Dim rng1 As Range
Dim tgt As Range
Dim ws As Worksheet
Dim cell As Object
Dim myarray As Variant
myarray = Array("1", "2", "3")  '4, 5, 6, 7, 8, 9)

Set ws = ActiveWorkbook.ActiveSheet
Set rng1 = ws.Range("K13:K1000")

'    If Intersect(ActiveCell, rng1) Is Nothing Then
'
'        MsgBox "The active cell does NOT Intersect " & rng1.Address
'
'    Else
'
'        MsgBox "The active cell does Intersect " & rng1.Address
'
'    End If

For Each cell In rng1

 'evaluate something

    If cell <> myarray Then
    MsgBox "no intersection"
'   MsgBox cell.Address
    End If

 '   Select Case
  '  Case 1

Next cell

End Sub

I am trying to run a check on each cell in the range selected and say that if the cell's value is not in the array (1-3), then

'do something..

I keep running into the "Type Mismatch error". I know it has to do with the array declaration as I think it's trying to compare a cell value to an array (which won't work).

How would I re-strcuture this?

Thanks

Body:
You will need to write a function to search an array for a value.  Modifying your code a little, I came up with the following:

Sub PipelineStatusConvert()
   Dim rng1 As Range
   Dim tgt As Range
   Dim ws As Worksheet
   Dim cell As Range
   Dim myarray As Variant

   myarray = Array("1", "2", "3")  '4, 5, 6, 7, 8, 9)

   Set ws = ActiveWorkbook.ActiveSheet
   Set rng1 = ws.Range("K13:K1000")

   For Each cell In rng1
       If Not isInArray(cell.Value, myarray) Then
          MsgBox "no intersection"
       End If
   Next
End Sub

Function isInArray(Match As String, SourceArray As Variant) As Boolean
   isInArray = (UBound(Filter(SourceArray, Match)) > -1)
End Function


问:
"Cannot open user default database. Login failed." after installing SQL Server Management Studio Express
I have a database in a local file that is used by a program.  The program has limited functionality and I needed to run some quick queries.  I installed SQL Server Management Studio Express 2005 (SSMSE), connected to the SQL Server instance, attached the database file, and ran the queries.  Now the original program will no longer connect to the database.  I receive the error:

Cannot open user default database. Login failed. Login failed for user 'MyComputer\MyUserName'.

I've gone back into SSMSE and tried to set the default database.  I've opened up Security, Logins, BUILTIN\Administrators and BUILTIN\Users.  Under General, I have set the default database to the program's database.  Under User Mappings, I made sure the database is ticked and that db_datareader and db_datawriter are ticked.

The program uses the connection string:

Server=(local)\Instance; AttachDbFilename=C:\PathToDatabase\Database.mdf; Integrated Security=True; User Instance=True;

I know jack-all about database administration.  What else am I missing?

答:
This problem manifested for me when I took my default db offline. Next thing I know I couldn't login. Switching to the Connection Properties tab and selecting the drop down to change the database I want to connect to also failed.

It let me in right away once I manually typed master as the db I wanted to connect to (on the Connection Properties tab).


问:
How to make this recorded macro apply for all sheets in workbook
I have this recorded macro which works for one sheet, but I copied and pasted and changed all sheet names and when I ran it, it only worked for the last sheet (wasnt even correct sheet name). How can I sort all the sheets of the workbook (there's like 8).

```<code>Sub Sort_Design_NEB()

    Range("A1").Select
 ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Clear
 ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Add Key:= _
    Range("E2:E55"), SortOn:=xlSortOnValues, Order:=xlAscending,      DataOption:= _
    xlSortNormal
ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Add Key:= _
    Range("H2:H55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Add Key:= _
    Range("G2:G55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
With ActiveWorkbook.Worksheets("NEB_D").Sort
    .SetRange Range("A1:H55")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
</code>```

End Sub

答:
Try with a loop for all sheets of the workbook. Like this:

```<code>Dim WS_Count As Integer
     Dim I As Integer

     ' Set WS_Count equal to the number of worksheets in the active
     ' workbook.
     WS_Count = ActiveWorkbook.Worksheets.Count

     ' Begin the loop.
     For I = 1 To WS_Count
         Range("A1").Select
         With ActiveWorkbook.Worksheets(I)
             .Sort.SortFields.Clear
             .Sort.SortFields.Add Key:= _
             .Range("E2:E55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
             xlSortNormal
             .Sort.SortFields.Add Key:= _
             .Range("H2:H55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
             xlSortNormal
         .Sort.SortFields.Add Key:= _
             .Range("G2:G55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
             xlSortNormal
         End With
         With ActiveWorkbook.Worksheets(I).Sort
             .SetRange Range("A1:H55")
             .Header = xlYes
             .MatchCase = False
             .Orientation = xlTopToBottom
             .SortMethod = xlPinYin
             .Apply
         End With
Next I
</code>```

Update with statement. Thank Thomas Inzina.

Body:
I have this recorded macro which works for one sheet, but I copied and pasted and changed all sheet names and when I ran it, it only worked for the last sheet (wasnt even correct sheet name). How can I sort all the sheets of the workbook (there's like 8).

Sub Sort_Design_NEB()

    Range("A1").Select
 ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Clear
 ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Add Key:= _
    Range("E2:E55"), SortOn:=xlSortOnValues, Order:=xlAscending,      DataOption:= _
    xlSortNormal
ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Add Key:= _
    Range("H2:H55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Add Key:= _
    Range("G2:G55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
With ActiveWorkbook.Worksheets("NEB_D").Sort
    .SetRange Range("A1:H55")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

End Sub

Body:
Try with a loop for all sheets of the workbook. Like this:

Dim WS_Count As Integer
     Dim I As Integer

     ' Set WS_Count equal to the number of worksheets in the active
     ' workbook.
     WS_Count = ActiveWorkbook.Worksheets.Count

     ' Begin the loop.
     For I = 1 To WS_Count
         Range("A1").Select
         With ActiveWorkbook.Worksheets(I)
             .Sort.SortFields.Clear
             .Sort.SortFields.Add Key:= _
             .Range("E2:E55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
             xlSortNormal
             .Sort.SortFields.Add Key:= _
             .Range("H2:H55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
             xlSortNormal
         .Sort.SortFields.Add Key:= _
             .Range("G2:G55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
             xlSortNormal
         End With
         With ActiveWorkbook.Worksheets(I).Sort
             .SetRange Range("A1:H55")
             .Header = xlYes
             .MatchCase = False
             .Orientation = xlTopToBottom
             .SortMethod = xlPinYin
             .Apply
         End With
Next I

Update with statement. Thank Thomas Inzina.


问:
Accessing totalResults property from google contacts returned xml
I'm trying to access 'totalResults' from following xml which was returned by google(contacts)

 <generator version="1.0" uri="http://www.google.com/m8/feeds">Contacts</generator>
 <openSearch:totalResults>29</openSearch:totalResults>
 <openSearch:startIndex>1</openSearch:startIndex>
 <openSearch:itemsPerPage>25</openSearch:itemsPerPage>```

答:
```<code>$xml = '<generator version="1.0" uri="http://www.google.com/m8/feeds">Contacts</generator>
 <openSearch:totalResults>29</openSearch:totalResults>
 <openSearch:startIndex>1</openSearch:startIndex>
 <openSearch:itemsPerPage>25</openSearch:itemsPerPage>'

$xml = simplexml_load_string($xml);
echo $xml->openSearch->totalResults;
</code>```


问:
jQuery slider with ajax content loading
I'm not JS expert so creating script from scratch will be difficult for me so I want to use plugin.
There is many slider plugins but all of them use pre-created elements and I want pagination with slide effect. </p>

<p>Do you know any plugin with that functionality? </p>

答:
You'll want to look at jQuery UI - especially the Tabs and Slider component. What you want sounds like you should combine two of the examples - Slider Controlled Tabs and Content via ajax.

Combining the two should be simple in terms of writing the JavaScript, although you might need to rewrite a large amount of CSS to create the desired pagination effect, and also look carefully at jQuery UI Tab's ajax mode options.

Title: jQuery slider with ajax content loading

Body:
I'm not JS expert so creating script from scratch will be difficult for me so I want to use plugin.
There is many slider plugins but all of them use pre-created elements and I want pagination with slide effect.

Do you know any plugin with that functionality?


问:
accessibilty issue with codeigniter session library
I'm working on user login system in codeigniter. When user clicks on login button the username and password are verified and the data is store in $this->session->set_userdata($arr); session library and the page redirects to home.php. Till here works fine but when is try to access the session in home.php as print_r($this->session->userdata);. it give me this errors

Here is the Controller code : Login.php

```<code>function login_user(){
    $login_btn = $this->input->post('login_btn');

    if($login_btn == TRUE){
        $arr['login'] = array(
            'username'=>$this->input->post('username'),
            'password'=>$this->input->post('password')
        );

        $query = $this->Login_model->users_login($arr);

        if($query->num_rows() > 0 && $query->num_rows() == 1){
            $this->load->library('session');
            $this->session->set_userdata($arr);
            redirect('Login/redirec_To_home','refresh');
        }
        else
        {
            $this->index();
        }
    }
    else
    {
        $this->index();
    }
}

function redirec_To_home(){
    $this->load->view('login/home');
}
</code>```

Here is the view html file name : path views/login/home.php

```<code><?php
    print_r($this->session->userdata); //ERRORS SHOWN IN THIS LINE NUMBER : 13
?>
</code>```

THANKS IN ADVANCE

答:
Please go to application/config/autoload.php in your project directory and search libraries, after that add session to this line which will look like this.</p>

```<code>$autoload['libraries'] = array('session');
</code>```

Body:
I'm working on user login system in codeigniter. When user clicks on login button the username and password are verified and the data is store in $this->session->set_userdata($arr); session library and the page redirects to home.php. Till here works fine but when is try to access the session in home.php as print_r($this->session->userdata);. it give me this errors

Here is the Controller code : Login.php

function login_user(){
    $login_btn = $this->input->post('login_btn');

    if($login_btn == TRUE){
        $arr['login'] = array(
            'username'=>$this->input->post('username'),
            'password'=>$this->input->post('password')
        );

        $query = $this->Login_model->users_login($arr);

        if($query->num_rows() > 0 && $query->num_rows() == 1){
            $this->load->library('session');
            $this->session->set_userdata($arr);
            redirect('Login/redirec_To_home','refresh');
        }
        else
        {
            $this->index();
        }
    }
    else
    {
        $this->index();
    }
}

function redirec_To_home(){
    $this->load->view('login/home');
}

Here is the view html file name : path views/login/home.php

<?php
    print_r($this->session->userdata); //ERRORS SHOWN IN THIS LINE NUMBER : 13
?>

THANKS IN ADVANCE

Body:
Please go to application/config/autoload.php in your project directory and search libraries, after that add session to this line which will look like this.

$autoload['libraries'] = array('session');


问:
Add image before all a href tags. works but not inline
This should be easy but can't figure it out.

I'm adding an image icon to all a tags:

```<code>a.textLink:before{
content: "";
background: url("../img/plus-button.png") no-repeat;
background-size:contain;
display: block;
width: 36px;
height: 36px;
float: left;
margin: -6px 6px 0 0;}
}
</code>```

My HTML is just 2 links inline:

```<code><a class="textLink" href="#">Link 1</a>  <a class="textLink clearFloat" href="#">Link 2</a>
</code>```

The problem is, both "plus-buytton.png" images float left, so they aren't inserting before each link but together.

答: remove float:left; and add display:inline-block, vertical-align:middle;

Body:
This should be easy but can't figure it out.

I'm adding an image icon to all a tags:

a.textLink:before{
content: "";
background: url("../img/plus-button.png") no-repeat;
background-size:contain;
display: block;
width: 36px;
height: 36px;
float: left;
margin: -6px 6px 0 0;}
}

My HTML is just 2 links inline:

Link 1  Link 2

The problem is, both "plus-buytton.png" images float left, so they aren't inserting before each link but together.