问:
How to make it run through the 3 validations before being able to send the form action to an address
My code currently validates that the name/email and postcode is valid before being able to send when there is NO address that the information is meant to go to in the form action ="". But when I put the address it's meant to go to it completely skips the validation and just sends whatever, empty or not empty.

Trying to re-position the form action, but really have no idea.

```<code><html>
<head>
<title>Online Food Delivery Form</title>
<h1>Online Food Delivery Form</h1>
</head>
<body>
<form action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi"
method="get"  onsubmit="return validation();">
Name* : <input type="text" name="name" id="name">
<br />
<br />
Email* :    <input type="email" name="email" id="email">
<br />
<br />
Postcode* : <input type="text" name="postcode" id="postcode" size="10">

<input type="reset" value="Reset"></button>
<input type="submit" name="submit" value="Submit"/>
</form>
<div id="eresult" style="color:red;"></div>
<script type="text/javascript">

function validation(){
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var postcode = document.getElementById('postcode').value;
if(name=='' || postcode=='' || email==''){
document.getElementById("eresult").innerHTML = "Name, Email and Postcode
are required.";
return false;
}
else if(name.length<3){
document.getElementById("eresult").innerHTML = "Name must be more than 3
characters.";
return false;
}
else if(postcode.length<4){
document.getElementById("eresult").innerHTML = "Postcode must be atleast
4 characters.";
return false;
}
else {
return true;
}
}
</script>
</body>
</html>
</code>```

Expected results is for the code to validate that the email/name and postcode is correct before sending the information to the designated site. But it's doing complete opposite.

答:
In your validation, your error messages are multi-line strings

```<code>if(name=='' || postcode=='' || email==''){
document.getElementById("eresult").innerHTML = "Name, Email and Postcode
are required.";
return false;
}
else if(name.length<3){
document.getElementById("eresult").innerHTML = "Name must be more than 3
characters.";
return false;
}
else if(postcode.length<4){
document.getElementById("eresult").innerHTML = "Postcode must be atleast
4 characters.";
return false;
}
</code>```

If you open up the developer console (usually F12), you'll see an error caused by an Invalid or Unexpected Token. Change these error messages to fit on one line to fix this error:

```<code>if(name=='' || postcode=='' || email==''){
document.getElementById("eresult").innerHTML = "Name, Email and Postcode are required.";
return false;
}
else if(name.length<3){
document.getElementById("eresult").innerHTML = "Name must be more than 3 characters.";
return false;
}
else if(postcode.length<4){
document.getElementById("eresult").innerHTML = "Postcode must be atleast 4 characters.";
return false;
}
</code>```

Also, you have a closing </button> tag but no opening one! Remove that tag from the line <input type="reset" value="Reset"></button>.

Hope this helps!

Body:
My code currently validates that the name/email and postcode is valid before being able to send when there is NO address that the information is meant to go to in the form action ="". But when I put the address it's meant to go to it completely skips the validation and just sends whatever, empty or not empty.

Trying to re-position the form action, but really have no idea.

<title>Online Food Delivery Form</title>

Online Food Delivery Form

<form action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi"
method="get"  onsubmit="return validation();">
Name* : <input type="text" name="name" id="name">

Email* :    <input type="email" name="email" id="email">

Postcode* : <input type="text" name="postcode" id="postcode" size="10">

<input type="reset" value="Reset"></button>
<input type="submit" name="submit" value="Submit"/>
</form>

Expected results is for the code to validate that the email/name and postcode is correct before sending the information to the designated site. But it's doing complete opposite.

Body:
In your validation, your error messages are multi-line strings

if(name=='' || postcode=='' || email==''){
document.getElementById("eresult").innerHTML = "Name, Email and Postcode
are required.";
return false;
}
else if(name.length<3){
document.getElementById("eresult").innerHTML = "Name must be more than 3
characters.";
return false;
}
else if(postcode.length<4){
document.getElementById("eresult").innerHTML = "Postcode must be atleast
4 characters.";
return false;
}

If you open up the developer console (usually F12), you'll see an error caused by an Invalid or Unexpected Token. Change these error messages to fit on one line to fix this error:

if(name=='' || postcode=='' || email==''){
document.getElementById("eresult").innerHTML = "Name, Email and Postcode are required.";
return false;
}
else if(name.length<3){
document.getElementById("eresult").innerHTML = "Name must be more than 3 characters.";
return false;
}
else if(postcode.length<4){
document.getElementById("eresult").innerHTML = "Postcode must be atleast 4 characters.";
return false;
}

Also, you have a closing </button> tag but no opening one! Remove that tag from the line <input type="reset" value="Reset"></button>.

Hope this helps!


来源: stackexchange

问:
Page is not working -- ERR_TOO_MANY_REDIRECTS
When this code implement in codeigniter  (this type of error show => localhost redirected you too many times.)

1)application/config/config.php

```<code>    $config['enable_hooks'] = TRUE;
</code>```

2)application/config/hooks.php

```<code>    $hook['post_controller_constructor'][] = array(
        'function' => 'checkAdminLogin',
        'filename' => 'authenticate_login.php',
        'filepath' => 'hooks',
    );
</code>```

3)application/hooks/authenticate_login.php  (make new php file (authenticate_login.php))

```<code>    function checkAdminLogin() {
        $CI = & get_instance();
        if (!getSession('is_logged_in')) {
            redirect('admin/login');
        } else
            return true;
    }

    function getSession($key) {
        $CI = & get_instance();
        return $CI->session->userdata(trim($key));
    }
</code>```

答:
When your visitor goes to admin/login your code will detect that he is not logged in and redirect it again to admin/login....and over, and over again...

You must detect login page route and not redirect from it.

Something like:

```<code>function checkAdminLogin() {
    $CI = & get_instance();
    if (!getSession('is_logged_in'))
    {
        if ($_SERVER['REQUEST_URI']!='/admin/login') {
            redirect('admin/login');
        }else{
            // User is on login page, don't redirect him again
        }
    } else
        return true;
}
</code>```

But I'm not sure what returning true means in your case. Basically you have 3 cases here:

Logged in

Not logged in, but on login page

Not logged in and not on login page

So you have to think of all those 3.

ContentLicense: CC BY-SA 4.0

Body:
When this code implement in codeigniter  (this type of error show => localhost redirected you too many times.)

1)application/config/config.php

    $config['enable_hooks'] = TRUE;

2)application/config/hooks.php

    $hook['post_controller_constructor'][] = array(
        'function' => 'checkAdminLogin',
        'filename' => 'authenticate_login.php',
        'filepath' => 'hooks',
    );

3)application/hooks/authenticate_login.php  (make new php file (authenticate_login.php))

    function checkAdminLogin() {
        $CI = & get_instance();
        if (!getSession('is_logged_in')) {
            redirect('admin/login');
        } else
            return true;
    }

    function getSession($key) {
        $CI = & get_instance();
        return $CI->session->userdata(trim($key));
    }

Body:
When your visitor goes to admin/login your code will detect that he is not logged in and redirect it again to admin/login....and over, and over again...

You must detect login page route and not redirect from it.

Something like:

function checkAdminLogin() {
    $CI = & get_instance();
    if (!getSession('is_logged_in'))
    {
        if ($_SERVER['REQUEST_URI']!='/admin/login') {
            redirect('admin/login');
        }else{
            // User is on login page, don't redirect him again
        }
    } else
        return true;
}

But I'm not sure what returning true means in your case. Basically you have 3 cases here:

Logged in

Not logged in, but on login page

Not logged in and not on login page

So you have to think of all those 3.


问:
asp.net mvc 3 'ModelType' is not declared
I created an Asp.NET MVC 3 web application. However, when I try to deploy it I get this error.

'ModelType' is not declared. It may be inaccessible due to its protection level.

