问:
Is it a bad idea to start a thread in init method?
I have a class which acts like a Queue in which I am creating a worker thread. This worker thread would be responsible for processing each item from the queue.

Since an instance of this class should always have a worker thread, I am creating and starting the worker thread in the init method itself.

I would like to know if it is a bad practice to do so.

e.g

```<code>class CustomQueue:

    def __init__(self):
        # some initialization
        self.worker = threading.Thread(target=sometarget)
        self.worker.start()
</code>```

答:
I don't know if I would go so far as to call it bad practice, but my
first instinct is to avoid all side-effects in constructors:
don't talk to DBs, don't interact with the file system, don't make
web requests, and, no, don't spin up processes or threads. Whenever possible,
object instantiation should be a cheap, lightweight operation.

This general rule is particularly useful when it comes to testing
and debugging. For example, imagine this scenario:

```<code>class CustomQueue:

    def __init__(self):
        # Side effects here...

    def fubb(self, x, y):
        ...
</code>```

If you want to unit test fubb(), or perhaps interact with it in the Python
REPL, it's fairly annoying to have to think about all those side-effects.

There are exceptions to most rules, and if it really makes sense for
this class to take immediate action, one workaround is to add an
optional parameter to support your testing/debugging use cases. For example:

```<code>class CustomQueue:

    def __init__(self, lightweight = False):
        if not lightweight:
            # Side effects here...
</code>```

Body:
I have a class which acts like a Queue in which I am creating a worker thread. This worker thread would be responsible for processing each item from the queue.

Since an instance of this class should always have a worker thread, I am creating and starting the worker thread in the init method itself.

I would like to know if it is a bad practice to do so.

e.g

class CustomQueue:

    def __init__(self):
        # some initialization
        self.worker = threading.Thread(target=sometarget)
        self.worker.start()

Body:
I don't know if I would go so far as to call it bad practice, but my
first instinct is to avoid all side-effects in constructors:
don't talk to DBs, don't interact with the file system, don't make
web requests, and, no, don't spin up processes or threads. Whenever possible,
object instantiation should be a cheap, lightweight operation.

This general rule is particularly useful when it comes to testing
and debugging. For example, imagine this scenario:

class CustomQueue:

    def __init__(self):
        # Side effects here...

    def fubb(self, x, y):
        ...

If you want to unit test fubb(), or perhaps interact with it in the Python
REPL, it's fairly annoying to have to think about all those side-effects.

There are exceptions to most rules, and if it really makes sense for
this class to take immediate action, one workaround is to add an
optional parameter to support your testing/debugging use cases. For example:

class CustomQueue:

    def __init__(self, lightweight = False):
        if not lightweight:
            # Side effects here...


来源: stackexchange

问:
How to stop a pseudo element from changing the width of other elements?
I'm trying to put a pseudo element as a background image that simply crops at the document's width. However, when I put a background image in it keeps expanding the width of the document, making some other divs really wide.

Specifically, you can see from the screenshot that the nav is extending its width to accommodate the pseudo element's background image.

My attempt:

I've seen it done, but am not what the difference is, as the code in the actual pseudo element is the same. An example:

HTML:

```<code>    <nav class="navbar navbar-default navbar-fixed-top navbar-custom">
        <div class="container nav-down">
            <div class="navbar-header page-scroll">
                <a class="navbar-brand" href="/"><img src="/static/ScoopsLogo.png" alt="${out.global.siteName} Logo"></a>
                <p class="navbar-blog"><a href="https://blog.scoops.io/">Blog</a></p>
            </div>
        </div>
        <div id="scroll-progress">
            <div id="scroll-progress-bar"></div>
        </div>
    </nav>
    <section id="home">
        <div class="home-1">
          <div class="home1-1">
            <h1>Sound smart at the dinner table</h1>
            <h5>Learning made easy & fun</h5>
          </div>
        </div>
        <div class="home-lessons fade-in-up-static delay-2">
            <!-- List of Lessons -->
            <h5 class="text-center">NEW SCOOPS</h5>
            <div class="lessons-list">
            </div>
        </div>
     </section>
</code>```

CSS:

```<code>.navbar {
    min-height: 50px;
    margin-bottom: 20px;
}
.navbar-default {
    background-color: #f8f8f8;
    border-color: #e7e7e7;
}
.navbar-fixed-top {
    top: 0;
    border-width: 0 0 1px;
}
.container {
    max-width: 600px;
}
.navbar-custom {
    .navbar-header {
      width: inherit;
      max-width: inherit;
    }
    .navbar-brand {
        img {
          width: auto;
          height: 100%;
        }
    }
    .navbar-blog {
      float: right;
      padding: 10px;
      margin: 3px 10px 0 0;
    }
}
.home-lessons {
    width: 100%;
    padding: 3%;
    @media (min-width: $screen-md-min) {
      margin-bottom: 20px;
      padding: 20px 40px;
    }
    h5 {
      margin-top: -100px;
    }
    &::before {
      content: '';
      background-image: url(/static/Scoops-Icons.png);
      background-size: cover;
      width: 500px;
      height: 500px;
      display: block;
      position: absolute;
      margin-left: 200px;
      margin-top: -200px;
    }
  }
</code>```

答:
Parent element should use a position: relative whilst the child element uses top: 0 and left: 0.

Like this:

