问:
Who can delete a branch in VSTS?
I am the owner of the Visual Studio Team Services account. I created a repo, it has 2 branches. I have given access to everyone i.e. every member can access the repo.

Though my team member didn't create the branch, he wanted to delete it, but he couldn't and I could(I also didn't create the branch). When I checked we have the same level of access i.e. both project administrators.

What could be the reason behind this issue?

答: Check Force push (rewrite history, delete branches and tags) permission for repo under Settings > Version Control is set to Allow. Force push to a branch, which can rewrite history and this permission is also required to delete a branch.

Title: Who can delete a branch in VSTS?


来源: stackexchange

问:
JS add a variable with ++ doesn't work inside a callback function
I'm trying to build my stopwatch for an assignment.

At first, I built my lap function in this way

  handleClickLap: function(){
    $('#lap').click(function(event){
    if (Stopwatch.isRunning) {
      let lapCounter = 0;
      lapCounter = lapCounter + 1;
      console.log(lapCounter);
    })
```

<p>and it was working perfectly.</p>

<p>I read carefully the assignment then I had to rewrite my code like this</p>

<pre class="lang-js prettyprint-override"><code>lap: function(){
    if (Stopwatch.isRunning) {
    let lapCounter = 0;
    lapCounter ++;
     console.log(lapCounter);
    }
  }

  handleClickLap: function(){
$('#lap').click(function(event){
  Stopwatch.lap();

})
</code>```

I call all my function here

window.onload = function(){
  AppController.handleClickStart();
  AppController.handleClickStopReset();
  AppController.handleClickLap();
};
```

The problem is, lap: function() dosen't run lapCounter ++; in never updates the counter i also tried ++ lapcounter.

What am I doing wrong?

答:
Since you didnt provide info on AppController and Stopwatch, I slightly tweaked your code. Hope this helps.

$(document).ready(() => {
  function lap (){
    Stopwatch = {
        isRunning : true
       }
      if (Stopwatch.isRunning) {
      let lapCounter = 0;
      lapCounter ++;
       console.log(lapCounter);
      }
    }

     $('#lap').click(function(event){
       lap();
     })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lap">
lap
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to build my stopwatch for an assignment.

At first, I built my lap function in this way

  handleClickLap: function(){
    $('#lap').click(function(event){
    if (Stopwatch.isRunning) {
      let lapCounter = 0;
      lapCounter = lapCounter + 1;
      console.log(lapCounter);
    })

and it was working perfectly.

I read carefully the assignment then I had to rewrite my code like this

lap: function(){
    if (Stopwatch.isRunning) {
    let lapCounter = 0;
    lapCounter ++;
     console.log(lapCounter);
    }
  }

  handleClickLap: function(){
$('#lap').click(function(event){
  Stopwatch.lap();

})

I call all my function here

window.onload = function(){
  AppController.handleClickStart();
  AppController.handleClickStopReset();
  AppController.handleClickLap();
};

The problem is, lap: function() dosen't run lapCounter ++; in never updates the counter i also tried ++ lapcounter.

What am I doing wrong?

Body:
Since you didnt provide info on AppController and Stopwatch, I slightly tweaked your code. Hope this helps.

$(document).ready(() => {
  function lap (){
    Stopwatch = {
        isRunning : true
       }
      if (Stopwatch.isRunning) {
      let lapCounter = 0;
      lapCounter ++;
       console.log(lapCounter);
      }
    }

     $('#lap').click(function(event){
       lap();
     })
})

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


问:
Sessions are getting crossed. Ruby on Rails
I have an app that is using devise for authentication.  Rails 3 on ruby 1.9.2, with passenger on top of nginx.

Here is my problem: I have noticed that occaisionally my sessions are getting crossed.  While being logged in as one user, I sometimes become another user.  This is really a horrible problem.  I have managed to get it to stop by using active_record sessions storage.  But I am stumped as to where it could be happening.  It happens both when using cookie storage, and memcached storage.  I am not sure where to start debugging. I have gone through all of my code, and I am only reading from 'current_user' not writing. I don't have any code storing items in session.

Can anyone give me suggestions as to where, or how this could be happening?

Update:

I setup a div at the top of the page to dump the session contents on each request.  It is not just the user switching, it is the whole session. There are some dummy variables that I set in the session just to see what would happen.  When the sessions get crossed, (User A becomes User B) User A now sees the dummy variables that User B had.  And User B is logged out.

UPDATE 2

I found another question here on stack overflow that describes the same exact problem: In Rails, what could cause a user to have another user's session?

It looks like it could be a passenger issue?  But more important, how come it is even happening? This is a REAL big problem.  How do I put a stop to this?

UPDATE 3

I am now using Unicorn to serve my app. I set config.threadsafe! and started using active-record sessions exclusively.  No more memcached sessions.  The problem is gone.  At least I can stop pulling my hair out because the security hole is plugged.

I would still like to know what exactly was causing it. Most of the tutorials out there show how to setup passenger, with the default spawning method. Naturally, I would think memcached would perform best for session management over the other methods. Especially in a multiple application server environment.

Update 4

Okay, last and final update.  This was an issue with forked processes using the same memcached connection. I fixed it by using dalli memcached client, and reseting the connection in the after_fork callback of either unicorn or passenger.

答:
I'd be willing to bet you're using Passenger's (default) smart spawning, and falling victim to the Spawning Gotcha.

Set your PassengerSpawnMethod to 'conservative' and see if this goes away.  This easily accounts for the memcache case, unless you are protecting against it.  Presumably a similar problem in devise (or your code).

Do you see sessions cross across physical servers, or only on one server?


问:
How do I exit a While(true) loop with a key?
So I have this while loop that looks something like this.

```<code>bool isTrue = true;
while(isTrue)
{
  //Do work over and over
}
</code>```

I'm wondering.. Can I add if statement that checks if a key has been pressed during the current loop to break out of it? WITHOUT INTERRUPTING THE LOOP so some sort of async task maybe? Because it's automating the task over and over again. For the sake of the question let's say it's printing out "Hello World!" to the console every third second.

答:
It's not a great idea to use a while loop like this. The suggestion that you're writing something to the console every one third of a second suggests that you're using a Thread.Sleep to wait that time out.

It's far better to use a timer or some other library that let's you do this kind of thing. I'd suggest Microsoft's Reactive Framework. Then you can do this:

```<code>IDisposable subscription =
    Observable
        .Interval(TimeSpan.FromSeconds(1.0 / 3.0))
        .TakeWhile(_ => !Console.KeyAvailable)
        .Subscribe(_ =>
        {
            Console.WriteLine("Hello World!");
        });
</code>```

Job done. If you want to stop the subscription early just call subscription.Dispose().

NuGet "System.Reactive" to get the bits you need.

Body:
So I have this while loop that looks something like this.

bool isTrue = true;
while(isTrue)
{
  //Do work over and over
}

I'm wondering.. Can I add if statement that checks if a key has been pressed during the current loop to break out of it? WITHOUT INTERRUPTING THE LOOP so some sort of async task maybe? Because it's automating the task over and over again. For the sake of the question let's say it's printing out "Hello World!" to the console every third second.

Body:
It's not a great idea to use a while loop like this. The suggestion that you're writing something to the console every one third of a second suggests that you're using a Thread.Sleep to wait that time out.

It's far better to use a timer or some other library that let's you do this kind of thing. I'd suggest Microsoft's Reactive Framework. Then you can do this:

IDisposable subscription =
    Observable
        .Interval(TimeSpan.FromSeconds(1.0 / 3.0))
        .TakeWhile(_ => !Console.KeyAvailable)
        .Subscribe(_ =>
        {
            Console.WriteLine("Hello World!");
        });

Job done. If you want to stop the subscription early just call subscription.Dispose().

NuGet "System.Reactive" to get the bits you need.


问:
Python Regex multi group pattern findall() returning empty list
I am trying to use Regex multi group pattern to extract different CPU specs from a line, but getting an empty list.When i try individual groups separately, i am able to extract corresponding values. How should i use multi group pattern here? Please help!</p>

```<code>import re

line = "R7000 CPU at 160MHz, Implementation 39, Rev 2.1, 256KB L2, 512KB L3 Cache"

pat_cpu_values_combined = r"(?P<freq>\s+\w+Hz)(?P<L2>\s+\w+\s+L2)(?P<L3>\s+\w+\s+L3)"
pat_cpu_freq = r"(?P<freq>\s+\w+Hz)"
pat_cpu_l2 = r"(?P<L2>\s+\w+\s+L2)"
pat_cpu_l3 = r"(?P<L3>\s+\w+\s+L3)"

# empty list coming when pat_cpu_values_combined is searched

print re.findall(pat_cpu_values_combined, line)

# below individual group pattern findall are working fine

print re.findall(pat_cpu_freq, line)
print re.findall(pat_cpu_l2, line)
print re.findall(pat_cpu_l3, line)
</code>```

答:
When you combine them, you are not accounting for the characters in between the things you want to match. Try using this for your combined regex:</p>

```<code>(?P<freq>\s+\w+Hz).*?(?P<L2>\s+\w+\s+L2).*?(?P<L3>\s+\w+\s+L3)
</code>```

Body:
I am trying to use Regex multi group pattern to extract different CPU specs from a line, but getting an empty list.When i try individual groups separately, i am able to extract corresponding values. How should i use multi group pattern here? Please help!

import re

line = "R7000 CPU at 160MHz, Implementation 39, Rev 2.1, 256KB L2, 512KB L3 Cache"

pat_cpu_values_combined = r"(?P<freq>\s+\w+Hz)(?P<L2>\s+\w+\s+L2)(?P<L3>\s+\w+\s+L3)"
pat_cpu_freq = r"(?P<freq>\s+\w+Hz)"
pat_cpu_l2 = r"(?P<L2>\s+\w+\s+L2)"
pat_cpu_l3 = r"(?P<L3>\s+\w+\s+L3)"

# empty list coming when pat_cpu_values_combined is searched

print re.findall(pat_cpu_values_combined, line)

# below individual group pattern findall are working fine

print re.findall(pat_cpu_freq, line)
print re.findall(pat_cpu_l2, line)
print re.findall(pat_cpu_l3, line)

Body:
When you combine them, you are not accounting for the characters in between the things you want to match. Try using this for your combined regex:

(?P<freq>\s+\w+Hz).*?(?P<L2>\s+\w+\s+L2).*?(?P<L3>\s+\w+\s+L3)


问:
iOS " current graphics context" - What is that
When I draw lines and shapes etc I get the " current graphics context" in iOS.

What exactly though is " current graphics context" - I'm looking for the 30,000 foot description.

Right now I just copy and paste UI code, not exactly sure what it's doing.

答:
The OS needs a place to save information, such as drawing state, which you don't want to specify in every single CG drawing command, such as in which bitmap or view to draw, the scale or other transform to use, the last color you specified, etc.

The context tells each CG call where to find all this "stuff" for your current drawing call.  Give a different context to the exact same drawing call, and that call might draw to a different bitmap in a completely different view, with a different color, different scale, etc.

ContentLicense: CC BY-SA 2.5


问:
Binding an Image Source based on property change of another object
I have an object which have for which I can bind a property like this:

```<code><Label Text = "{Binding id}"/>
</code>```

The binding there is done correctly. Now I would like to bind an image based on the property of the label.
I tried to use the DataTrigger like this

```<code><Image >
  <Image.Style>
    <Style TargetType="{x:Type Image}">
      <Style.Triggers>
          <DataTrigger Binding="{Binding id}" Value="1">
            <Setter Property="Source"   Value="mypic.png"/>
          </DataTrigger>
        </Style.Triggers>
     </Style>
   </Image.Style>
 </Image>
</code>```

But I am having the following error: The given key was not present in the dictionary. Everything look OK. What is wrong in my code?

答:
You should add

```<code>TargetType="Image"
</code>```

to the DataTrigger tag. Your code should be like this:

```<code><Image >
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Style.Triggers>
                <DataTrigger TargetType="Image" Binding="{Binding id}" Value="1">
                    <Setter Property="Source"   Value="mypic.png"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>
</code>```

Body:
I have an object which have for which I can bind a property like this:

The binding there is done correctly. Now I would like to bind an image based on the property of the label.
I tried to use the DataTrigger like this

<Image >
  <Image.Style>

     </Style>
   </Image.Style>
 </Image>

But I am having the following error: The given key was not present in the dictionary. Everything look OK. What is wrong in my code?

Body:
You should add

TargetType="Image"

to the DataTrigger tag. Your code should be like this:

<Image >
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Style.Triggers>
                <DataTrigger TargetType="Image" Binding="{Binding id}" Value="1">
                    <Setter Property="Source"   Value="mypic.png"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>


答:
pat_cpu_values_combined expects strings matching your three individual patterns to occur with nothing in between them.

If you want to find all three in that order, use something like:

```<code>pat_cpu_values_combined = r"(?P<freq>\s+\w+Hz).*?(?P<L2>\s+\w+\s+L2).*?(?P<L3>\s+\w+\s+L3)"
</code>```

Title: Python Regex multi group pattern findall() returning empty list

Body:
pat_cpu_values_combined expects strings matching your three individual patterns to occur with nothing in between them.

If you want to find all three in that order, use something like:

pat_cpu_values_combined = r"(?P<freq>\s+\w+Hz).*?(?P<L2>\s+\w+\s+L2).*?(?P<L3>\s+\w+\s+L3)"


问:
Regex to Match Valid Variable Pattern
Suppose I have a string s.  I want to write a function using a regular expression which returns True if s has the following characteristics.

ignore the leading whitespace.

after step 1, s can start with any of the following a-z, A-Z, or _

After the 1st character s can have 0 or more of the following a-z, A-Z, 0-9,  and/or _

s can have 1 or more trailing whitespace characters.

I have tried the solution suggested below where am I going wrong?

```<code>import re
def test_s(s):
     return bool(re.search("[A-Za-z_\s]{1}[A-Za-z0-9_]*[\s]*$",s))
</code>```

Update:
I tried the solution below (It fails to capture my last 2 test cases):

CASE: return bool(re.search(r'\s*[A-Za-z_]\w*\s*', s))

```<code>TESTLIST = ['__This_Is_a_StringThatShouldWork' , '     SoIsThis1    ' , '4getaboutThis1', '7his_ShouldReturnFalse']]
for s in TESTLIST:
    print(is_var(s))
</code>```

[Out]

```<code>True
True
True (Should be False)
True (Should be False)
</code>```

答:
I think this should work.</p>

```<code>import re

def test_s(s):
    return bool(re.match("\s+[a-zA-Z_][a-zA-Z0-9_]*\s+", s))
</code>```

Title: Regex to Match Valid Variable Pattern

Body:
Suppose I have a string s.  I want to write a function using a regular expression which returns True if s has the following characteristics.

ignore the leading whitespace.

after step 1, s can start with any of the following a-z, A-Z, or _

After the 1st character s can have 0 or more of the following a-z, A-Z, 0-9,  and/or _

s can have 1 or more trailing whitespace characters.

I have tried the solution suggested below where am I going wrong?

import re
def test_s(s):
     return bool(re.search("[A-Za-z_\s]{1}[A-Za-z0-9_]*[\s]*$",s))

Update:
I tried the solution below (It fails to capture my last 2 test cases):

CASE: return bool(re.search(r'\s*[A-Za-z_]\w*\s*', s))

TESTLIST = ['__This_Is_a_StringThatShouldWork' , '     SoIsThis1    ' , '4getaboutThis1', '7his_ShouldReturnFalse']]
for s in TESTLIST:
    print(is_var(s))

[Out]

True
True
True (Should be False)
True (Should be False)

Body:
I think this should work.

import re

def test_s(s):
    return bool(re.match("\s+[a-zA-Z_][a-zA-Z0-9_]*\s+", s))


问:
MySQL Workbench not displaying query results
When I query a table in MySQL Workbench, no results are shown, the result section is just blank, no grid or anything. However if I export the data, it is all there. Everything worked fine until a couple days ago.

Query settings:

Max Length = 65536

Continue on SQL Script Error = true

"Safe Updates = true

Leave autocommit mode enabled = true

Progress status update interval = 500

Default algorithm for ALTER table = Default

Default lock for ALTER table = Default

Limit Rows = true

Limit Rows Count = 1000

Max Field Value Length to Display = 256

Treat BINARY/VARBINARY as nonbinary character string = false

Confirm Data Changes = True

No queries work, an example would be SELECT * FROM database.address

答:
It was really frustrating as it was still happening in the workbench version 6.3.10 (for mac) available in the mysql official site (here).
I got it resolved by first collapsing the bottom panel (check the top right in the attached image (termed as collapse button)) and then pulling up the empty region from the bottom.
Now if I again click on collapse button this time result grid is visible along with the action grid.


答:
Try this:</p>

```<code>import re
def test_s(s):
    return bool(re.search(r'\s*[A-Za-z_]\w*\s*', s))
</code>```

Title: Regex to Match Valid Variable Pattern

Body:
Try this:

import re
def test_s(s):
    return bool(re.search(r'\s*[A-Za-z_]\w*\s*', s))


问:
How do I edit field types with managed schemas in solr 6+
I am migrating from solr 4 to solr 6.
Solr is using my old schema.xml to create a new managed_schema.
Using the solr admin website ui, I can edit the managed schema.
However, the field_types are not editable. I can't figure out how to change the analyzers.

I can edit it in my schema.xml and then delete managed_schema, causing it to rebuild the managed_schema. But that is tedious.

I know I can change solrconfig to use the schema.xml instead of the managed-schema. But what I would prefer to do is to migrate to the managed schema. I just need to be able to change the analyzers.

So my question is: how do I make changes to the analyzers inside of a field_type using the managed-schema UI (or another method is ok too if it is easy)?

答: You can edit managed_schema and then reload the core. You just should not be editing managed_schema by hand as you are changing it via UI as that will override hand changes.


问:
Number of users to a webpage
I have a webpage that reads data from an Access file (Microsoft Access file) on my website. How many users can visit that page at the same time?

Would the page crash at some time if too many users tried to visit that page at the same time? Is it better to use a PHP file that reads data from a text file or its just the same?

答:
There are many variables that influence how many people can simultaneousness use your website (loosely known as scalability), including your database, hardware, network, caching and more.  And yes, at some point your performance will degrade if more and more users access the page.

It would be really hard to say from the information you provided how scalable your website is.  PHP could be faster but not necessarily.  Always be skeptical about technologies that promise superior performance.

For the moment your best option is to try and estimate how many concurrent users you are expecting and then use a load testing tool like JMeter, Apache Bench or others to assess if you're website will stand up to the load.

ContentLicense: CC BY-SA 4.0

Title: Number of users to a webpage


问:
c# 3D Bin Packing for shipping
I try to implement optimisation for shipping product from my e-commerce website.

I don't use plugin for e-commerce, only asp.net mvc 5.

I ask FeDex API for shipping rate for all items in cart. So if the user have 3 item in cart it will calculate it like 3 package. I need a way to calculate what dimension will be the package and split it in more package if it exceed a dimension.

i have find example in c++ and php(Here and Here) but i don't know these languages ...

if you can help me finding c# example or help me convert this php to c# so i can understand how they work ...

Tanks!

EDIT:

i have found exacly what i need but it's in c ...
i need to make a dll for it then use it on my app
https://github.com/wknechtel/3d-bin-pack

答:
I recently finished a C# port of the same 3D bin packing algorithm:

https://github.com/davidmchapman/3DContainerPacking

I based the code on these two GitHub projects:

3d-bin-pack by wknechtel (C)

3dbinpackingjs by Kerem Demirer (JavaScript)

I also referenced the PDF of the original master's thesis by Erhan Baltacıoğlu, as needed. The project includes a set of 700 reference tests verifying that the algorithm output matches the results shown in Appendix E of the thesis.

Title: c# 3D Bin Packing for shipping


问:
Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\multiusers\users\user_Validate.php on line 13
It seem like the error in the if else statement but I can't trace that error.

Can anyone please help me to solve this error.

```<code><?php
    session_start();
    include("dbconfig.php");
    $table ="";
    $rurl="";
    extract($_REQUEST);
    if($role =="staff"){
        $table="multiusers_staff";
        $rurl="staff/trainer.php";
    }
    else($role=="student"){
        $table="multiusers_student";
        $rurl="student/suexecute.php";
    }
    $mail  = $role."_email";
    $uname = $role."_username";
    $pass  = $role."_password";
    echo $check1="SELECT * FROM $table WHERE $mail ='$uemail' AND $pass ='$upwd' ";
    $login1 = $con->query($check1);
    $login_result1 = $login1->num_rows;
    $row1 = mysqli_fetch_array($login1);
    if(is_array($row1)) {
        $_SESSION['s_usersid']      = $row1[0];
        $_SESSION['s_userrole']     = $role;
        $_SESSION['s_usersemail']   = $row1[$mail];
        $_SESSION['s_usersname']    = $row1[$uname];
    }
    else{
        echo $con->error;
    }
    if(isset($_SESSION["s_usersemail"])) {
        echo "<script>window.location.assign('".$rurl."')</script>";
    }
?>
</code>```

答:
```<code>else($role=="student") change this to else if ($role=="student")
</code>```

else can not have a condition Php Doc

Body:
It seem like the error in the if else statement but I can't trace that error.

Can anyone please help me to solve this error.

<?php
    session_start();
    include("dbconfig.php");
    $table ="";
    $rurl="";
    extract($_REQUEST);
    if($role =="staff"){
        $table="multiusers_staff";
        $rurl="staff/trainer.php";
    }
    else($role=="student"){
        $table="multiusers_student";
        $rurl="student/suexecute.php";
    }
    $mail  = $role."_email";
    $uname = $role."_username";
    $pass  = $role."_password";
    echo $check1="SELECT * FROM $table WHERE $mail ='$uemail' AND $pass ='$upwd' ";
    $login1 = $con->query($check1);
    $login_result1 = $login1->num_rows;
    $row1 = mysqli_fetch_array($login1);
    if(is_array($row1)) {
        $_SESSION['s_usersid']      = $row1[0];
        $_SESSION['s_userrole']     = $role;
        $_SESSION['s_usersemail']   = $row1[$mail];
        $_SESSION['s_usersname']    = $row1[$uname];
    }
    else{
        echo $con->error;
    }
    if(isset($_SESSION["s_usersemail"])) {
        echo "";
    }
?>

Body:
else($role=="student") change this to else if ($role=="student")

else can not have a condition Php Doc


问:
Spell email address for forums
How can I make the code of the mail to spell it  and undetectable for forum when I try to put it in html

Thank's anticipated

Like this ! but more sophisticated

```<code><h>mariaburkke76</h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h>@<h><h><h><h><h>g<h><h><h><h><h><h><h><h><h><h><h>m<h><h><h>a<h><h>i<h><h><h><h><h><h><h><h><h><h><h><h><h><h><h>l<h><h><h><h>.<h>com<h><h><h><h><h><h><h><h><h>
</code>```

答:
You could use a combination of XOR (w/ random key) and base64/atob.

Though it wont stop a bot which is specifically designed to scrape your forum, see below.

```<code><?php
$email = '<a href="mailto:mariaburkke76@gmail.com">mariaburkke76@gmail.com</a>';

function xor_email($str) {
    $key = mt_rand(1, 192);
    for ($i = 0; $i < strlen($str); $i++) {
        $str[$i] = chr(ord($str[$i]) ^ $key);
    }
    return $key.'.'.base64_encode($str);
}
$enc = xor_email($email);
?>

<e data-enc='<?= $enc ?>'/>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<script>
var decode = function(key, hash) {
    var salt = parseInt(key);
    var result = '';
    for (var i=0; i<hash.length; i++) {
        result += String.fromCharCode(salt ^ hash.charCodeAt(i));
    }
    return result;
}
$(document).find('e').each(function(){
    var data = $(this).data('enc').split(".");
    $(this).replaceWith(decode(data[0], atob(data[1])));
});
</script>
</code>```

Would generate the following.

<e data-enc='102.WgdGDhQDAFtECwcPChIJXAsHFA8HBBMUDQ0DUVAmAQsHDwpIBQkLRFgLBxQPBwQTFA0NA1FQJgELBw8KSAUJC1pJB1g='/>

```
</div>
</div>
</p>

<hr>

<p>From a harvesters point of view, once determined the method of protection one could easily scrape out the email as followed. Just so you're under no illusions that security through obscurity will not protect you from a custom-made email bot/scraper/harvester.</p>

```<?php
$html = '<e data-enc=\'102.WgdGDhQDAFtECwcPChIJXAsHFA8HBBMUDQ0DUVAmAQsHDwpIBQkLRFgLBxQPBwQTFA0NA1FQJgELBw8KSAUJC1pJB1g=\'/>

';

function xor_email($str, $key) {
    for ($i = 0; $i < strlen($str); $i++) {
        $str[$i] = chr(ord($str[$i]) ^ $key);
    }
    return $str;
}

$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);

//
foreach ($doc->getElementsByTagName('e') as $e) {
    // parse out XORed string
    $enc = $e->getAttribute('data-enc');
    $enc = explode('.', $enc);
    $decoded = xor_email(base64_decode($enc[1]), $enc[0]);

    // parse out email
    $sub_doc = new DOMDocument();
    $sub_doc->loadHTML($decoded);
    foreach ($sub_doc->getElementsByTagName('a') as $a) {
        echo $a->nodeValue;
    }
}
```

https://3v4l.org/T0mlp

Title: Spell email address for forums

Body:
How can I make the code of the mail to spell it  and undetectable for forum when I try to put it in html

Thank's anticipated

Like this ! but more sophisticated

<h>mariaburkke76</h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h><h>@<h><h><h><h><h>g<h><h><h><h><h><h><h><h><h><h><h>m<h><h><h>a<h><h>i<h><h><h><h><h><h><h><h><h><h><h><h><h><h><h>l<h><h><h><h>.<h>com<h><h><h><h><h><h><h><h><h>

Body:
You could use a combination of XOR (w/ random key) and base64/atob.

Though it wont stop a bot which is specifically designed to scrape your forum, see below.

<?php
$email = '<a href="mailto:mariaburkke76@gmail.com">mariaburkke76@gmail.com</a>';

function xor_email($str) {
    $key = mt_rand(1, 192);
    for ($i = 0; $i < strlen($str); $i++) {
        $str[$i] = chr(ord($str[$i]) ^ $key);
    }
    return $key.'.'.base64_encode($str);
}
$enc = xor_email($email);
?>

<e data-enc='<?= $enc ?>'/>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<script>
var decode = function(key, hash) {
    var salt = parseInt(key);
    var result = '';
    for (var i=0; i<hash.length; i++) {
        result += String.fromCharCode(salt ^ hash.charCodeAt(i));
    }
    return result;
}
$(document).find('e').each(function(){
    var data = $(this).data('enc').split(".");
    $(this).replaceWith(decode(data[0], atob(data[1])));
});
</script>

Would generate the following.

<e data-enc='102.WgdGDhQDAFtECwcPChIJXAsHFA8HBBMUDQ0DUVAmAQsHDwpIBQkLRFgLBxQPBwQTFA0NA1FQJgELBw8KSAUJC1pJB1g='/>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<script>
var decode = function(key, hash) {
    var salt = parseInt(key);
    var result = '';
    for (var i=0; i<hash.length; i++) {
        result += String.fromCharCode(salt ^ hash.charCodeAt(i));
    }
    return result;
}
$(document).find('e').each(function(){
    var data = $(this).data('enc').split(".");
    $(this).replaceWith(decode(data[0], atob(data[1])));
});
</script>

From a harvesters point of view, once determined the method of protection one could easily scrape out the email as followed. Just so you're under no illusions that security through obscurity will not protect you from a custom-made email bot/scraper/harvester.

<?php
$html = '<e data-enc=\'102.WgdGDhQDAFtECwcPChIJXAsHFA8HBBMUDQ0DUVAmAQsHDwpIBQkLRFgLBxQPBwQTFA0NA1FQJgELBw8KSAUJC1pJB1g=\'/>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<script>
var decode = function(key, hash) {
    var salt = parseInt(key);
    var result = \'\';
    for (var i=0; i<hash.length; i++) {
        result += String.fromCharCode(salt ^ hash.charCodeAt(i));
    }
    return result;
}
$(document).find(\'e\').each(function(){
    var data = $(this).data(\'enc\').split("-");
    $(this).replaceWith(decode(data[0], atob(data[1])));
});
</script>';

function xor_email($str, $key) {
    for ($i = 0; $i < strlen($str); $i++) {
        $str[$i] = chr(ord($str[$i]) ^ $key);
    }
    return $str;
}

$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);

//
foreach ($doc->getElementsByTagName('e') as $e) {
    // parse out XORed string
    $enc = $e->getAttribute('data-enc');
    $enc = explode('.', $enc);
    $decoded = xor_email(base64_decode($enc[1]), $enc[0]);

    // parse out email
    $sub_doc = new DOMDocument();
    $sub_doc->loadHTML($decoded);
    foreach ($sub_doc->getElementsByTagName('a') as $a) {
        echo $a->nodeValue;
    }
}

https://3v4l.org/T0mlp


问:
HTML including an input from one file to another
If you name an input from the user in one html file using  and  tags, how do you use it in another html file?? I want to use only html. No javascript or anything.

The main file:

```<code><HTML>
<HEAD>
<TITLE>
Harry Potter
</TITLE>
</HEAD>
<BODY text = "red" bgcolor = "green">
<CENTER><H1><B><U>Harry Potter</U></B></H1></CENTER>
Please register for HPhmR by <A href = form.html>Clicking Here</A>
</BODY>
</HTML>
</code>```

Form.html:

```<code><HTML>
<HEAD>
<TITLE>
HPhmR Resgistering
</TITLE>
</HEAD>
<BODY bgcolor = "turquoise">
<FORM action = "harry potter.html" method = "post" name = "HPhmR">
<P>Please enter your username :
<INPUT type = "text" size = "30" name = "username" maxlength = "20">
</P>
<P>Please enter your password :
<INPUT type = "password" size = "30" name = "password" maxlength = "15">
</P>
<P>Please choose your favourite character:<BR>
<SELECT name = "favcha" size = "8" MULTIPLE>
<OPTION value = "Dumbledore">Albus Dumbledore</OPTION>
<OPTION value = "Voldemort">Lord Voldemort</OPTION>
<OPTION value = "Harry">Harry Potter</OPTION>
<OPTION value = "Ron">Ron Weasely</OPTION>
<OPTION value = "Hermione">Hermione Granger</OPTION>
<OPTION value = "Sirius">Sirius Black</OPTION>
<OPTION value = "Bellatrix">Bellatrix Lestrange</OPTION>
<OPTION value = "Draco">Draco Malfoy</OPTION>
</SELECT>
</P>
<P>Select your age range :
<INPUT type = "radio" name = "10-15" value = "1">10 to 15 yrs
<INPUT type = "radio" name = "15-20" value = "2">15 to 20 yrs
<INPUT type = "radio" name = "20-30" value = "3">20 to 30 yrs
<INPUT type = "radio" name = "30-45" value = "4">30 to 45 yrs
<INPUT type = "radio" name = "45-60" value = "5">45 to 60 yrs
<INPUT type = "radio" name = "60+" value = "6">Above 60 yrs
</P>
<INPUT type = "submit" value = "Submit and Register">
</FORM>
</BODY>
</HTML>
</code>```

How do I use the input from the user in form.html? I want to use that input and do something else in the main file.

答: You can not do that using just html.but you can use php or asp.net to send forms from one file to another.</p>

Body:
If you name an input from the user in one html file using  and  tags, how do you use it in another html file?? I want to use only html. No javascript or anything.

The main file:

<TITLE>
Harry Potter
</TITLE>

Harry Potter

Please register for HPhmR by Clicking Here

Form.html:

<TITLE>
HPhmR Resgistering
</TITLE>

<FORM action = "harry potter.html" method = "post" name = "HPhmR">

Please enter your username :
<INPUT type = "text" size = "30" name = "username" maxlength = "20">

Please enter your password :
<INPUT type = "password" size = "30" name = "password" maxlength = "15">

Please choose your favourite character:

<SELECT name = "favcha" size = "8" MULTIPLE>
<OPTION value = "Dumbledore">Albus Dumbledore</OPTION>
<OPTION value = "Voldemort">Lord Voldemort</OPTION>
<OPTION value = "Harry">Harry Potter</OPTION>
<OPTION value = "Ron">Ron Weasely</OPTION>
<OPTION value = "Hermione">Hermione Granger</OPTION>
<OPTION value = "Sirius">Sirius Black</OPTION>
<OPTION value = "Bellatrix">Bellatrix Lestrange</OPTION>
<OPTION value = "Draco">Draco Malfoy</OPTION>
</SELECT>

Select your age range :
<INPUT type = "radio" name = "10-15" value = "1">10 to 15 yrs
<INPUT type = "radio" name = "15-20" value = "2">15 to 20 yrs
<INPUT type = "radio" name = "20-30" value = "3">20 to 30 yrs
<INPUT type = "radio" name = "30-45" value = "4">30 to 45 yrs
<INPUT type = "radio" name = "45-60" value = "5">45 to 60 yrs
<INPUT type = "radio" name = "60+" value = "6">Above 60 yrs

<INPUT type = "submit" value = "Submit and Register">
</FORM>

How do I use the input from the user in form.html? I want to use that input and do something else in the main file.


问:
window.location.reload(true) reloads page but page needs refreshing to show changes
Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.

This is an example that adds the button and reloads page on click

```<code>if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '<li><a href="" onclick="window.location.reload(true);return toggleLive(this, ' . $post->ID . ');">' . $text . '</a></li>';
}
</code>```

So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.

Thanks in advance for your help

EDIT -
I have already tried
location.href = location.href; and
document.location.reload();

ADDITIONAL INFO -

Function

```<code>add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
    die( __('No post ID specified.') );
}

// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
    die( __('You attempted to edit an item that doesn’t exist. Perhaps it was deleted?') );
}

// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
    die( __('You are not allowed to edit this item.') );
}

// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));

// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );

$index = array_search($live, $terms);
if ($_REQUEST['value']) {
    if ($index === false) {
        $terms[] = $live;
    }
} else {
    if ($index !== false) {
        unset($terms[$index]);
    }
}

wp_set_object_terms( $post_id, 'live', 'campaign_action' );

die('1');
});
</code>```

JS

```<code>function toggleLive(caller, post_id)
{

var $ = jQuery;
var $caller = $(caller);

var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";

// Check there's no request in progress
if ($caller.text() == waitText) {
    return false;
}

// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);

// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);

// Ajax request
var data = {
    action: "toggle_live",
    post:   post_id,
    value:  value
};

jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
    if (response == "1") {

        // Success
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    } else {

        // Error
        alert("Error: " + response);

        // Reset the text
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    }

    // Reset the width
    $caller.width("auto");
});

// Prevent the link click happening
return false;
}
</code>```

IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR

答: Is toggleLive the function that makes the AJAX request? You are calling reload immediately on click before changes are reflected on the backend. If you are using Jquery include your reload code in the complete callback function that indicates completion of your AJAX request.</p>

Body:
Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.

This is an example that adds the button and reloads page on click

if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '
ID . ');">' . $text . '
';
}