on the second line of the code where I declare my model type. It works great locally where MVC 3 is installed but not on the server where it isn't. I've included all the dll's that it normally requires to run without the installation. Also this code works fine on another server where MVC 3 isn't installed so I'm not sure what the problem is.

here is the beginning of the code:

```<code>@Imports System.Data.SqlClient
@ModelType SqlDataReader

@Code
    Layout = Nothing
End Code
</code>```

it fails on the second line

答:
This would happen if the MvcWebPageRazorHost wasn't registered.

Make sure that you have the configuration in your ~/Views/Web.config on that server:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
        </namespaces>
    </pages>
</system.web.webPages.razor>
```

ContentLicense: CC BY-SA 3.0

Body:
I created an Asp.NET MVC 3 web application. However, when I try to deploy it I get this error.

'ModelType' is not declared. It may be inaccessible due to its protection level.

on the second line of the code where I declare my model type. It works great locally where MVC 3 is installed but not on the server where it isn't. I've included all the dll's that it normally requires to run without the installation. Also this code works fine on another server where MVC 3 isn't installed so I'm not sure what the problem is.

here is the beginning of the code:

@Imports System.Data.SqlClient
@ModelType SqlDataReader

@Code
    Layout = Nothing
End Code

it fails on the second line


问:
Method does not work within the object in Javascript
I created a simple object that has a method to return some calculation but it doesn't work.

I declared the object with its properties and method as in the attached code.

```<code><p id="demo"></p>
<script>
    var person = new Object();
    person.firstName= "John";
    person.lastName= "Doe";
    person.age=40;
    person.retireAtAge= function (){ return (this.age+25);};
    document.getElementById("demo").innerHTML=person.firstName + " Retires at " + person.retireAtAge;
 </script>
</code>```

The expected output is:
John Retires at 65

but I get now is:
John Retires at function (){ return (this.age+25);}

答:
You need to call the method by putting () at the end of function variable.

```<code>document.getElementById("demo").innerHTML=person.firstName + " Retires at " + person.retireAtAge();
</code>```

Body:
I created a simple object that has a method to return some calculation but it doesn't work.

I declared the object with its properties and method as in the attached code.

The expected output is:
John Retires at 65

but I get now is:
John Retires at function (){ return (this.age+25);}

Body:
You need to call the method by putting () at the end of function variable.

document.getElementById("demo").innerHTML=person.firstName + " Retires at " + person.retireAtAge();


问:
Exec() php function dont work in linux empty request
I'm trying to execute this code on php in linux server

$some= exec("node-v");
echo $some;
```

but i don't have an anwers

答: If the comment above could not work than, maybe exec() is disabled. You can try to check php.ini file at disabled_functions line.

Body:
I'm trying to execute this code on php in linux server

$some= exec("node-v");
echo $some;

but i don't have an anwers


问:
Check if a group of values exist in array Javascript

I have a table like this in which i have some values for location . If this location values contains any other values except "California" "New york" ,"HQ" , "Florida" it should show alert message like location is not valid .
I have tried following code .

```<code>   tabledata.DataTable.forEach(function (data) {
       var locate = data.Location;
     if (locate.includes(data.BranchName)) {
       alert("Success");
      } else {
     alert("failure");
             }
      })
</code>```

UPDATE

```<code>branchDetails.forEach(function (data) {
       console.log(data.BranchName);
  });
</code>```

here data.BranchName contains "California" "New york" ,"HQ" , "Florida" and locate  contains the table location value .

My issue here is even though the table contains "HQ" it is showing as failure

答:
I think you just used includes the wrong way. Try using:

```<code>data.Branchname.includes(locate)
</code>```

EDIT

You could also safe check in case data.Branchname is undefined

```<code>data.Branchname && data.Branchname.includes(locate)
</code>```

Body:
I have a table like this in which i have some values for location . If this location values contains any other values except "California" "New york" ,"HQ" , "Florida" it should show alert message like location is not valid .
I have tried following code .

   tabledata.DataTable.forEach(function (data) {
       var locate = data.Location;
     if (locate.includes(data.BranchName)) {
       alert("Success");
      } else {
     alert("failure");
             }
      })

UPDATE

branchDetails.forEach(function (data) {
       console.log(data.BranchName);
  });

here data.BranchName contains "California" "New york" ,"HQ" , "Florida" and locate  contains the table location value .

My issue here is even though the table contains "HQ" it is showing as failure

Body:
I think you just used includes the wrong way. Try using:

data.Branchname.includes(locate)

EDIT

You could also safe check in case data.Branchname is undefined

data.Branchname && data.Branchname.includes(locate)


问:
Chart Skinning Using p:layout and Dashboards
I can't seem to get my code to work the way I want.  I'm attempting to format charts on a page with JSF templates.  I'm using JSF2.0, NetBeans 6.9.1, GlassFish 3.0.1 with Mojarra 2.0.3, and PrimeFaces 2.2. For the template I am using . I have placed the charts into dashboard panels. The charts themselves show up, but I cannot modify their size, or display the piechart legends. I have put the the style and script tags, shown in the documentation and showcase, on the main template page where the other css references are located. I've used this code:

```<code><style type="text/css">
        .chartClass {
            width: 250px;
            height: 145px;
        }
    </style>
    <script type="text/javascript">
        var piechartStyle = {
            padding:20,
            legend: {
                display: "right",
                spacing:10
            }
        };
    </script>
</code>```

On the template client page, where I display the charts, this is the code I've used:

```<code>    <ui:define name="main_base_content">
                <h:form>
                    <p:dashboard id="board" model="#{dashboardBean.model}">

                        <p:panel id="receipts_chart" header="Receipts Chart" toggleable="true" toggleSpeed="200">
                            <p:pieChart model="#{receiptsChartBean.model}" styleClass="piechartStyle" />
                        </p:panel>
                        <p:panel id="shipments_chart" header="Shipments Chart" toggleable="true" toggleSpeed="200">
                            <p:pieChart model="#{shipmentsChartBean.model}" styleClass="piechartStyle" />
                        </p:panel>

                        <p:panel id="receipts_graph" header="Receipts Graph" toggleable="true" toggleSpeed="200">
                            <p:lineChart model="#{receiptsChartBean.lineModel}" var="line" titleX="Date" titleY="Number of Receipts">
                                <p:chartSeries label="Receipts" value="#{line.receipts}" />
                            </p:lineChart>
                        </p:panel>
                        <p:panel id="shipments_graph" header="Shipments Graph" toggleable="true" toggleSpeed="200">
                            <p:lineChart model="#{shipmentsChartBean.lineModel}" var="line" titleX="Date" titleY="Number of Shipments">
                                <p:chartSeries label="Receipts" value="#{line.receipts}" />
                            </p:lineChart>
                        </p:panel>

                        <p:panel id="volume_received_graph" header="Volume Received - Graph" toggleable="true" toggleSpeed="200">
                            <p:stackedColumnChart model="#{shipmentsChartBean.stackModel}" var="stack" titleX="Date" titleY="Receipts by Weight">
                                <p:chartSeries label="Customer1" value="#{stack.stackedShipments}" />
                                <p:chartSeries label="Customer2" value="#{stack.stackedShipments}" />
                                <p:chartSeries label="Customer3" value="#{stack.stackedShipments}" />
                                <p:chartSeries label="Customer4" value="#{stack.stackedShipments}" />
                            </p:stackedColumnChart>
                        </p:panel>
                        <p:panel id="weight_received_graph" header="Weight Received - Graph" toggleable="true" toggleSpeed="200">
                            <p:stackedColumnChart model="#{receiptsChartBean.stackModel}" var="stack" titleX="Date" titleY="Receipts by Weight">
                                <p:chartSeries label="Customer1" value="#{stack.stackedReceipts}" />
                                <p:chartSeries label="Customer2" value="#{stack.stackedReceipts2}" />
                                <p:chartSeries label="Customer3" value="#{stack.stackedReceipts3}" />
                                <p:chartSeries label="Customer4" value="#{stack.stackedReceipts4}" />
                            </p:stackedColumnChart>
                        </p:panel>
                    </p:dashboard>
                </h:form>
            </ui:define>
</code>```