```<code>.parent {
    position: relative;
}
.child {
    top: 0;
    left: 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to put a pseudo element as a background image that simply crops at the document's width. However, when I put a background image in it keeps expanding the width of the document, making some other divs really wide.

Specifically, you can see from the screenshot that the nav is extending its width to accommodate the pseudo element's background image.

My attempt:

I've seen it done, but am not what the difference is, as the code in the actual pseudo element is the same. An example:

HTML:

Blog

Sound smart at the dinner table

Learning made easy & fun

NEW SCOOPS

CSS:

.navbar {
    min-height: 50px;
    margin-bottom: 20px;
}
.navbar-default {
    background-color: #f8f8f8;
    border-color: #e7e7e7;
}
.navbar-fixed-top {
    top: 0;
    border-width: 0 0 1px;
}
.container {
    max-width: 600px;
}
.navbar-custom {
    .navbar-header {
      width: inherit;
      max-width: inherit;
    }
    .navbar-brand {
        img {
          width: auto;
          height: 100%;
        }
    }
    .navbar-blog {
      float: right;
      padding: 10px;
      margin: 3px 10px 0 0;
    }
}
.home-lessons {
    width: 100%;
    padding: 3%;
    @media (min-width: $screen-md-min) {
      margin-bottom: 20px;
      padding: 20px 40px;
    }
    h5 {
      margin-top: -100px;
    }
    &::before {
      content: '';
      background-image: url(/static/Scoops-Icons.png);
      background-size: cover;
      width: 500px;
      height: 500px;
      display: block;
      position: absolute;
      margin-left: 200px;
      margin-top: -200px;
    }
  }

Body:
Parent element should use a position: relative whilst the child element uses top: 0 and left: 0.

Like this:

.parent {
    position: relative;
}
.child {
    top: 0;
    left: 0;
}


问:
Sorting a file based on a field that's not in a fixed position
i am a newbie in unix sort.
I have a set of data..example of lines:
as i tried sort -n command, it is given me this:
it start with 0_0 and the second one is 10_0, how i can make it to start at 0_0 then follow by 1_0 then 2_0 ....9_0...10_0..11_0...19_0...20_0....etc.?

Here is my input:

```<code>reg_0_0/clk
reg_10_0/clk
reg_11_0/clk
reg_12_0/clk
reg_13_0/clk
reg_14_0/clk
reg_15_0/clk
reg_16_0/clk
reg_17_0/clk
reg_18_0/clk
reg_19_0/clk
reg_1_0/clk
reg_20_0/clk
reg_21_0/clk
reg_22_0/clk
reg_23_0/clk
reg_24_0/clk
reg_25_0/clk
reg_26_0/clk
reg_27_0/clk
reg_28_0/clk
reg_29_0/clk
reg_2_0/clk
reg_30_0/clk
reg_31_0/clk
reg_3_0/clk
reg_4_0/clk
reg_5_0/clk
reg_6_0/clk
reg_7_0/clk
reg_8_0/clk
reg_9_0/clk
s_reg_0_0/clk
s_reg_10_0/clk
s_reg_11_0/clk
s_reg_12_0/clk
s_reg_13_0/clk
s_reg_14_0/clk
s_reg_15_0/clk
s_reg_16_0/clk
s_reg_17_0/clk
s_reg_18_0/clk
s_reg_19_0/clk
s_reg_1_0/clk
s_reg_20_0/clk
s_reg_21_0/clk
s_reg_22_0/clk
s_reg_23_0/clk
s_reg_24_0/clk
s_reg_25_0/clk
s_reg_26_0/clk
s_reg_27_0/clk
s_reg_28_0/clk
s_reg_29_0/clk
s_reg_2_0/clk
s_reg_30_0/clk
s_reg_31_0/clk
s_reg_3_0/clk
s_reg_4_0/clk
s_reg_5_0/clk
s_reg_6_0/clk
s_reg_7_0/clk
s_reg_8_0/clk
s_reg_9_0/clk
</code>```

答:
You can pass your file through awk, extract the number based on pattern (reg_ vs s_reg), add that as an extra field and then sort it.  And finally use cut to remove the extra field.

```<code>awk -F_ '/^reg/ { print $0":"$2 } /^s_reg/ { print $0":"$3 }' file | sort -t: -k2,2n | cut -f1 -d:
</code>```

Assuming that there are only two patterns, the above command can be further simplified as:

```<code>awk -F_ '/^reg/ { print $0":"$2; next } { print $0":"$3 }' file | sort -t: -k2,2n | cut -f1 -d:
</code>```

Produces this output:

```<code>reg_0_0/clk
s_reg_0_0/clk
reg_1_0/clk
s_reg_1_0/clk
reg_2_0/clk
s_reg_2_0/clk
reg_3_0/clk
s_reg_3_0/clk
reg_4_0/clk
s_reg_4_0/clk
reg_5_0/clk
s_reg_5_0/clk
reg_6_0/clk
s_reg_6_0/clk
reg_7_0/clk
s_reg_7_0/clk
reg_8_0/clk
s_reg_8_0/clk
reg_9_0/clk
s_reg_9_0/clk
reg_10_0/clk
s_reg_10_0/clk
reg_11_0/clk
s_reg_11_0/clk
reg_12_0/clk
s_reg_12_0/clk
reg_13_0/clk
s_reg_13_0/clk
reg_14_0/clk
s_reg_14_0/clk
reg_15_0/clk
s_reg_15_0/clk
reg_16_0/clk
s_reg_16_0/clk
reg_17_0/clk
s_reg_17_0/clk
reg_18_0/clk
s_reg_18_0/clk
reg_19_0/clk
s_reg_19_0/clk
reg_20_0/clk
s_reg_20_0/clk
reg_21_0/clk
s_reg_21_0/clk
reg_22_0/clk
s_reg_22_0/clk
reg_23_0/clk
s_reg_23_0/clk
reg_24_0/clk
s_reg_24_0/clk
reg_25_0/clk
s_reg_25_0/clk
reg_26_0/clk
s_reg_26_0/clk
reg_27_0/clk
s_reg_27_0/clk
reg_28_0/clk
s_reg_28_0/clk
reg_29_0/clk
s_reg_29_0/clk
reg_30_0/clk
s_reg_30_0/clk
reg_31_0/clk
s_reg_31_0/clk
</code>```

Body:
i am a newbie in unix sort.
I have a set of data..example of lines:
as i tried sort -n command, it is given me this:
it start with 0_0 and the second one is 10_0, how i can make it to start at 0_0 then follow by 1_0 then 2_0 ....9_0...10_0..11_0...19_0...20_0....etc.?

Here is my input:

reg_0_0/clk
reg_10_0/clk
reg_11_0/clk
reg_12_0/clk
reg_13_0/clk
reg_14_0/clk
reg_15_0/clk
reg_16_0/clk
reg_17_0/clk
reg_18_0/clk
reg_19_0/clk
reg_1_0/clk
reg_20_0/clk
reg_21_0/clk
reg_22_0/clk
reg_23_0/clk
reg_24_0/clk
reg_25_0/clk
reg_26_0/clk
reg_27_0/clk
reg_28_0/clk
reg_29_0/clk
reg_2_0/clk
reg_30_0/clk
reg_31_0/clk
reg_3_0/clk
reg_4_0/clk
reg_5_0/clk
reg_6_0/clk
reg_7_0/clk
reg_8_0/clk
reg_9_0/clk
s_reg_0_0/clk
s_reg_10_0/clk
s_reg_11_0/clk
s_reg_12_0/clk
s_reg_13_0/clk
s_reg_14_0/clk
s_reg_15_0/clk
s_reg_16_0/clk
s_reg_17_0/clk
s_reg_18_0/clk
s_reg_19_0/clk
s_reg_1_0/clk
s_reg_20_0/clk
s_reg_21_0/clk
s_reg_22_0/clk
s_reg_23_0/clk
s_reg_24_0/clk
s_reg_25_0/clk
s_reg_26_0/clk
s_reg_27_0/clk
s_reg_28_0/clk
s_reg_29_0/clk
s_reg_2_0/clk
s_reg_30_0/clk
s_reg_31_0/clk
s_reg_3_0/clk
s_reg_4_0/clk
s_reg_5_0/clk
s_reg_6_0/clk
s_reg_7_0/clk
s_reg_8_0/clk
s_reg_9_0/clk

Body:
You can pass your file through awk, extract the number based on pattern (reg_ vs s_reg), add that as an extra field and then sort it.  And finally use cut to remove the extra field.

awk -F_ '/^reg/ { print $0":"$2 } /^s_reg/ { print $0":"$3 }' file | sort -t: -k2,2n | cut -f1 -d:

Assuming that there are only two patterns, the above command can be further simplified as:

awk -F_ '/^reg/ { print $0":"$2; next } { print $0":"$3 }' file | sort -t: -k2,2n | cut -f1 -d:

Produces this output:

reg_0_0/clk
s_reg_0_0/clk
reg_1_0/clk
s_reg_1_0/clk
reg_2_0/clk
s_reg_2_0/clk
reg_3_0/clk
s_reg_3_0/clk
reg_4_0/clk
s_reg_4_0/clk
reg_5_0/clk
s_reg_5_0/clk
reg_6_0/clk
s_reg_6_0/clk
reg_7_0/clk
s_reg_7_0/clk
reg_8_0/clk
s_reg_8_0/clk
reg_9_0/clk
s_reg_9_0/clk
reg_10_0/clk
s_reg_10_0/clk
reg_11_0/clk
s_reg_11_0/clk
reg_12_0/clk
s_reg_12_0/clk
reg_13_0/clk
s_reg_13_0/clk
reg_14_0/clk
s_reg_14_0/clk
reg_15_0/clk
s_reg_15_0/clk
reg_16_0/clk
s_reg_16_0/clk
reg_17_0/clk
s_reg_17_0/clk
reg_18_0/clk
s_reg_18_0/clk
reg_19_0/clk
s_reg_19_0/clk
reg_20_0/clk
s_reg_20_0/clk
reg_21_0/clk
s_reg_21_0/clk
reg_22_0/clk
s_reg_22_0/clk
reg_23_0/clk
s_reg_23_0/clk
reg_24_0/clk
s_reg_24_0/clk
reg_25_0/clk
s_reg_25_0/clk
reg_26_0/clk
s_reg_26_0/clk
reg_27_0/clk
s_reg_27_0/clk
reg_28_0/clk
s_reg_28_0/clk
reg_29_0/clk
s_reg_29_0/clk
reg_30_0/clk
s_reg_30_0/clk
reg_31_0/clk
s_reg_31_0/clk


问:
Linq to make sure that no two objects have same property value
I've a class called Alarm with a property called Description.

```<code>public class Alarm
{
    public string Description { get; set; }
}
</code>```

In a list of Alarms, I've to make sure that no two Alarm in the list have same Description.

I want to use linq to do this check and get a list of alarms with duplicate description.

答:
var distinctAlarms = alarms.GroupBy(a => a.Description).Select(i => i.First()) .ToList();

That should do it

Body:
I've a class called Alarm with a property called Description.

public class Alarm
{
    public string Description { get; set; }
}

In a list of Alarms, I've to make sure that no two Alarm in the list have same Description.

I want to use linq to do this check and get a list of alarms with duplicate description.


问:
PHP array returns nothing (OOP newbie needs some help)
I am trying to create an form validator class that will check to make sure that people have typed a particular number of characters into specified fields.  Here is my page:

```<code>if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once('functions.php');
    require_once('formValidator.php');

    $validator = new FormValidator();
    $validator->setFirst($_POST['first']);
    $validator->setLast($_POST['last']);
    $validator->setEmail($_POST['email']);

    $errors = array();
    $validator->checkLength($errors);
    echo $errors;

    if (!empty($errors)) {
        echo '<p>' . $message . '</p>';
    }
}
</code>```

// form here (code above is in PHP tags, of course)

Here is my class:

```<code>class FormValidator {

    public $first;
    public $last;
    public $email;
    public $fields_with_lengths;

    public function setFirst($first) {
        $this->first = $first;
    }

    public function setLast($last) {
        $this->last = $last;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    function setLengths() {
        $this->fields_with_lengths = array('first' => 2, 'last' => 2, 'email' => 8);
    }

    function checkLength($fields_with_lengths) {
        $length_errors = array();

        foreach($fields_with_lengths as $fieldname => $maxlength) {
            if (strlen(trim($_POST[$fieldname])) > $maxlength) {
                $length_errors[] = $fieldname;
            }
        }

        if (!empty($length_errors)) {
            $message = 'There were no errors';
        } else {
            $message = 'There were errors';

        }
        return $message;
    }

}

$validator = new FormValidator();
$validator->setFirst($_POST['first']);
$validator->setLast($_POST['last']);
$validator->setEmail($_POST['email']);
</code>```

Can anyone see what I am doing wrong?  I'd be grateful for some help. Thanks.

答:
In PHP by default all values to functions are passed as values, not references (unless they are objects).

First of all, if you want to use a variable as a return value, you'd have to define checkLength($var) as:

```<code>function checkLength(&$fields_with_lengths) { /* ... */ }
</code>```

You could in PHP4 do a call like checkLength(&$errors), but that's deprecated as of PHP5 and will throw an E_STRICT warning. Of course, you still can (but that functionality may be thrown away soon), though the "correct" way is, as said, giving it as reference.

An even more elegant way of acting, and what should really be done in PHP, is to return the $fields_with_lengths. This way:

```<code>function checkLength() {
  $var = array();
  // Your code
  return $var;
}
</code>```

And in the call to the function, just say

```<code>$return = $validator->checkLength();
</code>```

But that does not solve the logic of your problem.

You are iterating over a parameter which is an empty array.
You are not iterating over $validator->fields_with_lengths.
Even more, $fields_with_lengths, in your code is not initialized ever.

You would have to call $validator->setLengths().
A better way of doing is (you are using PHP5) declaring a constructor, which in PHP5 is done with the magic function __construct().

However, as you are just initializing the variable always with the same constant values, you can do that in the very definition, just like this:

So you would have something like:

```<code>class FormValidator {

    pubilc $first;
    pubilc $last;
    pubilc $email;
    pubilc $fields_with_lengths = array('first' => 2, 'last' => 2, 'email' => 8);

    // Rest of code
}
</code>```

What's more..
¿Why are the attributes marked as public?

OOP theory tells us to close the scope of visibility as much as possible. And as you have setters, you don't need to access the attributes directly.
You can in PHP have a magic__get($var)to return a private $attribute if you want the syntactic sugar ofecho $validator->first;`.

Example:

```<code>function __get($var) {
    if(isset($this->{$var})) return $this->{$var}; // this $this->{$var} could even be written as $this->$var but I did it like that for clarity.
}
</code>```

If you also want the syntactic sugar of $validator->first = "John"; you can do the same with the setter, as in:

```<code>function __set($var, $value) {
    if(isset($this->{$var})) {
        return $this->{$var} = $value;
    } return null; // Or you can throw an exception if you like
}
</code>```

In PHP, as opposed to other languages, such as Java, you must explicitly use $this as the current instance of an object within a function.

So your checkLength is misdefined.

You should also do something with the return value, instead of just dropping it.

With just that minor modifications, you could fix your code with

```<code>function checkLength() {
    $length_errors = array();

    foreach($this->fields_with_lengths as $fieldname => $maxlength) {
        if (strlen(trim($_POST[$fieldname])) > $maxlength) {
            $length_errors[] = $fieldname;
        }
    }

    if (!empty($length_errors)) {
        $message = 'There were no errors';
    } else {
        $message = 'There were errors';

    }
    return array($length_errors, $message);
}
</code>```

You were using a variable ($length_errors otherwise inaccessible! so you were computing data which would never be useful).

And in the call to the function, something like
    $validator = new FormValidator();

```<code>// You could leave the setXXX($_POST[xxx])

$validator->first = $_POST['first'];
$validator->last = $_POST['last'];
$validator->email = ($_POST['email'];

$errors = $validator->checkLength();
echo "<p> {$errors[1]} </p>";

if(!empty($errors[0])) {
    // You could do something like foreach($errors[0] as $k => $fieldname) { echo "Error in $fieldname<br />" }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to create an form validator class that will check to make sure that people have typed a particular number of characters into specified fields.  Here is my page:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once('functions.php');
    require_once('formValidator.php');

    $validator = new FormValidator();
    $validator->setFirst($_POST['first']);
    $validator->setLast($_POST['last']);
    $validator->setEmail($_POST['email']);

    $errors = array();
    $validator->checkLength($errors);
    echo $errors;

    if (!empty($errors)) {
        echo '
' . $message . '
';
    }
}

// form here (code above is in PHP tags, of course)

Here is my class:

class FormValidator {

    public $first;
    public $last;
    public $email;
    public $fields_with_lengths;

    public function setFirst($first) {
        $this->first = $first;
    }

    public function setLast($last) {
        $this->last = $last;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    function setLengths() {
        $this->fields_with_lengths = array('first' => 2, 'last' => 2, 'email' => 8);
    }

    function checkLength($fields_with_lengths) {
        $length_errors = array();

        foreach($fields_with_lengths as $fieldname => $maxlength) {
            if (strlen(trim($_POST[$fieldname])) > $maxlength) {
                $length_errors[] = $fieldname;
            }
        }

        if (!empty($length_errors)) {
            $message = 'There were no errors';
        } else {
            $message = 'There were errors';

        }
        return $message;
    }

}

$validator = new FormValidator();
$validator->setFirst($_POST['first']);
$validator->setLast($_POST['last']);
$validator->setEmail($_POST['email']);

Can anyone see what I am doing wrong?  I'd be grateful for some help. Thanks.

Body:
In PHP by default all values to functions are passed as values, not references (unless they are objects).

First of all, if you want to use a variable as a return value, you'd have to define checkLength($var) as:

function checkLength(&$fields_with_lengths) { /* ... */ }

You could in PHP4 do a call like checkLength(&$errors), but that's deprecated as of PHP5 and will throw an E_STRICT warning. Of course, you still can (but that functionality may be thrown away soon), though the "correct" way is, as said, giving it as reference.

An even more elegant way of acting, and what should really be done in PHP, is to return the $fields_with_lengths. This way:

function checkLength() {
  $var = array();
  // Your code
  return $var;
}

And in the call to the function, just say

$return = $validator->checkLength();

But that does not solve the logic of your problem.

You are iterating over a parameter which is an empty array.
You are not iterating over $validator->fields_with_lengths.
Even more, $fields_with_lengths, in your code is not initialized ever.

You would have to call $validator->setLengths().
A better way of doing is (you are using PHP5) declaring a constructor, which in PHP5 is done with the magic function __construct().

However, as you are just initializing the variable always with the same constant values, you can do that in the very definition, just like this:

So you would have something like:

class FormValidator {

    pubilc $first;
    pubilc $last;
    pubilc $email;
    pubilc $fields_with_lengths = array('first' => 2, 'last' => 2, 'email' => 8);

    // Rest of code
}

What's more..
¿Why are the attributes marked as public?

OOP theory tells us to close the scope of visibility as much as possible. And as you have setters, you don't need to access the attributes directly.
You can in PHP have a magic__get($var)to return a private $attribute if you want the syntactic sugar ofecho $validator->first;`.

Example:

function __get($var) {
    if(isset($this->{$var})) return $this->{$var}; // this $this->{$var} could even be written as $this->$var but I did it like that for clarity.
}

If you also want the syntactic sugar of $validator->first = "John"; you can do the same with the setter, as in:

function __set($var, $value) {
    if(isset($this->{$var})) {
        return $this->{$var} = $value;
    } return null; // Or you can throw an exception if you like
}

In PHP, as opposed to other languages, such as Java, you must explicitly use $this as the current instance of an object within a function.

So your checkLength is misdefined.

You should also do something with the return value, instead of just dropping it.

With just that minor modifications, you could fix your code with

function checkLength() {
    $length_errors = array();

    foreach($this->fields_with_lengths as $fieldname => $maxlength) {
        if (strlen(trim($_POST[$fieldname])) > $maxlength) {
            $length_errors[] = $fieldname;
        }
    }

    if (!empty($length_errors)) {
        $message = 'There were no errors';
    } else {
        $message = 'There were errors';

    }
    return array($length_errors, $message);
}

You were using a variable ($length_errors otherwise inaccessible! so you were computing data which would never be useful).

And in the call to the function, something like
    $validator = new FormValidator();

// You could leave the setXXX($_POST[xxx])

$validator->first = $_POST['first'];
$validator->last = $_POST['last'];
$validator->email = ($_POST['email'];

$errors = $validator->checkLength();
echo "<p> {$errors[1]} </p>";

if(!empty($errors[0])) {
    // You could do something like foreach($errors[0] as $k => $fieldname) { echo "Error in $fieldname<br />" }
}


问:
Summing properties in an object array Angular
I am fairly new to Angular and Javascript so am in need of some guidance. I am wanting to work out the sum and average of values within an object array. The objects are pushed into the array through input boxes, here is my code so far:

```<code>var myApp = angular.module("myApp", []);

myApp.controller("myController", function($scope){

$scope.newLog = {};

$scope.logs = [
    {project: "",
     phase: "",
     date: "",
     startTime: "",
     intTime: "",
     endTime: "",
     comments: ""}
];

$scope.saveLog = function(){

    //CREATING DELTA TIME
    var newTimeLog = $scope.newLog;
    var begin = (newTimeLog.startTime).getTime();
    var end = (newTimeLog.endTime).getTime();

    var i = newTimeLog.intTime;
    var ii = parseInt(i);
    var intMilisec = ii*60000;

    if( isNaN(begin) )
        {
            return "";
        }

        if (begin < end) {
            var milisecDiff = end - begin;
        }else{
            var milisecDiff = begin - end;
        }

        var minusInt = milisecDiff - intMilisec;

        var milisec = parseInt((minusInt%1000)/100)
            , seconds = parseInt((minusInt/1000)%60)
            , minutes = parseInt((minusInt/(1000*60))%60)
            , hours = parseInt((minusInt/(1000*60*60))%24);

        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;

        var deltaFormat = hours + " Hours " + minutes + " Minutes";

    newTimeLog["deltaTime"] = deltaFormat;

    $scope.logs.push($scope.newLog);
    $scope.newLog = {};
};

$scope.intSum = function(){
    var sum = 0;
    for (var i = 0; i < $scope.logs.length; i++){
        sum += $scope.logs[i].intTime;
    }
    return sum;
};

});
</code>```

So the intSum function is where I am having issues - I am wanting to sum the intTime properties for all the objects. So if object1's intTime = 1, object2's intTime = 2, object3's intTime = 3 the intSum should be 6. However what I am getting from the IntSum currently is 123.

Any help would be greatly appreciated!

答:
You need to convert intTime of type string to int

You can use JavaScript reduce() function

arr.reduce(callback, [initialValue])

callback = function(accumulator, currentValue) { return accumulator + currentValue }  //accumulator is the currentSum since the last callback

Example: http://jsfiddle.net/GruffBunny/4cFU3/

Your sum function can be written as:

```<code> $scope.sum = function(items, prop){ //items is the array, prop is the property you want to its value to be calculated
     return items.reduce( function(a, b){
         return a + parseInt(b[prop]);  //in the first attempt, a=0 which is the same as initialValue
     }, 0);  //initially sum=0, so initialValue is 0
  };
</code>```

In your case, I would make the function call as $scope.sum($scope.logs, 'iniTime')

References:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=control

Better way to sum a property value in an array (Using Angularjs)

Body:
I am fairly new to Angular and Javascript so am in need of some guidance. I am wanting to work out the sum and average of values within an object array. The objects are pushed into the array through input boxes, here is my code so far:

var myApp = angular.module("myApp", []);

myApp.controller("myController", function($scope){

$scope.newLog = {};

$scope.logs = [
    {project: "",
     phase: "",
     date: "",
     startTime: "",
     intTime: "",
     endTime: "",
     comments: ""}
];

$scope.saveLog = function(){

    //CREATING DELTA TIME
    var newTimeLog = $scope.newLog;
    var begin = (newTimeLog.startTime).getTime();
    var end = (newTimeLog.endTime).getTime();

    var i = newTimeLog.intTime;
    var ii = parseInt(i);
    var intMilisec = ii*60000;

    if( isNaN(begin) )
        {
            return "";
        }

        if (begin < end) {
            var milisecDiff = end - begin;
        }else{
            var milisecDiff = begin - end;
        }

        var minusInt = milisecDiff - intMilisec;

        var milisec = parseInt((minusInt%1000)/100)
            , seconds = parseInt((minusInt/1000)%60)
            , minutes = parseInt((minusInt/(1000*60))%60)
            , hours = parseInt((minusInt/(1000*60*60))%24);

        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;

        var deltaFormat = hours + " Hours " + minutes + " Minutes";

    newTimeLog["deltaTime"] = deltaFormat;

    $scope.logs.push($scope.newLog);
    $scope.newLog = {};
};

$scope.intSum = function(){
    var sum = 0;
    for (var i = 0; i < $scope.logs.length; i++){
        sum += $scope.logs[i].intTime;
    }
    return sum;
};

});

So the intSum function is where I am having issues - I am wanting to sum the intTime properties for all the objects. So if object1's intTime = 1, object2's intTime = 2, object3's intTime = 3 the intSum should be 6. However what I am getting from the IntSum currently is 123.

Any help would be greatly appreciated!

Body:
You need to convert intTime of type string to int

You can use JavaScript reduce() function

arr.reduce(callback, [initialValue])

callback = function(accumulator, currentValue) { return accumulator + currentValue }  //accumulator is the currentSum since the last callback

Example: http://jsfiddle.net/GruffBunny/4cFU3/

Your sum function can be written as:

 $scope.sum = function(items, prop){ //items is the array, prop is the property you want to its value to be calculated
     return items.reduce( function(a, b){
         return a + parseInt(b[prop]);  //in the first attempt, a=0 which is the same as initialValue
     }, 0);  //initially sum=0, so initialValue is 0
  };

In your case, I would make the function call as $scope.sum($scope.logs, 'iniTime')

References:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=control

Better way to sum a property value in an array (Using Angularjs)


问:
How do I make a vertical graph based on inputs?
Input

```<code>1 1 3 1
</code>```

Output

```<code>  #
  #
####
</code>```

Input

```<code>0 3 0 4 5
</code>```

Output

```<code>    #
   ##
 # ##
 # ##
 # ##
</code>```

This is the code I have so far..

```<code>#include <stdio.h>
int main (void){
    int height[80],length=0,max=0;
    while ((scanf("%d",&height[length++])) != EOF && length <=79) {
        if (height[length-1] > max) {
            max=height[length-1];
        }
    }
}
</code>```

The input may not contain no more than 80 values.
I am not entire certain on how to add on more codes from here.

答:
Find the maximum height of all the inputs stored in arr[]. Now have an outer loop that iterates j from maximum height hm till 1. Every iteration of outer loop, go through all values of inner loop and check if arr[i] >= j. If yes, print a # else print a space.

```<code>int arr[80];
int n;

cin>>n;

int hm = -1;
for(int i = 0; i < n; i++){
    cin>>arr[i];
    hm = max(hm, arr[i]);
}

for(int i = hm; i > 0; i--){
    for(int j = 0; j<n; j++){
        if(arr[j]>=i)
            cout<<"#";
        else cout<<" ";
    }
    cout<<'\n';
}
</code>```

Body:
Input

1 1 3 1

Output

  #
  #
####

Input

0 3 0 4 5

Output

    #
   ##
 # ##
 # ##
 # ##

This is the code I have so far..

#include <stdio.h>
int main (void){
    int height[80],length=0,max=0;
    while ((scanf("%d",&height[length++])) != EOF && length <=79) {
        if (height[length-1] > max) {
            max=height[length-1];
        }
    }
}

The input may not contain no more than 80 values.
I am not entire certain on how to add on more codes from here.

Body:
Find the maximum height of all the inputs stored in arr[]. Now have an outer loop that iterates j from maximum height hm till 1. Every iteration of outer loop, go through all values of inner loop and check if arr[i] >= j. If yes, print a # else print a space.

int arr[80];
int n;

cin>>n;

int hm = -1;
for(int i = 0; i < n; i++){
    cin>>arr[i];
    hm = max(hm, arr[i]);
}

for(int i = hm; i > 0; i--){
    for(int j = 0; j<n; j++){
        if(arr[j]>=i)
            cout<<"#";
        else cout<<" ";
    }
    cout<<'\n';
}


问:
How to make a textView stick to the same position on imageView background with different screen ratios
-I'm new to constraintlayout  and I want to constraint a textview in some specific places on imageView like in here

-I tried to use guidelines anchoring the text to them like this but it didn't show the same between different screen sizes

so I need a way to connect the text to the image in way the text be all the time in the place I needed to be in different ratios

答: My suggestion would be to anchor each of your views to the top and bottom of the page and then set the slider % to 25% and 75%. You can adjust the views that way so that they're always relatively similar in positioning no matter the screen size. </p>


答:
like this:

```<code>length -= 1;
for(;max>=0;--max){
    for(int i = 0; i < length; ++i){
        putchar(height[i] > max ? '#' : ' ');
    }
    putchar('\n');
}
</code>```

Also while ((scanf("%d",&height[length++])) != EOF && length <=79){ is wrong.

This is because the while-body will not be executed after height[79] is read.

So, for example, modify it as follows.

```<code>#include <stdio.h>

#define DATA_MAX_LEN 80

int main (void){
    int height[DATA_MAX_LEN], length = 0, max = 0;
    for(int len = 0, h; len < DATA_MAX_LEN && scanf("%d", &h) == 1; ++len){
        height[length++] = h;
        if (height[length-1] > max){
            max=height[length-1];
        }
    }
    while(max--){
        for(int i = 0; i < length; ++i){
            putchar(height[i] > max ? '#' : ' ');
        }
        putchar('\n');
    }
}
</code>```

Title: How do I make a vertical graph based on inputs?

Body:
like this:

length -= 1;
for(;max>=0;--max){
    for(int i = 0; i < length; ++i){
        putchar(height[i] > max ? '#' : ' ');
    }
    putchar('\n');
}

Also while ((scanf("%d",&height[length++])) != EOF && length <=79){ is wrong.

This is because the while-body will not be executed after height[79] is read.

So, for example, modify it as follows.

#include <stdio.h>

#define DATA_MAX_LEN 80

int main (void){
    int height[DATA_MAX_LEN], length = 0, max = 0;
    for(int len = 0, h; len < DATA_MAX_LEN && scanf("%d", &h) == 1; ++len){
        height[length++] = h;
        if (height[length-1] > max){
            max=height[length-1];
        }
    }
    while(max--){
        for(int i = 0; i < length; ++i){
            putchar(height[i] > max ? '#' : ' ');
        }
        putchar('\n');
    }
}


答:
```<code>var dups = Alarms
  .GroupBy(a=>a.Description)
  .Where(a=>a.Count()>1)
  .SelectMany(a=>a);
</code>```

or

```<code>if (Alarms
  .GroupBy(a=>a.Description)
  .Where(a=>a.Count()>1)
  .Any())
{
  throw new Exception("You got dups!");
}
</code>```

Title: Linq to make sure that no two objects have same property value

Body:
var dups = Alarms
  .GroupBy(a=>a.Description)
  .Where(a=>a.Count()>1)
  .SelectMany(a=>a);

or

if (Alarms
  .GroupBy(a=>a.Description)
  .Where(a=>a.Count()>1)
  .Any())
{
  throw new Exception("You got dups!");
}


问:
How to prevent a textarea to insert extra blank spaces?
I have a textarea formatted like this:

```<code><textarea class="form-control">
  {{ field.value }}
</textarea>
</code>```

This is the result:

How can I prevent this from happening?

答: Rewrite it without formatting , in one line... textarea takes the spaces which are used in formatting.</p>

Body:
I have a textarea formatted like this:

<textarea class="form-control">
  {{ field.value }}
</textarea>

This is the result:

How can I prevent this from happening?


问:
Replace the list items with specific characters using lambda

This will give me the list of string having "WIGS_AUTH_" in each item. Now I want to remove this part from the list items in the same expression. Or any better way to achieve this?

答:
you can add another Select at the end

```<code>List<PermissionDto> ans = result
                         .Where(x => x.Contains("WIGS_AUTH_"))
                         .Select(x => new PermissionDto { Name = x.Replace("WIGS_AUTH_", "") })
                         .ToList();
</code>```

Body:
you can add another Select at the end

List<PermissionDto> ans = result
                         .Where(x => x.Contains("WIGS_AUTH_"))
                         .Select(x => new PermissionDto { Name = x.Replace("WIGS_AUTH_", "") })
                         .ToList();


问:
GCP Load Balancer or Kubernetes type = LoadBalancer
When working with Google Container Engine - would people recommend GCP's native load balancer or the Kubernetes Service type = LoadBalancer option?

Which do people recommend?

答:
In the service resource manifest, if you set the Type to LoadBalancer, Kubernetes on GKE (Google Container Engine) will automatically set up TCP load balancing (L4 Load balancer) using GCE. You will have to terminate connections in your pod using your own custom server or something like nginx/apache.

If your goal is to set up a L7 load balancer (HTTP/HTTPS), it will be better to make use of the Ingress resource in Kubernetes (starting with v1.1). GKE will automatically set up a GCE HTTP/HTTPS L7 load balancing for this setup. This setup has the following advantages:

Specify services per URL path and port (it uses URL Maps from GCE to configure this).

Set up and terminate SSL/TLS on the GCE load balancer (it uses Target proxies from GCE to configure this).

GKE will automatically also configure the GCE health checks for your services.

More info available on the GKE page about setting up HTTP load balancing.

Remember that GKE will automatically use the available GCE load balancer support for both the use cases described above and you will not need to manually set up GCE load balancing.


问:
Is there a way to send data directly to the JTAG port from application? (Cortex-M3)
I'm using an NXP LPC1769, which contains a Cortex-M3. So far, I've only been accessing it from the JTAG interface, but now I have to do it the other way around. An IT routine is supposed to read certain parts of the memory, and immediately send them out to the JTAG port. Is there a way to do this?

*UPDATE: After hours of research, I found something that might help: Cortex-M3 supports ITM (Instrumentation Trace Macrocell), which can send data through the TDO pin of the JTAG port. My question now is, how would one go about doing so? I only found debugger-specific applications of the ITM, where in my case, I want to be able to send specific JTAG messages (or write specific DP/AP registers) from the running application.

答:
There are several ways you can do host I/O over the JTAG port. The first one I normally turn to is called semihosting. Semihosting uses processor breakpoints in order to provide the debugged board with IO to the host. The mechanism is explained a little more here: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0471h/Bgbjjgij.html.

How you might enable semihosting on your debugger will change based on what tool you're using. For example, a thread for setting up semihosting in the LPCXpresso IDE can be found here: https://www.lpcware.com/content/forum/configure-lpcxpresso-use-semihosting and a guide for GNU Arm Eclipse can be found here: https://mcuoneclipse.com/2014/09/11/semihosting-with-gnu-arm-embedded-launchpad-and-gnu-arm-eclipse-debug-plugins/.

The downside to semihosting is that it is slow when compared to using ITM.

Another method, as you allude to in your question, is by using the ITM (Instrumentation Trace Macrocell) functionality. Unlike semihosting, the ITM can operate without waiting for the JTAG adapter to poll it for data if the SWO pin is enabled or a separate UART output has been configured. As with semihosting, the details will change based on the tools you're using.

A guide for using ITM as a standard output in the LPCXpresso IDE can be found here: https://www.lpcware.com/content/faq/lpcxpresso/how-use-itm-printf.


问:
PHP mail() function not working despite confirmation
I have created a form that allows people to send an email from a website. The HTML code (see attached) calls a PHP script (see attached), and the email is supposed to be sent. The webpage displays the message "Email successfully sent", but I never actually received the email (it's not in spam either).

I have reached out to my hosting service (awaiting reply) to check whether PHP is supported or not. In the meantime, I would like to ensure that my code has no errors.

HTML:

```<code><form action="message.php" method="post">
    <fieldset>
        <p>Name <span class="requiredAsterisk">*</span></p>
        <input name="name"/>
        <p>Email <span class="requiredAsterisk">*</span></p>
        <input name="email"/>
        <p>Message <span class="requiredAsterisk">*</span></p>
        <textarea name="message"></textarea>
    </fieldset>
    <fieldset>
        <input class="sendMessage w3-large" type="submit" value="Send Message"/>
    </fieldset>
  </form>
</code>```

PHP:

```<code><?php
$header = 'From: ' .$_POST['name'] ."\r\n" .'Reply-to: ' .$_POST['email'] ."\r\n" .'X-Mailer: PHP/' .phpversion();
if (mail("email@mail.com", "Email from website", $_POST['message'], $header)) {
    echo ("<p>Email successfully sent</p>");
} else {
    echo ("<p>Email failed</p>");
}
?>
</code>```

Thanks in advance

答:
A good alternative to the original mail() function in PHP would be something like PHPMailer. As stated in the github page:

the vast majority of code that you'll find online that uses the mail()
  function directly is just plain wrong! Please don't be tempted to do
  it yourself - if you don't use PHPMailer, there are many other
  excellent libraries that you should look at before rolling your own -
  try SwiftMailer, Zend_Mail, eZcomponents etc.

PHPMailer is super easy to set up and get going. This is the basic syntax to send an email:

```<code><?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'user@example.com';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net');     // Add a recipient

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created a form that allows people to send an email from a website. The HTML code (see attached) calls a PHP script (see attached), and the email is supposed to be sent. The webpage displays the message "Email successfully sent", but I never actually received the email (it's not in spam either).

I have reached out to my hosting service (awaiting reply) to check whether PHP is supported or not. In the meantime, I would like to ensure that my code has no errors.

HTML:

<form action="message.php" method="post">
    <fieldset>

Name *

        <input name="name"/>

Email *

        <input name="email"/>

Message *

        <textarea name="message"></textarea>
    </fieldset>
    <fieldset>
        <input class="sendMessage w3-large" type="submit" value="Send Message"/>
    </fieldset>
  </form>

PHP:

<?php
$header = 'From: ' .$_POST['name'] ."\r\n" .'Reply-to: ' .$_POST['email'] ."\r\n" .'X-Mailer: PHP/' .phpversion();
if (mail("email@mail.com", "Email from website", $_POST['message'], $header)) {
    echo ("
Email successfully sent
");
} else {
    echo ("
Email failed
");
}
?>

Thanks in advance

Body:
A good alternative to the original mail() function in PHP would be something like PHPMailer. As stated in the github page:

the vast majority of code that you'll find online that uses the mail()
  function directly is just plain wrong! Please don't be tempted to do
  it yourself - if you don't use PHPMailer, there are many other
  excellent libraries that you should look at before rolling your own -
  try SwiftMailer, Zend_Mail, eZcomponents etc.

PHPMailer is super easy to set up and get going. This is the basic syntax to send an email:

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'user@example.com';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net');     // Add a recipient

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}


答:
Here's one way to do it:

```<code>sed 's/g_/,/g' data.txt | sort -k2 -t, -n | sed 's/,/g_/g'
</code>```

(assuming data.txt is a file of the lines to sort)

Since some of the elements to sort have two underscores instead of one, but sort only accepts a single character field separator, you could use sed to replace "g_" with "," and so that there's only one unique separator before the number for each (so the number is the second field always). Then after sorting, filter it through sed again and replace "," back with "g_".

Output:

```<code>reg_0_0/clk
s_reg_0_0/clk
reg_1_0/clk
reg_2_0/clk
reg_3_0/clk
reg_4_0/clk
reg_5_0/clk
reg_6_0/clk
reg_7_0/clk
reg_8_0/clk
reg_9_0/clk
reg_10_0/clk
s_reg_10_0/clk
reg_11_0/clk
s_reg_11_0/clk
reg_12_0/clk
s_reg_12_0/clk
reg_13_0/clk
s_reg_13_0/clk
reg_14_0/clk
s_reg_14_0/clk
reg_15_0/clk
reg_16_0/clk
reg_17_0/clk
reg_18_0/clk
reg_19_0/clk
reg_20_0/clk
reg_21_0/clk
reg_22_0/clk
reg_23_0/clk
reg_24_0/clk
reg_25_0/clk
reg_26_0/clk
reg_27_0/clk
reg_28_0/clk
reg_29_0/clk
reg_30_0/clk
reg_31_0/clk
</code>```

If you only want unique elements, then just add a -u flag to sort.

Title: Sorting a file based on a field that's not in a fixed position

Body:
Here's one way to do it:

sed 's/g_/,/g' data.txt | sort -k2 -t, -n | sed 's/,/g_/g'

(assuming data.txt is a file of the lines to sort)

Since some of the elements to sort have two underscores instead of one, but sort only accepts a single character field separator, you could use sed to replace "g_" with "," and so that there's only one unique separator before the number for each (so the number is the second field always). Then after sorting, filter it through sed again and replace "," back with "g_".

Output:

reg_0_0/clk
s_reg_0_0/clk
reg_1_0/clk
reg_2_0/clk
reg_3_0/clk
reg_4_0/clk
reg_5_0/clk
reg_6_0/clk
reg_7_0/clk
reg_8_0/clk
reg_9_0/clk
reg_10_0/clk
s_reg_10_0/clk
reg_11_0/clk
s_reg_11_0/clk
reg_12_0/clk
s_reg_12_0/clk
reg_13_0/clk
s_reg_13_0/clk
reg_14_0/clk
s_reg_14_0/clk
reg_15_0/clk
reg_16_0/clk
reg_17_0/clk
reg_18_0/clk
reg_19_0/clk
reg_20_0/clk
reg_21_0/clk
reg_22_0/clk
reg_23_0/clk
reg_24_0/clk
reg_25_0/clk
reg_26_0/clk
reg_27_0/clk
reg_28_0/clk
reg_29_0/clk
reg_30_0/clk
reg_31_0/clk

If you only want unique elements, then just add a -u flag to sort.


问:
How to bind IsChecked to a ViewModel subclass
I'm trying to make a checkbox bind to a subclass of my ViewModel class (without much luck).

In my ViewModel class...

```<code>public class TestClass
{
   private bool _TestValue;
   public bool TestValue
   {
      get { return _TestValue; }
      set
      {
         _TestValue = value;
         System.Windows.MessageBox.Show("TestValue = " + _TestValue);
      }
   }
}
public TestClass TC;
</code>```

In my ViewModel constructor...

```<code>TC = new TestClass();
TC.TestValue = false;
</code>```

In my View...

```<code><CheckBox IsChecked="{Binding Path=TC.TestValue, Mode=TwoWay}">Option 1</CheckBox>
</code>```

My expectation is that when I toggle the checkbox I should see windows popping up that say "TestValue = True" or "TestValue = False", but that doesn't happen. What am I missing?

答:
Turn your TC public field into property and your binding will work.

```<code>public TestClass TC { get; }
</code>```

You can learn more about this behavior from this post.

Body:
I'm trying to make a checkbox bind to a subclass of my ViewModel class (without much luck).

In my ViewModel class...

public class TestClass
{
   private bool _TestValue;
   public bool TestValue
   {
      get { return _TestValue; }
      set
      {
         _TestValue = value;
         System.Windows.MessageBox.Show("TestValue = " + _TestValue);
      }
   }
}
public TestClass TC;

In my ViewModel constructor...

TC = new TestClass();
TC.TestValue = false;

In my View...

<CheckBox IsChecked="{Binding Path=TC.TestValue, Mode=TwoWay}">Option 1</CheckBox>

My expectation is that when I toggle the checkbox I should see windows popping up that say "TestValue = True" or "TestValue = False", but that doesn't happen. What am I missing?

Body:
Turn your TC public field into property and your binding will work.

public TestClass TC { get; }

You can learn more about this behavior from this post.


问:
Trying to understand why function is returning undefined in recursive function
I am having trouble understanding whats happening in this recursive function.
Why does y === undefined??

```<code>function f(num){
  if(num !== 10){
    f(num + 1);
  } else {
    return num;
  }

}

var y = f(0);
console.log(y);
</code>```

If I log "num" right before its returned the value is 10.
Here is a jsfiddle:
https://jsfiddle.net/

答:
if num is not 10, you just call f again. The value returned from f is not allocated anywhere. You should return that value.</p>

```<code>function f(num){
  if(num !== 10){
    return f(num + 1); //you were returning nothing except when num reached 10
  } else {
    return num;
  }

}

var y = f(0);
console.log(y);
</code>```

Body:
I am having trouble understanding whats happening in this recursive function.
Why does y === undefined??

function f(num){
  if(num !== 10){
    f(num + 1);
  } else {
    return num;
  }

}

var y = f(0);
console.log(y);

If I log "num" right before its returned the value is 10.
Here is a jsfiddle:
https://jsfiddle.net/

Body:
if num is not 10, you just call f again. The value returned from f is not allocated anywhere. You should return that value.

function f(num){
  if(num !== 10){
    return f(num + 1); //you were returning nothing except when num reached 10
  } else {
    return num;
  }

}

var y = f(0);
console.log(y);


问:
Convert ASCII to Int
I'm using an Arduino for a project that involves controlling a servo via the serial monitor. The Arduino was receiving different values than what I entered. I'm sure that this is because serial data is read as ASCII. Is there any way that I could convert it to Int? Thanks!</p>

答:
Do it like this:

string input = Serial.readString();
int angle = int(input);

As I answered here.

Title: Convert ASCII to Int


问:
Drupal 7 to Local Server
I currently work for a company that is developing a web and mobile application. I've been programming for a while now, but am less familiar with web development. I previously had been writing specialized python scripts for the company; they wanted me to transition into developing their web app. The web dev is currently being outsourced, so there aren't employees at the company that are familiar with how the website was developed. The third party is aware of my task, but is not very helpful and would prefer I only make changes locally.

What I need to do :

I need to put the Drupal site onto a local server, so I can make changes without breaking what was previously built or being on the outsourced web server.

Site specs:
Drupal 7.52
mySQL
PHP 5.6.30-1
Apache/2.2.22

My specs:
Windows 10

I have the website files (code and database). I keep encountering the same error, and have tried a number of different solutions and web stacks. When I go to upload our database into phpMyAdmin, I get an error about the database being too large (unzipped, around 118,000 KB, zipped, around 12,000 KB). I have tried a number of workarounds, and keep falling short. I've changed max_allowed_packets, $cfg['UploadDir'], and many more recommendations given here on Stack Overflow.

I've uninstalled everything from my system, so I can just start over from scratch. If anyone can give a set of instructions for how I would take the website files, upload the large database, and then have a copy of the website on a local server, that would be miraculously helpful.

Thank you!

答: You could use a virtual machine like this project https://www.drupal.org/project/vdd, which has what you need for local development and you will not need to mess up with our local OS</p>

Title: Drupal 7 to Local Server


问:
PHP foreach loop to populate dropdown list with values that exclude certain results
I have two tables. Enrollment and Product. I want to list Product on a <select>.

Within this <select>, I only want certain Product items to appear, whereby the condition is to read from Enrollment table's ProductID which is a foreign key to Product table.

How does one exclude certain results in a <select> that had already existed in a different table?

```<code><?php
    $sql = 'SELECT * FROM product ORDER BY ProductID ASC';
    $result_select = mysql_query($sql);
    $rows = array();
    while($row = mysql_fetch_array($result_select))
    $rows[] = $row;
    echo "<div class=\"spanstyle\">Add course/product:<select name='add_product'>";
    echo "<option selected>Choose here</option>";
    foreach ($rows as $row) {
        echo "<option value='" . $row['ProductID']."'>" . $row['ProductName']."</option>";
    }
    echo "</select></div>";
    $select1 = $_POST['add_product'];
    if (!strpos($select1, 'Choose here')) {
        $sql3="INSERT into enrollment (StudentID, ProductID) VALUES ($StudentID, $select1)";
        mysql_query($sql3);
        }
?>
</code>```

答:
First reaction is that you need to modify your SQL query here, not the PHP loop. Something like (and this is a quick first shot so don't trust it without testing)

SELECT * FROM product WHERE ProductID NOT IN (SELECT ProductID from enrollments) ORDER BY ProductID ASC

This would exclude any row in product whose ProductID also appears in the enrollments table.

Body:
I have two tables. Enrollment and Product. I want to list Product on a <select>.

Within this <select>, I only want certain Product items to appear, whereby the condition is to read from Enrollment table's ProductID which is a foreign key to Product table.

How does one exclude certain results in a <select> that had already existed in a different table?

<?php
    $sql = 'SELECT * FROM product ORDER BY ProductID ASC';
    $result_select = mysql_query($sql);
    $rows = array();
    while($row = mysql_fetch_array($result_select))
    $rows[] = $row;
    echo "
Add course/product:<select name='add_product'>";
    echo "<option selected>Choose here</option>";
    foreach ($rows as $row) {
        echo "<option value='" . $row['ProductID']."'>" . $row['ProductName']."</option>";
    }
    echo "</select>
";
    $select1 = $_POST['add_product'];
    if (!strpos($select1, 'Choose here')) {
        $sql3="INSERT into enrollment (StudentID, ProductID) VALUES ($StudentID, $select1)";
        mysql_query($sql3);
        }
?>


问:
Performing computation following groupby in pandas?
I have the following dataframe with four columns(I have simplified it, and it is also much longer). The user weights are always one, so their responses are treated equally. Although the same three users are assigned to each post in this example, users are actually randomly assigned to posts and each post has a variable amount of users assigned to it.

```<code>Post      userid     Weight  Response
-----     --------    ------  ---------
text1      A           1        0
text2      A           1        1
text1      B           1        0
text2      C           1        1
text1      C           1        1
text2      B           1        0
</code>```

I want the resulting dataframe to look like the following, after grouping by post. Average response just averages the users' responses by post (so if 0 represents false and 1 true, then this would essentially gauge how true or false users claim the post is). The second column indicates the agreement (so 1 is perfect agreement, and the higher the score, the better).

```<code>Post      Avg_Response     Agreement
-----     ------------     ---------
text1       0.33            0.66
text2       0.66            0.66
</code>```

I am confident for how to compute the average response (using the mean function), but I am not sure how to compute the agreement (the last column using pandas. I am sure there are some simple tricks to do this in one of two lines. My guess would be to count the number of 0s and 1s for each post divided the total number of responses for that divided. We would then take the ratio that is greater. If they are equal, then we get rid of them (so we don't want any posts in which users are evenly divided).

I would greatly appreciate help with code! Thank you.

答:
Here's one approach:

```<code>import pandas as pd
import numpy as np
from io import StringIO

df = pd.read_fwf(StringIO("""
Post      userid     Weight  Response
text1      A           1        0
text2      A           1        1
text1      B           1        0
text2      C           1        1
text1      C           1        1
text2      B           1        0
"""), header=1)

mn = df.groupby(['Post'])['Response'].mean()
md = df.groupby(['Post'])['Response'].agg(lambda x: max(np.mean(x), 1 - np.mean(x)))

mn.name = 'Avg_Response'
md.name = 'Agreement'
df2 = pd.concat([mn, md], axis=1)
df2
</code>```

Yielding...

```<code>       Avg_Response  Agreement
Post
text1      0.333333   0.666667
text2      0.666667   0.666667
</code>```

Body:
I have the following dataframe with four columns(I have simplified it, and it is also much longer). The user weights are always one, so their responses are treated equally. Although the same three users are assigned to each post in this example, users are actually randomly assigned to posts and each post has a variable amount of users assigned to it.

Post      userid     Weight  Response
-----     --------    ------  ---------
text1      A           1        0
text2      A           1        1
text1      B           1        0
text2      C           1        1
text1      C           1        1
text2      B           1        0

I want the resulting dataframe to look like the following, after grouping by post. Average response just averages the users' responses by post (so if 0 represents false and 1 true, then this would essentially gauge how true or false users claim the post is). The second column indicates the agreement (so 1 is perfect agreement, and the higher the score, the better).

Post      Avg_Response     Agreement
-----     ------------     ---------
text1       0.33            0.66
text2       0.66            0.66

I am confident for how to compute the average response (using the mean function), but I am not sure how to compute the agreement (the last column using pandas. I am sure there are some simple tricks to do this in one of two lines. My guess would be to count the number of 0s and 1s for each post divided the total number of responses for that divided. We would then take the ratio that is greater. If they are equal, then we get rid of them (so we don't want any posts in which users are evenly divided).

I would greatly appreciate help with code! Thank you.

Body:
Here's one approach:

import pandas as pd
import numpy as np
from io import StringIO

df = pd.read_fwf(StringIO("""
Post      userid     Weight  Response
text1      A           1        0
text2      A           1        1
text1      B           1        0
text2      C           1        1
text1      C           1        1
text2      B           1        0
"""), header=1)

mn = df.groupby(['Post'])['Response'].mean()
md = df.groupby(['Post'])['Response'].agg(lambda x: max(np.mean(x), 1 - np.mean(x)))

mn.name = 'Avg_Response'
md.name = 'Agreement'
df2 = pd.concat([mn, md], axis=1)
df2

Yielding...

       Avg_Response  Agreement
Post
text1      0.333333   0.666667
text2      0.666667   0.666667


问:
Forbidden header name
I'm confused while reading the document about Forbidden header name.MDN

These are forbidden, so the user agent retains full control over them

My question is "Forbidden header name" is forbidden to do what?

答: They are forbidden to be set or changed by javascript code, running in a browser sandbox.</p>

Title: Forbidden header name


答:
You're passing an empty array into checkLength(), then iterating over it (so the for loop will never have anything to iterate over). You're returning $message from checkLength() but not assigning it to anything.</p>

```<code>$errors = array('first' => 8,
                'last' => 8,
                'email' => 16
               );
$message = $validator->checkLength($errors);
</code>```

Title: PHP array returns nothing (OOP newbie needs some help)

Body:
I am trying to create an form validator class that will check to make sure that people have typed a particular number of characters into specified fields.  Here is my page:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once('functions.php');
    require_once('formValidator.php');

    $validator = new FormValidator();
    $validator->setFirst($_POST['first']);
    $validator->setLast($_POST['last']);
    $validator->setEmail($_POST['email']);

    $errors = array();
    $validator->checkLength($errors);
    echo $errors;

    if (!empty($errors)) {
        echo '
' . $message . '
';
    }
}

// form here (code above is in PHP tags, of course)

Here is my class:

class FormValidator {

    public $first;
    public $last;
    public $email;
    public $fields_with_lengths;

    public function setFirst($first) {
        $this->first = $first;
    }

    public function setLast($last) {
        $this->last = $last;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    function setLengths() {
        $this->fields_with_lengths = array('first' => 2, 'last' => 2, 'email' => 8);
    }

    function checkLength($fields_with_lengths) {
        $length_errors = array();

        foreach($fields_with_lengths as $fieldname => $maxlength) {
            if (strlen(trim($_POST[$fieldname])) > $maxlength) {
                $length_errors[] = $fieldname;
            }
        }

        if (!empty($length_errors)) {
            $message = 'There were no errors';
        } else {
            $message = 'There were errors';

        }
        return $message;
    }

}

$validator = new FormValidator();
$validator->setFirst($_POST['first']);
$validator->setLast($_POST['last']);
$validator->setEmail($_POST['email']);

Can anyone see what I am doing wrong?  I'd be grateful for some help. Thanks.

Body:
You're passing an empty array into checkLength(), then iterating over it (so the for loop will never have anything to iterate over). You're returning $message from checkLength() but not assigning it to anything.

$errors = array('first' => 8,
                'last' => 8,
                'email' => 16
               );
$message = $validator->checkLength($errors);


问:
How to display more than one row from database in a textarea
I'm trying to get all rows of beneficiaries table where localgovernment is the content of a text field "search" to display in a single textarea "result". the database is not having fix number of rows.

here is my code:

```<code>String bs = search.getText();

String SQL = "select * from BENEFICIARIES where localgovernment = '" +bs+"'";
        rs = stmt.executeQuery(SQL);

        String[] kjh;
        kjh = new String[20];
        int sd = 0;
        while(rs.next()){

        int id = rs.getInt("bid");
        String name = rs.getString("name");
        String gender = rs.getString("gender");
        String Phone = rs.getString("phone");
        String mail = rs.getString("email");
        String lga = rs.getString("localgovernment");
        String address = rs.getString("address");
        String etype = rs.getString("typeofempowerment");
        String benefits = rs.getString("listofbenefits");
        mega = id + " "+ name +" "+gender+" "+Phone+" "+mail+" "+lga+" "+address+" "+etype+" "+benefits;
       kjh[sd] = mega;
       sd = sd + 1;
        }
        String jhg = kjh[0] +"\n"+ kjh[1] +"\n"+ kjh[2] +"\n"+ kjh[3] +"\n"+ kjh[4] +"\n"+ kjh[5] +"\n"+ kjh[6] +"\n"+ kjh[7] +"\n"+ kjh[8] +"\n"+ kjh[9] +"\n"+ kjh[10] +"\n"+ kjh[11] +"\n"+ kjh[12] +"\n"+ kjh[13] +"\n"+ kjh[14] +"\n"+ kjh[15] +"\n"+ kjh[16] +"\n"+ kjh[17] +"\n"+ kjh[18] +"\n"+ kjh[19];

        result.setText(jhg);
</code>```

how do i make this to display rows of variable length in a textarea?

答:
Simply use loop.

One more thing to add, you can use List types like ArrayList or LinkedList.

Another simple way to display data is to use JTable instead of Textarea.

Try this...

```<code>String bs = search.getText();
String SQL = "select * from BENEFICIARIES where localgovernment = '" +bs+"'";
rs = stmt.executeQuery(SQL);
List<String> kjh = new ArrayList<String>();
while(rs.next()){
    int id = rs.getInt("bid");
    String name = rs.getString("name");
    String gender = rs.getString("gender");
    String Phone = rs.getString("phone");
    String mail = rs.getString("email");
    String lga = rs.getString("localgovernment");
    String address = rs.getString("address");
    String etype = rs.getString("typeofempowerment");
    String benefits = rs.getString("listofbenefits");
    mega = id + " "+ name +" "+gender+" "+Phone+" "+mail+" "+lga+" "+address+" "+etype+" "+benefits;
    kjh.add(mega);
}
String jhg="";
for(String s:kjh)
    jhg+=s+"\n";
result.setText(jhg);
</code>```

Body:
I'm trying to get all rows of beneficiaries table where localgovernment is the content of a text field "search" to display in a single textarea "result". the database is not having fix number of rows.

here is my code:

String bs = search.getText();

String SQL = "select * from BENEFICIARIES where localgovernment = '" +bs+"'";
        rs = stmt.executeQuery(SQL);

        String[] kjh;
        kjh = new String[20];
        int sd = 0;
        while(rs.next()){

        int id = rs.getInt("bid");
        String name = rs.getString("name");
        String gender = rs.getString("gender");
        String Phone = rs.getString("phone");
        String mail = rs.getString("email");
        String lga = rs.getString("localgovernment");
        String address = rs.getString("address");
        String etype = rs.getString("typeofempowerment");
        String benefits = rs.getString("listofbenefits");
        mega = id + " "+ name +" "+gender+" "+Phone+" "+mail+" "+lga+" "+address+" "+etype+" "+benefits;
       kjh[sd] = mega;
       sd = sd + 1;
        }
        String jhg = kjh[0] +"\n"+ kjh[1] +"\n"+ kjh[2] +"\n"+ kjh[3] +"\n"+ kjh[4] +"\n"+ kjh[5] +"\n"+ kjh[6] +"\n"+ kjh[7] +"\n"+ kjh[8] +"\n"+ kjh[9] +"\n"+ kjh[10] +"\n"+ kjh[11] +"\n"+ kjh[12] +"\n"+ kjh[13] +"\n"+ kjh[14] +"\n"+ kjh[15] +"\n"+ kjh[16] +"\n"+ kjh[17] +"\n"+ kjh[18] +"\n"+ kjh[19];

        result.setText(jhg);

how do i make this to display rows of variable length in a textarea?

Body:
Simply use loop.

One more thing to add, you can use List types like ArrayList or LinkedList.

Another simple way to display data is to use JTable instead of Textarea.

Try this...

String bs = search.getText();
String SQL = "select * from BENEFICIARIES where localgovernment = '" +bs+"'";
rs = stmt.executeQuery(SQL);
List<String> kjh = new ArrayList<String>();
while(rs.next()){
    int id = rs.getInt("bid");
    String name = rs.getString("name");
    String gender = rs.getString("gender");
    String Phone = rs.getString("phone");
    String mail = rs.getString("email");
    String lga = rs.getString("localgovernment");
    String address = rs.getString("address");
    String etype = rs.getString("typeofempowerment");
    String benefits = rs.getString("listofbenefits");
    mega = id + " "+ name +" "+gender+" "+Phone+" "+mail+" "+lga+" "+address+" "+etype+" "+benefits;
    kjh.add(mega);
}
String jhg="";
for(String s:kjh)
    jhg+=s+"\n";
result.setText(jhg);


问:
Event Handler Namespace in Vanilla JavaScript
I'm familiar with namespaces in jQuery's event handlers. I can add an event handler in a specific namespace:

```<code>$('#id').on('click.namespace', _handlerFunction);
</code>```

And then I can remove all event handlers in that namespace:

```<code>$('#id').off('.namespace');
</code>```

The advantage here is that I can remove only the events in this namespace, not any user-added/additional events that should be maintained.

Does anyone have any tips on how I can not use jQuery, but achieve a similar result?

答:
For anyone still looking for this, I ended up making a helper singleton which keeps track of the function references for me.

```<code>class EventHandlerClass {
  constructor() {
    this.functionMap = {};
  }

  addEventListener(event, func) {
    this.functionMap[event] = func;
    document.addEventListener(event.split('.')[0], this.functionMap[event]);
  }

  removeEventListener(event) {
    document.removeEventListener(event.split('.')[0], this.functionMap[event]);
    delete this.functionMap[event];
  }
}

export const EventHandler = new EventHandlerClass();
</code>```

Then just import EventHandler and use like:

```<code>EventHandler.addEventListener('keydown.doop', () => console.log("Doop"));
EventHandler.addEventListener('keydown.wap', () => console.log("Wap"));
EventHandler.removeEventListener('keydown.doop');
// keydown.wap is still bound
</code>```

Body:
I'm familiar with namespaces in jQuery's event handlers. I can add an event handler in a specific namespace:

$('#id').on('click.namespace', _handlerFunction);

And then I can remove all event handlers in that namespace:

$('#id').off('.namespace');

The advantage here is that I can remove only the events in this namespace, not any user-added/additional events that should be maintained.

Does anyone have any tips on how I can not use jQuery, but achieve a similar result?

Body:
For anyone still looking for this, I ended up making a helper singleton which keeps track of the function references for me.

class EventHandlerClass {
  constructor() {
    this.functionMap = {};
  }

  addEventListener(event, func) {
    this.functionMap[event] = func;
    document.addEventListener(event.split('.')[0], this.functionMap[event]);
  }

  removeEventListener(event) {
    document.removeEventListener(event.split('.')[0], this.functionMap[event]);
    delete this.functionMap[event];
  }
}

export const EventHandler = new EventHandlerClass();

Then just import EventHandler and use like:

EventHandler.addEventListener('keydown.doop', () => console.log("Doop"));
EventHandler.addEventListener('keydown.wap', () => console.log("Wap"));
EventHandler.removeEventListener('keydown.doop');
// keydown.wap is still bound


问:
Excel VBA To Process and Forward Emails Causing "Out of memory" Error
I hope someone can help- I'm hitting the dreaded "Out of memory or system resources" error with some code running in Excel and working with Outlook; from which the error originates.

Short description is it runs through a list of emails looking in the body/subject for a reference. If it finds it, it forwards the email item with the reference in the subject. MWE below; I'm not very experienced handling Outlook objects but I've spent nearly two hours trying different things with no luck. I can't use the GetTable() function since it doesn't include Body text data as far as I know (working off this), unless you can somehow add columns to include the body text?

If I run it in a freshly-opened Outlook session with only a dozen items it isn't a problem but I need it to work on hundreds of emails in one pop. Banging my head against a wall here. Thanks so much in advance!

```<code>Private Sub processMWE(ByVal oParent As Outlook.MAPIFolder)
        Dim thisMail As Outlook.MailItem
        Dim myItems As Outlook.Items
        Dim emailindex As Integer
        Dim folderpath As String
        Dim refandType As Variant
        Dim fwdItem
        Set myItems = oParent.Items
        folderpath = oParent.folderpath

        'Starting at row 2 on the current sheet
        i = 2

        With myItems
            'Data output to columns in Excel
            For emailindex = 1 To .Count
                Set thisMail = .Item(emailindex)

                'i takes row value
                Cells(i, 1).Value = folderpath
                Cells(i, 2).Value = thisMail.Subject + " " + thisMail.Body
                Cells(i, 3).Value = thisMail.SenderEmailAddress
                Cells(i, 4).Value = thisMail.ReceivedTime
                Cells(i, 6).Value = thisMail.Categories

                'Reference from body/subject and a match type (integer)
                refandType = extractInfo(Cells(i, 2))

                'This is the reference
                Cells(i, 5).Value = refandType(0)

                'And this is the match type.
                Select Case refandType(1)
                Case 1, 2
                    'do nothing
                Case Else
                    'For these match types, fwd the message
                    Set fwdItem = thisMail.Forward
                    fwdItem.Recipients.Add "#####@###"
                    fwdItem.Subject = Cells(i, 5) & " - " & thisMail.Subject
                    fwdItem.Send
                    'Edit original message category label
                    thisMail.Categories = "Forwarded"
                    thisMail.Save
                    'Note in spreadsheet
                    Cells(i, 7).Value = "Forwarded"
                    End If
                End Select
                i = i + 1
            Next
        End With
End Sub
</code>```

Edit: New development: not only is it always hanging on the same line of code (thisMail.Body) it's actually doing it for specific mail items?! If I give it a batch of one of these problem messages it hangs immediately. Could it be something to do with character encoding or message length? Something that means thisMail.Body won't work that triggers a resources error?

答:
Reason of the problem:

You are creating items without releasing them from memory -with these lines-

```<code>        For emailindex = 1 To .Count
            Set thisMail = .Item(emailindex)
</code>```

Solution

Release the objects once you are done with them

```<code> End Select
                i = i + 1
 Set thisMail = Nothing
 Next
        End With
</code>```

Common language explanation

In this scenario, think about VBA as a waiter, you are telling it that you are going to give some dishes to serve to the customers, you are giving all of them to it, but you never tell it to release them to the table, at one point, it will not be able to handle any more dishes ("Out of memory")

Body:
I hope someone can help- I'm hitting the dreaded "Out of memory or system resources" error with some code running in Excel and working with Outlook; from which the error originates.

Short description is it runs through a list of emails looking in the body/subject for a reference. If it finds it, it forwards the email item with the reference in the subject. MWE below; I'm not very experienced handling Outlook objects but I've spent nearly two hours trying different things with no luck. I can't use the GetTable() function since it doesn't include Body text data as far as I know (working off this), unless you can somehow add columns to include the body text?

If I run it in a freshly-opened Outlook session with only a dozen items it isn't a problem but I need it to work on hundreds of emails in one pop. Banging my head against a wall here. Thanks so much in advance!

Private Sub processMWE(ByVal oParent As Outlook.MAPIFolder)
        Dim thisMail As Outlook.MailItem
        Dim myItems As Outlook.Items
        Dim emailindex As Integer
        Dim folderpath As String
        Dim refandType As Variant
        Dim fwdItem
        Set myItems = oParent.Items
        folderpath = oParent.folderpath

        'Starting at row 2 on the current sheet
        i = 2

        With myItems
            'Data output to columns in Excel
            For emailindex = 1 To .Count
                Set thisMail = .Item(emailindex)

                'i takes row value
                Cells(i, 1).Value = folderpath
                Cells(i, 2).Value = thisMail.Subject + " " + thisMail.Body
                Cells(i, 3).Value = thisMail.SenderEmailAddress
                Cells(i, 4).Value = thisMail.ReceivedTime
                Cells(i, 6).Value = thisMail.Categories

                'Reference from body/subject and a match type (integer)
                refandType = extractInfo(Cells(i, 2))

                'This is the reference
                Cells(i, 5).Value = refandType(0)

                'And this is the match type.
                Select Case refandType(1)
                Case 1, 2
                    'do nothing
                Case Else
                    'For these match types, fwd the message
                    Set fwdItem = thisMail.Forward
                    fwdItem.Recipients.Add "#####@###"
                    fwdItem.Subject = Cells(i, 5) & " - " & thisMail.Subject
                    fwdItem.Send
                    'Edit original message category label
                    thisMail.Categories = "Forwarded"
                    thisMail.Save
                    'Note in spreadsheet
                    Cells(i, 7).Value = "Forwarded"
                    End If
                End Select
                i = i + 1
            Next
        End With
End Sub

Edit: New development: not only is it always hanging on the same line of code (thisMail.Body) it's actually doing it for specific mail items?! If I give it a batch of one of these problem messages it hangs immediately. Could it be something to do with character encoding or message length? Something that means thisMail.Body won't work that triggers a resources error?

Body:
Reason of the problem:

You are creating items without releasing them from memory -with these lines-

        For emailindex = 1 To .Count
            Set thisMail = .Item(emailindex)

Solution

Release the objects once you are done with them

 End Select
                i = i + 1
 Set thisMail = Nothing
 Next
        End With

Common language explanation

In this scenario, think about VBA as a waiter, you are telling it that you are going to give some dishes to serve to the customers, you are giving all of them to it, but you never tell it to release them to the table, at one point, it will not be able to handle any more dishes ("Out of memory")


问:
How can I globally set Oracle fetch size in my Scala Play (Anorm) application?
Our DBAs would like me to increase the fetch size from the JDBC's default (10). Is there a way to do this globally via application.conf, JDBC URL or similar?

My DB calls essentially look like

```<code>object SomeController extends Controller {
  def someMethod(acronym: String) = Action { implicit request =>
    DB.withConnection { implicit c =>
      val cust = SQL("""select whatever....  where acronym = {acronym}""").on("acronym" -> acronym).apply()
</code>```

But there's a lot of them over many controllers and methods.

What can be done to have a central setting?

答:
defaultRowPrefresh is an Oracle JDBC driver property than can be set to change from the default of 10 (Table 4-2 Connection Properties Recognized by Oracle JDBC Drivers)

While not explicitly documented, it looks like custom JDBC properties are done under the datasource key (see this and this)

So something like db.default.datasource.defaultRowsPrefetch="100" should work.

Body:
Our DBAs would like me to increase the fetch size from the JDBC's default (10). Is there a way to do this globally via application.conf, JDBC URL or similar?

My DB calls essentially look like

object SomeController extends Controller {
  def someMethod(acronym: String) = Action { implicit request =>
    DB.withConnection { implicit c =>
      val cust = SQL("""select whatever....  where acronym = {acronym}""").on("acronym" -> acronym).apply()

But there's a lot of them over many controllers and methods.

What can be done to have a central setting?


问:
Simple jQuery problem
This one should be easy

I've got this HTML

```<code><table class="PageNumbers">
<tr>
    <td colspan="3">text3
    </td>
</tr>
<tr>
    <td colspan="2">text
    </td>
    <td>text2
    </td>
</tr>
<tr>
    <td>moretext
    </td>
    <td>moretext2
    </td>
<td>moretext3
    </td>
</tr>
</table>
</code>```

I need to change the colspan of the first rows first column to one

This is what i've got

```<code>$('.PageNumbers tr:first td:first').attr('colspan') = '1'
</code>```

Doesn't seem to work though

Any ideas?

Thanks

答:
You're really close I think. Try this.

```<code>$('.PageNumbers tr:first td:first').attr('colspan', '1');
</code>```

Also, I think by specs class names are supposed to be lowercase? It shouldn't stop anything from working though.

Title: Simple jQuery problem

Body:
This one should be easy

I've got this HTML

    text3

    text

    text2

    moretext

    moretext2

moretext3

I need to change the colspan of the first rows first column to one

This is what i've got

$('.PageNumbers tr:first td:first').attr('colspan') = '1'

Doesn't seem to work though

Any ideas?

Thanks

Body:
You're really close I think. Try this.

$('.PageNumbers tr:first td:first').attr('colspan', '1');

Also, I think by specs class names are supposed to be lowercase? It shouldn't stop anything from working though.


问:
Stored procedure is working fine. But when use in SSRS report, I hit an error - Divide by zero error encountered
My stored procedure is working fine when run in SQL Server, but I'm getting an
error when I used it in SSRS.

Below is my stored procedure. I can't find where I'm hitting the error.
But I think it must be near the Case statement.

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[proc_rptAveragePricesFleet]
    @ShipManagerID bigint,
    @PeriodFrom DateTime,
    @PeriodTo DateTime
AS
    DECLARE @ExchangeRate decimal(18, 2)
    DECLARE @tblTotalPrice TABLE
                           (
                               ShipID bigint, ShipName varchar(MAX),
                               CategoryGroupDesc varchar(100),
                               ManagerName varchar(50),
                               PriceGram decimal(18, 2),
                               QuantityGr decimal(18, 2),
                               TotalPrice decimal(18, 2)
                           )
    DECLARE @tblAVGPrice TABLE
                         (
                             ShipID bigint, ShipName varchar(MAX),
                             CategoryGroupDesc varchar(100),
                             ManagerName varchar(50),
                             AveragePrice decimal(18, 2),
                             QuantityGr decimal(18, 2)
                         )

BEGIN
    SET NOCOUNT ON;

    SET @ExchangeRate = ISNULL((SELECT TOP 1 ExchangeRate
                                FROM tblExchangeRate ER
                                INNER JOIN dbo.tblOrderInfoHeader OIH ON ER.FromCurrencyID = OIH.OrderCurrencyID
                                INNER JOIN dbo.tblShips S ON OIH.ShipID = S.ShipID
                                INNER JOIN dbo.tblShipsManagerOwner SM ON S.ShipsManagerOwnerID = SM.ShipsManagerOwnerID
                                WHERE FromCurrencyID = OIH.SupplierCurrencyID
                                  AND ToCurrencyID =  201
                                  AND EffectivityDate <= OIH.OrderDate
                                  AND SM.ShipsManagerOwnerID = @ShipManagerID
                                  AND OIH.DeliveryDate >= @PeriodFrom
                                  AND OIH.DeliveryDate <= @PeriodTo
                                  AND OIH.IsCashOrder = 0
                                  AND OIH.OrderStatusID <> 11
                              ORDER BY EffectivityDate DESC), 1)

    INSERT INTO @tblTotalPrice (ShipID, ShipName, CategoryGroupDesc, ManagerName, PriceGram, QuantityGr, TotalPrice)
        SELECT
            S.ShipID, S.ShipName,
            CG.CategoryGroupDesc,
            SM.ManagerName,
            CASE
                WHEN OIH.OrderCurrencyID = 201
                   THEN SUM(OID.PriceRequestPrice / OID.WeightInGrams)
                ELSE SUM(OID.PriceRequestPrice * @ExchangeRate / OID.WeightInGrams)
            END AS PriceGram,
            SUM(OID.OrderQuantity * OID.WeightInGrams) AS QuantityGr,
            CASE
               WHEN OIH.OrderCurrencyID = 201
                  THEN SUM((OID.PriceRequestPrice / OID.WeightInGrams) * (OID.OrderQuantity * OID.WeightInGrams))
               ELSE SUM(((OID.PriceRequestPrice * @ExchangeRate) / OID.WeightInGrams) * (OID.OrderQuantity * OID.WeightInGrams))
            END AS TotalPrice
        FROM
            dbo.tblShips S
        INNER JOIN
            dbo.tblOrderInfoHeader OIH ON S.ShipID = OIH.ShipID
        INNER JOIN
            dbo.tblOrderInfoDetail OID ON OIH.OrderInfoHeaderID = OID.OrderInfoHeaderID
        INNER JOIN
            dbo.tblSuppliersProducts SP ON OID.SuppliersProductsID = SP.SuppliersProductsID
        INNER JOIN
            dbo.tblProducts P ON SP.ProductID = P.ProductID
        INNER JOIN
            dbo.tblSubCategory SC ON P.SubCategoryID = SC.SubCategoryID
        INNER JOIN
            dbo.tblCategory C ON SC.CategoryID = C.CategoryID
        INNER JOIN
            dbo.tblCategoryGroup CG ON C.CategoryGroupID = CG.CategoryGroupID
        INNER JOIN
            dbo.tblShipsManagerOwner SM ON S.ShipsManagerOwnerID = SM.ShipsManagerOwnerID
        WHERE
            (SM.ShipsManagerOwnerID = @ShipManagerID)
            AND OIH.DeliveryDate >= @PeriodFrom
            AND OIH.DeliveryDate <= @PeriodTo
            AND (OIH.IsCashOrder = 0)
            AND (OIH.OrderStatusID <> 11)
       GROUP BY
           S.ShipID, S.ShipName, CG.CategoryGroupDesc, SM.ManagerName, OIH.OrderCurrencyID
       ORDER BY
           CategoryGroupDesc

    INSERT INTO @tblAVGPrice(ShipID, ShipName, CategoryGroupDesc, ManagerName, AveragePrice, QuantityGr)
        SELECT
            ShipID, ShipName,
            CategoryGroupDesc,
            ManagerName,
            SUM(TotalPrice / (QuantityGr / 1000)) as AveragePrice,
            QuantityGr
        FROM
            @tblTotalPrice
        GROUP BY
            ShipID, ShipName,CategoryGroupDesc, ManagerName,  QuantityGr
        ORDER BY
            CategoryGroupDesc

    SELECT
        ShipID, ShipName,
        CategoryGroupDesc,
        ManagerName,
        AveragePrice, QuantityGr
    FROM
        @tblAVGPrice
    GROUP BY
        ShipID, ShipName,CategoryGroupDesc, ManagerName, AveragePrice,  QuantityGr
    ORDER BY
        CategoryGroupDesc
END
</code>```

答:
It can only be your parameters that are causing the issue,

Either OrderQuantity =0 or WeightInGrams = 0 when your proc is running.

can your write out your params from inside the proc?

ps: You don't need the case statements as your query because the exchange rate will be 1 if the oic.OrderCurrencyId = 201.

Also, @ExchangeRate could still be null if the inner query returns no records (ie no rows)

try it out

```<code>DECLARE @x VARCHAR(40)
SELECT @x = ISNULL(error,'nothing returned') FROM sysmessages t WHERE 1=2
PRINT isnull(@x,'what happened to my data?')
</code>```

Body:
My stored procedure is working fine when run in SQL Server, but I'm getting an
error when I used it in SSRS.

Below is my stored procedure. I can't find where I'm hitting the error.
But I think it must be near the Case statement.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[proc_rptAveragePricesFleet]
    @ShipManagerID bigint,
    @PeriodFrom DateTime,
    @PeriodTo DateTime
AS
    DECLARE @ExchangeRate decimal(18, 2)
    DECLARE @tblTotalPrice TABLE
                           (
                               ShipID bigint, ShipName varchar(MAX),
                               CategoryGroupDesc varchar(100),
                               ManagerName varchar(50),
                               PriceGram decimal(18, 2),
                               QuantityGr decimal(18, 2),
                               TotalPrice decimal(18, 2)
                           )
    DECLARE @tblAVGPrice TABLE
                         (
                             ShipID bigint, ShipName varchar(MAX),
                             CategoryGroupDesc varchar(100),
                             ManagerName varchar(50),
                             AveragePrice decimal(18, 2),
                             QuantityGr decimal(18, 2)
                         )

BEGIN
    SET NOCOUNT ON;

    SET @ExchangeRate = ISNULL((SELECT TOP 1 ExchangeRate
                                FROM tblExchangeRate ER
                                INNER JOIN dbo.tblOrderInfoHeader OIH ON ER.FromCurrencyID = OIH.OrderCurrencyID
                                INNER JOIN dbo.tblShips S ON OIH.ShipID = S.ShipID
                                INNER JOIN dbo.tblShipsManagerOwner SM ON S.ShipsManagerOwnerID = SM.ShipsManagerOwnerID
                                WHERE FromCurrencyID = OIH.SupplierCurrencyID
                                  AND ToCurrencyID =  201
                                  AND EffectivityDate <= OIH.OrderDate
                                  AND SM.ShipsManagerOwnerID = @ShipManagerID
                                  AND OIH.DeliveryDate >= @PeriodFrom
                                  AND OIH.DeliveryDate <= @PeriodTo
                                  AND OIH.IsCashOrder = 0
                                  AND OIH.OrderStatusID <> 11
                              ORDER BY EffectivityDate DESC), 1)

    INSERT INTO @tblTotalPrice (ShipID, ShipName, CategoryGroupDesc, ManagerName, PriceGram, QuantityGr, TotalPrice)
        SELECT
            S.ShipID, S.ShipName,
            CG.CategoryGroupDesc,
            SM.ManagerName,
            CASE
                WHEN OIH.OrderCurrencyID = 201
                   THEN SUM(OID.PriceRequestPrice / OID.WeightInGrams)
                ELSE SUM(OID.PriceRequestPrice * @ExchangeRate / OID.WeightInGrams)
            END AS PriceGram,
            SUM(OID.OrderQuantity * OID.WeightInGrams) AS QuantityGr,
            CASE
               WHEN OIH.OrderCurrencyID = 201
                  THEN SUM((OID.PriceRequestPrice / OID.WeightInGrams) * (OID.OrderQuantity * OID.WeightInGrams))
               ELSE SUM(((OID.PriceRequestPrice * @ExchangeRate) / OID.WeightInGrams) * (OID.OrderQuantity * OID.WeightInGrams))
            END AS TotalPrice
        FROM
            dbo.tblShips S
        INNER JOIN
            dbo.tblOrderInfoHeader OIH ON S.ShipID = OIH.ShipID
        INNER JOIN
            dbo.tblOrderInfoDetail OID ON OIH.OrderInfoHeaderID = OID.OrderInfoHeaderID
        INNER JOIN
            dbo.tblSuppliersProducts SP ON OID.SuppliersProductsID = SP.SuppliersProductsID
        INNER JOIN
            dbo.tblProducts P ON SP.ProductID = P.ProductID
        INNER JOIN
            dbo.tblSubCategory SC ON P.SubCategoryID = SC.SubCategoryID
        INNER JOIN
            dbo.tblCategory C ON SC.CategoryID = C.CategoryID
        INNER JOIN
            dbo.tblCategoryGroup CG ON C.CategoryGroupID = CG.CategoryGroupID
        INNER JOIN
            dbo.tblShipsManagerOwner SM ON S.ShipsManagerOwnerID = SM.ShipsManagerOwnerID
        WHERE
            (SM.ShipsManagerOwnerID = @ShipManagerID)
            AND OIH.DeliveryDate >= @PeriodFrom
            AND OIH.DeliveryDate <= @PeriodTo
            AND (OIH.IsCashOrder = 0)
            AND (OIH.OrderStatusID <> 11)
       GROUP BY
           S.ShipID, S.ShipName, CG.CategoryGroupDesc, SM.ManagerName, OIH.OrderCurrencyID
       ORDER BY
           CategoryGroupDesc

    INSERT INTO @tblAVGPrice(ShipID, ShipName, CategoryGroupDesc, ManagerName, AveragePrice, QuantityGr)
        SELECT
            ShipID, ShipName,
            CategoryGroupDesc,
            ManagerName,
            SUM(TotalPrice / (QuantityGr / 1000)) as AveragePrice,
            QuantityGr
        FROM
            @tblTotalPrice
        GROUP BY
            ShipID, ShipName,CategoryGroupDesc, ManagerName,  QuantityGr
        ORDER BY
            CategoryGroupDesc

    SELECT
        ShipID, ShipName,
        CategoryGroupDesc,
        ManagerName,
        AveragePrice, QuantityGr
    FROM
        @tblAVGPrice
    GROUP BY
        ShipID, ShipName,CategoryGroupDesc, ManagerName, AveragePrice,  QuantityGr
    ORDER BY
        CategoryGroupDesc
END

Body:
It can only be your parameters that are causing the issue,

Either OrderQuantity =0 or WeightInGrams = 0 when your proc is running.

can your write out your params from inside the proc?

ps: You don't need the case statements as your query because the exchange rate will be 1 if the oic.OrderCurrencyId = 201.

Also, @ExchangeRate could still be null if the inner query returns no records (ie no rows)

try it out

DECLARE @x VARCHAR(40)
SELECT @x = ISNULL(error,'nothing returned') FROM sysmessages t WHERE 1=2
PRINT isnull(@x,'what happened to my data?')