So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.

Thanks in advance for your help

EDIT -
I have already tried
location.href = location.href; and
document.location.reload();

ADDITIONAL INFO -

Function

add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
    die( __('No post ID specified.') );
}

// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
    die( __('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?') );
}

// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
    die( __('You are not allowed to edit this item.') );
}

// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));

// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );

$index = array_search($live, $terms);
if ($_REQUEST['value']) {
    if ($index === false) {
        $terms[] = $live;
    }
} else {
    if ($index !== false) {
        unset($terms[$index]);
    }
}

wp_set_object_terms( $post_id, 'live', 'campaign_action' );

die('1');
});

JS

function toggleLive(caller, post_id)
{

var $ = jQuery;
var $caller = $(caller);

var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";

// Check there's no request in progress
if ($caller.text() == waitText) {
    return false;
}

// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);

// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);

// Ajax request
var data = {
    action: "toggle_live",
    post:   post_id,
    value:  value
};

jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
    if (response == "1") {

        // Success
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    } else {

        // Error
        alert("Error: " + response);

        // Reset the text
        if (value) {
            $caller.text(deactivateText);
        } else {
            $caller.text(liveText);
        }

    }

    // Reset the width
    $caller.width("auto");
});

// Prevent the link click happening
return false;
}

IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR


问:
Why doesn't app.component.html render?
I have the following Angular plnkr.co: https://plnkr.co/edit/xA8jU4QYDGxzohNg5NFj?p=preview.