The charts are filled with dummy data. They display, but the skinning is not working. I looked at the page with Firebug and see that despite setting the width and height of charts to 250px and 145px respectively, they remain at the default values.

I'm not sure where I've gone wrong. Do charts not work in layouts and/or dashboards? Oh, I've also tried putting the .chartClass into the cssLayout.css document - that did not work either.

答:
I figured out how to re-size the charts, and it has nothing to do with

```<code><style type="text/css">
    .chartClass {
        width: 250px;
        height: 145px;
    }
</style>
</code>```

I just used the "height" and "width" attributes of the different chart tags.  NOTE: for the pie chart tags, only the width seems to work. If I add in the height attribute the chart won't show.  That's okay though, because the width attribute seems to re-size the whole chart proportionately (which makes sense if you think about it - its a circle).  For the other chart types I used both the height an width tags.

I would still like to use the code shown above to resize all charts at the same time, but I'll work with what I've got.

ContentLicense: CC BY-SA 2.5

Body:
I can't seem to get my code to work the way I want.  I'm attempting to format charts on a page with JSF templates.  I'm using JSF2.0, NetBeans 6.9.1, GlassFish 3.0.1 with Mojarra 2.0.3, and PrimeFaces 2.2. For the template I am using . I have placed the charts into dashboard panels. The charts themselves show up, but I cannot modify their size, or display the piechart legends. I have put the the style and script tags, shown in the documentation and showcase, on the main template page where the other css references are located. I've used this code:

On the template client page, where I display the charts, this is the code I've used:

    <ui:define name="main_base_content">
                <h:form>

                </h:form>
            </ui:define>

The charts are filled with dummy data. They display, but the skinning is not working. I looked at the page with Firebug and see that despite setting the width and height of charts to 250px and 145px respectively, they remain at the default values.

I'm not sure where I've gone wrong. Do charts not work in layouts and/or dashboards? Oh, I've also tried putting the .chartClass into the cssLayout.css document - that did not work either.

Body:
I figured out how to re-size the charts, and it has nothing to do with

<style type="text/css">
    .chartClass {
        width: 250px;
        height: 145px;
    }
</style>

I just used the "height" and "width" attributes of the different chart tags.  NOTE: for the pie chart tags, only the width seems to work. If I add in the height attribute the chart won't show.  That's okay though, because the width attribute seems to re-size the whole chart proportionately (which makes sense if you think about it - its a circle).  For the other chart types I used both the height an width tags.

I would still like to use the code shown above to resize all charts at the same time, but I'll work with what I've got.


问:
Regular expression for an alphanumeric word
I have a requirement to find and return the first occurrence of a pattern from a string.

Example: hello my SNO is 05FK3NEK900058V please add it

expected output: 05FK3NEK900058V

Condition for the pattern to match

Combination of digits and alphabets

Character length between 12 to 16

Can I do it using regular expression or do I need to loop thought the words?

What I tried but it didn't work

```<code>const regex = /\b^(?!\d*$|[a-zA-Z]*$)[a-zA-Z\d]{12,16}$\b/gm;
const str = `hello my SNO is 05FK3NEK900058V please add it `;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
</code>```

答:
You may use a single regex like

```<code>/\b(?=[a-zA-Z\d]{12,16}\b)(?:[a-zA-Z]*\d|\d*[a-zA-Z])[a-zA-Z\d]*\b/
</code>```

See the regex demo.

Details

\b - word boundary

(?=[a-zA-Z\d]{12,16}\b) - up to the next word boundary, there must be 12 through 16 alphanumeric chars

(?:[a-zA-Z]*\d|\d*[a-zA-Z]) - either 0+ letters and a digit or 0+ digits and then a letter

[a-zA-Z\d]* - 0+ alphanumeric chars

\b - word boundary.

See a JS demo below:

var str = "hello my SNO is 05FK3NEK900058V please add it ";
var reg = /\b(?=[a-zA-Z\d]{12,16}\b)(?:[a-zA-Z]*\d|\d*[a-zA-Z])[a-zA-Z\d]*\b/;
var m = str.match(reg) || [""];
console.log(m[0]);```

Body:
I have a requirement to find and return the first occurrence of a pattern from a string.

Example: hello my SNO is 05FK3NEK900058V please add it

expected output: 05FK3NEK900058V

Condition for the pattern to match

Combination of digits and alphabets

Character length between 12 to 16

Can I do it using regular expression or do I need to loop thought the words?

What I tried but it didn't work

const regex = /\b^(?!\d*$|[a-zA-Z]*$)[a-zA-Z\d]{12,16}$\b/gm;
const str = `hello my SNO is 05FK3NEK900058V please add it `;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Body:
You may use a single regex like

/\b(?=[a-zA-Z\d]{12,16}\b)(?:[a-zA-Z]*\d|\d*[a-zA-Z])[a-zA-Z\d]*\b/

See the regex demo.

Details

\b - word boundary

(?=[a-zA-Z\d]{12,16}\b) - up to the next word boundary, there must be 12 through 16 alphanumeric chars

(?:[a-zA-Z]*\d|\d*[a-zA-Z]) - either 0+ letters and a digit or 0+ digits and then a letter

[a-zA-Z\d]* - 0+ alphanumeric chars

\b - word boundary.

See a JS demo below:

var str = "hello my SNO is 05FK3NEK900058V please add it ";
var reg = /\b(?=[a-zA-Z\d]{12,16}\b)(?:[a-zA-Z]*\d|\d*[a-zA-Z])[a-zA-Z\d]*\b/;
var m = str.match(reg) || [""];
console.log(m[0]);


问:
How can i convert my dataset into json format like my required format
i want to convert my this dataset
enter image description here

into this json format using pandas

```<code>y = {'name':['a','b','c'],"rollno":[1,2,3],"teacher":'xyz',"year":1998}
</code>```

答:
First create dictionary by DataFrame.to_dict and filter out duplicated lists for scalars in dictionary comprehension with if-else by check length of sets:

```<code>d = {k:v if len(set(v)) > 1 else v[0] for k, v in df.to_dict('l').items()}
print (d)
{'name': ['a', 'b', 'c'], 'rollno': [1, 2, 3], 'teacher': 'xyz', 'year': 1998}
</code>```

And then convert to json:

```<code>import json

j = json.dumps(d)
print (j)
{"name": ["a", "b", "c"], "rollno": [1, 2, 3], "teacher": "xyz", "year": 1998}
</code>```

If values should be duplicated:

```<code>import json

j = json.dumps(df.to_dict(orient='l'))
print (j)
{"name": ["a", "b", "c"], "rollno": [1, 2, 3],
 "teacher": ["xyz", "xyz", "xyz"], "year": [1998, 1998, 1998]}
</code>```

Body:
i want to convert my this dataset
enter image description here

into this json format using pandas

y = {'name':['a','b','c'],"rollno":[1,2,3],"teacher":'xyz',"year":1998}

Body:
First create dictionary by DataFrame.to_dict and filter out duplicated lists for scalars in dictionary comprehension with if-else by check length of sets:

d = {k:v if len(set(v)) > 1 else v[0] for k, v in df.to_dict('l').items()}
print (d)
{'name': ['a', 'b', 'c'], 'rollno': [1, 2, 3], 'teacher': 'xyz', 'year': 1998}

And then convert to json:

import json

j = json.dumps(d)
print (j)
{"name": ["a", "b", "c"], "rollno": [1, 2, 3], "teacher": "xyz", "year": 1998}

If values should be duplicated:

import json

j = json.dumps(df.to_dict(orient='l'))
print (j)
{"name": ["a", "b", "c"], "rollno": [1, 2, 3],
 "teacher": ["xyz", "xyz", "xyz"], "year": [1998, 1998, 1998]}


答:
You just need to reverse the includes() as it is array.includes(value)

tabledata.DataTable.forEach(function (data) {
       var locate = data.Location;
       var branch = data.BranchName;
       //if branch is string you need to do like this
       /*
        var branch = data.BranchName.split(',');
       */
     if (branch.includes(locate)) {
       alert("Success");
      } else {
     alert("failure");
             }
      })```

