Reliably determine what shell (cmd, bash, or etc) was used to run node.js script

Question: As the title states, I'd like determine what shell (cmd, bash, or etc)  was used to run the node.js script (from within the script).
While detecting the OS with the os module can give some clues, it is not enough is some instances, such as as if I were executing from bash on win32 through a terminal like GitBash or Cygwin.
Is there a property somewhere on the process object that has this information?
*Edit: While process.env.SHELL is an option, it is not always populated and maybe undefined when using some terminals
Comment: Can you get the parent process id (PPID) in node.js? Might be related: http://stackoverflow.com/questions/5541288/detect-when-parent-process-exits
Comment: What problem are you actually trying to solve by getting this information?  What are you going to do with this information if/when you know it?
Comment: So specifically what i'm trying to do is add support for single quoted string args from a `cmd` shell, starting with detection.  @lit, how could one use a PPID to discover the shell?
Comment: I have recently seen a command that will show what program started a process, but cannot recall it. You can see it in Process Explorer. If I can find it, I will get back to you.
Answer: You can use the process.env.SHELL property to get that as seen in the official documentation,
The process.env property returns an object containing the user environment. An example of this object looks like:
{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}

Comment: Unfortunately `process.env.SHELL` is not guaranteed to be populated.  With some terminals, like Window Command Prompt, it is `undefined`


How to Fetch Latest youtube Video's in Laravel

Question: I am using alaouy/Youtube package on my laravel 5.4 its fetching my all video's from my channel with that code
$videoList = Youtube::listChannelVideos('UC9PWIZ20pnEXgT1fT69bX8A', 50);

but its showing me old first i want to to fetch latest first what do i do
thank you
Answer: In git repository of that package we can se this:
public function listChannelVideos($channelId, $maxResults = 10, $order = null, $part = ['id', 'snippet'], $pageInfo = false)
{
    $params = array(
        'type' => 'video',
        'channelId' => $channelId,
        'part' => implode(', ', $part),
        'maxResults' => $maxResults,
    );
    if (!empty($order)) {
        $params['order'] = $order;
    }
    return $this->searchAdvanced($params, $pageInfo);
}

That function seems to accept a third parameter "order"
So maybe this work:
$videoList = Youtube::listChannelVideos('UC9PWIZ20pnEXgT1fT69bX8A', 50, "date");

Comment: i just added
$videoList = Youtube::listChannelVideos('UC9PWIZ20pnEXgT1fT69bX8A', 50, "date");
and its working no need to declare listChannelVideos function
Answer: I ran the snippet you pasted and the videos do not appear to be in an order at all - the top few are 2016, then 2017, then 2016 again.
You can fetch the latest first by sorting the list:
$videoList = Youtube::listChannelVideos('UC9PWIZ20pnEXgT1fT69bX8A', 50);

usort($videoList, function ($a, $b) {
    return strtotime($a->snippet->publishedAt) < strtotime($b->snippet->publishedAt);
});

Once the list is sorted, $videoList[0] will contain your most recent video
Answer: I am just trying this package too and found that by using the search method you can loop through all of your videos and store the results in your database whilst capturing the publish date and other properties. From there you can use these records to easily sort by date or title etc and paginate through your videos. This also saves on multiple requests to the you tube api.
Anyone else taken that approach?


Should one learn piano by using solfege or numbers rather than using other methods?

Question: Most piano books begin by asking the student to play simple melodies in C major and then F major.
Does this mean that it is extremely difficult for a beginner to play in F# major? It takes time to get used to this key.
I am not sure it is good to begin by focusing on these two keys. To me thinking in keys can be problematic as it can make you think of a melodies as certain white notes rather than a pattern that can be transposed to all keys. It can be difficult to play the black notes at first but my experience is that myself and many others find focusing on playing a key in only key to be confusing us. I myself use solfege or numbers instead of thinking too much in note names. I never really learn a tune untill I use solfege or numbers. This is why most piano lessons hasn't helped me much.
Should one learn piano by using solfege or numbers rather than using other methods?
Answer:
To me thinking in keys can be problematic as it can make you think of a melodies as certain white notes rather than a pattern that can be transposed to all keys

Well, "thinking in keys" should be exactly like that.
Starting from a key that has lots of alterations (for instance, Ab) doesn't offer real benefits, and since beginners need to grasp lots of concepts in their first lessons, there's really no reason to make things even more complex than they are.
Most methods use those two tonalities (often along with G major) for various reasons, but mostly:

beginners are usually children, with small fingers and relatively limited control on their "finger coordination" (a white key is much easier to press than a black one);
the concepts of tone/half tone are not immediate, especially by looking at a keyboard: the "spaces" are not even in different tonalities, children usually have a simpler perception of distance, and to them (but not only) moving between a white and a black key means doing a bigger distance than between two white keys;
both scales, especially in the first 5 degrees, offer easy visual response of intervals, with the benefit of allowing introduction of alteration for the Bb in F and simple transposition (they usually go with something like "it sounds strange" when pressing the B-flat key for the fourth degree);

Actually, many methods use the "Movable Do" system, which is very useful as it introduces the concept of scale degrees and the relations between them, more importantly if done along with singing.
Using numbers might seem a better approach, but it implies that some level of good abstraction already exists (which can be difficult for some tonalities just by looking at the keys) and, considering that numbers are normally used for fingering, it may create further confusion (that's why scale degrees use roman numbers).
So, using tonalities with few (or no) alterations is usually better for lots of aspects, but it should also be done with awareness. You should not "focus" on the tonality itself, but on its concept and the relations between its notes.
In this way you then can begin to think in any tonality from different aspects, with a higher level of abstraction that almost ignores the actual keys you're pressing.
Comment: @andrewjohnsson - as musicamante says, there will be other answers, maybe even controversial ones! It makes interesting reading for future visitors when there are more answers, points of view. Upvote any answers you really like!
Comment: very interesting answer!
Comment: @andrewjohnsson - by accepting an answer (which may well be excellent) after a very short time, you may be putting other answerers off proffering theirs. It's often prudent to wait until you have several to choose from.
Comment: I agree with @Tim, your question doesn't have a *definitive* answer, and others might be discouraged to offer their own (which could be a completely different point of view, or even a more detailed/expanded answer).
Comment: @Tim thanks for telling me about this. I just wanted to say that I liked it and that people did not have to bother answering it and focus on other questions. I do not want anyone to waste time on my questions.
Answer: Starting with the key of C on the piano is simple. To make reading and memory simple, a key with one accidental is a good second choice. Using the key of F has one advantage, the F scales are fingered (on the piano) differently from C whereas G uses the same fingering. (Also historically though not relevant, Bb has been part of the musical note collections since before Guido.)
The importance of learning simple pieces in different keys is to understand (by muscle memory, ear, and sight) that the different major keys are just translations (math term) of notes; the relative positions of notes are the same. It's identical for minors.  There are minor differences in fingering for piano (and big differences for clarinet or oboe.)
One often has to transpose at sight (especially when working with bands for which other musicians cannot read and play only by ear or when the singer had a bad night and wants to sing in Eb rather than G that day.)
Answer: Thinking in keys is encouraged when learning classical music like piano lessons by default provide (at least in Canada). Classical music is often labelled with its key (e.g. Ludwig van Beethoven's Piano Sonata No. 23 in F minor, Op. 57, "Appassionata"). Some multi-movement classical works explicitly have entries in all 24 major and minor keys (e.g. The Well-Tempered Clavier). In that respect, music is not treated as a pattern that can be transposed to all keys. Be prepared for listeners to flip their lids if you play the start of "Für Elise" in anything other than its home key of A minor.
In addition, the white notes of a piano are notated without accidentals (until accidentals are introduced to the curriculum, then they might need naturals or maybe even sharps, flats, double sharps, or double flats), so they are easier to read, and beginners will learn them first.
You can learn piano with solfege or numbers, but normal piano lessons discourage you from going in that direction or thinking that is the best way to learn music.
Music lessons involving coordinating with others, such as band class and choir, are even nastier in this aspect. Unless you want the music to sound like an unintentional polytonal mess, following the sheet music you are given is paramount. You cannot get the entire band to learn the piece in solfege without also assigning what their initial notes are for each performance together.
Comment: Adding to the last point: It just absolutely never happens that you have to switch to different key because it's a better fit for a singer or some instrument that wasn't in original arrangement.
Comment: My music instructor is a professional musician and he has encouraged me to transpose my written music up a whole step (and other transpositions).  In a Gig, a singer started singing 1/2 step down from his rehearsal pitch and the entire band of professionals **all** transposed down 1/2 step from the written music to remain in-sync with the singer.  It nearly blew my mind when I heard he's also transposed a minor or major 3rd and really can do any transposition.  Over time I've learned that **transposing on the fly** is possible.  You just have to practice and practice it!
Comment: @PatS - I have had to transpose on the fly before (e.g. fit my mother's singing range better, sight sing B-flat clarinet music, reconcile audio with sheet music when the audio is at least one semitone below or above the sheet music).


PHP Script taking up way more memory than expected

Question: We have a script that is meant to clean up some user data. Essentially, we 1) load all user ids and loop through them. For each user we 1) load the user object then 2) alter some data and finally 3) we save the user.
We originally did all of this in one script file but we were running into memory issues about 15% of the way through processing all the users and weren't certain why. So we've tried the following:

Unset any variable instanced in the for-loop at the end of the for-loop using unset
Any variable instanced in the for-loop is set to NULL at the end of the for-loop
Loading, Altering, and Saving the user object functionality was extracted to a service method that the script will call

The hope for attempted fixes 1 and 2 would be that the memory would be deallocated and php's garbage collector would clear up memory, but it did not
The hope for attempted fix 3 was that the memory from the user object and all that would be cleaned up after the service function finished since, I believe, it should run on a different process.
I'm very confused as I don't know what variable(s) are taking up so much memory, if anything, the list of user ids should be the largest variable taking up memory but it doesn't even take up that much... In our D7 project, I had many scripts that ran through each user and did some work and saved the user and it had no issues, but in this D8 version I'm having memory issues.
Here is the code we have now, and I simply cannot find anything here that would suggest something continually to take up memory...
Script
<?php
use Drupal\user\Entity\User;

$user_service = \Drupal::service('my_user.my_user_service');

$uids = \Drupal::entityQuery('user')
                ->condition('status', '1')
                ->execute();
$total_users = count($uids);
$user_index = 0;

foreach($uids as $uid) {
  $user_index += 1;

  $ytp_user_service->cleanUp($uid);

  $percent_complete = ($user_index / $total_users) * 100;
  $percent_complete_formatted = number_format($percent_complete, 2, '.', ' ');
  $memory =  memory_get_usage()/1000000;
  print_r("\r\033[KUSER: {$uid} | COMPLETION: {$percent_complete_formatted}% | MEMORY:  {$memory} MB");
  $start_memory = memory_get_usage();
}