//app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent { name = 'Angular'; }
</code>```

//app.component.html

```<code>testing...
<router-outlet></router-outlet>
</code>```

The oputput in the browser is:

```<code>Loading AppComponent content here ...
</code>```

Why doesn't it see the app.component.html file? Or is this some other issue?

答:
app.component.ts

import { Component } from '@angular/core';

@Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
})
export class AppComponent {
        title = 'app';
}
```
<p>app.component.html</p>
<pre class="lang-html prettyprint-override"><code><router-outlet></router-outlet>
</code>```

Please write the below code in the index.html

<!doctype html>

    <meta charset="utf-8">
    <title>Myapp</title>
    <base href="/">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">

    <app-root></app-root>

```

Title: Why doesn't app.component.html render?

Body:
I have the following Angular plnkr.co: https://plnkr.co/edit/xA8jU4QYDGxzohNg5NFj?p=preview.

//app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent { name = 'Angular'; }

//app.component.html

testing...
<router-outlet></router-outlet>

The oputput in the browser is:

Loading AppComponent content here ...

Why doesn't it see the app.component.html file? Or is this some other issue?

Body:
app.component.ts

import { Component } from '@angular/core';

@Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
})
export class AppComponent {
        title = 'app';
}

app.component.html

<router-outlet></router-outlet>