Title: Check if a group of values exist in array Javascript


问:
How get Id of element when i click on the element
I have 2 div(HTML) element and id is div1 and div2, When I click on any div then I want id of current div... idea?</p>

```<code><div id="div1"></div>
<div id="div2"></div>

<div id="displayid"></div>
</code>```

```<code>if(clickedDivId = this.id){
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;
for (var i = 0; i < divCount; i += 1) {

    div[i].onclick = function(e) {
        clickedDivId = this.id;
        event.stopPropagation();

    };
}
}

document.getElementById("displayid").innerHTML = ??clickedDivId??how;
</code>```

答:
document.addEventListener('click',function(e){
  var divToDisplay = event.target.id
  document.getElementById('displayid').innerHTML = divToDisplay
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="div1">DIV TEST 1</div>
<div id="div2">DIV TEST 2</div>

<div id="displayid"></div></code>```

Body:
I have 2 div(HTML) element and id is div1 and div2, When I click on any div then I want id of current div... idea?

if(clickedDivId = this.id){
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;
for (var i = 0; i < divCount; i += 1) {

    div[i].onclick = function(e) {
        clickedDivId = this.id;
        event.stopPropagation();

    };
}
}

document.getElementById("displayid").innerHTML = ??clickedDivId??how;

Body:
document.addEventListener('click',function(e){
  var divToDisplay = event.target.id
  document.getElementById('displayid').innerHTML = divToDisplay
})

<div id="div1">DIV TEST 1</div>
<div id="div2">DIV TEST 2</div>

<div id="displayid"></div>


问:
str.zfill() in pandas has problem with ' character
In connection with the question I asked here: https://stackoverflow.com/questions/56375651/add-zeros-to-string-in-pandas-column-depends-of-length
I have a problem with str.zfill() method.

My example data (column of DF):

```<code>0002131
dsda2123
eew12341
wewqsws1'
123
</code>```

Following @jezrael advice I fill each row to 12 char by str.zfill() method.

Code:
 df['SampleNumber'] = df['SampleNumber'].str.zfill(12)

Result file:

```<code>000000002131
0000dsda2123
0000eew12341
wewqsws1'
000000000123
</code>```

So all work fine but I have a problem with names where I have a ' character. The method passes it, and in result series I got a unchanged name. What is the problem here? How can I deal with it? In the documentation of that method, I found nothing about a similar problem. And type(wewqsws1') it's str.

Can someone know how to fix it?

Expecting result:

```<code>000000002131
0000dsda2123
0000eew12341
000wewqsws1'
000000000123
</code>```

答:
You probably have empty space in the end try str.strip().str.zfill(12)

Ex:

```<code>import pandas as pd

df = pd.DataFrame({"SampleNumber": ['000000002131', '0000dsda2123', '0000eew12341', "wewqsws1'  ", '000000000123']})
df['SampleNumber'] = df['SampleNumber'].str.strip().str.zfill(12)
print(df)
</code>```

Body:
In connection with the question I asked here: https://stackoverflow.com/questions/56375651/add-zeros-to-string-in-pandas-column-depends-of-length
I have a problem with str.zfill() method.

My example data (column of DF):

0002131
dsda2123
eew12341
wewqsws1'
123

Following @jezrael advice I fill each row to 12 char by str.zfill() method.

Code:
 df['SampleNumber'] = df['SampleNumber'].str.zfill(12)

Result file:

000000002131
0000dsda2123
0000eew12341
wewqsws1'
000000000123

So all work fine but I have a problem with names where I have a ' character. The method passes it, and in result series I got a unchanged name. What is the problem here? How can I deal with it? In the documentation of that method, I found nothing about a similar problem. And type(wewqsws1') it's str.

Can someone know how to fix it?

Expecting result:

000000002131
0000dsda2123
0000eew12341
000wewqsws1'
000000000123

Body:
You probably have empty space in the end try str.strip().str.zfill(12)

Ex:

import pandas as pd

df = pd.DataFrame({"SampleNumber": ['000000002131', '0000dsda2123', '0000eew12341', "wewqsws1'  ", '000000000123']})
df['SampleNumber'] = df['SampleNumber'].str.strip().str.zfill(12)
print(df)


问:
Different rows for results while using the SQL case statement for same value
The result should be in a single row with logged in and not logged in counts. Why it is coming in two different rows for same account?</p>

```<code>SELECT distinct  Account
     , SUM(CASE Val WHEN status='logged in' THEN  1 Else 0  END) AS 'Total logged in'
     , SUM(CASE Val WHEN status='not logged in' THEN  1 Else 0 END) AS 'total not logged in '
FROM TableAccount
GROUP BY Account

account    logged in    not logged in
A            21             0
A            0              2
</code>```

答:
SELECT DISTINCTis almost never needed with GROUP BY.  Also, you are correct, there should only be one row for 'A' -- assuming the account is exactly the same.

The fact that you are getting two rows means that they are not the same.  One issue could be trailing blanks.  You can check for this:

```<code>SELECT DISTINCT '|' +  Account + '|'
FROM TableAccount ;
</code>```

Other problems could be characters that look the same or hidden characters.  Finding the problem might require some investigation.

Body:
The result should be in a single row with logged in and not logged in counts. Why it is coming in two different rows for same account?

SELECT distinct  Account
     , SUM(CASE Val WHEN status='logged in' THEN  1 Else 0  END) AS 'Total logged in'
     , SUM(CASE Val WHEN status='not logged in' THEN  1 Else 0 END) AS 'total not logged in '
FROM TableAccount
GROUP BY Account

account    logged in    not logged in
A            21             0
A            0              2

Body:
SELECT DISTINCTis almost never needed with GROUP BY.  Also, you are correct, there should only be one row for 'A' -- assuming the account is exactly the same.

The fact that you are getting two rows means that they are not the same.  One issue could be trailing blanks.  You can check for this:

SELECT DISTINCT '|' +  Account + '|'
FROM TableAccount ;

Other problems could be characters that look the same or hidden characters.  Finding the problem might require some investigation.


问:
How to import a Amplitude js in html
I just got into web developing and have this 'basic' question.. I have built this website for my brother who is an artist and I am trynna import 'Amplitude js' into the html so I can use that audio player to play his musics. I just want the player to be in the center of the page, not the whole page.

The source files are on https://github.com/521dimensions/amplitudejs

I have tried using the 3rd method explained, and included

```<code> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/amplitudejs@{{3.2.1}}/dist/amplitude.js"></script>
</code>```

in my html head section. Nothing is happening.

I just don't understand how to implement it into my html so it shows up in the page.

Any idea on something I might be missing out ?

答:
This is because Your head section of HTML is not fetching javascript from the CDN.

As per documentation, You will need to put version number.

Here is right example:

For Latest version do not use any number.

ex:

and For any version, just put your number after @

Now you can use your script to call js function anywhere under the html section, best to call your script before ending body section.

Title: How to import a Amplitude js in html

Body:
I just got into web developing and have this 'basic' question.. I have built this website for my brother who is an artist and I am trynna import 'Amplitude js' into the html so I can use that audio player to play his musics. I just want the player to be in the center of the page, not the whole page.

The source files are on https://github.com/521dimensions/amplitudejs

I have tried using the 3rd method explained, and included

in my html head section. Nothing is happening.

I just don't understand how to implement it into my html so it shows up in the page.

Any idea on something I might be missing out ?

Body:
This is because Your head section of HTML is not fetching javascript from the CDN.

As per documentation, You will need to put version number.

Here is right example:

For Latest version do not use any number.

ex:

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/amplitudejs/dist/amplitude.js"></script>

and For any version, just put your number after @

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/amplitudejs@4.1.0/dist/amplitude.js"></script>

Now you can use your script to call js function anywhere under the html section, best to call your script before ending body section.


问:
.net construct / pattern to block by segment of code, not by thread
Is there a construct or pattern in .net that defines a segment of code that can be accessed by multiple threads but blocks if any thread is in some other segment of code (and vice-versa)?  For example:

```<code>void SomeOperationA()
{
    Block( B )
    {
        Segment1:
        ... only executes if no threads are executing in Segment2 ...
    }
}

}

void SomeOperationB()
{
    Block( A )
    {
        Segment2:
        ... only executes if no threads are executing in Segment1 ...
    }
}
</code>```

Edit

Several threads should be able to access Segment1/Segment2 simultaneously (only one Segment being "active" at a time.  If Segment 1 is executing, another thread should be able to execute Segment1 but not Segment2.

Edit 2

Given all the comments/replies and my real-world scenario, I realize that its a bit crazy to require Segment2 to be accessed by multiple-threads.

答:
Given your edit, it sounds like the proper approach would be to use a ReaderWriterLockSlim, since you really shouldn't be modifying the collection when Segment2 is running, and you shouldn't allow more than 1 Segment2 to run:</p>

```<code>private static ReaderWriterLockSlim readerLock = new ReaderWriterLockSlim();
void SomeOperationA()
{
    try
    {
        readerLock.EnterReadLock();
        // Segment1:
        // ... only executes if no threads are executing in Segment2 ...
    }
    finally
    {
        readerLock.ExitReadLock();
    }
}

void SomeOperationB()
{
    try
    {
        readerLock.EnterWriteLock();
        // Prevents multiple Segment2 from serializing, and prevents all Segment1 threads...
    }
    finally
    {
        readerLock.ExitWriteLock();
    }
}
</code>```

Body:
Is there a construct or pattern in .net that defines a segment of code that can be accessed by multiple threads but blocks if any thread is in some other segment of code (and vice-versa)?  For example:

void SomeOperationA()
{
    Block( B )
    {
        Segment1:
        ... only executes if no threads are executing in Segment2 ...
    }
}

}

void SomeOperationB()
{
    Block( A )
    {
        Segment2:
        ... only executes if no threads are executing in Segment1 ...
    }
}

Edit

Several threads should be able to access Segment1/Segment2 simultaneously (only one Segment being "active" at a time.  If Segment 1 is executing, another thread should be able to execute Segment1 but not Segment2.

Edit 2

Given all the comments/replies and my real-world scenario, I realize that its a bit crazy to require Segment2 to be accessed by multiple-threads.

Body:
Given your edit, it sounds like the proper approach would be to use a ReaderWriterLockSlim, since you really shouldn't be modifying the collection when Segment2 is running, and you shouldn't allow more than 1 Segment2 to run:

private static ReaderWriterLockSlim readerLock = new ReaderWriterLockSlim();
void SomeOperationA()
{
    try
    {
        readerLock.EnterReadLock();
        // Segment1:
        // ... only executes if no threads are executing in Segment2 ...
    }
    finally
    {
        readerLock.ExitReadLock();
    }
}

void SomeOperationB()
{
    try
    {
        readerLock.EnterWriteLock();
        // Prevents multiple Segment2 from serializing, and prevents all Segment1 threads...
    }
    finally
    {
        readerLock.ExitWriteLock();
    }
}


答:
After @bobble buble comment

I think this will works:

```<code>\w{12,16}
</code>```

Demo

Also you can use words boundaries if you match required to be a word.

```<code>\b\w{12,16}\b
</code>```

Demo:

Updated after @PeterM Comment:

The last version more verbose but more accurate:

string=`Johannsonoff 111111111111111 05FK3NEK900058Vf 05FK3NEK900058Vfaf48 hello my SNO is fFK3NEK9000515 05FK3NEK9000515 please add it 05FK3NEK900058Vfaf48 faf fasf1654 EK90058Vs11 EK9005f8Vs12 05FK3NE90058Vs16 05FK3NEK90058Vs17`;
// Returns an Array in which elements are strings between 12 and 16 characters.
const groupMathed = string.match(/\b\w{12,16}\b/g)
// Returns the first element that have a digit [0-9] follow by a alphabetic character or a alphabetic character followed by a digit.
const alphanumericWord = groupMathed.find(e => /[0-9]+[a-zA-z]+|[a-zA-z]+[0-9]+/.test(e))
console.log(alphanumericWord)```
</div>
</div>
</p>

<p>Another approach can be use <strong>this regex which is more verbose but reduce the code</strong>:</p>

```(?=(\b\d+[a-zA-Z]|\b[a-zA-Z]\d+))[a-zA-Z0-9]{12,16}\b
```

<p>Demo: https://regex101.com/r/0lMyoV/11/</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>string=`asdfghjlqerut hello my SNO is 1234567891234 05FK3NEK900058V 0FK3NEK900058V asdfasfd25fasfaa please add it 05FK3NEK900058Vfaf48 faf fasf1654 F0K3NEK900058V Johannsonoff 111111111111111 05FK3NEK900058Vf 05FK3NEK900058Vfaf48 hello my SNO is fFK3NEK9000515 05FK3NEK9000515 please add it 05FK3NEK900058Vfaf48 faf fasf1654 EK90058Vs11 EK9005f8Vs12 05FK3NE90058Vs16 05FK3NEK90058Vs17 05FK3NEK900058Vfaf48`;

const regex = /(?=(\b\d+[a-zA-Z]|\b[a-zA-Z]\d+))[a-zA-Z0-9]{12,16}\b/g
const groupMathed = string.match(regex)
console.log(groupMathed)</code>```

Title: Regular expression for an alphanumeric word

Body:
After @bobble buble comment

I think this will works:

\w{12,16}

Demo

Also you can use words boundaries if you match required to be a word.

\b\w{12,16}\b

Demo:

Updated after @PeterM Comment:

The last version more verbose but more accurate:

string=`Johannsonoff 111111111111111 05FK3NEK900058Vf 05FK3NEK900058Vfaf48 hello my SNO is fFK3NEK9000515 05FK3NEK9000515 please add it 05FK3NEK900058Vfaf48 faf fasf1654 EK90058Vs11 EK9005f8Vs12 05FK3NE90058Vs16 05FK3NEK90058Vs17`;
// Returns an Array in which elements are strings between 12 and 16 characters.
const groupMathed = string.match(/\b\w{12,16}\b/g)
// Returns the first element that have a digit [0-9] follow by a alphabetic character or a alphabetic character followed by a digit.
const alphanumericWord = groupMathed.find(e => /[0-9]+[a-zA-z]+|[a-zA-z]+[0-9]+/.test(e))
console.log(alphanumericWord)

Another approach can be use this regex which is more verbose but reduce the code:

(?=(\b\d+[a-zA-Z]|\b[a-zA-Z]\d+))[a-zA-Z0-9]{12,16}\b

Demo: https://regex101.com/r/0lMyoV/11/

string=`asdfghjlqerut hello my SNO is 1234567891234 05FK3NEK900058V 0FK3NEK900058V asdfasfd25fasfaa please add it 05FK3NEK900058Vfaf48 faf fasf1654 F0K3NEK900058V Johannsonoff 111111111111111 05FK3NEK900058Vf 05FK3NEK900058Vfaf48 hello my SNO is fFK3NEK9000515 05FK3NEK9000515 please add it 05FK3NEK900058Vfaf48 faf fasf1654 EK90058Vs11 EK9005f8Vs12 05FK3NE90058Vs16 05FK3NEK90058Vs17 05FK3NEK900058Vfaf48`;

const regex = /(?=(\b\d+[a-zA-Z]|\b[a-zA-Z]\d+))[a-zA-Z0-9]{12,16}\b/g
const groupMathed = string.match(regex)
console.log(groupMathed)


问:
How to add a new method to an existing import in python? Specifically moviepy
For whatever reason, Python is not allowing me to access a custom method I created in moviepy's preview.py file. I just want to know how to correctly implement it into the file. For reference, before I changed the name of the method, it was working correctly.

I checked at least two __init.py__ files and they were effectively empty. I couldn't find if methods are initialized anywhere, and is probably what I'm missing.

I also tried restarting Git Bash and that didn't work either (another solution I saw).

Original:

```<code>@convert_masks_to_RGB
def preview(clip, fps=15, audio=True, audio_fps=22050, audio_buffersize=3000,
            audio_nbytes=2, fullscreen=False):
</code>```

Changed:

```<code>@requires_duration
@convert_masks_to_RGB
def preview_custom(clip, marker_overlay="marker_overlay.png", fps=15, audio=True, audio_fps=22050, audio_buffersize=3000,
            audio_nbytes=2, fullscreen=False):
</code>```

There are more than a few differences between the changed and original method, however at the moment the only result I expect is having the method be called correctly. Error is below:

```<code>Traceback (most recent call last):
  File "T3AJM.py", line 249, in <module>
    main()
  File "T3AJM.py", line 34, in main
    GUI_main_menu()
  File "T3AJM.py", line 85, in GUI_main_menu
    GUI_play_markers()
  File "T3AJM.py", line 125, in GUI_play_markers
    video.preview_custom(marker_overlay=TEMP_OVERLAY_FILE)
AttributeError: 'VideoFileClip' object has no attribute 'preview_custom'
</code>```

Thank you for your time.

答:
I'm not even sure if this technically fixes the problem, but just doing:

```<code>from moviepy.video.io.preview import *
</code>```

and

```<code>preview_custom(video, marker_overlay=TEMP_OVERLAY_FILE)
</code>```

fixed the problem. I have no idea why I had to change the way it was called, as doing clip.preview(), or in this case video.preview() worked perfectly fine before, but whatever.

Body:
For whatever reason, Python is not allowing me to access a custom method I created in moviepy's preview.py file. I just want to know how to correctly implement it into the file. For reference, before I changed the name of the method, it was working correctly.

I checked at least two __init.py__ files and they were effectively empty. I couldn't find if methods are initialized anywhere, and is probably what I'm missing.

I also tried restarting Git Bash and that didn't work either (another solution I saw).

Original:

@convert_masks_to_RGB
def preview(clip, fps=15, audio=True, audio_fps=22050, audio_buffersize=3000,
            audio_nbytes=2, fullscreen=False):

Changed:

@requires_duration
@convert_masks_to_RGB
def preview_custom(clip, marker_overlay="marker_overlay.png", fps=15, audio=True, audio_fps=22050, audio_buffersize=3000,
            audio_nbytes=2, fullscreen=False):

There are more than a few differences between the changed and original method, however at the moment the only result I expect is having the method be called correctly. Error is below:

Traceback (most recent call last):
  File "T3AJM.py", line 249, in <module>
    main()
  File "T3AJM.py", line 34, in main
    GUI_main_menu()
  File "T3AJM.py", line 85, in GUI_main_menu
    GUI_play_markers()
  File "T3AJM.py", line 125, in GUI_play_markers
    video.preview_custom(marker_overlay=TEMP_OVERLAY_FILE)
AttributeError: 'VideoFileClip' object has no attribute 'preview_custom'

Thank you for your time.

Body:
I'm not even sure if this technically fixes the problem, but just doing:

from moviepy.video.io.preview import *

and

preview_custom(video, marker_overlay=TEMP_OVERLAY_FILE)

fixed the problem. I have no idea why I had to change the way it was called, as doing clip.preview(), or in this case video.preview() worked perfectly fine before, but whatever.


问:
How to manage inventory using macro in excel
I am trying to get Excel to work as a inventory scan reader.
When i scan any item using barcode scanner,it should recognize the item in the excel and add my current inventory.

In my excel i have following data  COL A is DESCRIPTION,COL B is Barcode,COL C is QTY_before sale and COL D is Current_scan_stock.

Column D will be empty and as i scan the barcode it should recognize the item and add the qty, every-time i scan same barcode it should add +1

答:
If you manage to pass in excel the bar code you could use the below:</p>

```<code>Option Explicit

Sub test()

    Dim LastRow As Long
    Dim rngToSearch As Range, rngFound As Range
    Dim LookingValue As String

    'Create a with statement refer to the sheet that your data are store
    With ThisWorkbook.Worksheets("Sheet1")
        'Assigg to LookingValue the barcode scanned
        LookingValue = "1234"
        'Find the last row of column A
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        'Set the range to search for the barcode in
        Set rngToSearch = .Range("B2:B" & LastRow)
        'Set to rngFound the results from the find
        Set rngFound = rngToSearch.Find(LookingValue, LookIn:=xlValues)
        'If the result is nothing
        If rngFound Is Nothing Then
            'Message box
            MsgBox "Barcode was not found."
        'if you find a result
        Else
            'Add 1 to the existing value
            .Cells(rngFound.Row, 4).Value = 1 + .Cells(rngFound.Row, 4).Value
        End If

    End With

End Sub
</code>```

Body:
If you manage to pass in excel the bar code you could use the below:

Option Explicit

Sub test()

    Dim LastRow As Long
    Dim rngToSearch As Range, rngFound As Range
    Dim LookingValue As String

    'Create a with statement refer to the sheet that your data are store
    With ThisWorkbook.Worksheets("Sheet1")
        'Assigg to LookingValue the barcode scanned
        LookingValue = "1234"
        'Find the last row of column A
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        'Set the range to search for the barcode in
        Set rngToSearch = .Range("B2:B" & LastRow)
        'Set to rngFound the results from the find
        Set rngFound = rngToSearch.Find(LookingValue, LookIn:=xlValues)
        'If the result is nothing
        If rngFound Is Nothing Then
            'Message box
            MsgBox "Barcode was not found."
        'if you find a result
        Else
            'Add 1 to the existing value
            .Cells(rngFound.Row, 4).Value = 1 + .Cells(rngFound.Row, 4).Value
        End If

    End With

End Sub


问:
navigationClick() problem for more then one item on Blackberry
I have a ListField and ObjectChoiceField.

In the navigationClick method, how do you figure out which one is selected?

In navigationClick() method:

```<code>Field field = getFieldWithFocus();
if (field instanceof ListField)         // returns false
if (field instanceof ObjectChoiceField) // returns false
if (field == myListField)               // returns false
if (field == myObjectChoiceField)       // returns false
</code>```

答: Just override navigationClick for both ListField and ObjectChoiceField. Then inside of each overriden methods you will only receive clicks that is related to the "owner" of the method (e.g. either ListField or ObjectChoiceField).

Body:
I have a ListField and ObjectChoiceField.

In the navigationClick method, how do you figure out which one is selected?

In navigationClick() method:

Field field = getFieldWithFocus();
if (field instanceof ListField)         // returns false
if (field instanceof ObjectChoiceField) // returns false
if (field == myListField)               // returns false
if (field == myObjectChoiceField)       // returns false


问:
Move files between two AWS S3 buckets using boto3
I have to move files between one bucket to another with Python Boto API. (I need it to "Cut" the file from the first Bucket and "Paste" it in the second one).
What is the best way to do that?

** Note: Is that matter if I have two different ACCESS KEYS and SECRET KEYS?

答:
This is code I used to move files within sub-directories of a s3 bucket</p>

```<code># =============================================================================
# CODE TO MOVE FILES within subfolders in S3 BUCKET
# =============================================================================

from boto3.session import Session

ACCESS_KEY = 'a_key'
SECRET_KEY = 's_key'
session = Session(aws_access_key_id=ACCESS_KEY,
            aws_secret_access_key=SECRET_KEY)
s3 = session.resource('s3')#creating session of S3 as resource

s3client = session.client('s3')

resp_dw = s3client.list_objects(Bucket='main_bucket', Prefix='sub_folder/', Delimiter="/")

forms2_dw = [x['Key'] for x in resp_dw['Contents'][1:]]#here we got all files list (max limit is 1000 at a time)
reload_no = 0
while len(forms2_dw) != 0 :

    #resp_dw = s3client.list_objects(Bucket='main_bucket', Prefix='sub_folder/', Delimiter="/")
    #with open('dw_bucket.json','w') as f:
    #    resp_dws =str(resp_dw)
       # f.write(json.dumps(resp_dws))
    #forms_dw = [x['Prefix'] for x in resp_dw['CommonPrefixes']]
    #forms2_dw = [x['Key'] for x in resp_dw['Contents'][1:]]
    #forms2_dw[-1]
    total_files = len(forms2_dw)
    #i=0
    for i in range(total_files):
    #zip_filename='1819.zip'
        foldername = resp_dw['Contents'][1:][i]['LastModified'].strftime('%Y%m%d')#Put your logic here for folder name
        my_bcket   =  'main_bucket'

        my_file_old = resp_dw['Contents'][1:][i]['Key'] #file to be copied path
        zip_filename =my_file_old.split('/')[-1]
        subpath_nw='new_sub_folder/'+foldername+"/"+zip_filename #destination path
        my_file_new = subpath_nw
        #
        print str(reload_no)+ ':::  copying from====:'+my_file_old+' to :====='+s3_archive_subpath_nw
        #print my_bcket+'/'+my_file_old

        if zip_filename[-4:] == '.zip':
            s3.Object(my_bcket,my_file_new).copy_from(CopySource=my_bcket+'/'+my_file_old)
            s3.Object(my_bcket,my_file_old).delete()

            print str(i)+' files moved of '+str(total_files)

    resp_dw = s3client.list_objects(Bucket='main_bucket', Prefix='sub-folder/', Delimiter="/")

    forms2_dw = [x['Key'] for x in resp_dw['Contents'][1:]]
    reload_no +=1
</code>```

Body:
This is code I used to move files within sub-directories of a s3 bucket

# =============================================================================
# CODE TO MOVE FILES within subfolders in S3 BUCKET
# =============================================================================

from boto3.session import Session

ACCESS_KEY = 'a_key'
SECRET_KEY = 's_key'
session = Session(aws_access_key_id=ACCESS_KEY,
            aws_secret_access_key=SECRET_KEY)
s3 = session.resource('s3')#creating session of S3 as resource

s3client = session.client('s3')

resp_dw = s3client.list_objects(Bucket='main_bucket', Prefix='sub_folder/', Delimiter="/")

forms2_dw = [x['Key'] for x in resp_dw['Contents'][1:]]#here we got all files list (max limit is 1000 at a time)
reload_no = 0
while len(forms2_dw) != 0 :

    #resp_dw = s3client.list_objects(Bucket='main_bucket', Prefix='sub_folder/', Delimiter="/")
    #with open('dw_bucket.json','w') as f:
    #    resp_dws =str(resp_dw)
       # f.write(json.dumps(resp_dws))
    #forms_dw = [x['Prefix'] for x in resp_dw['CommonPrefixes']]
    #forms2_dw = [x['Key'] for x in resp_dw['Contents'][1:]]
    #forms2_dw[-1]
    total_files = len(forms2_dw)
    #i=0
    for i in range(total_files):
    #zip_filename='1819.zip'
        foldername = resp_dw['Contents'][1:][i]['LastModified'].strftime('%Y%m%d')#Put your logic here for folder name
        my_bcket   =  'main_bucket'

        my_file_old = resp_dw['Contents'][1:][i]['Key'] #file to be copied path
        zip_filename =my_file_old.split('/')[-1]
        subpath_nw='new_sub_folder/'+foldername+"/"+zip_filename #destination path
        my_file_new = subpath_nw
        #
        print str(reload_no)+ ':::  copying from====:'+my_file_old+' to :====='+s3_archive_subpath_nw
        #print my_bcket+'/'+my_file_old

        if zip_filename[-4:] == '.zip':
            s3.Object(my_bcket,my_file_new).copy_from(CopySource=my_bcket+'/'+my_file_old)
            s3.Object(my_bcket,my_file_old).delete()

            print str(i)+' files moved of '+str(total_files)

    resp_dw = s3client.list_objects(Bucket='main_bucket', Prefix='sub-folder/', Delimiter="/")

    forms2_dw = [x['Key'] for x in resp_dw['Contents'][1:]]
    reload_no +=1


问:
laravel .htaccess in root folder
I am following this article.

I am using laravel 5.6.

I moved .htaccess file from public to root and renamed server.php to index.php.

.htaccess :

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
</code>```

But css and js files are not loaded.

答:
since your app is now getting served from your app root instead of app/public, the app is looking css and js files in the root of your app.

You can easily fix this issue, by adding {{ asset('public') }} in front of your css and js files.

for example

```<code><link type="text/css" rel="stylesheet" href="{{ asset('public') }}/css/style.min.css"/>
<script src="{{ asset('public') }}/js/jquery.min.js"></script>
</code>```

Title: laravel .htaccess in root folder

Body:
I am following this article.

I am using laravel 5.6.

I moved .htaccess file from public to root and renamed server.php to index.php.

.htaccess :

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]