Service Method
  function cleanUp($uid) {
    $today = new DateTime();
    $entityManager = \Drupal::service('entity_field.manager');
    $fields = $entityManager->getFieldStorageDefinitions('user', 'user');
    $countries = options_allowed_values($fields['field_country']);
    $lower_case_countries = array_map('strtolower', $countries);
    $formatted_date = date('Y-m-d\TH:i:s', time());

    $user = User::load($uid);
    $username = $user->getUsername();
    $roles = $user->getRoles();
    if (in_array('administrator', $roles) || in_array('advisor', $roles)) {
      return;
    }

    // Convert Birthdate to age and update ages (Can be done during migrations)
    // Subtract year of birth from Registration date
    // Ex: Registration Date: June 1st, 2020
    // Year of birth: 2005
    // Age: 15 (June 1st, 2020 – June 1st 2005)
    $age = $user->get('field_age')->value ?? '';
    $reg_timestamp = $user->getCreatedTime();
    $birthdate = strtotime($user->get('field_birthdate')->value) ?? '';
    if(!$age && $birthdate) {
      $reg_month = date('m', $reg_timestamp);
      $reg_day = date('d', $reg_timestamp);
      $birth_year = date('Y', $birthdate);
      $new_birthday = $birth_year.'-'.$reg_month.'-'.$reg_day;
      $birth_date_time = new DateTime($new_birthday);
      $diff = $today->diff($birth_date_time);
      $user->set('field_age', $diff->y);
    } else if ($age) {
      $reg_date = date('Y-m-d', $reg_timestamp);
      $diff = $today->diff(new DateTime($reg_date));
      $new_age = $age + $diff->y;
      $user->set('field_age', $new_age);
    }

    // Add Country of Residence to people who don't have them
    // Only if their Nationality is Emirati or they have an emirate of Residence and they don't have a country
    // get country options
    // compare country to options
    // if it is not in options make it other
    $country = $user->get('field_new_residence')->value;
    $nationality = strtolower(trim($user->get('field_nationality')->value));
    $emirate = $user->get('field_country_residence')->value ?? '';
    if (($nationality === 'uae/emirati citizen' || $emirate) && !$country) {
      $user->set('field_country', 'United Arab Emirates');
    } else if (!in_array(trim(strtolower($country)), $lower_case_countries)) {
      $user->set('field_country', 'Other');
    } else {
      $user->set('field_country', trim(ucwords($country)));
    }

    // Remove hashtags from existing registration codes entered by users
    $reg_code = $user->get('field_workshop_code')->value;
    if($reg_code) {
      $user->set('field_workshop_code', strtolower(str_replace ('#', '', $reg_code)));
    }

    // Levels tasks
    // task 1_1
    // complete me3 and match 3 careers
    $task_1_1 = $user->get('field_task_1_1')->value;
    $matched_degs = $user->get('field_matched_degrees')->getValue();
    if(!$task_1_1 && count($matched_degs) >= 3) {
      $user->set('field_task_1_1', 1);
      $user->set('field_task_1_1_date', $formatted_date);
    }

    // task 1_2
    // enroll in one course
    $task_1_2 = $user->get('field_task_1_2')->value;
    $enrolled_courses = $user->get('field_current_courses')->getValue();
    if(!$task_1_2 && count($enrolled_courses)) {
      $user->set('field_task_1_2', 1);
      $user->set('field_task_1_2_date', $formatted_date);
    }

    // task 2_1
    // complete 1 one course
    $task_2_1 = $user->get('field_task_2_1')->value;
    $completed_courses = $user->get('field_completed_courses')->getValue();
    if(!$task_1_2 && count($completed_courses)) {
      $user->set('field_task_2_1', 1);
      $user->set('field_task_2_1_date', $formatted_date);

    }

    // task 2_2
    // request certificate
    $task_2_2 = $user->get('field_task_2_2')->value;
    $certificates = $user->get('field_course_certificates')->getValue();
    foreach($certificates as $cert_string) {
      $decoded_data = json_decode($cert_string['value']);
      if(is_null($cert_data)) {
        continue;
      } else {
        $cert_data = reset($decoded_data);
      }
      if ($cert_data->grading->certificate->download_url) {
        $user->set('field_task_2_2', 1);
        $user->set('field_task_2_2_date', $formatted_date);
        break;
      }
    }

    // task 3_2
    // complete 3 online courses
    $task_3_2 = $user->get('field_task_3_2')->value;
    if(!$task_3_2 && count($completed_courses) >= 3) {
      $user->set('field_task_3_2', 1);
      $user->set('field_task_3_2_date', $formatted_date);
    }

    // Save User
    $user->save();
  }

What am I missing here that is causing the script build up so much memory as it processes items?
UPDATE
Updated the code to the suggested existing answer in the comments, but it still seems to gradually grow in memory usage in a similar rate as before.
$chunks = array_chunk($uids, 100);

foreach($chunks as $chunk) {
  $users = User::loadMultiple($chunk);

  foreach($users as $user) {
    // instead of using the `cleanUp` service method, we directly modify and save the user here now
  }

  Drupal::entityTypeManager()->getStorage('user')->resetCache($chunk);
}

UPDATE 2
I commented out the $user->save() in the user for-loop and it performed well and memory didn't creep up... Is there a different storage cache I need to reset aside from 'user' when I save on the records?
Comment: Looks like the answer has a small bug, should be `->resetCache($chunk)`, minus the square brackets
Comment: See https://drupal.stackexchange.com/questions/280707/memory-leak-when-looping-through-nodes - the accepted answer is what you're looking for
Comment: I tried the accepted answer, but with `Drupal::entityTypeManage()->getStorage('user')->resetCache()` but I just keep getting a warning for each chunk `Illegal offset type in unset ContentEntityStorageBase.php:1117` and the memory appears to still be building...
Comment: Yup, that was it. It without warning now, but the memory usage is still creeping up...
Comment: @Clive It reset cache doesn't appear to work when saving the user... please see updated to question
Comment: I think at this point you'll have to profile the code properly - certainly the original code had a big memory-smell about it, but if fixing that doesn't stop the memory creep, you need to isolate where it's happening. I doubt anyone would be able to do that from afar (beyond guesswork)
Comment: This needs to be either a batch process or a queue. Check out Drupal's Batch API and Queue API.
Comment: Why does it "need" to be either of those? What's wrong with a simple script, something that any decent frameworks is able to handle without issues? Sounds more like Drupal needs to fix their memory issues with `user->save()` as that is clearly the issue here.
Comment: Like, I have literally never had an issue in any other framework with using a script to iterate over a large number of entities and modify/save them, until Drupal...
Answer: I would use a Queue. You can check https://api.drupal.org/api/drupal/core!core.api.php/group/queue/8.9.x for more information.
The point is each item will be processed one at a time, by timed chunks (30 seconds in my example). So the queue will process as many items it could in a 30 seconds span (or less, or more, you can adapt this in the annotation), then the process will stop and will restart next time the cron is run.
Over time, the queue will be treated. Caveat is if you absolutely need to have all users updated at once : with queue you can't tell how much time it will take - in my experience it's reliable - but eventually every user will be updated. We use it with a 5-minutes cron interval.
If you throw an \Exception in the processItem() function in the QueueWorker, the item will stay in the queue and will be reprocessed. Otherwise, the item will be delete from the queue.
You could use the __construct() method of the QueueWorker to use dependency injection to load services.
This is a pseudo/partial implementation :