Please write the below code in the index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Myapp</title>
    <base href="/">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
  </head>
  <body>
    <app-root></app-root>
  </body>
</html>


问:
Wordcloud is cropping text
I am using twitter API to generate sentiments. I am trying to generate a word-cloud based on tweets.

Here is my code to generate a wordcloud

```<code>wordcloud(clean.tweets, random.order=F,max.words=80, col=rainbow(50), scale=c(3.5,1))
</code>```

Result for this:

I also tried this:

```<code>pal <- brewer.pal(8,"Dark2")

wordcloud(clean.tweets,min.freq = 125,max.words = Inf,random.order  = TRUE,colors = pal)
</code>```

Result for this:

Am I missing something?

This is how I am getting and cleaning tweets:

```<code>#downloading tweets
tweets <- searchTwitter("#hanshtag",n = 5000, lang = "en",resultType = "recent")
# removing re tweets
no_retweets <- strip_retweets(tweets , strip_manual = TRUE)

#converts to data frame
df <- do.call("rbind", lapply(no_retweets , as.data.frame))

#remove odd characters
df$text <- sapply(df$text,function(row) iconv(row, "latin1", "ASCII", sub="")) #remove emoticon
df$text = gsub("(f|ht)tp(s?)://(.*)[.][a-z]+", "", df$text) #remove URL
sample <- df$text

    # Cleaning Tweets
    sum_txt1 <- gsub("(RT|via)((?:\\b\\w*@\\w+)+)","",sample)
    sum_txt2 <- gsub("http[^[:blank:]]+","",sum_txt1)
    sum_tx3 <- gsub("@\\w+","",sum_txt2)
    sum_tx4 <- gsub("[[:punct:]]"," ", sum_tx3)
    sum_tex5 <- gsub("[^[:alnum:]]", " ", sum_tx4)
    sum_tx6 <- gsub("RT  ","", sum_tex5)

    # WordCloud

    # data frame is not good for text convert it corpus
    corpus <- Corpus(VectorSource(sum_tx6))
    clean.tweets<- tm_map(corpus , content_transformer(tolower)) #converting everything to lower cases
    clean.tweets<- tm_map(guj_clean,removeWords, stopwords("english")) #stopword are words like of, the, a, as..
    clean.tweets<- tm_map(guj_clean, removeNumbers)
    clean.tweets<- tm_map(guj_clean, stripWhitespace)
</code>```

Thanks in advance!

答:
Try changing the scale on your wordcloud from c(3.5,1) to c(3.5,0.25).</p>

```<code>wordcloud(clean.tweets, random.order=F,max.words=80, col=rainbow(50), scale=c(3.5,0.25))
</code>```

Title: Wordcloud is cropping text

Body:
I am using twitter API to generate sentiments. I am trying to generate a word-cloud based on tweets.

Here is my code to generate a wordcloud

wordcloud(clean.tweets, random.order=F,max.words=80, col=rainbow(50), scale=c(3.5,1))

Result for this:

I also tried this:

pal <- brewer.pal(8,"Dark2")

wordcloud(clean.tweets,min.freq = 125,max.words = Inf,random.order  = TRUE,colors = pal)

Result for this:

Am I missing something?

This is how I am getting and cleaning tweets:

#downloading tweets
tweets <- searchTwitter("#hanshtag",n = 5000, lang = "en",resultType = "recent")
# removing re tweets
no_retweets <- strip_retweets(tweets , strip_manual = TRUE)

#converts to data frame
df <- do.call("rbind", lapply(no_retweets , as.data.frame))

#remove odd characters
df$text <- sapply(df$text,function(row) iconv(row, "latin1", "ASCII", sub="")) #remove emoticon
df$text = gsub("(f|ht)tp(s?)://(.*)[.][a-z]+", "", df$text) #remove URL
sample <- df$text

    # Cleaning Tweets
    sum_txt1 <- gsub("(RT|via)((?:\\b\\w*@\\w+)+)","",sample)
    sum_txt2 <- gsub("http[^[:blank:]]+","",sum_txt1)
    sum_tx3 <- gsub("@\\w+","",sum_txt2)
    sum_tx4 <- gsub("[[:punct:]]"," ", sum_tx3)
    sum_tex5 <- gsub("[^[:alnum:]]", " ", sum_tx4)
    sum_tx6 <- gsub("RT  ","", sum_tex5)

    # WordCloud

    # data frame is not good for text convert it corpus
    corpus <- Corpus(VectorSource(sum_tx6))
    clean.tweets<- tm_map(corpus , content_transformer(tolower)) #converting everything to lower cases
    clean.tweets<- tm_map(guj_clean,removeWords, stopwords("english")) #stopword are words like of, the, a, as..
    clean.tweets<- tm_map(guj_clean, removeNumbers)
    clean.tweets<- tm_map(guj_clean, stripWhitespace)

Thanks in advance!

Body:
Try changing the scale on your wordcloud from c(3.5,1) to c(3.5,0.25).

wordcloud(clean.tweets, random.order=F,max.words=80, col=rainbow(50), scale=c(3.5,0.25))


问:
Unhelpful (maybe wrong?) gcc error message
I just spent a couple of hours debugging a compiler error that I could have fixed immediately if the compiler's error message had been more helpful.

I've reduced it to a simple example:

```<code>template <typename T>
int f(int);

template <typename U>
auto g(U x) -> decltype(f(x));

int main()
{
    g(0);
}
</code>```

The error is:

```<code>test.cpp: In function 'int main()':
test.cpp:9:8: error: no matching function for call to 'g(int)'
test.cpp:9:8: note: candidate is:
test.cpp:5:29: note: template<class U> decltype (f(x)) g(U)
</code>```