But css and js files are not loaded.

Body:
since your app is now getting served from your app root instead of app/public, the app is looking css and js files in the root of your app.

You can easily fix this issue, by adding {{ asset('public') }} in front of your css and js files.

for example

<link type="text/css" rel="stylesheet" href="{{ asset('public') }}/css/style.min.css"/>
<script src="{{ asset('public') }}/js/jquery.min.js"></script>


问:
What can I do if I have 2 equal average?
I have a list of students and some notes, and I have to find the average of each student's grades and show them the following way(if the average is greater than or equal to 6.0):

[student name, average] (in descending order of the average).

I did this, but the problem is that I have 2 equal averages and I can not correspond with the name of the student, he takes my first student with the average '6.0' in both cases.

My lists look like this:

```<code>info = [['Frank Morgan', '7.89', '3.19', '6.90', '9.90'], ['Jesse Lawrence', '6', '6', '6', '6'], ['Mark Porter', '9.00', '7.87', '9.12', '10.00'], ['Philip Sanchez', '6', '6', '6', '6']]

average= [6.970000000000001, 6.0, 8.9975, 6.0]
</code>```

I want to create the following:

```<code>result = [['Frank Morgan', 6.970000000000001], ['Jesse Lawrence', 6.0],['Mark Porter', 8.9975], ['Philip Sanchez', 6.0]]
</code>```