Create a queue (Worker) in your namespace \Drupal\mymodule\Plugin\QueueWorker
This Worker will implement updating/saving user part (either in the body function or by using your user service).

    namespace Drupal\mymodule\Plugin\QueueWorker;

    /**
     * Executes queue tasks.
     *
     * @QueueWorker(
     *   id = "mymodule.user.queue",
     *   title = @Translation("Deal user"),
     *   cron = {"time" = 30}
     * )
     */
    class UserUpdateWorker extends QueueWorkerBase implements ContainerFactoryPluginInterface {

  /**
   * Update user.
   *
   * @param string $data
   *   What was injected : User ID.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   * @throws \Exception
   */
  public function processItem($data): void {
    $user = User::load($uid);
    // What you need to do.
  }

Create a queue (service) like this in your mymodule.services.yml
mymodule.user.queue.service:
  class: Drupal\Core\Queue\QueueInterface
  factory: queue:get
  arguments: ['mymodule.user.queue'] // this is the annotation Worker ID.

Use a (drush || cron || post_update hook) function to get the list of all users and send each ID in a the queue you created.

$queue = \Drupal::service('mymodule.user.queue.service');

$uids = \Drupal::entityQuery('user')
                ->condition('status', '1')
                ->execute();

foreach($uids as $uid) {
   $queue->createItem($uid);
}```

The queue will process items at the next cron.
Comment: My guess is user_load/saves within the same process across a number of entities.
Comment: That was going to be my fallback solution, but was just curious about why the memory issue was happening


Can a Windows machine authenticate against Samba with Kerberos when users are stored in AD?

Question: I understand the title is probably less clear that it should be, but I couldn't think of anything better.
We have two domains, let's call them example.com and subnet.example.com. The former is managed by an Active Directory server, and houses some servers as well as all the Windows clients. The latter houses a number of Unix machines (mostly Solaris). There is a one-way trust from the realm SUBNET.EXAMPLE.COM to EXAMPLE.COM.
With this setup, the usual stuff works fine, like ssh login, NFSv4, etc.
Now, what I want to be able to do is to run Samba servers on the Unix machines in subnet.example.com. Windows users should be able to access the files on these servers.
I set up Kerberos authentication in Samba, and it works perfectly from any Linux client. I can access the machines via smbclient when I have a Kerberos TGT, and it stops working if I drop it. User mapping works exactly as expected. The machines have cifs/hostname entries in the MIT Kerberos server.
However, Windows clients are unable to do the same. When looking at the Samba logs I can see that the Samba server attempts to talk to the AD server, but is not allowed to do this since the Samba server has not joined the AD domain.
So, I hear you ask: "Why don't you just join the AD domain?". The answer is that I'm not able to do that since the systems on the subnet are test systems that are being installed and reinstalled, often many times per day, and we do not wish to have an AD admin configuring this (and removing them as well) every time a test system is installed or taken offline.
Besides, everything works perfectly for the Linux clients, which leads me to believe that it should be possible to get this to work somehow.
So, my question is: Is this even possible? Is there some limitation in Windows that prevents them from being clients in a normal Kerberos realm? If so, what would be the best workaround for this problem?
Answer: I solved the problem. The issue was that the Windows client did not know that subnet.example.com belongs to a different realm. The solution is to inform the client of this. It can be done with the following two commands that, I believe, i similar to adding domain information in krb5.conf on a Unix system:
ksetup /addkdc SUBNET.EXAMPLE.COM hostname.of.kerberos.server
ksetup /addhosttorealmmap .subnet.example.com SUBNET.EXAMPLE.COM

After I did this, client authentication worked as expected.
Comment: Note: Realm to KDC mapping can be configured with group policy. (Req: DC functional level >=Server2008; Client >=Vista or >=Server2008)


I have installed Apache server on Windows server 2019 and am trying to restrict phpMyAdmin from access outside of server

Question: I have installed Apache. php and MariaDB  on Windows server 2019. No xampp, wamp or any other platform installer. What I am trying to do is restrict opening of phpmyadim from out side of the server while allowing accessto the LMS. PhpMyAdmin along with a production LMS site are located in the htdocs folder. Currently the LMS is open on the local area network as is phpmyadmin. I am assuming changes will have to be made in httpd-vhosts.conf file but having no luck. In previous install I have used xampp.
Answer: To set it up as a alias which is normal I think, in httpd.conf add an include like
Include "C:/folder_above_DocumentRoot_for_security/alias/phpMyAdmin.conf"

Then the conf file looks like
Alias /phpmyadmin "c:/Wherever/YouInstalled/phpmyadmin/"

<Directory "c:/Wherever/YouInstalled/phpmyadmin/">
    Options +Indexes +FollowSymLinks +MultiViews
    AllowOverride all
    Require local
</Directory>


Problems connecting to MySQL using PDO

Question: I've been trying to convert my application from using the depreciated mysql syntax to PDO for connecting to the database and performing queries, and it's been a pain so far.
Right now I have a class, db_functions.php, in which I'm trying to create a PDO connection to the database, as well as perform all the CRUD operations inside of.
Here is a sampling of the code:
db_functions.php
<?php

class DB_Functions {

    private $db;

    // constructor
    function __construct() {
        require_once 'config.php';
        // connecting to mysql
        try {
        $this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);
        }
        catch (PDOException $e) {
            $output = 'Unable to connect to database server.' .
            $e->getMessage();
            exit();
        }
    }

    // destructor
    function __destruct() {

    }

public function getAllUsers() {
    try {
    $sql = "select * FROM gcm_users";
    //$result = mysql_query("select * FROM gcm_users");
    $result = $this->$db->query($sql);
    return $result;
    }
    catch (PDOException $e) {
        $error = 'Error getting all users: ' . $e->getMessage();
    }
}

With that code, i'm getting the following error:
Notice: Undefined variable: db in C:\xampp\htdocs\gcm\db_functions.php on line 12

Fatal error: Cannot access empty property in C:\xampp\htdocs\gcm\db_functions.php on line 12

Line 12 is:
 $this->$db = new PDO('mysql:host=localhost;dbname=gcm', DB_USER, DB_PASSWORD);

How could I fix this so that I have a proper instance of a PDO connection to my database that I can use to create queries in other methods in db_functions, such as getAllUsers()
I used the answer found at How do I create a connection class with dependency injection and interfaces? to no avail.
Comment: Do `$this->db` instead of `$this->$db` - That [**link you provided**](http://stackoverflow.com/questions/12183819/how-do-i-create-a-connection-class-with-dependency-injection-and-interfaces) specifically states `$this->pdo = new PDO( '...');` without the `$` in front of `pdo`, so do the same here.
Comment: Thanks, that seemed to work. I'm curious as to why you don't use the '$' symbol in front of it, since db is still referring to a variable, correct?
Comment: because you working in a class and classes working with objects. its not actually a variable. so its a object. :)
Answer: TYPO
//$this->$db =
$this->db =

same here
//$this->$db->query($sql);
$this->db->query($sql);

and i also would use 127.0.0.1 instead of localhost to improve the performance otherwise making a connection will take very long... a couple of seconds just for connection...

Problems connecting to MySQL using PDO


Why does CNAME for a root domain conflict with most other records?

Question: As far as I understand, a CNAME record is served to retrieve only the A record of its destination. E.g.:
www.example.com CNAME domain.com
Here the DNS resolver will search for the A record (IP address) of domain.com.
It is not allowed by RFC to use the CNAME record for the bare domain name, although, technically, it is possible. Like here:
example.com CNAME domain.com
example.com MX mail.example.com
(MX will not work in this case)
However, I still don't understand how this record conflicts with other records like MX from the technical point of view and why the A record does not conflict, for instance. I guess I've missed something.
By the way, there are CNAME Flattening, ANAME or ALIAS records that have different implementations than the standard CNAME and they do not conflict with other records.
Could you explain?
Answer: An entry of type:
alias.example.com. CNAME canonical.example.com.

means that all records for alias should be fetched from canonical. If you are looking for alias's MX record, you should retrieve canonical's MX record instead. Therefore mostly all other records for alias will be ignored.
This behaviour is semantic, not technical. You can still ask for alias's MX record, but the server will answer with the CNAME record instead.
The exception of the above rule is DNSSEC records. An RRSET for alias will not be ignored, since it certifies the CNAME record authenticity.
Comment: "You can still ask for alias's MX record, but no client will do it." On the contrary, all clients will do it. A client can not know in advance there is a CNAME. So it will ask whatever record it wants, and will learn there is a CNAME in the reply and then do the query again to go further (this is done in the recursive namesever).
Comment: Thanks for the correction, I edited the answer accordingly.


Inhomogeneous non-linear Euler-Lagrange equation

Question: Let $1<p<\infty$.
Let $u\in W^{1,p}(\Omega)$, where $\Omega \subset \mathbb{ R^n},$ bounded and open and connected.
First suppose we have a homogeneous PDE: $$ -\sum_{i=1}^n(|\nabla u|^{p-2}u_{x_i})_{x_i}+|u(x)|^{p-2}u(x)=0.$$
Then the Lagragian $L$ can be chosen as $$L(q,z,x)=\frac{|q|^p}{p}+\frac{|z|^p}{p}$$ ,where $q\in \mathbb{R^n},z\in \mathbb{R}, x\in \mathbb{R^n}.$
And the standard theory of calculus of variation applies then.
But if our PDE is inhomogeneous, say:
$$ -\sum_{i=1}^n(|\nabla u|^{p-2}u_{x_i})_{x_i}+|u(x)|^{p-2}u(x)=f(x),$$
with any fixed $f$ s.t. $\int_{\Omega} f\varphi dx$ defines a bounded linear functional for all $\varphi\in C_c^\infty(\Omega).$
Now it seems like we cannot write out a Lagrangian $L$ for this inhomogeneous PDE and the theory of calculus of variation doesn't apply.
My question is, can we write out a Lagrangian $L$ for this inhomogeneous PDE? If not, can one tell me why? Thanks a lot.
Answer: $f$ is just a source term. It can be modeled with a term of the form $zf$ in the Lagrangian $L$. See also e.g. this related Phys.SE post.


Imagem alternativa no caso de fallha ao carregar

Question: Estou a criar um script que mostra aleatoriamente um mosaico de instaram.
Eu guardo os URLs da imagem original numa BD, mas acontece que as vezes tenho URLs de imagens que não carregam porque os utilizadores eliminaram as imagens no instagram.
Qual sera a melhor forma de  mostrar uma imagem alternativa no caso da a imagem de origem não ser encontrada?
Answer: Ok, pesquisando um pouco encontrei o parametro onError que executa um script quando a imagem não carega.

Aqui fica também a tabela de compatibilidade com a lista dos navegadores que suportam o parametro:
http://www.quirksmode.org/dom/events/error.html
Comment: o atributo `alt="descrição da imagem aqui"` também serve para isso e é amiga do SEO.  "[*The required alt attribute specifies an alternate text for an image, if the image cannot be displayed.*](http://www.w3schools.com/tags/att_img_alt.asp) "


The average denominator of the continued fraction expansion of $\pi$.

Question: I was interested in the long term behavior of continued fraction denominators, so I plotted the average of the first $n$ terms in the continued fraction expansion of $\pi$ as a function of $n$ and got the following graph:

And it turns out that at the $453294$th position, we suddenly get a $12996958$ among many one and two digit numbers. Why the sudden large number?
I know there are other continued fractions with strange behavior, notably the Champernowne's Numbers. $C_{10}$ seems especially weird, as its continued fraction expansion begins with:
$$ [0; 8, 9, 1, 149083, 1, 1, 1, 4, 1, 1, 1, 3, 4, 1, 1, 1, 15,
4 57540 11139 10310 76483 64662 82429 56118 59960 39397 10457 55500 06620\\ 04393 09026 26592 56314 93795 32077 47128 65631 38641 20937 55035 52094 60718 30899\\ 84575 80146 98631 48833 59214 17830 10987,
6, 1, 1, 21, 1, 9, 1, 1, 2, 3, 1, 7, 2, 1]$$
What is known about the asymptotic behavior of continued fractions? Why do such large terms appear between smaller ones? Is there a measure of how "erratic" the expansion is, such as the limit of the variance of the denominators?
EDIT: Fixed reason for jump.
Comment: @Robert: See [OEIS](http://oeis.org/A001203) and [MathWorld](http://mathworld.wolfram.com/PiContinuedFraction.html).
Comment: There seems to be something wrong with either the plot or your description of the numbers. A $5763$ in the $452155$th position wouldn't cause a jump by more than $20$ in the average.
Comment: I'm suspicious of how you obtained your plot.  To get the millionth term in the continued fraction, you'll need an awfully good approximation for $\pi$.
Comment: I picked the wrong large value. No wonder it seemed fishy. All fixed, though.
Answer: There is a theorem from real analysis using the ideas of ergodic theory that states, for almost every real number $x \in \mathbb R$, the natural number $n$ appears in the continued fraction expansion of $x$ with frequency $\log_{2} \left ( \frac{(n+1)^{2}}{n(n+2)} \right )$.
To prove this fact, consider the Gauss measure $\nu (E) = \frac{1}{\log(2)} \int_{0}^{1} \frac{1}{1+t} dt$, on $([0,1]\setminus \mathbb Q)$. Also consider the transformation $U(x)= \{\frac{1}{x}\}$, where $\{\}$ denotes fractional part. This transformation is ergodic, and from here proving the theorem is a straightforward application of the ergodic theorem.
Comment: I believe that is called the Gauss-Kuzmin theorem. But I  think it's not known whether the continued fraction for $\pi$ actually has the Gauss-Kuzmin distribution.
Answer: For almost every real number, the geometric mean of the denominators is equal to Khinchin's constant, about $2.6854$, if we can believe that Wikipedia page.
The article mentions that $e$ is an exception, and that's easy if one knows its simple continued fraction expansion.
The article says:

Among the numbers whose geometric mean of the coefficients $a_i$ in the continued fraction expansion apparently (based on numerical evidence) tends to Khinchin's constant are $\pi$, the Euler–Mascheroni constant $\gamma$, and Khinchin's constant itself. However, none of these limits has been rigorously established,

One could wonder whether for almost every real number, the asymptotic distribution of the denominators is the same.
Answer: Not sure about pi, but about Champernowne's number (CN from now on), it's not terribly hard to see why it has such huge numbers near the beginning of its continued fraction.
For example, CN is 0.12345679 when rounded to eight decimals, just like 10/81, which equals
10 (1/9)^2 = 1/10 + 2/100 + 3/1000 + 4/10,000 + ...
This explains the first few coefficients.  However, CN isn't periodic.  After the first nine decimals, CN consists of the numbers 10 to 99, then 100 to 999 and so on.
Now, the number 0.01020304050607080910111213...9799000102(repeating a 198-digit sequence)... equals 100/9891, the square of 10/99, which has a much simpler decimal expansion, = 0.101010...
One can see that CN is quite well approximated by a rather simple combination of the two quantities 10/81 and 100/9801, and that approximation is good for almost 189 digits, where CN has exhausted all possible 2-digit sequences.
[0;8,9,1,149083,1,1,1,4,1,1,1,3,4,1,1,1,15] is probably a number 0.123456789 followed by a repeating part 198 digits in length and starting with 10111213...9091929394959697...
And even if it's not, the length is probably 180 to 200 digits, with the same initial digits given above.
So, after a few small coefficients, one moderately big one, and another few small ones, we encounter a coefficient with close to 180 digits.
Likewise, one would expect a coeffient with almost 2700 digits that approximates CN up to the end of the 900 different 3-digit sequences, another with close to 36000 digits that includes most of the 4-digit sequences, and so on.  CN can therefore generate huge coefficients rather soon in its continued fraction expansion.
That's not a rigorous proof, but the chance that a significantly smaller coefficient (let's say, at most half the predicted digits) would do at some point is negligibly small, even with only a coarse statistical argument.
Most of my reasoning seems to hold for any base > 2, so I'd challenge the notion that C10 is "especially weird", at least among other Champernowne numbers.  But that could be an ambiguous wording in the question.  (If you use a different base than 10, there should be one where my argument can be replicated for any given Champernowne number except maybe C2.)


Are there any standard metrics in use that take into account the "variability" in a pitcher's ERA?

Question: Early in his career (as a Pirate), current ace Charlie Morton once gave up ten runs in a single inning. That's a bad, 90.00 ERA for that one "frame."
But you can only lose one game at a time. Suppose a reliever gave up those ten runs in one inning, and then pitched eight one-inning stints with 0 runs. Over those nine innings, his ERA would still be a lousy 10.00, but he would have been responsible for losing at most the one game.
So are there ways that managers adjust for "kitchen sink" pitchers, that "bunch" a disproportionate number of their lost runs into a handful of outings?*
*In the case of Morton, I did my own rough calculation. I calculated that his ERA would be about 3.00, after taking out his worst three outings (which ballooned his ERA to 5.00). So I started him at 0-3 for the three bad (and presumably lost) games. Another pitcher with a 3.00 ERA had a W-L record of 9-4. I "estimated" Morton's record at 9-7 (after adding the three "kitchen-sink" losses), which is a decidedly better record than that of a typical 5.00 ERA pitcher.
Answer: No, not really.  What you're describing would only be useful if it could be shown that this ability to have mostly good performance with little blips of horrible performance was something that was innate, rather than just a normal observation of random chance.  It's not, most likely.  You also nearly never have pitchers who have quite this extreme of results - starters might sometimes give up this many runs (as Charlie Morton was), but they have huge numbers of innings - 150-200 for a full time starter - and a few "blips" won't matter very much.  Relivers, who pitch much fewer innings, would be taken out before they could give up ten runs nearly always.
But either way, you would need to show this was an innate trait of the pitcher, and not just artifacts of chance, for this to be of value.  Otherwise you're just describing something random - which everyone is as likely to have as any others.  You also have the issue that, perhaps in this 10 run game, the pitcher was injured, or was tipping his pitches, or had some other issue that caused it - stats don't catch that, because they can't.  That's why you have to use statistics in combination with other analytical approaches, and not just blindly rely on a few numbers to paint a picture of a player's abilities and likely future performance.
You also use statistics like FIP, instead of ERA, because they take more of the pitcher's performance into account - even with things like streakiness.  They don't directly factor it in, mind you, but they more accurately reflect how the pitcher performed relative to possible future performance.  Removing the results of random things like high BABIP and mediocre (but not error-prone) fielding, they focus on the things the pitcher can control - and that  control is always a factor, streakiness or not.
Finally, you talk about "wins"; that's one statistic that is entirely worthless, and no statistical pitching model worth its salt would even factor at all.  You found a 3.0 ERA pitcher with a 9-4 record?  Great!  May I introduce to you Felix Hernandez, who won a Cy Young with a 2.25 ERA... and a 13-12 record.  Pitcher Wins are too much a factor of other things - run support, what team they're playing on, etc. - that they're not predictive at all of future individual performance.
For the most part, pitchers are evaluated on things - like K/BB, K/9, etc. - that wouldn't even really be impacted by these bad games meaningfully; unless he gave up 10 runs all on walks, his rates would likely be mostly be minimally affected by the couple of bad games.  There are definitely relievers who do have "high" ERAs from a few bad games - and they're valued because of these other statistics, rather than some sort of made up statistic to evaluate ERA (which, itself, isn't very useful).


Adding a License to your .Net Web Application

Question: I am currently looking at adding some licensy type software which will protect my .net web application source code. Was wondering if you guys had any experience with this and knew perhaps any companies or sources which provide such utilities ?
So my main aim is to protect the actual files
i.e Default.aspx
Default.aspx.cs
....
being copied in the future without me being able to stop them from using it.
Thanks
EDIT : From reading the replies i seem to think obfuscator seems to be the way to go.
Does a obfuscator program only work on exe or dll's or does it also work on individual pages ?
Comment: From reading the replies i seem to think obfuscator seems to be the way to go. Does a obfuscator program only work on exe or dll's or does it also work on individual pages ?
Comment: Licensing software varies from country to country, in what country are you in?
Comment: its obfuscation, not protection, just so you know the terms :).
Comment: So is the only way they to protect your source code, using obfuscation ?
Answer: One step you can do is to release it as a Web Application rather than a Web Site.
Differences here from asp.net
As far as the Default.aspx, I don't know of a way to encrypt html pages that are served over standard web servers, and either way, the clients will all still be able to View Source, unless you write the entire page in JavaScript writes (horrible to manage).
Your best bet is to not include any application logic code what-so-ever in the aspx and compile your binaries using an obfusicator.
Comment: Is there no software where for example I can put a License on my code on the code which I can remove from the web app to make it unusable at any code.

Or is the only way to achieve is to use obfuscator and encrypt the pages ?
Comment: I'm not even sure you can encrypt the pages, but as far as I know, I don't think there is.
Answer: I wondering if a simple pre-compile will do the trick in your ASP.NET application, we do that here in the company. We ship our Web modules pre-compiled and no one will see what's in the aspx code, all the "code-behind" files are translated into DLL's.
see more here
Comment: Is this like using the option in Visual Studio "Add as a web development Project".

Im wondering how easy this code is maintable during development etc ?
Comment: you need to generate and ship the entire web folder every time, but no one can look inside your code!
Answer: I wouldn't bother with obfuscation: the latest syntax-sugar, compile-time tricks and optimisations in .Net 3.5 make simple reverse engineering pretty tough already.
For instance each time you use the yield keyword it generates an enumeration class with a complex structure and an unreadable name.
Obfuscation will make it tougher to reverse engineer, but not by a enough. Either will deter the basic hack with a copy of reflector, neither will deter or stop a determined and expert cracker.
I would key-sign all your assemblies - then if they reverse one they have to reverse all.
I'd take as much of the actual application logic out of the web project and into referenced DLLs - your web project should really be all about the UI. This makes it easier to unit test the underlying logic, and easier to obfuscate if you decide that it's worth it.
Answer: your web site can send to you some of the server machine information on each user login.
If the mechine information is wrong, cancel the login.
Answer: I was wondering if there was any other way to protect your sour code other than obfuscator or precompiling.
I.e you have a list of pages
Default.aspx
Default.aspx.cs
web.config
Where your main aim is to prevent a 3rd party from taking your code if they have access to the source code ?
Answer: unless you obfuscate it in some way so it is more effort than it is worth, or you precompile I don't see how you could prevent them from just isolating the license checking code - and removing it.
You can run an obfuscator over the source code and distribute the obfuscated version, there are numerous examples of this around, particularly for javascript.
Comment: This would be in .net. So your saying the obfuscator can run on the actually code behind pages, so the web app does not need to be compilted into a DLL ?

Also lets say my pages are scrambled with obfuscator how do these work when they are run live ?
Answer: I think you are mixing two different things here. One is law protection (that's what licences are for) and the other is physical protection. If everyone would obey law, then physical protection would not be needed.
I suggest you choose a licence that fits you (there are many of them), then take care of the physical protection in whatever way.


Alertmanager only goes through default receiver

Question: As stated in the title, I have an issue with alertmanager from prometheus-operator. I'm trying to filter some alerts using routes but it doesn't seem to be taken into account.
When I use the default receiver everything seems to be working fine but if I try to filter with a default receiver that does nothing and then a route, it doesn't goes in the route and I don't get any error.
The secret I'm using:
<code>    route:
      group_wait: 30s
      group_interval: 5m
      repeat_interval: 4h
      group_by: [cluster]
      receiver: 'default'
      routes:
      - match:
          alertname: !Watchdog
        receiver: 'slack-devops'
        continue: true
    templates: ['/etc/alertmanager/config/*.tmpl']
    receivers:
    - name: 'default'
    - name: 'slack-devops'
      slack_configs:
      - channel: "tmp-test-srv-alerting"

With this configuration it puts everything in the default route and neither goes in the routes, I don't even get an error. Would someone has an idea on how to make this work?
</code>
Comment: What do you mean by this section 'alertname: !Watchdog' ? Did you mean everything except Watchdog ?
Comment: Yes, that is what I was trying to do, I found an example using this writing, but it doesn't seem to be working...
Comment: Seems like the question should be 'how to use negative matchers'?
Comment: Maybe, Without an error message it was difficult to evaluate where was the error.
Comment: There shouldn't be an error. It's just misused
Answer: Try using 'matchers' instead of 'match' which supports negative matching:
Instead of
<code># ❌ This is invalid
route:
- match:
   alertname: !WatchDog

# ✅ This is correct
route:
- matchers:
   - alertname!=Watchdog
</code>
Docs: https://prometheus.io/docs/alerting/latest/configuration/#matcher


Only execute onEdit if the users make edit within a specific range

Question: How can I trigger onEdit only when users make any edits with a specific range in Google App Script?
Answer: You cannot create an onEdit that only fires when certain cells are edited, but you can put a condition in the beginning of your function to check if the edited cells are part of the range you want to track changes from. You can do that with the use of an event object for that.
For example, you can do this (check inline comments):
function onEdit(e) {
  // Information from edited range:
  var range = e.range;
  var editedRow = range.getRow();
  var editedCol = range.getColumn();
  var editedSheet = range.getSheet();
  // Range to track (please change accordingly):
  var sheetName = "Sheet To Track";
  var minCol = 3;
  var maxCol = 7;
  var minRow = 2;
  var maxRow = 5;
  // Check that edited sheet, column and row are the ones you want to track changes from:
  if (editedSheet.getName() === sheetName && editedRow >= minRow && editedRow <= maxRow && editedCol >= minCol && editedCol <= maxCol) {
    // Actions to perform if edited range is correct
  }
}

The function above will first check if the edited range is (1) between columns 3 and 7, (2) between rows 2 and 5 and (3) in the sheet called Sheet To Track.
Reference:

Event Objects: Edit
Comment: Thanks for your recommendation, that's what I was planning to do.


angular login with ui-router can't redirect to login page

Question: I create a login module for my website like:
angular.module('caknow', [
  'ui.router',
  'ngStorage',
  'authentication',
  'login'
])
  .config(['$stateProvider', '$urlRouterProvider',function($stateProvider, $urlRouterProvider) {

    $stateProvider
      .state('index', {
        url: '/',
        templateUrl: '../template/dashboard/dashboard.html'
      })
      .state('login', {
        url: '/login',
        templateUrl: '../template/authen/login.html',
        controller: 'loginController'
      });
  }])
  .run(['$location', '$http', 'tokenSer', '$state', '$rootScope', function($location, $http, tokenSer, $state, $rootScope) {
    $http.defaults.headers.common['x-api-key'] = '*********';
    var token = tokenSer.get(); // service to get token store in localStorage.
    if (token) {
      $http.defaults.headers.common['x-access-token'] = 'token';
    }

    console.log("hello world");
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options){
      if ($location.path() != '/login' && !token) {
          console.log("hello world login");
        $state.go('login');
      }
    });
  }])

The main page like:

For index state, I want main page load dashboard.html template.
For login state, I want main page load login.html template.
If user doesn't login and get a token from server, user will be redirected to login state. But, when I use http-server to start a server and try to access localhost:port at first time. I don't redirect to login page and show a white page. In my opinion, I find that $stateChangeStart doesn't emit.
Answer: You have to prevent the default event so you can start another:
event.preventDefault();
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options){
    if ($location.path() != '/login' && !token) {
        event.preventDefault();
        $state.go('login');
    }
});

Comment: It doesn't work. I see that the $stateChangeStart even is emitted infinitely
Comment: You could try adding it into $stateChangeSuccess and see if that works?


Linux Web Server Permissions - Best Practices

Question: On a privately owned server with one website, is there any reason the files/directories within /var/www can't be group owned by www-data?
My understanding is that security risks with www-data having write access only arise if you have multiple websites running on the same box.
Answer: I wrote a simple script for my WordPress site. This script gives Apache only write-access to what it needs to write to. Everything else under the webroot is read-only. I think this is a good step towards a more secure site, and should be practiced.
<code>#!/bin/bash

PATH=/bin:/usr/bin
WEBROOT="/var/www/www.example.com"

UPLOADS="${WEBROOT}/wp-content/uploads"

chown -R nobody:nogroup ${WEBROOT}
find ${WEBROOT} -type d -exec chmod 0555 {} \;
find ${WEBROOT} -type f -exec chmod 0444 {} \;

chown nobody:www-data ${WEBROOT}/sitemap.xml ${WEBROOT}/sitemap.xml.gz
chmod 0464 ${WEBROOT}/sitemap.xml ${WEBROOT}/sitemap.xml.gz

chown -R nobody:www-data ${UPLOADS}
find ${UPLOADS} -type d -exec chmod 2575 {} \;
find ${UPLOADS} -type f -exec chmod 0464 {} \;
</code>
Comment: Appreciate the script above (pkhamre) but no luck for me with wp-content/uploads on the equivalent in CentOS. I created my own www-data, since that is not default on CentOS-apache.
useradd --system www-data cd wp-content/uploads; chown -R www-data:www-data . usermod -a -G www-data apache //thinking I'm going to let apache write files with sguid //still in wp-content... find . -type d -exec chmod 2575 {} \; find . -type f -exec chmod 0464 {} \; I also tried chmod 3575 on the directories as this sets sticky as well as setgid ...no luck, meaning wordpress still fails to upload media. Any ideas?
Answer: The principle of least privilege applies.  Only give users the rights they need and no more.
In this case, if apache is only serving up pages, give the user acct no rights to edit.  Possible risks include: changing file content or uploading new one; adding executable code to files, etc.  These risks exists regardless of whether it is a single site up multiples.  If the application has a need to edit a specific file, restrict permissions changes to that file.
Answer: I wouldn't see why not. If there is one site, this should be ok. But do mind you might want to grant read only to some files. (well whitelist if they need write access :) )
Answer: Even if you have only one website, compromising apache user will enable the hacker to change the files under <code>/var/www</code> if the folder is writable by apache user.
Comment: You can change only the needed folders such as the folders that need to get uploaded files.
Comment: What if certain folders of my site need write access? Would you just change the ownership to www-data on those specific folders, leaving everything else as owned by a web developer account/root?


Scala - Abstract message handlers with Generic parameters

Question: I'm using Scala with AWS lambdas, handling different types of events. Each 'Handler' class is a different lambda handler and will only be used for one type of message, but to share common handling code, I'm pulling stuff up into abstract classes + traits
When the time comes to hand off processing specific to each message type to the subclass, I end up with an abstract method and I still need to do a pattern match on the type of the message, always logging some sort of error if the wrong type of message makes it into the handler subtype.
These default cases seem redundant as the wrong type of message will never get to the wrong handler subtypes.
This is a simplified version of what I've got
trait Message {
    val text: String
}

case class MessageA(text: String, errorCode: Int) extends Message
case class MessageB(text: String, url: String) extends Message

abstract class MessageHandler {
  protected def processMessage(message: Message)

  ...
}

//Lambda handler 1
class MessageAHandler extends MessageHandler {

  override protected def processMessage(message: Message) = message match {
    case a: MessageA => handleErrorCode(a.errorCode)
    case _ => //log some error - This should never be reached
  }

  ...
}

//Lambda handler 2
class MessageBHandler extends MessageHandler {
  override protected def processMessage(message: Message) = message match {
    case b: MessageB => handleUrl(b.url)
    case _ => //log some error - This should never be reached
  }

  ...
}

I've tried to implement the processMessage call with Type bounds, but this doesn't seem to make much difference, I still need to pattern match on 'M' to determine the Subtype of the message parameter, so it can be treated as such.

  protected def processMessage[M <: Message](message: M)

Has anyone had to do anything similar and is there a cleaner way to do this?
Answer: You can keep the Message type abstract in the base type:
abstract class MessageHandler {
  type Msg <: Message
  protected def processMessage(message: Msg)
}

class MessageAHandler extends MessageHandler {
  type Msg = MessageA
  protected def processMessage(message: MessageA) =
    handleErrorCode(message.errorCode)
}

But I'm not sure whether this will then be easy to handle from the call-site (the code calling processMessage). Potentially the pattern match just moves there (but would probably still be more elegant overall).
Comment: Thanks, this helped a lot. I was looking at  Abstract Types but hadn't actually tried it yet. I managed to do it without the pattern matching moving up in to the call-site by pulling the calling code down into the sub classes. It still  ends up cleaner and more elegant than before.
Answer: You can make use of inheritance here. Put the code to handle the message inside of your trait, and let polymorphism do the work for you.
trait Message {
  val text: String
  def handleMessage
}

case class MessageA(text: String, errorCode: Int) extends Message
{
  override def handleMessage = handleErrorCode(errorCode)
}

case class MessageB(text: String, url: String) extends Message
{
  override def handleMessage = handleUrl(url)
}

case object MessageHandler
{
  def processMessage(message: Message) = message.handleMessage
}

Comment: This is a good suggestion, and normally I would take it, however, the message case classes are used for JSON deserialisation (circe) and I'd prefer to keep handler code out of them. That said, I have partially used your suggestion so thank you


$f(x)$ is uniformly continuous $\Rightarrow f'(x)$ is uniformly continuous

Question: $f(x)$ is uniformly continuous $\Rightarrow f'(x)$ is uniformly continuous
I've encountered with an example which is basing on this statement.
Is this statement true?
Comment: Did you tried to find any counter example?
Comment: Your question is missing crucial information, e.g.: Is $f$ a real-valued function of a real variable? Are you assuming $f$ is differentiable everywhere?
Comment: I believe $f(x)=x^2\sin(1/x)$, $x\ne0$; $f(0)=0$ is a counterexample ($f'$ isn't even continuous).
Answer: what about $F(t)=\int^t_0 \sin(x^2) dx\,$
Answer: Hint: Any continuous function defined on a compact set is uniformly continuous.
Comment: $f'$ need not be continuous.
Comment: @DavidMitra, sorry but what is the idea behind your comment. I post this hint, so Op can see the possibility of a continuous function with discontinuous derivative. Maybe I misunderstood the question?
Answer: Try $f(x) = \sqrt{x}$ on $(0,1)$.


Proof by contradiction. Statement negation

Question: This should be an easy question. Yet, the provided solution confuses me.
The question comes from "Understanding analysis" by S. Abbot, 2nd edition (Exercise 1.2.11).

Negate the statement. Make an intuitive guess as to whether the claim or its negation is the true statement.

(b) There exists a real number $x > 0$ such that $x < 1/n\;\;\forall n \in \mathbb{N}$.

The provided solution says:

The solution seems correct, apart from: shouldn't the negation be with $\exists n \in \mathbb{N}$, i.e.:
$$\forall x >0 \;\; \exists n \in \mathbb{N}: x \geq 1/n$$
?
Comment: The statement given is false, so it cannot be proved, not by contradiction nor by any other method. Your negation of the statement is correct, and is therefore a true statement.
Comment: The solution that you quote is a flawed attempt at a proof of a true statement, that is not the same as the true statement that you correctly give as the negation of the statement given in the question. The flaw in the purported proof is that "for all n" should be "there exists n".
Comment: You are welcome ! The statement given in the question is false, and therefore it implies ANY statement, whether the latter is true or false (implication is false only when the hypothesis is true and the conclusion false). The negation of the statement given in the question is true, and can be used to prove the other true statement (the one in the solution), as follows: By the hypothesis, there exists m in N such that 1/m <= 1/n. Let x=1/(2m). Then x < 1/n. About your last sentence - in general, the contrapositive of a true implication need not be true. I'm not an expert in logic though !
Comment: I suspect that you have made a mistake in transcribing the problem from the book, or else that it is a typo in the book.
Comment: The statement has been correctly transcribed from the book.
Comment: Thank you for the link in your comment below. Indeed you have transcribed the statement correctly, but the question is not "Provide a proof by contradiction for" the statement, it is simply to negate the statement and put your answer in a "positive" form, and then to make an educated guess as to which of the statement and its negation is true.
Comment: Yes, I just wanted to contrast that with the solution, which gives a proof by contradiction.
Comment: You are right, thank you for clarifying that.
Question: the statement given in the question implies the statement which is proven. Right?
This means that if the former is true, the latter is true as well. Does it also mean that if the former is false then the latter is not necessarily false?
Comment: @Sandy Ursu: your negation is correct. The author just does a proof by contradiction to show that for all $n$ there exists an $x>0$ such that $x < \frac {1}{n} $
Answer: This is why putting quantifiers at the end of a formula is a bad practice. It creates ambiguity. The statements

$(\forall n \in \mathbb{N})(\exists x > 0)(x < \frac{1}{n})$
$(\exists x > 0)(\forall n \in \mathbb{N})(x < \frac{1}{n})$

are not equivalent. The second one is obviously false, however it's more likely to interpret your formulation as the second statement. Undoubtedly, the first statement is what's actually meant. For proving by contradiction, we need its negation which goes as follows:
$$(\exists n \in \mathbb{N})(\forall x > 0)\left(x \ge \frac{1}{n}\right)$$
Comment: @AaronStevens I suppose you mean lower. (2) is false, yes. But I meant in general, statements of the form $\exists x \;\forall y \;P(x,y)$ imply $\forall y \;\exists x \; P(x,y)$.
Comment: The second statement (which is the one from the question) implies the first one (which is the one from the provided solution).
Comment: Only because the second statement is false, and a false statement implies any statement.
Comment: If (2) were true it would still imply (1), no?
Comment: @SanduUrsu Think of the second statement. Can you really find a real number $x>0$  that is larger than every possible $1/n$?
Comment: @SanduUrsu Oh I see. Yes I think you are right.
Answer: Regarding Ex.1.2.11 (b) :

Form the logical negation of [...] there exists a real number $x > 0$ such that  $x < \dfrac 1 n$ for all $n \in \mathbb N$,

the formula to be negated is :

$\exists x > 0 \ \forall n \in \mathbb N \ (x < \dfrac 1 n)$.

Thus, tou are right. The correct negation will be :

$\forall x > 0 \ \exists n \in \mathbb N \ (x \ge \dfrac 1 n)$.

But in the solution provided, the author exhibits a proof of the statement; from this, we have to assume that the formula above is not what the author alludes to.
We have instead to transalte the semi-formal statement with :

$\forall n \in \mathbb N  \ \exists x > 0 \ (x < \dfrac 1 n)$

which is true.
Its negation will then be : $\exists n \in \mathbb N  \ \forall x > 0 \ (x \ge \dfrac 1 n)$.
Comment: Exercise 1.2.11 [here](https://books.google.it/books?id=p1t1CQAAQBAJ&pg=PA13#v=onepage&q&f=false)
Comment: Is this in the 2nd edition of the book? (I've just edited my description to mention that)
Answer:

There exists a real number $x > 0$ such that $x < 1/n\;\;\forall n \in \mathbb{N}$.

Is this statement really valid? Let's check.
$nx<1 \;\;\forall n\in\mathbb{N}$ is valid only for $x\leq 0$.
(Because $n$ becomes very large, and if $x\gt 0$ then $nx$ diverges to infinity)
So there is no such $x$ exist.
Comment: @AaronStevens yes absolutely. See the last line of my answer.
Comment: @AaronStevens is $x$ exist? How long  $x$ close to $0$?
Comment: You should note that carefully..... We are working on **For all n in N**
Comment: @AaronStevens Here $n$ is not fixed. We are going to find a positive $x$ which is strictly less than $1/n$ for every $n$.
Comment: ${1,1/2,1/3,1/4,...}$. What is the infimum of this collection?
Comment: I see the issue. Your interpretation of the ambiguous statement is different than the intention. Look at the solution provided.
Comment: Question has been edited. I have post the answer before the edit.
Comment: @AvinashN argues that the statement is false. This is relevant to the question. The negation would be true. If one would attempt to prove the negation by contradiction, again, he could use these arguments.


Difference between Welch Two Sample t-test and Two Sample t-test

Question: I would like to compare two means
I have the following variables
group variable (IND)

12 (161 observations)
17 (151 observations)

output variable (pv1)

scale from 1 to 5

I am working with R
one test is a Welch two sample t-test and the other test is a two Sample t-test
The output is slightly different. I've never heard of a Welch two sample t-test. Which test should I use?
data=read.csv("teilzeitarbeit.csv",header=T,sep=";")

t.test(data$pv1~data$IND)

t.test(data$pv1~data$IND, var.equal=TRUE, data=data)

Sorry, I don't know why you can't see the tilde and dollar sign.
Comment: What are 12 and 17?
Comment: In order to get lines of `code`, put four blank spaces at the start of each line.
If using \$ for money and not to begin 'math mode' type `\$`. In math expressions (between \$-signs), use `\sim` to get $\sim$.
Comment: Should your code look like this: `t.test(data$pv1 ~ data$IND)`?
Answer: The pooled two-sample t-test must be used only when you 'know' that
the two populations have equal variances. You can 'know' because of prior
experience with similar data or because you're really sure of a model for
the data. [For example, that might occur when variance is almost completely due to
instrument error and the same instrumentation has been used for both groups.]
However that 'knowing' should not be because you did a test for equal variances. There are
several reasons for this prohibition, probably the most important of which is that
variance tests have poor power and can give misleading results. [Based on simulation studies, the use of
a test for equal variances as a 'screening test' to decide between pooled
and Welch t tests has been deprecated.]
If you use a pooled 2-sample t test when the two populations have
substantially different variances, especially if the sample size is
smaller for the group with the larger variance, you are likely to
get 'false rejections' even when the two population means are equal.
In the following example, sample 1 with $n_1=15$ is from $\mathsf{Norm}(\mu_1 = 100, \sigma_1=20)$
and sample 2 with $n_2=50$ is from $\mathsf{Norm}(\mu_2 = 100, \sigma_1=5).$ And we are testing
$H_0: \mu_1 = \mu_2$ vs. $H_a: \mu_1 \ne \mu_2$ at the 5% level. But a pooled t test
falsely rejects $H_0$ with a P-value below 1%.
set.seed(4)
x1 = rnorm(15, 100, 20)
x2 = rnorm(50, 100, 5)
t.test(x1, x2, var.eq=T)$p.val  # pooled
[1] 0.004382463

Of course, the 5% significance level
anticipates that this kind of error will happen about 5% of the time. But
when variances are unequal as in this example, false rejection or 'false discovery'
happens very much more frequently than anticipated. [See Note (2) at end.]
By contrast, the Welch 2-sample t test does not require the two groups
to have the same variance. If we use the same data as before, we see that the Welch 2-sample t test does not
reject $H_0$ at the 5% level.
t.test(x1, x2)$p.val   # Welch
[1] 0.09780939

It is considered good statistical practice always to use the Welch 2-sample t test
in preference to the pooed test, unless you have reliable advance knowledge
that the two populations have essentially the same variance. In R, and many other statistical software
programs, the Welch test is the 'default', so you have to so something extra
to tell the software to use the pooled test. [In R, the extra step is to include
the parameter var.eq=T in the t.test procedure.]

Notes:
(1) If the two population means are truly different, the Welch t test has about
the same power (probability of rejecting when $H_0$ is false) as does the pooled t test. So there is seldom any downside to using the Welch t test.
set.seed(5)
x1 = rnorm(15, 95, 20)         # Null hypothesis false
x2 = rnorm(50, 110, 5)
t.test(x1, x2)$p.val
[1] 0.001372652                # Welch t rejects

(2) A simulation shows that when sample sizes and population variances are
as in the beginning examples and $H_0$ is true, then the pooled test
(falsely) rejects about 25% of the time (instead of expected 5%).
pv = replicate(10^6, t.test(rnorm(15,100,20),
                            rnorm(50,100,5),var.eq=T)$p.val)
mean(pv <= 0.05)
[1] 0.252237

However, in these same circumstances, the Welch test rejects 5% of
the time at the 5% level, as it should.
set.seed(2020)
pv = replicate(10^6, t.test(rnorm(15,100,20), rnorm(50,100,5))$p.val)
mean(pv <= 0.05)
[1] 0.050142

(3) Both t tests assume that we have two independent random samples and that data are normal. Both tests are somewhat robust if data are not exactly normally distributed. The major difference between the pooled and Welch tests
is that the Welch test behaves as it should even when population variances
are unequal.
Answer: I recommend using the data = ... argument inside of the t.test() function to avoid redundancies in your code. For example, this saves you extra keystrokes:
# --- Welch t procedure

t.test(pv1 ~ IND, data = data)

# --- Pooled-variance t procedure

t.test(pv1 ~ IND, var.equal = TRUE, data = data)

Your first run does not specify the argument var.equal = ... inside of the t.test() function. As a result, it will default to the Welch-Satterthwaite approximation to the degrees of freedom. This is a degrees of freedom adjustment when the variances are not equal. Your second run, however, explicitly includes var.equal = TRUE, which uses the pooled-variance $t$ procedure.
We usually make the following assumptions when performing a two-sample $t$-test:

Independent random samples (or a randomized experiment)
Normally distributed populations (though not very important with large sample sizes)
Equal population variances: $\sigma^{2}_{1} = \sigma^{2}_{2}$

The Welch $t$ procedure is very similar to the pooled-variance $t$ procedure. But unlike the pooled-variance $t$ procedure, the Welch $t$ procedure does not require the assumption of equal population variances. As a consequence, Welch procedures have a different standard error and degrees of freedom than the pooled-variance $t$ procedure. Because the Welch (unpooled variance) $t$-test does not make assumptions with respect to equality of the variances, it can be used in a wider variety of situations.
Comment: My output for the Welch two sample t-test says that df=307.74. Why is it not 150 since the smaller population is 151? I though it is df=min{n1,n2}.
Comment: The Welch procedure does not simply take the minimum of the two groups. Was that referenced somewhere?


Prove that a set is countable if the sup of the sum of its finite subsets is finite.

Question: Let $A$ be an infinite set of positive real numbers. Define $S := \sup_{B \in \mathcal{B}}\sum_{x\in B}x$, where $\mathcal{B}$ is the collection of all finite subsets of $A$. I want to show that $A$ is countable if $S < \infty$.
Since $S < \infty$, for all $\epsilon > 0$, there exists a finite subset $B$ of $A$ such that $S - \epsilon < \sum_{x \in B} x < S$. My ultimate idea is to show that $A_n := A \cap (1/n, \infty)$ is finite and therefore $A = \cup_n A_n$ is countable. But it is not clear to me that the existence of such an finite subset $B$ implies that $A_n$ is finite. Is there something I am missing? Thanks in advance!
Comment: Maybe you could just show directly that $A_n$ is finite by showing that $|A_n|\le nS$?
Comment: Could you elaborate a bit on why this is true?
Comment: You want me to elaborate on why I think that, if I have more than $nS$ numbers, and each of those numbers is bigger than $1/n$, then the sum will be bigger than $S$? Sorry, I can't explain it, it's just a hunch I have. That's why I said "maybe" in my previous comment.
Comment: @bof I just have a quick question. If $A_n$ contains infinitely many elements, then is it okay if their sum is greater than $S$? Your reasoning seems to be based on the assumption that $A_n$ is a finite subset, but isn't this what I'm trying to show there?
Answer: $\sum_{x \in A_n} x \leq S$. But $x \in A_n$ implies $x >\frac 1 n$ so $\sum_{x \in A_n} x >\frac  1n Card(A_n)$. So we get $Card (A_n) \leq nS$. In poarticular, $Card (A_n) <\infty$ for each $n$. Since $A =\bigcup A_n$ we are done.
Comment: I see! Thank you very much!
Comment: Just a quick question. Can I use $\sum_{x\in A_n} x \le S$ if I do not know whether $A_n$ is finite or not? Since $S$ is the sup of the sum of elements of finite subsets, the argument seems a bit circular.
Comment: @InsultedByMathematics If $A$ is an infinite set, then for any natural number $k$, there is a subset of $A$ with exactly $k$ elements. (You can prove that by induction on $k$.) In particular, in the case at hand, $A$ has a finite sebset with more than $nS$ elements.
Comment: @InsultedByMathematics If every finite subset of $A_n$ has cardinality at most $nS$ then $A_n$ has to be a finite set with at most $nS$ elements.
Comment: @geetha290krm I see! This answers my question. So the proof technically should with "consider an arbitrary finite subset of $A_n$ ... "?


unterminated string literal

Question: The following code:
var str= "English Comprehension<\/strong>

  Synonyms/Antonyms/Word Meaning (Vocabulary)<\/li>

  Complete the Sentence (Grammar)<\/li>

  Spot error/Correct sentence (Grammar/sentence construction)<\/li>

  Sentence Ordering (Comprehension skills)<\/li>

  Questions based on passage (Comprehension skills)<\/li>
                    <\/ul>

";

Gives the error: "unterminated string literal". Whats the problem?
Comment: Why do you have `\/` in your code? A slash is not a special character. It does not need to be escaped.
Comment: Related: https://stackoverflow.com/questions/1659749/script-tag-in-javascript-string
Answer: You can't split a string across lines like that in javascript. You could accomplish the same readability by making each line a separate string and concatenating them with the plus sign like so:
var str = "English Comprehension"
    + "
"
    + "
"
    + "
Synonyms/Antonyms/Word Meaning (Vocabulary)
"

and so on...
Answer: If using multiline string in JavaScript you must use '\' in the end of each line:
var str = "abc\
def\
ghi\
jkl";

Also beware extra whitespace if your code is indented.
Answer: I suggest to do it differently... have hidden element with that HTML e.g.

English Comprehension

...

Then simply read its inner HTML:
var str = document.getElementById("myHiddenDiv").innerHTML;

The big advantage is that you won't have to fight your way with literal strings and it's much easier to edit, the downside is that you add another element to the DOM. Your choice. :)
Comment: Cheers @VIKASH, feel free to Accept the answer in such a case by clicking the "V" icon to the left.. same for your other questions - accepting the correct answers is how this place works. :)
Comment: eventually i did it using your method. Using Jquery.
Answer: It is not a best practice to write multiline strings in Javascript.
But, you can do that with the \ terminator:
var str= "English Comprehension<\/strong>\

\

\

  Synonyms/Antonyms/Word Meaning (Vocabulary)<\/li>\

  Complete the Sentence (Grammar)<\/li>\

  Spot error/Correct sentence (Grammar/sentence construction)<\/li>\

  Sentence Ordering (Comprehension skills)<\/li>\

  Questions based on passage (Comprehension skills)<\/li>\
                <\/ul>\

";

Note that trailing spaces are part of the string, so it is better to get rid of them, unless they are intentional:
var str= "English Comprehension<\/strong>\

\

\

  Synonyms/Antonyms/Word Meaning (Vocabulary)<\/li>\

  Complete the Sentence (Grammar)<\/li>\

  Spot error/Correct sentence (Grammar/sentence construction)<\/li>\

  Sentence Ordering (Comprehension skills)<\/li>\

  Questions based on passage (Comprehension skills)<\/li>\
<\/ul>\

";

Answer: A good way to concatenate strings in javascript is fallowing:
var stringBuilder = [];

stringBuilder.push("English Comprehension");
stringBuilder.push("
");
stringBuilder.push("
");
...
var resultString = stringBuilder.join("");

This method faster than
var str = "a"+"b" +"c"

Comment: Interesting trick, though in the original code there's no string concatenation.
Answer: JavaScript doesn't allow literal line breaks in strings unless you escape them with \:
var str= "English Comprehension<\/strong>\

\

\

  Synonyms/Antonyms/Word Meaning (Vocabulary)<\/li>\

  Complete the Sentence (Grammar)<\/li>\

  Spot error/Correct sentence (Grammar/sentence construction)<\/li>\

  Sentence Ordering (Comprehension skills)<\/li>\

  Questions based on passage (Comprehension skills)<\/li>\
    <\/ul>\

";

You might look at ES2015+ template literals instead, which use backticks instead of ' or " and allow literal line breaks:
var str= `English Comprehension<\/strong>

  Synonyms/Antonyms/Word Meaning (Vocabulary)<\/li>

  Complete the Sentence (Grammar)<\/li>

  Spot error/Correct sentence (Grammar/sentence construction)<\/li>

  Sentence Ordering (Comprehension skills)<\/li>

  Questions based on passage (Comprehension skills)<\/li>
    <\/ul>

`;

But of course, that only works on ES2015-compatible JavaScript engines (or if you transpile).
Note that within a template literal ${...} has special meaning (allowing you to substitute the result of any expression:
let v = "Ma";
console.log(`Look ${v}, no hands!`); // Look Ma, no hands!

Answer: Remove the newlines, it will work. GOTCHA to keep in mind ;)
See it simple works all fine here without newlines:
http://jsfiddle.net/87dYh/
var str= "English Comprehension<\/strong>

  Synonyms/Antonyms/Word Meaning (Vocabulary)<\/li>
  Complete the Sentence (Grammar)<\/li>
  Spot error/Correct sentence (Grammar/sentence construction)<\/li>
  Sentence Ordering (Comprehension skills)<\/li>
  Questions based on passage (Comprehension skills)<\/li>                 <\/ul>
";

alert(str);

Answer: If you want to maintain your data in one block of string, try:
var str= "English Comprehension\n\

\n\

\n\

  Synonyms/Antonyms/Word Meaning (Vocabulary)
\n\

  Complete the Sentence (Grammar)
\n\

  Spot error/Correct sentence (Grammar/sentence construction)
\n\

  Sentence Ordering (Comprehension skills)
\n\

  Questions based on passage (Comprehension skills)
\n\

\n\

";

notice the \n\ at the end of each line.
Answer: My code was a response.write() where I needed to insert html to be outputted POST SUbmit on a form within an Iframe.  When copying my code over from an text editor the carraige return carried over into the code window.  Once I deleted my returns and whitespace between tags so that the code looked like a block paragraph that fixed the issue:
("loremIPSUM.

Title

loremIPSUM:

lnk1

loremIPSUMlnk2

loremIPSUM

IF THE case id is: ""+value)

unterminated string literal


How to do autocomplete in a Bootstrap modal form?

Question: I've got a D7 page that constructs a Twitter Bootstrap modal form; it appears in response to a click on a button on the page.  I'd like to have in that form a textfield that uses the standard Drupal autocomplete mechanism; the problem is that the textfield isn't getting properly hooked into the autocomplete system.  I'm loading the Bootstrap versions of misc/ajax.js and misc/autocomplete.js into the page with drupal_add_js() so that they'll be around if the modal is invoked, but all the attached behaviors in autocomplete.js aren't getting invoked when the modal form is constructed and presented, and so the textfield stays a regular textfield.  Or so I think, anyway -- I'm kinda out of my depth here.
I suppose I could roll my own ajax code for the field, but the basic autocomplete behavior is so obviously the right thing that it ought to be used.  Any advice out there?  Thanks!
Comment: You can always call `Drupal.attachBehaviors();` to get Drupal's js api kickstarted
Answer: Drupal's JS is powered by behaviors. If you find yourself in a situation where you need to poke the system into life, you can manually attach the behaviors like so:
<code>Drupal.attachBehaviors();
</code>
Comment: This works nicely, as noted above.  For future visitors, I also had to add a call like `"drupal_add_library('system', 'drupal.autocomplete')"` along with the drupal_add_js's.


Dividir Array em várias Threads

Question: Preciso fazer uma Query em meu Banco de dados, que retornará cada uma das Linhas. No entanto, para cada uma delas, durante o Retorno, preciso aguardar cerca de 5 segundos, pois é o tempo que preciso esperar para o Ping concluir e me retornar se o Host está ou não de pé.
@GetMapping
public Iterable<MonitoriaEntidade> resposta() throws UnknownHostException, IOException{

    Iterable<MonitoriaEntidade> findAll = monitoriaRepositorio.findAll();

    for (MonitoriaEntidade monitoriaEntidade : findAll) {
        if (InetAddress.getByName(monitoriaEntidade.getIp()).isReachable(5000)) monitoriaEntidade.setStatus(true);
    }

    return findAll;
}

Minha dúvida, é: Como faço para separar essa Query em várias Threads diferentes, para que eu não faça apenas uma de cada vez, mas, de preferência, o quanto o Servidor conseguir.
Comment: @StatelessDev, para a parte em threads, creio que seja melhor mesmo é usar `parallelStream`. Isso evita você, como programador, ter de lidar explicitamente com o paralelismo, quando esse paralelismo em específico tem todo o jeito de ser totalmente não concorrente. Parece-me um típico cenário que só preciso esperar pelos `joins` das threads
Comment: Você tem que ter um pool de conexões com o banco, ou seja, cada _thread_ vai ter que separadamente fazer a sua chamada para o banco e fazer a pesquisa, já que cada conexão suporta apenas um objeto (a chamada). Quanto às _threads_, pesquise por `ExecutorService`, que é uma API _core_ do Java para lidar com um _pool_ de _threads_ de maneira assíncrona. Dê uma olhada em `CompletableFuture` também, que é para o retorno assíncrono do seu método (a sua busca) ser armazenado e manipulado.
Answer: Você pode fazer através de uma stream em paralelo. Mas, para tal, primeiro se faz necessário "esconder" a exceção para uma RuntimeException (leia mais).
Vamos por uma RTE que carregue UnknownHostException ou IOException, para usá-la dentro da expressão lambda:
class WrapperException extends RuntimeException {
    final UnknownHostException uhe;
    final IOException ioe;

    WrapperException(UnknownHostException uhe) {
      super(uhe);
      this.uhe = uhe;
      this.ioe = null;
    }

    WrapperException(IOException ioe) {
      super(ioe);
      this.uhe = null;
      this.ioe = ioe;
    }

    void throwWrappedException() throws UnknownHostException, IOException {
      if (this.uhe != null) throw uhe;
      if (this.ioe != null) throw ioe;
    }
}

Agora, vamos transformar a parte interna do seu laço em um método que não lance exceção checadas, que as transforme em WrapperException:
void setStatusMonitoriaEntidade(MonitoriaEntidade monitoriaEntidade) {
  try {
    if (InetAddress.getByName(monitoriaEntidade.getIp()).isReachable(5000)) {
      monitoriaEntidade.setStatus(true);
    }
  } catch (IOException e) {
    throw new WrapperException(e);
  } catch (UnknownHostException e) {
    throw new WrapperException(e);
  }
}

Então, se hipoteticamente o método findAll retornasse uma Collection (como uma List), podemos transformar esse laço for em um parallelStream:
@GetMapping
public List<MonitoriaEntidade> resposta() throws UnknownHostException, IOException {
    List<MonitoriaEntidade> findAll = monitoriaRepositorio.findAll();

    try {
      findAll.parallelStream().forEach(this::setStatusMonitoriaEntidade);
    } catch (WrapperException e) {
      // se um dos processamentos der ruim, lança a exceção; mesmo comportamento anterior
      e.throwWrappedException();
    }

    return findAll;
}

Em meus experimentos (não encontrei a documentação oficial sobre o assunto), fazer essas chamadas através de parallelStream usa o máximo de núcleos disponíveis para processamento, mas não cria threads além do que pode de fato ser consumido.
Em compensação, não é o caso, como você me lembrou. Entretanto, quase nada está perdido. Tem um ótimo artigo do Baeldung sobre o assunto. Ele resolve isso usando StreamSupport:
@GetMapping
public Iterable<MonitoriaEntidade> resposta() throws UnknownHostException, IOException {
    Iterable<MonitoriaEntidade> findAll = monitoriaRepositorio.findAll();

    try {
      StreamSupport.stream(findAll.spliterator(), true).forEach(this::setStatusMonitoriaEntidade);
    } catch (WrapperException e) {
      // se um dos processamentos der ruim, lança a exceção; mesmo comportamento anterior
      e.throwWrappedException();
    }

    return findAll;
}

Comment: Excelente, Jefferson. Apenas um detalhe bobo que você certamente sabe: dá para usar o operador lógico `|` no `catch`, pegando as duas exceções e economizando um `catch` e um `throw` com isso.
Comment: @StatelessDev eu só quis garantir a chamada correta do construtor. Como escrevi isto sem estar em um computador, fiquei com dúvidas se o `javac` conseguiria resolver corretamente qual dos construtores chamar, então preferi ser explícito. Eu não sei qual vai ser o tipo de `e` usando o `multi-catch` quando for resolver qual construtor chamar...
Comment: @FernandoCampanate perdão minha displicência, juro que tinha visto `Collection` ou `List`. Você precisa transformar numa `Stream` e paralelizar. Vou editar a resposta
Comment: O problema que estou tendo, é que o Método parallelStream() não está disponível no Iterable, o que eu preciso fazer para poder usá-lo?
Comment: @FernandoCampanate como você voltou a marcar minha resposta como aceita, estou julgando que deram certo seus testes. Confere? Se restou qualquer dúvida sobre as coisas nesta resposta, ou se tiver algo na sua dúvida ainda não contemplado, pode por aqui que tentarei complementar a resposta
Comment: Consegui implementar o que você falou, mas ainda estou tentando fazer funcionar. Pois antes eu não estava usando o Lambda, assim que tiver uma conclusão, te respondo aqui.
Comment: FUNCIONOU!!! E extremamente rápido!

Dividir Array em várias Threads


`@post.userview.users << current_user`

Question: Every post has a userview, and each userview has many users. I want one single many to many to have a simple .add() and .remove() function like django. How do I place the current_user into the many-to-many relationship of the views?
I found this:
@post.userview.users << current_user

But it brings up some SQL error. It's suggesting I add a post_id:
ERROR:  column userviews.post_id does not exist
LINE 1: SELECT  "userviews".* FROM "userviews" WHERE "userviews"."po...
                                                     ^
HINT:  Perhaps you meant to reference the column "userviews.posts_id".

After the answer, now the error is:
can't write unknown attribute `userview_id`

Because I changed the migrations around a little, userview has references to posts and users. Post has_one userview, has_many users through userview, userview has_many posts and has_many users.
create_table "posts", force: :cascade do |t|
    t.integer "userview_id"
    t.bigint "userviews_id"
    t.index ["userviews_id"], name: "index_posts_on_userviews_id"
  end

create_table "userviews", force: :cascade do |t|
    t.bigint "users_id"
    t.bigint "posts_id"
    t.integer "post_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["posts_id"], name: "index_userviews_on_posts_id"
    t.index ["users_id"], name: "index_userviews_on_users_id"
  end

class User < ActiveRecord::Base
  has_many :viewed_posts, through: :userview, class_name: 'Post'
...

class Userview < ApplicationRecord
    belongs_to :post
    belongs_to :user
end

class Post < ApplicationRecord
    belongs_to :user
    has_many :userviews
    has_many :viewers, through: :userview, class_name: 'User'
...

Could not find the source association(s) "viewer" or :viewers in model Userview. Try 'has_many :viewers, :through => :userviews, :source => <name>'. Is it one of post or user?

Although, that's for unless @post.viewers.include?(current_user)
Comment: Looks like you have some errors in your associations. Please, add `schema.rb` and models files to the question
Comment: @Vasilisa updated
Comment: And please users table in schema, and User, Userview and Post models (app/models/user.rb etc)
Answer: Not sure if I understood correctly what are you trying to achieve, but I'll try to fix your associations.
To associate 2 models you need to store foreign key in one of them. Model which stores the key belongs_to other model. Eg in posts table you have user_id column, it means Post belongs_to: user and User has_many :posts (or has_one :post if you need one-to-one association). For such association you can write:
user = User.first
post = Post.last
user.posts << post

If you want all this stuff to work automatically you should follow the convention about naming. Foreign keys should be in singular form, like user_id, not users_id
If you want many-to-many association you need to create an intermediate table, which stores both foreign keys. It can be done using simple direct has_and_belongs_to_many association or with more complex has_many through:
I suppose that in your case it should be:
class User < ActiveRecord::Base
  has_many :userviews
  # it is posts viewed by the user
  # you need to specify class name because it differs from association name
  has_many :viewed_posts, through: :userviews, class_name: 'Post'

  # posts written by the user
  has_many :posts
end

class Userview < ApplicationRecord
  belongs_to :post
  belongs_to :user
end

class Post < ApplicationRecord
  belongs_to :user
  has_many :userviews
  has_many :viewers, through: :userviews, source: :user
end

It means that you need post_id and user_id columns in userviews table and user_id in posts table. Please, remove useless columns and add needed in migration. When you set it all correctly you'll be able to do
@post.viewers << current_user

to add current_user to viewers list. Corresponding userview instance is created automagically
Comment: Thank you, that's really close to it, but getting the following error, I'll update.
Comment: Do I need t.references :users in the posts for the viewers?
Comment: @AdenHandasyde happy to help you! Updated my answer,  I was in a hurry and made a mistake about `source`. Great, that you solved the error yourself. You don't need ` t.references :users` in the posts for the viewers, all needed references are inside `userviews` table
Answer: Changed has_many :viewers, through: :userviews, class_name: 'User'
to has_many :viewers, through: :userviews, source: :user

`@post.userview.users << current_user`


Converting .OVA-formatted VM to Hyper-V

Question: I am struggling with importing an .OVA VM into my Hyper-V infrastructure.
I managed to extract the .ova file using tar which yields three fiels - .ovf .mf and .vmdk. The .mf-contained SHA1 sums matched the .vmdk file. The .vmdk seems to be in the stream-optimized format in version 9 according to the data contained in the ovf and the .vmdk file's contents:
createType="streamOptimized"

# Extent description
RDONLY 104857600 SPARSE "generated-stream.vmdk"

I tried VirtualBox' VBoxManage to perform the conversion, but without success:
# VBoxManage clonehd --format VHD MyVM-disk1.vmdk MyVM.vhd
/usr/lib/virtualbox/VBoxManage: /usr/lib/vmware-vix-disklib/lib64/libcurl.so.4: no version information available (required by /usr/lib/virtualbox/VBoxRT.so)
0%...
Progress state: VBOX_E_FILE_ERROR
VBoxManage: error: Failed to clone hard disk. Error message: Could not open the medium storage unit '/home/dj/MyVM-disk1.vmdk'.
VBoxManage: error: VMDK: incorrect ordering of entries in descriptor in '/home/dj/MyVM-disk1.vmdk' (VERR_VD_VMDK_INVALID_HEADER).
VBoxManage: error: VD: error VERR_VD_VMDK_INVALID_HEADER opening image file '/home/dj/MyVM-disk1.vmdk' (VERR_VD_VMDK_INVALID_HEADER)

My vSphere hosts would not accept the .vmdk for a valid disk too, so I tried converting it to growable using vmware-vdiskmanager from the 5.1.1 VDDK which is available from the VMWare site. Yet, this also did not work out as intended:
# vmware-vdiskmanager -r ./myVM-disk1.vmdk -t 0 ./myVM-growable.vmdk
Creating disk './myVM-growable.vmdk'
Failed to convert disk: The file specified is not a virtual disk (0xf00003ebf).

What's wrong here? How do I get it converted / imported properly?
Comment: Did you try qemu-img?
Comment: @JiriXichtkniha I did, but it seems my version (1.0) does not support the `vhd` output format.
Answer: It turns out that it was a mistake using VBoxManage from the VirtualBox package. The call has altered the VMDK and apparently has rendered it invalid. I would not have expected VBoxManage to write to the source file, thus it took a while before I noticed that I am trying to work with a broken virtual disk.

Converting .OVA-formatted VM to Hyper-V