Is this error not at best misleading and at worst, outright wrong? The way I see it, the problem is not that the given definition of g is not a match for the call, but that the definition is malformed (since in the expression f(x) in the decltype, it tries to call f without specifying f's template parameter).

Wouldn't a much more reasonable error message be something like:

```<code>no matching function for call to 'f(int)' in 'decltype(f(x))'
in instantiation of 'g(U)' with U = int
</code>```

or even better:

```<code>failed to deduce template parameter 1 in call to 'f(int)' in 'decltype(f(x))'
in instantiation of 'g(U)' with U = int
</code>```

I would have expected something like that...

答:
With Clang I get this error

```<code>C:\Users\SUPER USER\Desktop>clang++ -cc1 -std=c++0x aa.cpp
aa.cpp:9:5: error: no matching function for call to 'g'
    g(0);
    ^
aa.cpp:5:6: note: candidate template ignored: substitution failure [with U = int
]
auto g(U x) -> decltype(f(x)){}
     ^
1 error generated.
</code>```

Much easier to understand than the error produced by g++

Body:
I just spent a couple of hours debugging a compiler error that I could have fixed immediately if the compiler's error message had been more helpful.

I've reduced it to a simple example:

template <typename T>
int f(int);

template <typename U>
auto g(U x) -> decltype(f(x));

int main()
{
    g(0);
}

The error is:

test.cpp: In function 'int main()':
test.cpp:9:8: error: no matching function for call to 'g(int)'
test.cpp:9:8: note: candidate is:
test.cpp:5:29: note: template<class U> decltype (f(x)) g(U)

Is this error not at best misleading and at worst, outright wrong? The way I see it, the problem is not that the given definition of g is not a match for the call, but that the definition is malformed (since in the expression f(x) in the decltype, it tries to call f without specifying f's template parameter).

Wouldn't a much more reasonable error message be something like:

no matching function for call to 'f(int)' in 'decltype(f(x))'
in instantiation of 'g(U)' with U = int

or even better:

failed to deduce template parameter 1 in call to 'f(int)' in 'decltype(f(x))'
in instantiation of 'g(U)' with U = int

I would have expected something like that...

Body:
With Clang I get this error

C:\Users\SUPER USER\Desktop>clang++ -cc1 -std=c++0x aa.cpp
aa.cpp:9:5: error: no matching function for call to 'g'
    g(0);
    ^
aa.cpp:5:6: note: candidate template ignored: substitution failure [with U = int
]
auto g(U x) -> decltype(f(x)){}
     ^
1 error generated.

Much easier to understand than the error produced by g++


答:
Try this regex:</p>

```<code>[a-zA-Z_]\w*\s+
</code>```

Title: Regex to Match Valid Variable Pattern

Body:
Try this regex:

[a-zA-Z_]\w*\s+


问:
How to rotate an image before uploading, rotation not working as a variable
This function works perfectly when defining the rotation degrees in text such as "-90" but when I try to us the degrees parameter as a $variable the image does not rotate.  Any ideas? thanks in advance.</p>

```<code> function compress_image($source_url, $destination_url, $quality) {

    $info = getimagesize($source_url);

        if ($info['mime'] == 'image/jpeg')
                $image = imagecreatefromjpeg($source_url);

        elseif ($info['mime'] == 'image/gif')
                $image = imagecreatefromgif($source_url);

    elseif ($info['mime'] == 'image/png')
                $image = imagecreatefrompng($source_url);

                $rotate = imagerotate($image,"-90",0); //Does Work
                $degrees = "-90"
                $rotate = imagerotate($image,$degrees,0); //Does Not Work
                $image = $rotate;

        imagejpeg($image, $destination_url, $quality);
    return $destination_url;
}
</code>```

答:
you can rotate as follow:

```<code>resource imagerotate ( resource $image , float $angle , int $bgd_color [, int $ignore_transparent = 0 ] )
</code>```

Rotates the image image using the given angle in degrees.

The center of rotation is the center of the image, and the rotated image may have different dimensions than the original image.

Parameters :-

image:

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

angle

Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image anticlockwise.

bgd_color

Specifies the color of the uncovered zone after the rotation

ignore_transparent

If set and non-zero, transparent colors are ignored (otherwise kept).

Example:

```<code><?php
 // File and rotation
 $filename = 'test.jpg';
 $degrees = 180;

 // Content type
 header('Content-type: image/jpeg');

 // Load
 $source = imagecreatefromjpeg($filename);

 // Rotate
 $rotate = imagerotate($source, $degrees, 0);

 // Output
 imagejpeg($rotate);

 // Free the memory
 imagedestroy($source);
 imagedestroy($rotate);
?>
</code>```

Body:
This function works perfectly when defining the rotation degrees in text such as "-90" but when I try to us the degrees parameter as a $variable the image does not rotate.  Any ideas? thanks in advance.

 function compress_image($source_url, $destination_url, $quality) {

    $info = getimagesize($source_url);

        if ($info['mime'] == 'image/jpeg')
                $image = imagecreatefromjpeg($source_url);

        elseif ($info['mime'] == 'image/gif')
                $image = imagecreatefromgif($source_url);

    elseif ($info['mime'] == 'image/png')
                $image = imagecreatefrompng($source_url);

                $rotate = imagerotate($image,"-90",0); //Does Work
                $degrees = "-90"
                $rotate = imagerotate($image,$degrees,0); //Does Not Work
                $image = $rotate;

        imagejpeg($image, $destination_url, $quality);
    return $destination_url;
}

Body:
you can rotate as follow:

resource imagerotate ( resource $image , float $angle , int $bgd_color [, int $ignore_transparent = 0 ] )

Rotates the image image using the given angle in degrees.

The center of rotation is the center of the image, and the rotated image may have different dimensions than the original image.

Parameters :-

image:

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

angle

Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image anticlockwise.

bgd_color

Specifies the color of the uncovered zone after the rotation

ignore_transparent

If set and non-zero, transparent colors are ignored (otherwise kept).

Example:

<?php
 // File and rotation
 $filename = 'test.jpg';
 $degrees = 180;

 // Content type
 header('Content-type: image/jpeg');

 // Load
 $source = imagecreatefromjpeg($filename);

 // Rotate
 $rotate = imagerotate($source, $degrees, 0);

 // Output
 imagejpeg($rotate);

 // Free the memory
 imagedestroy($source);
 imagedestroy($rotate);
?>


问:
Which is a better design: store single character or meaningful string in DB row?
Given I have a DB table as follows:

```<code><TableName>
  id: string
  sym: string
  type: string
</code>```

I can store the data into the DB table with two methods:

```<code>Method one:
0001, IBM, Stock
0002, IBM18Jan, Option

Method one:
0001, IBM, '1'
0002, IBM18Jan, '2'
</code>```

For method one, I don't need to make any conversion when I display the data.
However, I need to make a conversion from '1' to Stock and '2' to Option in method two. Basically, I have to maintenance a mapping somewhere in the query code.

Question> Which method is better? Obviously, by using method two, I can save lots of DB space but the conversion is required in later query statements.

答: It depends on frequency of usage/change and size of reference data. If reference data  is very large in terms of number of rows then though you will save time in conversion but you will lose time when you want to update any of the value or if you want to use this reference data in you other queries. Also reference table makes maintenance and updation of data easier.</p>

Body:
Given I have a DB table as follows:

<TableName>
  id: string
  sym: string
  type: string

I can store the data into the DB table with two methods:

Method one:
0001, IBM, Stock
0002, IBM18Jan, Option

Method one:
0001, IBM, '1'
0002, IBM18Jan, '2'

For method one, I don't need to make any conversion when I display the data.
However, I need to make a conversion from '1' to Stock and '2' to Option in method two. Basically, I have to maintenance a mapping somewhere in the query code.

Question> Which method is better? Obviously, by using method two, I can save lots of DB space but the conversion is required in later query statements.


问:
MVC 2 Twitter Application
This is my first time here so I apologize in advance if this question is not relevant here. I have just started to learn C# and MVC 2. Most of my learning so far has been from examples and I wanted to learn from an example which I can learn a lot from.

So my example is I want to create a C# web-app for twitter. Meaning the web application that has a text box and a submit button using MVC 2 and entity framework and When any content is submitted via the text box, the content is posted to a Twitter account. The content and twitter id are logged to a database and the form is shown again with the most recent content on the page.

Much obliged to anyone who can help/guide me on this and truly appreciate the help.

Derek

答:
Download and follow the tutorial:

http://mvcmusicstore.codeplex.com/Wikipage?ProjectName=mvcmusicstore

Pretty much everything you want to learn about MVC is shown there. Granted it's MVC3 but you might as well start learning with the newest version.

Title: MVC 2 Twitter Application

OwnerDisplayName: delete


问:
Recursively cycle every path of an array
I have the following(json) object:

```<code>$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);
</code>```

I'm trying to figure out how to recursively travel through it so I can see all the different paths that is in the array.

It could be 4 separate echo's or a 4 line string. The > could be replaced with anything or nothing at all. If each line was echo'd separately or pushed to an array that would probably give the most flexibility.

```<code>Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)
</code>```

I can't wrap my head around it so any help would be appreciated.

I'm thinking I can somehow cycle through each like:

```<code>foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}
</code>```

答:
I've boiled down my method to something VERY simple and easy to read.  See inline comments for explanations.  I have two versions: a 4-line echoing function and an array returning function.

*Note this method is very SPECIFICALLY built for this question because:

The input array will ALWAYS have a depth of at least two levels AND

Method #1 - echo strings from inside the function: (Demo)

```<code>$array=json_decode('{
    "Group1": {
        "Blue": {
            "Round": {
                "One": [
                    "Lawrence",
                    "Anant",
                    "B."
                ],
                "Two": [
                    "Erwin"
                ]
            }
        },
        "Green": [
           "Bryan",
           "Mick"
        ]
    },
    "Group2": [
        "Peter",
        "Kris"
    ]
}', true);

function recurse($array,$path=''){
    foreach($array as $k=>$v){
        if(!is_array(current($v))){  // check type of the first sub-element's value
            echo ($path?"$path > ":''),"$k > (".implode(', ',$v).")\n";  // don't recurse, just implode the indexed elements
        }else{                                                           // recurse because at least 2 levels below
            recurse($v,($path?"$path > $k":$k));                         // build path appropriately
        }
    }
}
recurse($array);
</code>```

Output:

```<code>Group1 > Blue > Round > One > (Lawrence, Anant, B.)
Group1 > Blue > Round > Two > (Erwin)
Group1 > Green > (Bryan, Mick)
Group2 > (Peter, Kris)
</code>```

Method #2 - return a 4-element array of paths: (Demo)

```<code>function recurse($array,$path='',&$result=[]){
    foreach($array as $k=>$v){
        if(!is_array(current($v))){  // check type of the first sub-element's value
            $result[]=($path?"$path > ":'')."$k > (".implode(', ',$v).')';  // don't recurse, just implode the indexed elements
        }else{  // recurse because at least 2 levels below
            recurse($v,($path?"$path > ":'').$k,$result);  // build path appropriately
        }
    }
    return $result;
}
var_export(recurse($array));
</code>```

Output:

```<code>array (
  0 => 'Group1 > Blue > Round > One > (Lawrence, Anant, B.)',
  1 => 'Group1 > Blue > Round > Two > (Erwin)',
  2 => 'Group1 > Green > (Bryan, Mick)',
  3 => 'Group2 > (Peter, Kris)',
)
</code>```

And one final update:

The best advice I can give would be to cut out this middle step and just convert your raw/initial json string to your new desired output (no recursion/stacking required):

Code: (Demo)

```<code>$seperateArray = json_decode('[
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "Lawrence" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "Anant" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "B." },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Two", "tier5": "Erwin" },
{ "tier1": "Group1", "tier2": "Green", "tier3": "Bryan" },
{ "tier1": "Group1", "tier2": "Green", "tier3": "Mick" },
{ "tier1": "Group2", "tier2": "Peter" },
{ "tier1": "Group2", "tier2": "Kris" }]',true);

foreach($seperateArray as $row){
    $last_val=current(array_splice($row,-1));  // extract last element, store as string
    $results[implode(' > ',$row)][]=$last_val;
}
foreach($results as $k=>$v){
    echo "$k > (",implode(', ',$v),")\n";
}
// same output as earlier methods
</code>```

Body:
I have the following(json) object:

$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);

I'm trying to figure out how to recursively travel through it so I can see all the different paths that is in the array.

It could be 4 separate echo's or a 4 line string. The > could be replaced with anything or nothing at all. If each line was echo'd separately or pushed to an array that would probably give the most flexibility.

Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)