I tried in the following way:

```<code>result = []
for i in average:
    if i >= 6.0:
        result.append([info[average.index(i)][0], i])
print result
</code>```

But I got:

```<code>result = [['Frank Morgan', 6.970000000000001], ['Jesse Lawrence', 6.0],['Mark Porter', 8.9975], ['Jesse Lawrence', 6.0]]
</code>```

'Jesse Lawrence' instead of 'Philip Sanchez'

Please help me to find another solution for this matching problem.

答:
when you do info[average.index(i)] then average.index(i) will return the first occurrence of i in average.

you can use enumerate()

```<code>info = [['Frank Morgan', '7.89', '3.19', '6.90', '9.90'], ['Jesse Lawrence', '6', '6', '6', '6'], ['Mark Porter', '9.00', '7.87', '9.12', '10.00'], ['Philip Sanchez', '6', '6', '6', '6']]
average= [6.970000000000001, 6.0, 8.9975, 6.0]
for idx, value in enumerate(average):
    if value >= 6.0:
        result.append([info[idx])][0], value])
print result
</code>```

or even better - use zip()

```<code>info = [['Frank Morgan', '7.89', '3.19', '6.90', '9.90'], ['Jesse Lawrence', '6', '6', '6', '6'], ['Mark Porter', '9.00', '7.87', '9.12', '10.00'], ['Philip Sanchez', '6', '6', '6', '6']]
average= [6.970000000000001, 6.0, 8.9975, 6.0]
result = []
for student, value in zip(info, average):
    if value >= 6.0:
        result.append([student[0], value])

print result
</code>```

as a side note - start using python3

Body:
I have a list of students and some notes, and I have to find the average of each student's grades and show them the following way(if the average is greater than or equal to 6.0):

[student name, average] (in descending order of the average).

I did this, but the problem is that I have 2 equal averages and I can not correspond with the name of the student, he takes my first student with the average '6.0' in both cases.

My lists look like this:

info = [['Frank Morgan', '7.89', '3.19', '6.90', '9.90'], ['Jesse Lawrence', '6', '6', '6', '6'], ['Mark Porter', '9.00', '7.87', '9.12', '10.00'], ['Philip Sanchez', '6', '6', '6', '6']]

average= [6.970000000000001, 6.0, 8.9975, 6.0]

I want to create the following:

result = [['Frank Morgan', 6.970000000000001], ['Jesse Lawrence', 6.0],['Mark Porter', 8.9975], ['Philip Sanchez', 6.0]]

I tried in the following way:

result = []
for i in average:
    if i >= 6.0:
        result.append([info[average.index(i)][0], i])
print result

But I got:

result = [['Frank Morgan', 6.970000000000001], ['Jesse Lawrence', 6.0],['Mark Porter', 8.9975], ['Jesse Lawrence', 6.0]]

'Jesse Lawrence' instead of 'Philip Sanchez'