I can't wrap my head around it so any help would be appreciated.

I'm thinking I can somehow cycle through each like:

foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}

Body:
I've boiled down my method to something VERY simple and easy to read.  See inline comments for explanations.  I have two versions: a 4-line echoing function and an array returning function.

*Note this method is very SPECIFICALLY built for this question because:

The input array will ALWAYS have a depth of at least two levels AND

Method #1 - echo strings from inside the function: (Demo)

$array=json_decode('{
    "Group1": {
        "Blue": {
            "Round": {
                "One": [
                    "Lawrence",
                    "Anant",
                    "B."
                ],
                "Two": [
                    "Erwin"
                ]
            }
        },
        "Green": [
           "Bryan",
           "Mick"
        ]
    },
    "Group2": [
        "Peter",
        "Kris"
    ]
}', true);

function recurse($array,$path=''){
    foreach($array as $k=>$v){
        if(!is_array(current($v))){  // check type of the first sub-element's value
            echo ($path?"$path > ":''),"$k > (".implode(', ',$v).")\n";  // don't recurse, just implode the indexed elements
        }else{                                                           // recurse because at least 2 levels below
            recurse($v,($path?"$path > $k":$k));                         // build path appropriately
        }
    }
}
recurse($array);

Output:

Group1 > Blue > Round > One > (Lawrence, Anant, B.)
Group1 > Blue > Round > Two > (Erwin)
Group1 > Green > (Bryan, Mick)
Group2 > (Peter, Kris)

Method #2 - return a 4-element array of paths: (Demo)

function recurse($array,$path='',&$result=[]){
    foreach($array as $k=>$v){
        if(!is_array(current($v))){  // check type of the first sub-element's value
            $result[]=($path?"$path > ":'')."$k > (".implode(', ',$v).')';  // don't recurse, just implode the indexed elements
        }else{  // recurse because at least 2 levels below
            recurse($v,($path?"$path > ":'').$k,$result);  // build path appropriately
        }
    }
    return $result;
}
var_export(recurse($array));

Output:

array (
  0 => 'Group1 > Blue > Round > One > (Lawrence, Anant, B.)',
  1 => 'Group1 > Blue > Round > Two > (Erwin)',
  2 => 'Group1 > Green > (Bryan, Mick)',
  3 => 'Group2 > (Peter, Kris)',
)

And one final update:

The best advice I can give would be to cut out this middle step and just convert your raw/initial json string to your new desired output (no recursion/stacking required):

Code: (Demo)

$seperateArray = json_decode('[
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "Lawrence" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "Anant" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "One", "tier5": "B." },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Two", "tier5": "Erwin" },
{ "tier1": "Group1", "tier2": "Green", "tier3": "Bryan" },
{ "tier1": "Group1", "tier2": "Green", "tier3": "Mick" },
{ "tier1": "Group2", "tier2": "Peter" },
{ "tier1": "Group2", "tier2": "Kris" }]',true);

foreach($seperateArray as $row){
    $last_val=current(array_splice($row,-1));  // extract last element, store as string
    $results[implode(' > ',$row)][]=$last_val;
}
foreach($results as $k=>$v){
    echo "$k > (",implode(', ',$v),")\n";
}
// same output as earlier methods


问:
Iterate geolocation over pandas dataframe
I have a dataframe that has two columns, Hospital name and Address, and I want to iterate through each address to find the latitude and longitude. My code seems to be taking the first row in the dataframe and I can't seem to select the address to find the coordinates.

```<code>import pandas
from geopy.geocoders import Nominatim

geolocator = Nominatim()
for index, item in df.iterrows():
    location = geolocator.geocode(item)
    df["Latitude"].append(location.latitude)
    df["Longitude"].append(location.longitude)
</code>```

Here is the code I used to scrape the website. Copy and run this and you'll have the data set.

```<code>import requests
from bs4 import BeautifulSoup
import pandas
import numpy as np

r=requests.get("https://www.privatehealth.co.uk/hospitals-and-
clinics/orthopaedic-surgery/?offset=300")
c=r.content
soup=BeautifulSoup(c,"html.parser")
all=soup.find_all(["div"],{"class":"col-9"})
names = []
for item in all:
    d={}
    d["Hospital Name"] = item.find(["h3"],{"class":"mb6"}).text.replace("\n","")
    d["Address"] = item.find(["p"],{"class":"mb6"}).text.replace("\n","")
    names.append(d)
df=pandas.DataFrame(names)
df = df[['Hospital Name','Address']]
df
</code>```

Currently the data looks like (one hospital example):

```<code>Hospital Name   |Address
Fulwood Hospital|Preston, PR2 9SZ
</code>```

The final output that I'm trying to achieve looks like.

```<code>Hospital Name   |Address         | Latitude | Longitude
Fulwood Hospital|Preston, PR2 9SZ|53.7589938|-2.7051618
</code>```

答:
Seems like there are a few issues here.   Using data from the URL you provided:

```<code>df.head()
                                Hospital Name                   Address
0                        Fortius Clinic City           London, EC4N 7BE
1  Pinehill Hospital - Ramsay Health Care UK           Hitchin, SG4 9QZ
2                  Spire Montefiore Hospital              Hove, BN3 1RD
3             Chelsea & Westminster Hospital           London, SW10 9NH
4   Nuffield Health Tunbridge Wells Hospital   Tunbridge Wells, TN2 4UL
</code>```

(1) If your data frame column names really are Hospital name and Address, then you need to use item.Address in the call to geocode().

Just using item will give you both Hospital name and Address.

```<code>for index, item in df.iterrows():
    print(f"index: {index}")
    print(f"item: {item}")
    print(f"item.Address only: {item.Address}")

# Output:
index: 0

item: Hospital Name    Fortius Clinic City
Address              London, EC4N 7BE
Name: 0, dtype: object

item.Address only: London, EC4N 7BE
...
</code>```

(2) You noted that your data frame only has two columns.  If that's true, you'll get a KeyError when you try to perform operations on df["Latitude"] and df["Longitude"], because they don't exist.

(3) Using apply() on the Address column might be clearer than iterrows().

Note that this is a stylistic point, and debatable.  (The first two points are actual errors.)

For example, using the provided URL:

```<code>from geopy.geocoders import Nominatim
geolocator = Nominatim()

tmp = df.head().copy()

latlon = tmp.Address.apply(lambda addr: geolocator.geocode(addr))

tmp["Latitude"] = [x.latitude for x in latlon]
tmp["Longitude"] = [x.longitude for x in latlon]
</code>```

Output:

```<code>                                Hospital Name                   Address  \
0                        Fortius Clinic City           London, EC4N 7BE
1  Pinehill Hospital - Ramsay Health Care UK           Hitchin, SG4 9QZ
2                  Spire Montefiore Hospital              Hove, BN3 1RD
3             Chelsea & Westminster Hospital           London, SW10 9NH
4   Nuffield Health Tunbridge Wells Hospital   Tunbridge Wells, TN2 4UL

    Latitude  Longitude
0  51.507322  -0.127647
1  51.946413  -0.279165
2  50.840871  -0.180561
3  51.507322  -0.127647
4  51.131528   0.278068
</code>```

Body:
I have a dataframe that has two columns, Hospital name and Address, and I want to iterate through each address to find the latitude and longitude. My code seems to be taking the first row in the dataframe and I can't seem to select the address to find the coordinates.

import pandas
from geopy.geocoders import Nominatim

geolocator = Nominatim()
for index, item in df.iterrows():
    location = geolocator.geocode(item)
    df["Latitude"].append(location.latitude)
    df["Longitude"].append(location.longitude)

Here is the code I used to scrape the website. Copy and run this and you'll have the data set.

import requests
from bs4 import BeautifulSoup
import pandas
import numpy as np

r=requests.get("https://www.privatehealth.co.uk/hospitals-and-
clinics/orthopaedic-surgery/?offset=300")
c=r.content
soup=BeautifulSoup(c,"html.parser")
all=soup.find_all(["div"],{"class":"col-9"})
names = []
for item in all:
    d={}
    d["Hospital Name"] = item.find(["h3"],{"class":"mb6"}).text.replace("\n","")
    d["Address"] = item.find(["p"],{"class":"mb6"}).text.replace("\n","")
    names.append(d)
df=pandas.DataFrame(names)
df = df[['Hospital Name','Address']]
df

Currently the data looks like (one hospital example):

Hospital Name   |Address
Fulwood Hospital|Preston, PR2 9SZ

The final output that I'm trying to achieve looks like.

Hospital Name   |Address         | Latitude | Longitude
Fulwood Hospital|Preston, PR2 9SZ|53.7589938|-2.7051618

Body:
Seems like there are a few issues here.   Using data from the URL you provided:

df.head()
                                Hospital Name                   Address
0                        Fortius Clinic City           London, EC4N 7BE
1  Pinehill Hospital - Ramsay Health Care UK           Hitchin, SG4 9QZ
2                  Spire Montefiore Hospital              Hove, BN3 1RD
3             Chelsea & Westminster Hospital           London, SW10 9NH
4   Nuffield Health Tunbridge Wells Hospital   Tunbridge Wells, TN2 4UL

(1) If your data frame column names really are Hospital name and Address, then you need to use item.Address in the call to geocode().

Just using item will give you both Hospital name and Address.

for index, item in df.iterrows():
    print(f"index: {index}")
    print(f"item: {item}")
    print(f"item.Address only: {item.Address}")

# Output:
index: 0

item: Hospital Name    Fortius Clinic City
Address              London, EC4N 7BE
Name: 0, dtype: object

item.Address only: London, EC4N 7BE
...

(2) You noted that your data frame only has two columns.  If that's true, you'll get a KeyError when you try to perform operations on df["Latitude"] and df["Longitude"], because they don't exist.

(3) Using apply() on the Address column might be clearer than iterrows().

Note that this is a stylistic point, and debatable.  (The first two points are actual errors.)

For example, using the provided URL:

from geopy.geocoders import Nominatim
geolocator = Nominatim()

tmp = df.head().copy()

latlon = tmp.Address.apply(lambda addr: geolocator.geocode(addr))

tmp["Latitude"] = [x.latitude for x in latlon]
tmp["Longitude"] = [x.longitude for x in latlon]

Output:

                                Hospital Name                   Address  \
0                        Fortius Clinic City           London, EC4N 7BE
1  Pinehill Hospital - Ramsay Health Care UK           Hitchin, SG4 9QZ
2                  Spire Montefiore Hospital              Hove, BN3 1RD
3             Chelsea & Westminster Hospital           London, SW10 9NH
4   Nuffield Health Tunbridge Wells Hospital   Tunbridge Wells, TN2 4UL

    Latitude  Longitude
0  51.507322  -0.127647
1  51.946413  -0.279165
2  50.840871  -0.180561
3  51.507322  -0.127647
4  51.131528   0.278068


问:
Iterating javascript object synchronously
I have an object like so:

```<code>let myObject = {
'db1': [db1_file1Id,db1_file2Id,db_1file3Id],
'db2': [db2_file1Id, db2_file2Id]
...
}
</code>```

I iterate through through this object and on each iteration: I connect to the database, retrieve the file, do some stuff and save the file back. Basically asynchronous stuff.

```<code>  for (let prop in myObject) {
    if (myObject.hasOwnProperty(prop)) {
      doStuff(prop, myObject[prop]);
    }
  }
</code>```

Now the doStuff function makes sure I have a local scope so there is no inconsistencies. But still, the execution is not synchronous due to the asynchronous operations inside each loop. I basically need one db to be completely processed before moving on to the next. How do I fix this?

One approach that I thought of was to have recursive loop. But as per my understanding, this would require me to change my data structure extensively which is sub-optimal imo.

```<code>let arr; //containing my data

process(x) {
 if (x < arr.length){
   //process(x+1) is called inside doStuff after asynchronous operations are complete
   doStuff(arr[x]);
 }
}
</code>```

答:
The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. you can try like .

$("#myPara").delay(4500).fadeOut().promise().done(function(){
     $("#myHeading").attr("style","display:none;")  ;
      for(var i=10;i<15;i++){
      console.log(i);
      }
});
console.log("Hello promise !");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="myPara"> Hello </p>
<h1 id="myHeading">to be hide</h1></code>```

```<code>  for (let prop in myObject) {
    if (myObject.hasOwnProperty(prop)) {
      var stuff= doStuff(prop, myObject[prop]).promise().done(function(){
      // Do whatever u want after completion of doStuff
     });
    }
   }
</code>```

Have a look at Mozila ref.

Body:
I have an object like so:

let myObject = {
'db1': [db1_file1Id,db1_file2Id,db_1file3Id],
'db2': [db2_file1Id, db2_file2Id]
...
}

I iterate through through this object and on each iteration: I connect to the database, retrieve the file, do some stuff and save the file back. Basically asynchronous stuff.

  for (let prop in myObject) {
    if (myObject.hasOwnProperty(prop)) {
      doStuff(prop, myObject[prop]);
    }
  }

Now the doStuff function makes sure I have a local scope so there is no inconsistencies. But still, the execution is not synchronous due to the asynchronous operations inside each loop. I basically need one db to be completely processed before moving on to the next. How do I fix this?

One approach that I thought of was to have recursive loop. But as per my understanding, this would require me to change my data structure extensively which is sub-optimal imo.

let arr; //containing my data

process(x) {
 if (x < arr.length){
   //process(x+1) is called inside doStuff after asynchronous operations are complete
   doStuff(arr[x]);
 }
}

Body:
The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. you can try like .

$("#myPara").delay(4500).fadeOut().promise().done(function(){
     $("#myHeading").attr("style","display:none;")  ;
      for(var i=10;i<15;i++){
      console.log(i);
      }
});
console.log("Hello promise !");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="myPara"> Hello </p>
<h1 id="myHeading">to be hide</h1>

  for (let prop in myObject) {
    if (myObject.hasOwnProperty(prop)) {
      var stuff= doStuff(prop, myObject[prop]).promise().done(function(){
      // Do whatever u want after completion of doStuff
     });
    }
   }

Have a look at Mozila ref.


问:
Checking if folder exists in directory
I want to know if the folder foo exists in my current directory, so I wrote a function to do so:

```<code>use std::env;
use std::fs;
use std::io;

fn does_folder_foo_exist_in_current_directory() -> Result<bool, io::Error> {
    let cur_path_buf = env::current_dir()?;
    let cur_dir = cur_path_buf.as_path();
    Ok(fs::read_dir(cur_dir)?.find(|ref x| {
        let x = x.unwrap();
        x.file_type().unwrap().is_dir() && x.file_name().to_str().unwrap() == "foo"
    }).is_some())
}
</code>```

However, the compiler says that I cannot move out of borrowed content here: let x = x.unwrap();.

Why is this moving out of borrowed content since I ref x?

答:
ref in patterns is used to construct a reference. If the pattern x would have type T, then the pattern ref x will have type &T instead. However, it's not valid to move out of a reference, so you definitely don't want to construct a reference! (unwrap takes self by value, which is why the code is trying to do a move in the first place.)

Here, the type of the parameter on the closure is a reference, because that's what Iterator::find wants to pass as an argument. If you want to deconstruct a reference, you want to use & instead. However, if you write the pattern &x here, you'll still get the error cannot move out of borrowed content, but this time directly on &x.

What can we do instead? DirEntry doesn't implement Clone, therefore we can't clone x (which is an &std::io::Result<DirEntry>). Instead, we could turn the &Result<DirEntry> into a Result<&DirEntry>. There's a method in the standard library to do just that: as_ref.

```<code>fn does_folder_foo_exist_in_current_directory() -> Result<bool, io::Error> {
    let cur_path_buf = env::current_dir()?;
    let cur_dir = cur_path_buf.as_path();
    Ok(fs::read_dir(cur_dir)?.find(|x| {
        let x = x.as_ref().unwrap();
        x.file_type().unwrap().is_dir() && x.file_name().to_str().unwrap() == "foo"
    }).is_some())
}
</code>```

By the way, instead of doing find(...).is_some(), you can use any(...), which is shorter and perhaps slightly more efficient. any also passes ownership of each iterated value to the closure, so we don't actually need to use as_ref with it!

```<code>fn does_folder_foo_exist_in_current_directory() -> Result<bool, io::Error> {
    let cur_path_buf = env::current_dir()?;
    let cur_dir = cur_path_buf.as_path();
    Ok(fs::read_dir(cur_dir)?.any(|x| {
        let x = x.unwrap();
        x.file_type().unwrap().is_dir() && x.file_name().to_str().unwrap() == "foo"
    }))
}
</code>```

Title: Checking if folder exists in directory

Body:
I want to know if the folder foo exists in my current directory, so I wrote a function to do so:

use std::env;
use std::fs;
use std::io;

fn does_folder_foo_exist_in_current_directory() -> Result<bool, io::Error> {
    let cur_path_buf = env::current_dir()?;
    let cur_dir = cur_path_buf.as_path();
    Ok(fs::read_dir(cur_dir)?.find(|ref x| {
        let x = x.unwrap();
        x.file_type().unwrap().is_dir() && x.file_name().to_str().unwrap() == "foo"
    }).is_some())
}

However, the compiler says that I cannot move out of borrowed content here: let x = x.unwrap();.

Why is this moving out of borrowed content since I ref x?

Body:
ref in patterns is used to construct a reference. If the pattern x would have type T, then the pattern ref x will have type &T instead. However, it's not valid to move out of a reference, so you definitely don't want to construct a reference! (unwrap takes self by value, which is why the code is trying to do a move in the first place.)

Here, the type of the parameter on the closure is a reference, because that's what Iterator::find wants to pass as an argument. If you want to deconstruct a reference, you want to use & instead. However, if you write the pattern &x here, you'll still get the error cannot move out of borrowed content, but this time directly on &x.

What can we do instead? DirEntry doesn't implement Clone, therefore we can't clone x (which is an &std::io::Result<DirEntry>). Instead, we could turn the &Result<DirEntry> into a Result<&DirEntry>. There's a method in the standard library to do just that: as_ref.

fn does_folder_foo_exist_in_current_directory() -> Result<bool, io::Error> {
    let cur_path_buf = env::current_dir()?;
    let cur_dir = cur_path_buf.as_path();
    Ok(fs::read_dir(cur_dir)?.find(|x| {
        let x = x.as_ref().unwrap();
        x.file_type().unwrap().is_dir() && x.file_name().to_str().unwrap() == "foo"
    }).is_some())
}

By the way, instead of doing find(...).is_some(), you can use any(...), which is shorter and perhaps slightly more efficient. any also passes ownership of each iterated value to the closure, so we don't actually need to use as_ref with it!

fn does_folder_foo_exist_in_current_directory() -> Result<bool, io::Error> {
    let cur_path_buf = env::current_dir()?;
    let cur_dir = cur_path_buf.as_path();
    Ok(fs::read_dir(cur_dir)?.any(|x| {
        let x = x.unwrap();
        x.file_type().unwrap().is_dir() && x.file_name().to_str().unwrap() == "foo"
    }))
}


问:
Video website with suggestion/recommendation feature
i have been assigned on making a simple video lecture website with a recommendation feature for students in  my place. I have little knowledge on html,css,java & php since i only learnt through YouTube. My main concerns are what should i do first or next and as for recommendation feature, they wanted to use a 'knowledge tree' concept.

E.g. when a student plays video topic V, then the recommended videos will be either video topic X and video topic Z. These recommended videos are based on lecturer's suggestion.

As for the recommendation feature part, the only idea came into my mind is using the (If Else) statement for each video but not sure in what language or where to put the algorithm. Lastly, is it a good practice to store video in mysql database?

答: You can use video names to show similar videos below active one or you can manualy give each video a code or name and show every video that has that code or name below active one.</p>


问:
Adding an Audio object to my react state array
```<code>componentWillMount() {

    console.log('Component WILL MOUNT!')

    axios.get('/channels').then( (res) => {
        console.log(res.data.data.playList);
        this.setState({
            categories: res.data.data.playList,
            audioList: res.data.data.playList.url
        })
    }).catch( (err) => {
        console.log(err);
    });

}
</code>```

In my componentWillMount() I get bunch of mp3 urls from a database and stores into a state called audioList so it has a bunch of URLs of a sound file. However, what I actually want to store is an Audio object (HTML5 Audio).

Usually, to make it playable, I would have to make a new Audio object like

```<code>this.audio = new Audio([URL]);
</code>```

then do

```<code>this.audio.play()
</code>```

Since I want to make a list of music, I would like to but everything like

```<code>this.state.audioList = [ audioObject1, audioObject2, audioObject3, ... ]
</code>```

How can I do this?

EDIT

```<code>componentWillMount() {

    console.log('Component WILL MOUNT!')

    let playLists = [];

    axios.get('/channels').then( (res) => {
        //console.log(res.data.data.playList);
        res.data.data.playList.map((value, key) => playLists.push(new Audio(value.url)));
        this.setState((prevState) => {
            return { audioList: playLists}
        }, () => console.log("dddd" + this.state.audioList));

    }).catch( (err) => {
        console.log(err);
    });

}
</code>```

This gives me

EDIT2

```<code>componentWillMount() {

    console.log('Component WILL MOUNT!')

let playLists = [];

axios.get('/channels').then( (res) => {
    //console.log(res.data.data.playList);
    res.data.data.playList.map((value, key) => playLists.push(new Audio(value.url)));
    this.setState((prevState) => {
        return { audioList: playLists, categories: res.data.data.playList}
    });
}).catch( (err) => {
    console.log(err);
});

}
</code>```

答:
You can try with array push like below for objects available inside array,

```<code>let playlists = [];
res.data.data.playList.map((value, key) => playlists.push(new Audio(value.url)));
this.setState((prevState) => {
    return { audioList: playlists}
}, () => console.log(this.state.audioList));
</code>```

Body:
componentWillMount() {

    console.log('Component WILL MOUNT!')

    axios.get('/channels').then( (res) => {
        console.log(res.data.data.playList);
        this.setState({
            categories: res.data.data.playList,
            audioList: res.data.data.playList.url
        })
    }).catch( (err) => {
        console.log(err);
    });

}

In my componentWillMount() I get bunch of mp3 urls from a database and stores into a state called audioList so it has a bunch of URLs of a sound file. However, what I actually want to store is an Audio object (HTML5 Audio).

Usually, to make it playable, I would have to make a new Audio object like

this.audio = new Audio([URL]);

then do

this.audio.play()

Since I want to make a list of music, I would like to but everything like

this.state.audioList = [ audioObject1, audioObject2, audioObject3, ... ]

How can I do this?

EDIT

componentWillMount() {

    console.log('Component WILL MOUNT!')

    let playLists = [];

    axios.get('/channels').then( (res) => {
        //console.log(res.data.data.playList);
        res.data.data.playList.map((value, key) => playLists.push(new Audio(value.url)));
        this.setState((prevState) => {
            return { audioList: playLists}
        }, () => console.log("dddd" + this.state.audioList));

    }).catch( (err) => {
        console.log(err);
    });

}

This gives me

EDIT2

componentWillMount() {

    console.log('Component WILL MOUNT!')

let playLists = [];

axios.get('/channels').then( (res) => {
    //console.log(res.data.data.playList);
    res.data.data.playList.map((value, key) => playLists.push(new Audio(value.url)));
    this.setState((prevState) => {
        return { audioList: playLists, categories: res.data.data.playList}
    });
}).catch( (err) => {
    console.log(err);
});

}

Body:
You can try with array push like below for objects available inside array,

let playlists = [];
res.data.data.playList.map((value, key) => playlists.push(new Audio(value.url)));
this.setState((prevState) => {
    return { audioList: playlists}
}, () => console.log(this.state.audioList));


问:
Obtaining an average from if statement Python 3
Ok so I got everything figured out. But now I am trying to use an if statement to tell the loop to take the average mpg (from the .txt file) from vehicles that get less than 22 mpg and then just average that up and output it IDLE. I feel like I should run the if statement before the loop. I am just not sure what I really need to change. I figure I should be able to slice variable holding the text file data. anyways here is my code. Can someone help me understand what I am not doing right?

```<code>def cityGasGuzzler():
# Input:that assigns a text file to a value and provides other definition
 values
cityGuzz = open("carModelData_city.","r")
# Process: For loop to get average of gas guzzling city street driving
  vehicles
for line in cityGuzz:
# Process: Uses if statement to get the average of lower mpg or gas guzzlers
    if cityGuzz[0:-1] < 22:
        sum = sum + eval(line)
        count = count + 1
        avrg = sum / count
# Output: using the round function to get average to the 2nd decimal place
#         and prints string and rounded variable to IDLE.
print("The average city MPG is,", round(avrg, 2))

cityGasGuzzler()
</code>```

Just to clarify, my main objective is as follows, take the numeric values from the text file that are less than 22, average those up and output the average to IDLE.

答:
If I understand the question correctly, your issue is with this line:

```<code>if cityGuzz[0:-1] < 22:
</code>```

That's not working for several reasons, not least because cityGuzz is the file object, not the current line. You need to convert the current line into a number before comparing it with a number like 22.

Try something like this:

```<code>total = 0 # renamed to avoid masking the builtin sum function
count = 0

for line in cityGuzz:
    mpg = float(line)
    if mpg < 22:
        total += mpg
        count += 1

average = total / count
</code>```

I renamed sum to total because sum is the name of a builtin function. In fact, it might be a useful one to replace the explicit loop to add up the values from the file. Here's an alternative implementation of the average calculation:

```<code>guzzlers = [mpg for mpg in map(float, cityGuzz) if mpg < 22]
average = sum(guzzlers) / len(guzzlers)
</code>```

Body:
Ok so I got everything figured out. But now I am trying to use an if statement to tell the loop to take the average mpg (from the .txt file) from vehicles that get less than 22 mpg and then just average that up and output it IDLE. I feel like I should run the if statement before the loop. I am just not sure what I really need to change. I figure I should be able to slice variable holding the text file data. anyways here is my code. Can someone help me understand what I am not doing right?

def cityGasGuzzler():
# Input:that assigns a text file to a value and provides other definition
 values
cityGuzz = open("carModelData_city.","r")
# Process: For loop to get average of gas guzzling city street driving
  vehicles
for line in cityGuzz:
# Process: Uses if statement to get the average of lower mpg or gas guzzlers
    if cityGuzz[0:-1] < 22:
        sum = sum + eval(line)
        count = count + 1
        avrg = sum / count
# Output: using the round function to get average to the 2nd decimal place
#         and prints string and rounded variable to IDLE.
print("The average city MPG is,", round(avrg, 2))

cityGasGuzzler()

Just to clarify, my main objective is as follows, take the numeric values from the text file that are less than 22, average those up and output the average to IDLE.

Body:
If I understand the question correctly, your issue is with this line:

if cityGuzz[0:-1] < 22:

That's not working for several reasons, not least because cityGuzz is the file object, not the current line. You need to convert the current line into a number before comparing it with a number like 22.

Try something like this:

total = 0 # renamed to avoid masking the builtin sum function
count = 0

for line in cityGuzz:
    mpg = float(line)
    if mpg < 22:
        total += mpg
        count += 1

average = total / count

I renamed sum to total because sum is the name of a builtin function. In fact, it might be a useful one to replace the explicit loop to add up the values from the file. Here's an alternative implementation of the average calculation:

guzzlers = [mpg for mpg in map(float, cityGuzz) if mpg < 22]
average = sum(guzzlers) / len(guzzlers)


问:
Google Datastore bulk retrieve data using urlsafe
Is there a way in Google DataStore to bulk fetch entities using their urlsafe key values?

I know about ndb.get_multi([list]) which takes a list of keys and retrieves the entities in bulk which is more efficient. But in our case we have a webpage with a few hundred entities, embedded with the entities urlsafe key values. At first we were only doing operations on single entities, so we were able to use the urlsafe value to retrieve the entity and do the operation without much trouble. Now, we need to change multiple entities at once, and looping on them one by one does not sound like an efficient approach. Any thoughts?

Is there any advantage of using the entities key ID directly (versus the key urlsafe value)? get_by_id() in the documentation does not imply being able to get entities in bulk (takes only one ID).

If the only way to retrieve entities in bulk is using the entities key, yet, exposing the key on the webpage is not a recommended approach, does that mean we're stuck when it comes to bulk operations on a page with a few hundred entities?

答:
The keys and the urlsafe strings are exactly in a 1:1 relationship. When you have one you can obtain the other:

```<code>urlsafe_string = entity_key.urlsafe()
entity_key = ndb.Key(urlsafe=urlsafe_string)
</code>```

So if you have a bunch of urlsafe strings you can obtain the corresponding keys and then use ndb.get_multi() with those keys to get all entities, modify them as needed then use ndb.put_multi() to save them back into the datastore.

As for using IDs - that only works (in a convenient manner) if you do not use entity ancestry. Otherwise to obtain a key you need both the ID and the entity's parent key (or its entire ancestry) - it's not convenient, better use urlsafe strings in this case.

But for entities with no parents (aka root entities in the respective entity groups) the entity keys and their IDs are always in a 1:1 relationship and again you can obtain one if you have the other:

```<code>entity_key_id = entity_key.id()
entity_key = ndb.Key(MyModel, entity_key_id)
</code>```

So again from a bunch of IDs you can obtain keys to use with ndb.get_multi() and/or ndb.put_multi().

Using IDs can have a cosmetic advantage over the urlsafe strings - typically shorter and easier on the eyes when they apear in URLs or in the page HTML code :)

Another advantage of using IDs is the ability to split large entities or to deal in a simpler manner with entities in a 1:1 relationship. See re-using an entity's ID for other entities of different kinds - sane idea?

For more info on keys and IDs see  Creating and Using Entity Keys.

Body:
The keys and the urlsafe strings are exactly in a 1:1 relationship. When you have one you can obtain the other:

urlsafe_string = entity_key.urlsafe()
entity_key = ndb.Key(urlsafe=urlsafe_string)

So if you have a bunch of urlsafe strings you can obtain the corresponding keys and then use ndb.get_multi() with those keys to get all entities, modify them as needed then use ndb.put_multi() to save them back into the datastore.

As for using IDs - that only works (in a convenient manner) if you do not use entity ancestry. Otherwise to obtain a key you need both the ID and the entity's parent key (or its entire ancestry) - it's not convenient, better use urlsafe strings in this case.

But for entities with no parents (aka root entities in the respective entity groups) the entity keys and their IDs are always in a 1:1 relationship and again you can obtain one if you have the other:

entity_key_id = entity_key.id()
entity_key = ndb.Key(MyModel, entity_key_id)

So again from a bunch of IDs you can obtain keys to use with ndb.get_multi() and/or ndb.put_multi().

Using IDs can have a cosmetic advantage over the urlsafe strings - typically shorter and easier on the eyes when they apear in URLs or in the page HTML code :)

Another advantage of using IDs is the ability to split large entities or to deal in a simpler manner with entities in a 1:1 relationship. See re-using an entity's ID for other entities of different kinds - sane idea?

For more info on keys and IDs see  Creating and Using Entity Keys.