Please help me to find another solution for this matching problem.

Body:
when you do info[average.index(i)] then average.index(i) will return the first occurrence of i in average.

you can use enumerate()

info = [['Frank Morgan', '7.89', '3.19', '6.90', '9.90'], ['Jesse Lawrence', '6', '6', '6', '6'], ['Mark Porter', '9.00', '7.87', '9.12', '10.00'], ['Philip Sanchez', '6', '6', '6', '6']]
average= [6.970000000000001, 6.0, 8.9975, 6.0]
for idx, value in enumerate(average):
    if value >= 6.0:
        result.append([info[idx])][0], value])
print result

or even better - use zip()

info = [['Frank Morgan', '7.89', '3.19', '6.90', '9.90'], ['Jesse Lawrence', '6', '6', '6', '6'], ['Mark Porter', '9.00', '7.87', '9.12', '10.00'], ['Philip Sanchez', '6', '6', '6', '6']]
average= [6.970000000000001, 6.0, 8.9975, 6.0]
result = []
for student, value in zip(info, average):
    if value >= 6.0:
        result.append([student[0], value])

print result

as a side note - start using python3


问:
What does the '@' symbol do in JavaScript multiline comments?
Just really curious after I was poking around the Muuri source code and saw this everywhere:

```<code>var htmlCollectionType = '[object HTMLCollection]';
var nodeListType = '[object NodeList]';

/**
 * Check if a value is a node list
 *
 * @param {*} val
 * @returns {Boolean}
 */
export default function isNodeList(val) {
  var type = Object.prototype.toString.call(val);
  return type === htmlCollectionType || type === nodeListType;
}
</code>```

@param and @returns don't seem to actually do anything (I think), but they ARE highlighted differently. In fact, if you look at the code in git they're highlighted as though they're not comments.

Is this some JavaScript syntax I'm unaware of? What's going on here? I would love to know.

答:
This is just utilisting JSDoc comments. The syntax is influenced by Java which has JavaDoc comments as part of the standard. In short, the comment is documenting what a function or method does and it has slightly special syntax - it is a block comment that starts with /** instead of merely /* to differentiate it from a normal block comment and you can use some annotations to denote different meanings:

@param means this is a parameter.

The value inside {} denotes the type of the parameter - in this case * means "any", but you to document something like @param {string} or @param {number}

the val is the name of the parameter that the function uses.

you can optionally add a description for the parameter e.g., something like @param {*} val - used for foo and bar

the @return documents the return of the function.

the value inside {} is the type again. In this case, a boolean.

you can still optionally add a comment for the return value, for example: @returns {Boolean} true if correct, false if incorrect

There are more things you can document using JSDoc syntax, like @copyright to specify a license or @throws to declare what are the expected exceptions that some code can throw. Some syntax is specific for functions or methods, other for objects or even whole files.

All in all, it's an attempt to standardise the descriptions left in files. You don't need to do anything with the comment but you can also use tools that read the comments and act on them - some like Tern.js will read the comments and try to check if your code conforms, e.g., if you have

/**
 * @param {number} bar
 * @return {boolean}
 */
function foo(bar) {}
```

and you call foo("abc") then you might get a warning by the tool that you should be passing a number. Or if you do foo(123).replace("a", "b") you can get a warning that you're trying to use string methods on what should be a boolean.

Other tools might instead just crawl your JS files and generate documentation. Java does this with JavaDoc - you can generate the documentation for your methods and classes automatically basing it on the JavaDoc comments. You would get a documentation in the official Java style which means any documentation will be consistent.

Body:
Just really curious after I was poking around the Muuri source code and saw this everywhere:

var htmlCollectionType = '[object HTMLCollection]';
var nodeListType = '[object NodeList]';

/**
 * Check if a value is a node list
 *
 * @param {*} val
 * @returns {Boolean}
 */
export default function isNodeList(val) {
  var type = Object.prototype.toString.call(val);
  return type === htmlCollectionType || type === nodeListType;
}

@param and @returns don't seem to actually do anything (I think), but they ARE highlighted differently. In fact, if you look at the code in git they're highlighted as though they're not comments.

Is this some JavaScript syntax I'm unaware of? What's going on here? I would love to know.

Body:
This is just utilisting JSDoc comments. The syntax is influenced by Java which has JavaDoc comments as part of the standard. In short, the comment is documenting what a function or method does and it has slightly special syntax - it is a block comment that starts with /** instead of merely /* to differentiate it from a normal block comment and you can use some annotations to denote different meanings:

@param means this is a parameter.

The value inside {} denotes the type of the parameter - in this case * means "any", but you to document something like @param {string} or @param {number}

the val is the name of the parameter that the function uses.

you can optionally add a description for the parameter e.g., something like @param {*} val - used for foo and bar

the @return documents the return of the function.

the value inside {} is the type again. In this case, a boolean.

you can still optionally add a comment for the return value, for example: @returns {Boolean} true if correct, false if incorrect

There are more things you can document using JSDoc syntax, like @copyright to specify a license or @throws to declare what are the expected exceptions that some code can throw. Some syntax is specific for functions or methods, other for objects or even whole files.

All in all, it's an attempt to standardise the descriptions left in files. You don't need to do anything with the comment but you can also use tools that read the comments and act on them - some like Tern.js will read the comments and try to check if your code conforms, e.g., if you have

/**
 * @param {number} bar
 * @return {boolean}
 */
function foo(bar) {}

and you call foo("abc") then you might get a warning by the tool that you should be passing a number. Or if you do foo(123).replace("a", "b") you can get a warning that you're trying to use string methods on what should be a boolean.

Other tools might instead just crawl your JS files and generate documentation. Java does this with JavaDoc - you can generate the documentation for your methods and classes automatically basing it on the JavaDoc comments. You would get a documentation in the official Java style which means any documentation will be consistent.