text:
Q: How to validate all fields with different aura:Id? I am trying to validate all fields when the user click's on the submit button.
Issue: I had to maintain different aura: id's for the lightning input elements, due to some other logic needs to be done on every input.
I would like to know how can I validate all elements on click?
Can someone please advise?
Component:
<aura:component implements="forceCommunity:availableForAllPageTypes" access="global" >
    <lightning:input aura:id="fieldId" label="First name" placeholder="First name" required="true" messageWhenValueMissing="Enter FirstName"/>
        <lightning:input aura:id="fieldId" label="Last name" placeholder="Last name" required="true" messageWhenValueMissing="Enter LastName" />
        <lightning:input aura:id="MiddleName" label="Middle name" placeholder="Middle name" required="true" messageWhenValueMissing="Enter Middle" />
        <lightning:button aura:id="submit" type="submit" label="Submit" onclick="{!c.onClick}" />
</aura:component>

Controller :
({
    onClick: function(component, event, helper) {
         console.log("On Click");
       helper.ValidateFirstName(component, event, helper);
       helper.ValidateMiddleName(component, event, helper);
    }
})

Helper :
({
    ValidateFirstName: function(component, event, helper) {
       console.log("On Click helper");
        var allValid = component.find('fieldId').reduce(function (validSoFar, inputCmp) {
            inputCmp.showHelpMessageIfInvalid();
            return validSoFar && !inputCmp.get('v.validity').valueMissing;
        }, true);
   },
    ValidateMiddleName: function(component, event, helper) {
       console.log("On Click Middle Name helper");
        var allValid = component.find('MiddleName').reduce(function (validSoFar, inputCmp) {
            inputCmp.showHelpMessageIfInvalid();
            return validSoFar && !inputCmp.get('v.validity').valueMissing;
        }, true);
   },

})

Thanks in Advance !!!!

A: Instad of using the aura:id to perform validations per field type, use a genric aura:id for all your required fields, such as aura:id='req-fields' and assigning a representative name attribute for your field types, ex. name='MiddleName' this way, you can run your validate method regardless, and instead, check the field name while doing so:
Validate: function(component, event, helper) {
    const fieldName = event.getSource().get("v.name");
    //do your validations based on field name
    ...},

ValidateSubmit: function(component, event, helper) {
    const allReqFields= component.find('req-fields');
    // do your validations for allReqFields which is an array of all
    // components with the specified aura:id
    ...},

you can invoke your validate method with onchange for lightning:input

A: Why would you go for checking all validations using this way. Instead, I would recommend going this way.
Connect Your Lightning input tag with value attribute:
Example :
 <aura:attribute name="firstName" type="String" default="" />

 <lightning:input aura:id="fieldId" label="First name" placeholder="First
       name" required="true" messageWhenValueMissing="Enter FirstName" value =
       "{!v.firstName}"/>

 <lightning:button aura:id="submit" type="submit" label="Submit" onclick="{!c.ValidateSubmit}" />

  ValidateSubmit :  function(component, event) {

     if(component.get('v.showErrorPrimary') || component.get('v.firstName') || component.get('v.LastNameName') || component.get('v.age'){
       // Your error string.
        return true;
    } else {
        return false;
    }
},


text:
Q: How to parse a JSON file into jsonlines with python for GPT-3 fine-tuning I'm trying to parse a json data file into jsonl for GPT-3 fine-tuning.
I'm specifically trying to find out how to merge contents from the same Author ID.
Where user 123 is prompt and user 456 is completion.
The data:
{
  "messages": [
    {
      "content": "hello",
      "author": {
        "id": "123"
      }
    },
    {
      "content": "how are you",
      "author": {
        "id": "123"
      }
    },
    {
      "content": "hey! I'm good",
      "author": {
        "id": "456"
      }
    },
    {
      "content": "That's nice!",
      "author": {
        "id": "123"
      }
    },
    {
      "content": "I'm glad to hear you're doing well.",
      "author": {
        "id": "123"
      }
    },
    {
      "content": "Thank you. what about you?",
      "author": {
        "id": "456"
      }
    }
  ]
}

Output should look like this:
{"prompt": "hello how are you", "completion": "hey! I'm good"}
{"prompt": "That's nice! I'm glad to hear you're doing well.", "completion": "Thank you. what about you?"}

I'm super close to figuring this out. I'll be updating the question if I ever find an answer. Thank you for your time!
My attempt so far.
myjson = {
    "messages": [
        {
            "content": "hello",
            "author": {
                "id": "123"
            }
        },
        {
            "content": "how are you",
            "author": {
                "id": "123"
            }
        },
        {
            "content": "hey! I'm good",
            "author": {
                "id": "456"
            }
        },
        {
            "content": "That's nice!",
            "author": {
                "id": "123"
            }
        },
        {
            "content": "I'm glad to hear you're doing well.",
            "author": {
                "id": "123"
            }
        },
        {
            "content": "Thank you. what about you?",
            "author": {
                "id": "123"
            }
        }
    ]
}
messages = []
for k1, v1 in myjson.items():
    for k2 in v1:
        messages.append((k2["author"]["id"], k2["content"]))
jsons = {}
j = 0
i = 0
while j < len(messages)-1:
    message = ""
    answer = ""
    temp = messages[j][0]
    while j < len(messages)-1 and messages[j][0] == temp:
        message += f"\n{messages[j][1]}"
        j += 1
    temp = messages[j][0]
    while j < len(messages)-1 and messages[j][0] == temp:
        answer += f"\n{messages[j][1]}"
        j += 1
    jsons[i] = {"prompt": message, "completion": answer}
    i += 1
for v1 in jsons.values():
    print(v1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use a library in my struct struct date
{
  int day;
  int month;
  int year;
  void input()
  {
      std::cin>>day>>month>>year;
  }
};

#include<iostream>

main()
{
  date d1;
  d1.input();
}

cin is not working unless iostream is included. But we cannot declare a struct as global unless we define it before main function.
How can I use library functions in my struct.

A: Put the #include <iostream> at the top. This should fix it.
Normally includes are done at the very beginning anyway. This has nothing to do with codeblocks, only c++.


text:
Q: Can the Code Runner extension in VS Code use the selected kernel when running a piece of code? I'm new to programming and I'm setting up setting up Visual Studio Code to start learning some Python. I've got the following setup:

*

*MacOS 10.6.4 (I've got a system Python 2.7.16)

*installed Anaconda ('base' environment with Python 3.9.7 and 'Python310InclCoreDS' environment with Python 3.10.4)

*installed Visual Studio Code 1.66.2

*

*ext: Python 2022.4.1

*ext: Pylance 2022.4.3

*ext: Jupyter Notebook Renderers v1.0.6

*ext: Jupyter Keymap v1.0.0

*ext: Jupyter 2022.3.1000901801

*ext: Code Runner 0.11.7

*ext: Black Formatter v2022.1.11231003

Now I have some trouble understanding the way the Code Runner extension picks it's Python version. See the screenshot below.

*

*Whenever I run a complete regular Python file (.py) the Python kernel picker works as expected and the selected Python version is used. (This scenario is not in the screenshot.)

*Whenever I run a code cell in a Jupyter notebook using the "Execute Cell" button the Jupyter kernel picker works as expected and the selected Python version is used. (This scenario is shown in my screenshot in red.)

*Whenever I select a piece of code using Code Runner in either a regular Python file (.py) or a Jupyter notebook the kernel pickers don't work as expected. I've noticed it will use my system Python 2.7.16 if terminal.integrated.inheritEnv=True. (This scenario is shown in my screenshot in blue.) It will use my Python 3.9.7 Anaconda environment when terminal.integrated.inheritEnv=False. (This scenario is not in the screenshot.)

Now I wonder: can Code Runner when running a piece of code also use the selected kernel (either when executing a piece of a .py file, or when executing a piece of a Jupyter notebook)?
Solution summary
Quick summary of the solution, because part of it is in a comment below. You need to configure the Executor Map of Code Runner as described below. Apart from that, Code Runner always uses the kernel selected in the Python extension, never the one from the Jupyter extension.

A: This should be related to the default Python interpreter used by code-runner, which you can change in setting.json.
You can refer to this page on github for more related information.


text:
Q: Make TableViewColumn not resizeable I've got a TableView with two TableViewColumns and would like to prevent them from being resized.
How can I do this?
TableView {

   TableViewColumn {
      title: "Name"
      width: parent.width - 20
   }

   TableViewColumn {
      width: 18
      delegate: CheckBox {
   }
}

A:   TableViewColumn {
     title: "Name"
     width: parent.width - 20
     resizable: false
  }


text:
Q: symfony contact form is submitted but emails dont arrive I need some help regarding sending emails in symfony 4.
I made a contact form in symfony 4.
where i use formbuilder and swiftmailer. The contact form works, it validates and i can submit. but emails don't arrive plus i don't get a confirmation message on the contactpage itself after sending.
i use mailer with host of the website itself. The website is in production mode.
See below the code i used. Maybe i missed some settings? thanks in advance!
ContactType.php
<?php
// your-path-to-types/ContactType.php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;

class ContactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name',TextType::class);
        $builder->add('email',EmailType::class);
        $builder->add('subject',TextType::class);
        $builder->add('body',TextareaType::class);
    }

    public function getBlockPrefix()
    {
        return 'contact';
    }
}

Contact.php my entity
<?php

// src/Entity/Contact.php

namespace App\Entity;

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Doctrine\Common\Collections\ArrayCollection;

class Contact

{

    protected $name;
    protected $email;
    protected $subject;
    protected $body;
    public function getName()

    {
        return $this->name;
    }

    public function setName($name)

    {
        $this->name = $name;
    }

    public function getEmail()

    {
        return $this->email;
    }

    public function setEmail($email)

    {
        $this->email = $email;
    }

    public function getSubject()

    {
        return $this->subject;
    }

    public function setSubject($subject)

    {
        $this->subject = $subject;
    }

    public function getBody()

    {
        return $this->body;
    }

    public function setBody($body)

    {
        $this->body = $body;

    }

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('name', new NotBlank());

        $metadata->addPropertyConstraint('email', new Email());

        $metadata->addPropertyConstraint('subject', new NotBlank());
        $metadata->addPropertyConstraint('subject', new Length(array('max'=> 50)));

        $metadata->addPropertyConstraint('body', new Length(array('min'=> 5)));
    }

}

and my controller
<?php
namespace App\Controller;

use App\Entity\Contact;
use App\Form\ContactType;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;

final class PagesController extends DefaultController

{

    /**
     * @Route("/contact", name="contact")
     * @Method("GET|POST")
     */
    public function contact(Request $request,  \Swift_Mailer $mailer)
    {

        $enquiry = new Contact();
        $form = $this->createForm(ContactType::class, $enquiry);

         $this->request = $request;
            if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isValid()) {

                        $message = (new \Swift_Message('Hello Email'))
                            ->setFrom('contact@example.com')
                            ->setTo('xxxxxxx@gmail.com')
                            ->setBody($this->renderView('contact/contactEmail.txt.twig', array('enquiry' => $enquiry)));
                        $mailer->send($message);

                    $this->get('session')->getFlashbag('blog-notice', 'Your contact enquiry was successfully sent. Thank you!');

                // Redirect - This is important to prevent users re-posting
                // the form if they refresh the page
                return $this->redirect($this->generateUrl('contact'));

            }
        }

        return $this->render('pages/contact.html.twig', array(
            'form' => $form->createView(),
        ));
    }

}

and in my main.env file i have this
MAILER_URL=smtp://localhost:25?encryption=ssl&auth_mode=login&username=xxx&password=xxxx

So email does not get delivered. After submit I am transferred back to contact page, and no flash message either :/
Have I missed anything else for this to work?
example:

*

*does my username have to be a whole email address that I also need to decode, etc?

*do I need to change something on the server also? please advise.

A: Alright so i set up the gmail account for now. and yes it sent an email now :)
So my code was alright i guess. just server settings not good, but works with gmail now :)
Thank you all for helping :)

A: This is another question related to the email setup. By changing to a gmail setup i have my gmail address as sender. But i want to use the website address as sender (like a no-reply@)
How does this work? how do i set this up?

A: Alright i can answer my own original question.
I got the smtp to work:
in the swiftmailer.yaml it put the following, and i disabled the mailer in yaml.
swiftmailer:
    transport:        smtp
    username:         null
    password:         null
    host:             localhost
    port:             465
    encryption:       ssl
    auth-mode:        login
    spool: { type: 'memory' }
    stream_options:
        ssl:
            allow_self_signed: true
            verify_peer: false
            verify_peer_name: false

Emails arrive in my mailbox where sender is the xxx@website.com


text:
Q: Updating different unique value to each group I have a table where everything that has the same classification_id and application_id have the same group_id.
id                                  |classification_id                   |application_id                      |authorisation_id                    |group_id                            |
------------------------------------+------------------------------------+------------------------------------+------------------------------------+------------------------------------+
54f614f3-7582-4ae9-a07e-5ff6d29e7a3b|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|25a7e1f7-4d8c-4e12-a10f-3654d7ef5ee9|8e563f95-ff0c-41e7-b211-d5ac6f78d056|
a01571a1-4f04-4ff9-9a7b-3a720736b9ec|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|302b23f1-ce57-4219-bcae-7bdbc3b86cb4|8e563f95-ff0c-41e7-b211-d5ac6f78d056|
3e18f2d0-4d5f-41b3-baf5-ba0feac8f43e|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|5e3bce60-b0d8-436c-9d33-b3a1d4c9a308|8e563f95-ff0c-41e7-b211-d5ac6f78d056|
b2ebe2ee-ffed-4e32-8abe-cd8b7d400646|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|a4edd12d-c19e-4e0d-badd-d3cf5e6d6d82|8e563f95-ff0c-41e7-b211-d5ac6f78d056|
ef01e6f7-f6ad-4d4d-b129-9c756734bef5|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|5e3bce60-b0d8-436c-9d33-b3a1d4c9a308|8e563f95-ff0c-41e7-b211-d5ac6f78d056|
7d340811-b679-49fd-bdd6-32a1bb9bbfed|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|25a7e1f7-4d8c-4e12-a10f-3654d7ef5ee9|8e563f95-ff0c-41e7-b211-d5ac6f78d056|
c45d7bb6-2146-48d0-a804-929cc42484cd|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|a4edd12d-c19e-4e0d-badd-d3cf5e6d6d82|8e563f95-ff0c-41e7-b211-d5ac6f78d056|
ddec5929-a08f-4f48-97f8-ccc2b85531ac|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|302b23f1-ce57-4219-bcae-7bdbc3b86cb4|8e563f95-ff0c-41e7-b211-d5ac6f78d056|
ae9edbb2-def3-4c4e-9a27-72454a09e146|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|a4edd12d-c19e-4e0d-badd-d3cf5e6d6d82|8e563f95-ff0c-41e7-b211-d5ac6f78d056|
3a3fd904-1988-4f8c-bf27-8cdf349b8431|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|25a7e1f7-4d8c-4e12-a10f-3654d7ef5ee9|8e563f95-ff0c-41e7-b211-d5ac6f78d056|
27c669b9-763c-49cf-887a-b9b1f85dc1ab|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|302b23f1-ce57-4219-bcae-7bdbc3b86cb4|8e563f95-ff0c-41e7-b211-d5ac6f78d056|
03820732-32c4-4cd4-910b-4e27fdd44bdf|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|5e3bce60-b0d8-436c-9d33-b3a1d4c9a308|8e563f95-ff0c-41e7-b211-d5ac6f78d056|

I've managed to sort out subgroups of this group by authorisation_id and I've created a group_helper which basically shows my end goal - from this data set I want to get three different groups:
id                                  |classification_id                   |application_id                      |authorisation_id                    |group_id                            |group_helper|
------------------------------------+------------------------------------+------------------------------------+------------------------------------+------------------------------------+------------+
54f614f3-7582-4ae9-a07e-5ff6d29e7a3b|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|25a7e1f7-4d8c-4e12-a10f-3654d7ef5ee9|8e563f95-ff0c-41e7-b211-d5ac6f78d056|           2|
a01571a1-4f04-4ff9-9a7b-3a720736b9ec|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|302b23f1-ce57-4219-bcae-7bdbc3b86cb4|8e563f95-ff0c-41e7-b211-d5ac6f78d056|           2|
3e18f2d0-4d5f-41b3-baf5-ba0feac8f43e|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|5e3bce60-b0d8-436c-9d33-b3a1d4c9a308|8e563f95-ff0c-41e7-b211-d5ac6f78d056|           2|
b2ebe2ee-ffed-4e32-8abe-cd8b7d400646|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|a4edd12d-c19e-4e0d-badd-d3cf5e6d6d82|8e563f95-ff0c-41e7-b211-d5ac6f78d056|           2|
ef01e6f7-f6ad-4d4d-b129-9c756734bef5|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|5e3bce60-b0d8-436c-9d33-b3a1d4c9a308|8e563f95-ff0c-41e7-b211-d5ac6f78d056|           3|
7d340811-b679-49fd-bdd6-32a1bb9bbfed|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|25a7e1f7-4d8c-4e12-a10f-3654d7ef5ee9|8e563f95-ff0c-41e7-b211-d5ac6f78d056|           3|
c45d7bb6-2146-48d0-a804-929cc42484cd|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|a4edd12d-c19e-4e0d-badd-d3cf5e6d6d82|8e563f95-ff0c-41e7-b211-d5ac6f78d056|           3|
ddec5929-a08f-4f48-97f8-ccc2b85531ac|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|302b23f1-ce57-4219-bcae-7bdbc3b86cb4|8e563f95-ff0c-41e7-b211-d5ac6f78d056|           3|
ae9edbb2-def3-4c4e-9a27-72454a09e146|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|a4edd12d-c19e-4e0d-badd-d3cf5e6d6d82|8e563f95-ff0c-41e7-b211-d5ac6f78d056|            |
3a3fd904-1988-4f8c-bf27-8cdf349b8431|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|25a7e1f7-4d8c-4e12-a10f-3654d7ef5ee9|8e563f95-ff0c-41e7-b211-d5ac6f78d056|            |
27c669b9-763c-49cf-887a-b9b1f85dc1ab|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|302b23f1-ce57-4219-bcae-7bdbc3b86cb4|8e563f95-ff0c-41e7-b211-d5ac6f78d056|            |
03820732-32c4-4cd4-910b-4e27fdd44bdf|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|5e3bce60-b0d8-436c-9d33-b3a1d4c9a308|8e563f95-ff0c-41e7-b211-d5ac6f78d056|            |

Now, I want each of those groups to have a different group_id. I don't have to update the one which has group_id = NULL since it is already unique. Now I want to give every row that has group_helper  = 2 same (but different from those where group_id = NULL) UUID, every row that has group_helper = 3 same UUID (but different from those which have group_id = NULL or 2) and so on. This has to work on n amount of group_helper values because there can be much more than maximum 2.
So my end goal would look like this:
id                                  |classification_id                   |application_id                      |authorisation_id                    |group_id                            |group_helper|
------------------------------------+------------------------------------+------------------------------------+------------------------------------+------------------------------------+------------+
54f614f3-7582-4ae9-a07e-5ff6d29e7a3b|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|25a7e1f7-4d8c-4e12-a10f-3654d7ef5ee9|fd3e63d1-d59c-477f-b58b-3ae3726c7992|           2|
a01571a1-4f04-4ff9-9a7b-3a720736b9ec|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|302b23f1-ce57-4219-bcae-7bdbc3b86cb4|fd3e63d1-d59c-477f-b58b-3ae3726c7992|           2|
3e18f2d0-4d5f-41b3-baf5-ba0feac8f43e|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|5e3bce60-b0d8-436c-9d33-b3a1d4c9a308|fd3e63d1-d59c-477f-b58b-3ae3726c7992|           2|
b2ebe2ee-ffed-4e32-8abe-cd8b7d400646|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|a4edd12d-c19e-4e0d-badd-d3cf5e6d6d82|fd3e63d1-d59c-477f-b58b-3ae3726c7992|           2|
ef01e6f7-f6ad-4d4d-b129-9c756734bef5|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|5e3bce60-b0d8-436c-9d33-b3a1d4c9a308|ed3ff96c-2f93-4182-8e4f-4594cb20cbb6|           3|
7d340811-b679-49fd-bdd6-32a1bb9bbfed|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|25a7e1f7-4d8c-4e12-a10f-3654d7ef5ee9|ed3ff96c-2f93-4182-8e4f-4594cb20cbb6|           3|
c45d7bb6-2146-48d0-a804-929cc42484cd|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|a4edd12d-c19e-4e0d-badd-d3cf5e6d6d82|ed3ff96c-2f93-4182-8e4f-4594cb20cbb6|           3|
ddec5929-a08f-4f48-97f8-ccc2b85531ac|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|302b23f1-ce57-4219-bcae-7bdbc3b86cb4|ed3ff96c-2f93-4182-8e4f-4594cb20cbb6|           3|
ae9edbb2-def3-4c4e-9a27-72454a09e146|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|a4edd12d-c19e-4e0d-badd-d3cf5e6d6d82|8e563f95-ff0c-41e7-b211-d5ac6f78d056|            |
3a3fd904-1988-4f8c-bf27-8cdf349b8431|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|25a7e1f7-4d8c-4e12-a10f-3654d7ef5ee9|8e563f95-ff0c-41e7-b211-d5ac6f78d056|            |
27c669b9-763c-49cf-887a-b9b1f85dc1ab|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|302b23f1-ce57-4219-bcae-7bdbc3b86cb4|8e563f95-ff0c-41e7-b211-d5ac6f78d056|            |
03820732-32c4-4cd4-910b-4e27fdd44bdf|63a7b151-2b8d-4b6a-b9a1-108a80ae4cdf|cd3d597b-25d1-4b4b-92f0-2ad8fcb4698c|5e3bce60-b0d8-436c-9d33-b3a1d4c9a308|8e563f95-ff0c-41e7-b211-d5ac6f78d056|            |

A: You can create a CTE which generates new group_id, selecting a single value for each group_helper column, then use update ... from ....  (see demo)
with grouper(helper, gid) as
     (select distinct on (group_helper)
              group_helper
            , gen_random_uuid()
         from sometable
        where group_helper is not null
        order by group_helper
     ) --select * from grouper
update sometable
   set group_id = gid
  from grouper
 where helper = group_helper;


text:
Q: Fourier transforms and convolutions I am really stuck at problems relating to this subject. This leads me to believe that I have fundamentally misunderstood some properties or something. I have two examples that I would like to have clarified. The first one is:
"Compute the Fourier transform of $f(x) = \cos \left( \frac{\pi}{2} x \right) \chi_{[-1,1]}(x)$ and justify the equation $\widehat f = \widehat{\cos\left( \frac{\pi}{2} x \right)} * \widehat{\chi_{[-1,1]}(x)}$."
My thoughts on this problem goes along the way of showing that the functions are contained in function spaces which we know satisfies the property that pointwise products and convolutions are interchangeable under the Fourier transform. Specifically the book lists the options: Both functions in $L^2$; One Schwartz function and a tempered distribution. Furthermore it is noted that $\widehat{S * T} = \widehat S \cdot \widehat T$ where both are tempered distributions and at least one of them has compact support.
However I cannot seem to make sense of any of these properties and at this point I start to think that the "justify"-bit in the question just refers to showing that equality holds? The problem is then that I cannot manage to do that either. That might have something to do with me staring at this problem for too long.
The other problem is as follows:
"Compute the Fourier transform of $\text{pv} \left( \frac{1}{x} \right)$ from the relation $x \cdot \text{pv} \left( \frac{1}{x} \right) = 1$."
Also here I have the same problems as over trying to characterize the functions into a function space which allows me to do the operation that is glaring at me.
As always I would appreciate some hints in the right direction rather than have the solution printed out in front of me. The problems are found in Gasquet and Witomski "Fourier analysis and applications", chapter/lesson 33.
Thanks.


text:
Q: C++ Making/Naming vectors without initialization (in a while loop) Is there a way to make multiple vectors and name them each inside a while loop?
Example:
string name;
while(true){
    cout << "Name the vector :" << endl;
    cin >> name;
    vector<string> ?name?;
}

I know this is bad code, just want to see how it would work
Couldn't find anything online, thanks in advance.

A: Yes, you can use a std::map to bind names to objects:
string name;
map<string, vector<string>> vecs;
while(true){
    cout << "Name the vector :" << endl;
    cin >> name;
    vecs[name]; // inserts if does not exist
    vecs[name].push_back("example"); // or you can do this without the prior line
}


text:
Q: Microsoft Graph SendMail returns ErrorInternalServerError I'm writing a program to send internal emails in VB.Net using the official Microsoft Graph package. At first I got it to send calendar invites and that worked fine for months, but when I tried to add the ability to send emails I keep getting an Internal Server Error.
From looking at other times people have got this error from Graph, it appears to be when a malformed request is sent or when values that don't quite make sense are given. I'm using the constructors from the package and using basically the same construction method as every example online, so the structure of the request can't be wrong, and the only fields that I'm using just take text and don't do anything with it, so I don't think that can be the issue either.
I have the correct permissions in Azure:  Screenshot of permissions in Azure, including Mail.Send
Here's my code for constructing the email:
Function DefineImportantEmail(Locations As String, Recipients As List(Of (String, String))) As Message
    Dim title = "IMPORTANT OUTAGE NOTIFICATION"
    Dim message = "Outage at " & Locations

    Dim RecipientList = New List(Of Recipient)
    For Each recipient In Recipients
        RecipientList.Add(New Attendee With {
                .EmailAddress = New EmailAddress With {
                    .Address = recipient.Item1,
                    .Name = recipient.Item2
                },
                .Type = AttendeeType.Optional
            })
    Next

    Return New Message With {
        .Subject = title,
        .Body = New ItemBody With {
            .ContentType = BodyType.Text,
            .Content = message
        },
        .ToRecipients = RecipientList
    }
End Function

And here's the code I use to send the email:
Sub SendImportantEmail(Locations As String, Recipients As List(Of (String, String)))
    Dim SaveToSentItems = True
    Dim graphClient = GetGraphClient()
    Dim EventObject = DefineImportantEmail(Locations, Recipients)
    Dim request = graphClient.Users("xxxxx@xxxxxxxxxxxxxxx.com").SendMail(EventObject, SaveToSentItems).Request().PostAsync()
    request.Wait()
End Sub

The GetGraphClient function works for any other API endpoint I've tried, so I haven't included it. The censored user is from our organisation and is also the user I sent calendar invites from in the first version of this program.
Here's the full error message I get:
(Code: ErrorInternalServerError
Message: An internal server error occurred. The operation failed.
ClientRequestId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
)
---> Status Code: InternalServerError
Microsoft.Graph.ServiceException: Code: ErrorInternalServerError
Message: An internal server error occurred. The operation failed.
ClientRequestId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx


text:
Q: Cannot get PHP to serve on Nginx -- Error 502 Bad Gateway I'm fairly new to nginx and assumed it would be very straightforward to serve php with it since that setup is so common, but it seems like it's much more complex than I anticipated.
Here's my config..
    server {
            listen 80;
            server_name domain.com www.domain.com;

            location / {
                    root   /srv/www/domain.com/public_html;
                    index index.php;
            }

    # serve static files directly
    #location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt)$
    #    access_log        off;
    #    expires           30d;

            location ~ [^/]\.php(/|$) {
                    fastcgi_split_path_info ^(.+?\.php)(/.*)$;
                    if (!-f $document_root$fastcgi_script_name) {
                            return 404;
                    }

                    fastcgi_pass /var/run/php5-fpm.sock;
                    fastcgi_index index.php;
                    include fastcgi_params;
            }
    }

If I replace the "index.php" with a "index.html" file, nginx serves up the html perfectly. But switching over to php causes a 502 error.
I've seen guides that recommend modifying anything from iptables to php-fpm to the php.ini, to fast-cgi to sites-available..?
I'm not sure what many of these tutorials are trying to do exactly... for now I'd just like my index.php to serve up phpinfo(). What's the next step?
Is there a clear guide that goes over the various options available for serving php with nginx?

A: You have to install php-fpm and add this section: http://wiki.nginx.org/PHPFcgiExample

A: I assume you have successfully installed php-fpm (FastCGI Process Manager)
Go to php-fpm/php.ini
Find the line cgi.fix_pathinfo=1, uncomment it and change the value 1 to 0.
cgi.fix_pathinfo=0
Now restart php-fpm service.
Through your terminal
service php5-fpm restart (I'm not sure about your Linux distro must be same)

A: This might be the issue with the permission, you can identify the error in the log file

*

*Extract the record from the log
022/08/09 20:37:27 [crit] 3930#0: *17 connect() to unix:/var/run/php/php-fpm.sock failed (13: Permission denied) while connecting to upstream, client: 192.168.80.36, server: 127.0.0.1, request: "GET /info.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php-fpm.sock:", host: "127.0.0.1"
This give clue that server conflict, now to verify which user running we need to check the php-fpm and nginx worker node

*

*Worker Node
Execute the command
ps aux | grep 'nginx'
this will indicate the user of the nginx worker node, in this case it is nobody
root@ubuntu:/var/nginx/html# ps aux | grep 'nginx'

*nobody    3930  0.0  0.0  37636  3784 ?        S    20:37   0:00 nginx: worker process

*Check the php fpm service
Execute the command
ps aux | grep 'php-fpm'
It will indicate the user as "www-data" in my case
root@ubuntu:/var/nginx/html# ps aux | grep 'php'

*www-data  1320  0.0  0.2 498796 11908 ?        S    19:34   0:00 php-fpm: pool www

*www-data  1323  0.0  0.2 498796 11908 ?        S    19:34   0:00 php-fpm: pool www
To resolve this conflict, in the nginx.conf file, you have to define the user derivate at top to be www-data i.e. user www-data;


text:
Q: filter and sort an array of objects in Vue I'm trying to create a filtered and sorted computed in Vue that is based on an array of objects but have not figured out how to get it to work.  The project has access to the vue-filter library.
Here are the pertinent pieces of code:
in script tags -
export default {
    computed: {
        filteredOfficialScenarios() {
            return [
                {"scenarioName": "scenario 1", "created": "2020-01-01T10:30:00"},
                {"scenarioName": "scenario 2", "created": "2019-01-01T09:15:00"},
                {"scenarioName": "scenario 3", "created": "2020-01-15T11:00:00"},
                {"scenarioName": "scenario 4", "created": "2018-01-31T11:00:00"},
                {"scenarioName": "scenario 5", "created": "2019-01-31T11:00:00"}
            ];
        }
    }
}

in HTML -

{{officialScenario}}

Only scenarios with created > 2019-01-01 are supposed to be in the final output and the final output is to be sorted by descending created date.
I tried figuring out sorting and filtering separately but have not gotten either to work, much less figure out how to combine them so they occur at the same time.  Here is what's been tried, to no avail -
for sorting -
computed: {
    filteredOfficialScenarios() {
        return [
            {"scenarioName": "scenario 1", "created": "2020-01-01T10:30:00"},
            {"scenarioName": "scenario 2", "created": "2019-01-01T09:15:00"},
            {"scenarioName": "scenario 3", "created": "2020-01-15T11:00:00"},
            {"scenarioName": "scenario 4", "created": "2018-01-31T11:00:00"},
            {"scenarioName": "scenario 5", "created": "2019-01-31T11:00:00"}
        ] | sortBy("created");
    }
}

This is an attempt to get it to do a simple sort without being concerned with the sort direction.  This results in a console error and all output on the app's page in the browser disappears.
for filtering -
computed: {
    filteredOfficialScenarios() {
        return [
            {"scenarioName": "scenario 1", "created": "2020-01-01T10:30:00"},
            {"scenarioName": "scenario 2", "created": "2019-01-01T09:15:00"},
            {"scenarioName": "scenario 3", "created": "2020-01-15T11:00:00"},
            {"scenarioName": "scenario 4", "created": "2018-01-31T11:00:00"},
            {"scenarioName": "scenario 5", "created": "2019-01-31T11:00:00"}
        ] | filter(function (scenario) { return scenario.created > "2019-01-01"} );
    }
}

This results in a console error and all output on the app's page in the browser disappears.
Is there a way to do sorting and filter AND get them to work simultaneously?

A: You can appy filter and sort to your original list of scenarios. Here's an example:
<template>

      {{ officialScenario }}

</template>

const SCENARIOS = [
  { scenarioName: 'scenario 1', created: '2020-01-01T10:30:00' },
  { scenarioName: 'scenario 2', created: '2019-01-01T09:15:00' },
  { scenarioName: 'scenario 3', created: '2020-01-15T11:00:00' },
  { scenarioName: 'scenario 4', created: '2018-01-31T11:00:00' },
  { scenarioName: 'scenario 5', created: '2019-01-31T11:00:00' },
];

const START_DATE = new Date('2019-01-01');

export default {
  computed: {
    filteredOfficialScenarios() {
      return SCENARIOS
        .filter(s => new Date(s.created) >= START_DATE)
        .sort((a, b) => new Date(a.created) - new Date(b.created)
      );
    },
  },
};

If you need the list sorted in the opposite way, you can simply swap (a, b) with (b, a).
The code would be a little more straightforward if you were to modify the scenarios to have Date objects instead of strings, but I'm not sure what your exact output requirements are.


text:
Q: Load custom html & css on a webpage? I don't really know what you call this, so I don't know what to type in Google to further research this. I was wondering how you delete certain elements of a webpage as it loads. A lot of userscripts use this. I want to know how do it. I think some webpages are just way to cluttered and I'm tired of editing the source code to clean it up. So how would I do this?
Thanks.

A: You can delete elements after it's loaded. Some browsers cannot remove element until whole source code is loaded. Than google for removeNode. Usage is parentElement.removeNode(removingElement). ParentElement and removingElement are referencies to elements, NOT ther IDs.
If on server side, than you have to use some preg functions to match and replace the code, or better, use XML functions to parse code and delete some elements (note: this require 100% valid code).

A: How can a script ever determine what is useful for you or not?its a subjective issue
Do you want every code on a new line uncluttered?for example do you want this type code where everthing is on a new line instead of something like  this
Update:
Here is a trick
copy paste the whole code to jsfiddle.and save it every time you change it

A: For firefox, you can use greasemonkey https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/ an here's how to use greasemonkey for chrome on Windows http://mashable.com/2008/12/15/google-chrome-greasemonkey-scripts/


text:
Q: How to dynamically set 'name' attribute of a simple form input I am using Simple Form in a Rails application in which a FormsController controller was defined as follow :
class FormsController < ApplicationController
  def index
      @forms = Form.all
  end

  def new
    @form = Form.new(form_params)
  end

  ...

  private
    def form_params
      params.require(:form).permit(:user, :name, :tag, :link, :repo)
    end
end

A new view is used to get some inputs from user

  <%= simple_form_for @param do |f| %>

      <%= f.input :user %>
      <%= f.input :name %>
      <%= f.input :tag %>
      <%= f.input :link %>
      <%= f.input :repo %>

      <%= f.button :submit, "Create", class: "btn-primary" %>

  <% end %>

I checked what's the generated name for a each field using inspect :
<input type="text" name="form[user]" id="form_user">

Printing parameters in controller while submitting a form returns :
{"user"=>"value1", "name"=>"value2", "tag"=>"value3", "link"=>"value4", "repo"=>"value5"}

From now, I would like to duplicate that's simple form few times. So, I first updated the field name from form[<parameter>] to form[1][<parameter>]

      <%= f.input :user, input_html: { name: 'form[1][user]' } %>
      <%= f.input :name, input_html: { name: 'form[1][name]' } %>
      <%= f.input :tag, input_html: { name: 'form[1][tag]' } %>
      <%= f.input :link, input_html: { name: 'form[1][link]' } %>
      <%= f.input :repo, input_html: { name: 'form[1][repo]' } %>

What I get from now as parameters output is :
"form"=>{"1"=>{""user""=>"value1", ""name""=>"value2", ""tag""=>"value3", ""link""=>"value4", ""repo""=>"value5"}}

What's the best way to dynamically allocate the id to the form[<id>][user] to the field ?
Is it possible to get parameters formatted as follow ?
form => { 1 => {user: "user1" }, 2 => {user: "user2" }, 3 => {user: "user3" }.. }
form => { 1 => {name: "name1" }, 2 => {name: "name2" }, 3 => {name: "name3" }.. }
...


text:
Q: Combining raster stacks I have multiple raster stacks containing temperature data from CRU TS 3.23
I have read in the files as follows:
nc = stack("cru_ts3.23.1951.1960.pre.dat.nc", varname = "pre")
nc2 = stack("cru_ts3.23.1961.1970.pre.dat.nc", varname = "pre")
...
nc7 = stack("cru_ts3.23.2011.2014.pre.dat.nc", varname = "pre")

Is there any way I can combine all these rasters to create one big one? I am looking at precipitation trends, so much easier to do when they're all in one object! Thanks

A: raster::stack(nc, nc2, nc3, nc4, nc5, nc6, nc7) should do the trick. A very similar approach has been described e.g. here.
However, be aware that the objects you would like to stack are required to have an identical coordinate references system (CRS), resolution (res), and extent. Otherwise, stack will most likely fail. You could deploy raster::projectRaster and raster::resample to create objects with uniform spatial properties if one (or several) of the above criteria is different.


text:
Q: Использование Node.JS на локальном сервере Хочу понять принцип работы с Node.JS.

*

*Скачал с официального сайта пакет установки (система Win64).

*Установил себе на компьютер.

Создаю в диске С файл test.js следующего содержания:
var beep = require('beeper');
beep();

Пишу в командной строке три строчки (выполняя последовательно):
cd C:/
npm install beeper
node test.js

Должен прозвучать одиночный звук. Звучит. Всё работает.
Что делать дальше? У меня стоит локальный сервер. Есть отдельный сайт. В нём есть HTML и JS файлы. Как работать с Node.JS через эти файлы? Меня интересует сам принцип работы, как это делается. Поскольку через командную строку, пользоваться сайтом как-то неудобно, сами понимаете. Как прикрутить Node.JS к сайту и его файлам? Чтобы не через командную строку работать, а через сайт на локальном хостинге. Первый раз сталкиваются с такой задачей, не знаю с какой стороны подойти.
Моя основная цель - сделать чат на Node.JS с сохранением сообщений в БД. Но об этом пока думать рано. Прежде нужно понять основные принципы.

A: Node.js - это V8 плюс libuv.
V8 - это движок JavaScript. Он позволяет выполнять код написанный на языке JavaScript. Этот движок используется в браузере Chrome
libuv (Unicorn Velociraptor Library) - это библиотека асинхронного ввода/вывода на основе цикла событий (event loop).
Node.js позволяет выполнять JavaScript не только в браузере (как это было задумано при создании языка), но и на сервере. То есть используя Node.js вы можете создать собственный сервер, который будет общаться с браузером используя протокол HTTP, а так же выполнять серверные процессы - работать с сервером баз данных, работать с удаленными серверами, обрабатывать какие-нибудь данные и т.п.
Node.js может вам целиком заменить ваш существующий локальный веб-сервер. Node.js будет раздавать ваши HTML и JS файлы.
Для создания чата вам нужно написать код, который будет работать как на стороне сервера (Node.js), так и на стороне клиента (браузер). Но основной плюс от использования Node.js - это то, что код для обеих частей вы пишите на одном языке - JavaScript.
Что бы разобраться с основами начните с сайта NodeSchool


text:
Q: Set Spinner background colour without removing default dropdown indicator icon Please let me know how I can change background colour for a spinner in Android.
<Spinner
        android:id="@+id/addData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/blue" />

Above code adds the colour BLUE but it also hides the default drop down icon.
Is there a way without using custom background xml to add colour and not hide the icon?
Thanks
Abhinav Tyagi

A: There is an easy workaround. Just wrap your Spinner in a FrameLayout (for exapmle) and set background color of your choice to the Layout.
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    >

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</FrameLayout>

A: add hexdecimal  number for blue android:background="HEX_COLOR_CODE" or use android:popupBackground="YOUR_HEX_COLOR_CODE"
<Spinner
        android:id="@+id/addData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#0000FF" />


text:
Q: Detect Metro UI Version of IE What's the fastest method, to detect User-Agent as metro UI version of internet-explorer >=10 ?

A: I don't believe there is a way to determine if a request is coming from the Metro version of IE10 versus the regular desktop mode version. Metro IE has no unique HTTP headers or user-agent string to identify it by.
Internet Explorer 10 User Agent Strings On Windows 8 64bit
Metro IE10 is a 64-bit application, so you'll see "Win64" in the user-agent string. Regular desktop IE10, by default, is 32-bit and will show "WOW64". You could sort-of make an educated guess based on this, but you would falsely identify anyone who chose to run the 64-bit version of IE10 in desktop mode. As you can see from that chart, the user-agent strings are identical. [edit: as noted in the comments, this won't work for 32-bit PCs.]
I could see why you may want to detect Metro IE, but this type of "browser sniffing" is generally discouraged because it's so cumbersome and error-prone.  It would be best to feature test for certain browser functionality that you require using something like Modernizr, if you can.

A: Thanks John Rajakumar and Alexis Pigeon. I was able to use your Metro IE check as the basis to load a separate CSS style sheet for Metro tablets (MS Surface).  To add a bit more certainty in my mind, I used cssuseragent to detect IE10 first, and then combined both tests in a final yepnope test.
var IEmetrotest = ((cssua.userAgent.ie > 9) && (metrotest()));
yepnope({
    test: IEmetrotest,
    yep : ['ie_metro.css']
    });

Tested it in Browserstack and it's working as expected.  (I would have up-ticked you, but don't have enough points yet.)
// Minor revisions to isBrowserSupportPlugin() previously posted
// Renamed function to metrotest() and inverted the returned value.
var errorName = null;
function metrotest() {
    var supported = null;
    try {
        new ActiveXObject("");
    }
    catch (e) {
        // FF has ReferenceError here
        errorName = e.name;
    }
    try {
        supported = !!new ActiveXObject("htmlfile");
    } catch (e) {
        supported = false;
    }
    if(errorName != 'ReferenceError' && supported==false){
        supported = false;
    }else{
        supported =true;
    }
    return !supported;
}

A: So, there doesn't appear to be a definitive test to identify Metro IE vs Desktop IE, but there does seem to be a few different pieces of data you can attempt to use to assume that it is Metro.  Unfortunately, none of the items I have found can't be explained away by other settings.  In other words, for all the "feature" tests I have found, Desktop IE could be configured in a way to trick the tests into thinking it was running on Metro.
Is ActiveX disabled (Metro doesn't allow any activex content, but desktop IE can have it set to disabled as well):
function isActivexEnabled() {
    var supported = null;
    try {
        supported = !!new ActiveXObject("htmlfile");
    } catch (e) {
        supported = false;
    }

    return supported;
}

User Agent string check (Metro will always run in 64bit mode, but won't on a 32bit machine, and Desktop IE can be configured to run in 64bit mode as well not sure how popular either of those options will be)
function isWin64() {
    return navigator.platform == "Win64";
}

Full screen check (Metro will always be in full screen mode, however Desktop IE can also run in full screen mode, but this could be used as supporting evidence of Metro mode)
function isFullScreen() {
   return (window.innerWidth == screen.width &&
           window.innerHeight == screen.height);
}

In short, I think you have to try to check a bunch of features, and then guess, there is no definitive way.  Or you could just accept that MS doesn't want you to do this, and use feature detection for the features you want to use.
For those that want to try to provide UI to refer to the containing browser UI (to indicate how to Pin the web page for example), keep in mind that other Metro apps can embed the IE10 Metro browser as a control, so even if you could identify the browser as Metro vs desktop, the UI might not be where you'd attempt to refer to it, so this can end up being a pretty tricky situation to get right 100% of the time.  So either, don't try, or you could attempt the other detection techniques and accept that there are use cases that you could be displaying the wrong UI.

A: METRO IE never supports ActiveX or any plugin objects. Based on that the following script is tested & working fine.
//---------------------------Metro IE check-------------------------
    var errorName = null;
    function isBrowserSupportPlugin() {
        var supported = null;
        try {
            new ActiveXObject("");
        }
        catch (e) {
            // FF has ReferenceError here
            errorName = e.name;
        }
        try {
            supported = !!new ActiveXObject("htmlfile");
        } catch (e) {
            supported = false;
        }
        if(errorName != 'ReferenceError' && supported==false){
            supported = false;
        }else{
            supported =true;
        }
        return supported;
    }
//----------------------------------------------------------------

A: Reliable Modern/Metro detection!
I have found a way to detect Modern versus Desktop which you can try here: http://jsbin.com/genac/2 (edit using Chrome or Firefox not IE http://jsbin.com/genac/2/edit).
It seems to be a fairly robust detection because:

*

*it works even if pinch-zoomed

*it works even if two windows snapped side by side on Modern(Metro)

*it works even if page zoomed using ctrl-+ and ctrl--

*it works even if desktop is fullscreen using F11 key on Desktop (autohiding taskbar)

The trick is that the page scrollbars on Modern do not make the client window size smaller (they appear above the page), but the page scrollbars on Desktop do affect client window size (usable window size is smaller).
The main downside is that the test requires that you have a scrollbar on the page to sniff the difference. Does the same difference in scrollbars happen in an iframe or autoscrollable div?
Edit: I would test that the browser is IE11 before using this code, because Windows 10 doesn't have Metro/Modern and Edge acts slightly differently.
<!DOCTYPE html>

  <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
  <title>Metro width detector - robocat</title>

You can look at page/window dimensions using: http://jsbin.com/AbimiQup/10 (edit using Chrome or Firefox not IE  http://jsbin.com/AbimiQup/10/edit)
PS: There might be some way to sniff the scrollbar difference from the runtimeStyle for body or document.documentElement because maybe -ms-overflow-style: -ms-autohiding-scrollbar is used (e.g. document.documentElement.runtimeStyle.msOverflowStyle) but I couldn't find anything.
PPS: The ActiveX method given in other answers is not particularly reliable (e.g. users can disable) and it causes UI uglyness because in IE11 it shows a "ActiveX" icon next to the url.

A: Here is a consistent method, with no ActiveX check dependency, as tested in IE10 and IE11 specifically.
if (window.screenY === 0 && (window.innerHeight+1) !== window.outerHeight){ //IE metro/modern UI }

The first rule detect IE's full screen or modern view (which may or can also be true on IEMobile).
Maximized mode being historically always associated with positive or negative screenX and screenY.
And the last rule excludes [Full screen/F11] mode, which for some reason constantly shows a 1px discrepancy between outerHeight and innerHeight as tested on IE10/Win8 and IE11/Win8.1
PS: I voluntarily do not declare window.screenX === 0. Only use screenY in order to cover Modern/Metro in snap-mode with a window context snapped to the right (i.e. screenX !== 0).

A: I tested the following and it works, a jsfiddle showing this can be found here.

This is a bit of long shot, but seems quite a sensible solution:
Why not check whether the browser is full screen1 and depending on that call the fullscreen one metro. I have windows 8 running on my computer at work, so I will try to check tomorrow whether there are any GUI's still around (don't think I remember any) and if so, you would need to manually subtract them. True, it's not the most beautiful solution, but as far as I know there won't be any 'beautiful' solution and this could prove to be a pretty solid hack, as the GUI of metro IE can't be changed with any toolbars or similar software (as far as I know). True, it could lead to a misidentification of the desktop IE, but even that is within reason, as a fullscreen desktop IE will still give a similar experience.

1 Giving something along the lines of:
if(window.innerWidth == screen.width && window.innerHeight == screen.height) {
  // metro
} else {
  // desktop
}

A: By the sounds of it you are looking to do something along the lines of Pinning a site to the start screen within Metro. To do that you can check if a site can be pinned by using this code that was brought in with IE9 and can be done by doing something like this...
function doChecks_Browser() {
  // full pin abilities == can pin && Win7+
  if (pinnedSiteDetection.hasFullPinAbilityBrowser)
}

More info on that here.
From this this post on MSDN...

Windows 8 Release Preview implements pinned sites by using tiles on the Start screen. When a user clicks the tile of a pinned site, the site opens in Windows Internet Explorer 10 Release Preview in the Windows Metro style UI environment.

Hope that helps!

A: It tried out the code below and it seems to work.
It doesn't catch if the user goes InternetOptions->CustomLevel->ScriptActivexControlsMarkedSafeForScripting=false on you though. If the user does this the code believes it's a Metro/Modern.
Presently I see no way around this by checking OS, FullScreen and whatnot.
isWinModern checks for Metro/Modern.
isWinDesktop checks for Windows as Desktop (=non modern in this case)
The code below is not guaranteed to work.
    function isWin8Modern() {
        if (!!window.ActiveXObject) {
            try {
                !!new window.ActiveXObject('htmlfile');
                return false;
            } catch (exc) {
                return true;
            }
        } else {
            return false;
        }
    }

    function isWinDesktop() {
        if (window.ActiveXObject) {
            try {
                new window.ActiveXObject('htmlfile');
                return true;
            } catch (exc) {
                return false;
            }
        } else {
            return false;
        }
    }

A: var _ua = window.navigator.userAgent;
var isIDevice = (/iphone|ipod|ipad/i).test(_ua);
var isMobileChrome = (_ua.indexOf('Android') > -1 && (/Chrome\/[.0-9]*/).test(_ua) && _ua.indexOf("Version") == -1);
var isMobileIE = _ua.indexOf('Windows Phone') > -1;
function isActivexEnabled()
{
    var supported = null;
    try
    {
        supported = !!new ActiveXObject("htmlfile");
    }
    catch (e)
    {
        supported = false;
    }
    return supported;
}
if (!isIDevice && !isMobileChrome && !isMobileIE &&  _ua.toLowerCase().indexOf("wow") == -1 && !isActivexEnabled())
{
    //IE Metro UI
}

This Work For Me..

A: I spent some time on this and figured out a way.  I thought about what is missing from IE10 Metro and only one thing that is documented isn't supported in the Metro UI.  The developer tools.   Well, those tools have objects in the window object.   One of these is "__IE_DEVTOOLBAR_CONSOLE_COMMAND_LINE".
If you do something like
if (window.__IE_DEVTOOLBAR_CONSOLE_COMMAND_LINE)
{
    // In IE 10 Standard UI
}
else
{
    // In IE 10 Metro UI
}

I've tested it in a few different environments and it appears to work most places.  The only hiccup I can think of is if the developer tools were somehow disabled on the user's browser.


text:
Q: PIL Image mode I is grayscale? I'm trying to specify the colours of my image in Integer format instead of (R,G,B) format. I assumed that I had to create an image in mode "I" since according to the documentation:

The mode of an image defines the type and depth of a pixel in the
image. The current release supports the following standard modes:

*

*1 (1-bit pixels, black and white, stored with one pixel per byte)

*L (8-bit pixels, black and white)

*P (8-bit pixels, mapped to any other mode using a colour palette)

*RGB (3x8-bit pixels, true colour)

*RGBA (4x8-bit pixels, true colour with transparency mask)

*CMYK (4x8-bit pixels, colour separation)

*YCbCr (3x8-bit pixels, colour video format)

*I (32-bit signed integer pixels)

*F (32-bit floating point pixels)

However this seems to be a grayscale image. Is this expected? Is there a way of specifying a coloured image based on a 32-bit integer? In my MWE I even let PIL decide how to convert "red" to the "I" format.

MWE
from PIL import Image

ImgRGB=Image.new('RGB', (200,200),"red") # create a new blank image
ImgI=Image.new('I', (200,200),"red") # create a new blank image
ImgRGB.show()
ImgI.show()

A:
Is there a way of specifying a coloured image based on a 32-bit integer?

Yes, use the RGB format for that, but instead use an integer instead of "red" as the color argument:
from PIL import Image

r, g, b = 255, 240, 227
intcolor = (b << 16 ) | (g << 8 ) | r
print intcolor # 14938367
ImgRGB = Image.new("RGB", (200, 200), intcolor)
ImgRGB.show()


text:
Q: How to use bootstrap drapdown along with text box and a submit button to post data This is what I want to achieve this in django/bootstrap.
The user is supposed to select options from two DDLs and enter a number in the box, then press update to post parameters to server.
But it does not work.

And below is the code I have written:
(I have removed some django lines - but there will be loops and variables to get data from the form)
<form class="form-inline " method="post" action="{% url 'historical' %}">

    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownCrypto"
       name="crypto" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
       {{Selected-Coin}}
    </button>

        BTC
        XRP

      <button class="btn btn-outline-secondary dropdown-toggle" type="button"
           id="dropdownCurrency" data-toggle="dropdown" aria-haspopup="true"
           aria-expanded="false">
        {{Selected-Currency}}
      </button>

          USD
          EUR

    <input class="form-control " type="number" aria-label="Period"
         name="period" value="10"> days
    <button class="btn btn-outline-secondary " type="submit">Update</button>
</form>


text:
Q: Obtener valor de un node en xml y que un número x se encuentre entre los valores correspondientes a un tag padre Tengo este xml en SQL y un valor de entrada de 15000.
<?xml version="1.0" encoding="UTF-8" ?>
<Node1>
<Node2 MIN="0" MAX="10000">
    <value VAL="100"/>
</Node2>
<Node2 MIN="10000" MAX="">
    <value VAL="50"/>
</Node2>
</Node1>

Lo que necesito es obtener el valor del tag "value" cuyo dato de entrada (15000) corresponda a encontrarse entre los valores del tag "Node2".
La rpta sería: 50


text:
Q: Find all $n \in N$ such that $11 | a_n$, with the following sequence defined $\{a_n\}_{n \in \Bbb N}$ with $a_1=1, a_2=3$
and for $n \ge 1$:
$a_{n+2} = (n+3)a_{n+1}-(n+2)a_n$
as the title states, find all $n \in \Bbb N$ such that $11 | a_n$

A: Edit: I originally computed the table from the incorrect value $a_2=2$. Fortunately, finial caught this, and I've recomputed it with the correct initial value, modifying the rest of the hint accordingly.
HINT: If you calculate the first few values of $a_n\bmod 11$, you get this:
$$\begin{array}{r|c}
n:&1&2&3&4&5&6&7&8&9&10&11&12&13\\ \hline
a_n:&1&3&9&0&10&4&6&0&1&0&0&0&0
\end{array}$$
That string of $0$'s should suggest a conjecture: $a_n\equiv 0\pmod{11}$ for $n\ge 10$. Since the $a_n$'s are defined by a recurrence, induction is the natural choice for a method of proof.

A: HINT: If you let $b_n=a_n-a_{n-1}$ you find that $$b_{n+2}=(n+2)b_{n+1}$$
We have $b_2=2$ (the first defined value) and it is then easy to see (and prove) a simple formula for $b_n$.
You still have a little work to do, and the idea of working modulo 11 may be quicker, but this is another way of seeing what is happening.

A: By calculation, we can get that $a_{n}=1!+2!+\cdots+n!$, as $11|k!$ for $k\geq11$,and $11|(9!+10!)$ ($9!+10!=11\cdot9!$), you can only check them for $n=1,2,\cdots,10$, and that $a_{n}$ is divisible by 11 or not for $n\geq11$ follows from that $a_{8}$ (or $a_{10}$) is divisible by 11 or not.


text:
Q: Divide document into a black and color file before printing I want to print a large docx file that has many pages of color images but I need to print these pages only as color and the remaining as b/w to save money.
Is there a way to detect and create a new color pdf file for the figure pages only. and save the remaining pages into a new B/W pdf file.
Thanks

A: If the B/W pages are plain black text, then your printer will automatically print those with black ink/toner only. The colour pages will of course be printed in colour. The only problem occurs when your document contains greyscale images. In that case the printer may (depending on printer and settings) use some colour inks to get a larger grey gamut. In that case, see if there is a driver setting to print greys with black ink only.
Hence, in the majority of cases, you don't have to worry about it. If there are greyscale images and there is no suitable driver setting, the amount of colour ink used will be minimal, so again it will not increase the cost by much.


text:
Q: how to fix "Duplicate extensions not allowed" with logstash/jruby? I'm running logstash like it saids in the starting page:
java -jar logstash-1.2.1-flatjar.jar agent --config logstash-dev.conf

With logstash-dev.conf like this:
input {
  file {
    path => ["/tmp/catalina.jsonevent.log"]
    codec => json {
      charset => "UTF-8"
    }
  }
}

output {
# Use stdout in debug mode again to see what logstash makes of the event.
  stdout {
    debug => true
  }
  elasticsearch_http {
    host => "127.0.0.1"
  }
}

And it jumps with this error:
Exception in thread "LogStash::Runner" org.jruby.exceptions.RaiseException: (StoreError) loading file failed: problem creating X509 Aux certificate: java.io.IOException: problem parsing cert: java.security.cert.CertificateParsingException: java.io.IOException: Duplicate extensions not allowed
    at org.jruby.ext.openssl.X509Store.add_file(org/jruby/ext/openssl/X509Store.java:151)
    at RUBY.initialize(file:/usr/local/bin/logstash/logstash-1.2.1-flatjar.jar!/ftw/agent.rb:70)
    at RUBY.register(file:/usr/local/bin/logstash/logstash-1.2.1-flatjar.jar!/logstash/outputs/elasticsearch_http.rb:46)
    at org.jruby.RubyArray.each(org/jruby/RubyArray.java:1617)
    at RUBY.outputworker(file:/usr/local/bin/logstash/logstash-1.2.1-flatjar.jar!/logstash/pipeline.rb:208)
    at RUBY.start_outputs(file:/usr/local/bin/logstash/logstash-1.2.1-flatjar.jar!/logstash/pipeline.rb:140)

I've looking everywhere (google, mail groups of logstash and jruby, and the same with their ircs) but I don't find a way to solve this. I only see similar stacktraces but no solution.
Can you give me any pointer in address this?
thanks in advance

A: We've been looking for this as well and this fixed it for us:
curl http://curl.haxx.se/ca/cacert.pem -o /usr/local/etc/openssl/cert.pem


text:
Q: Three.js - EffectComposer - Blended scene is blinking I'm new to three.js and I have problems to achieve the following effect : render 2 scenes and mix them with a blending shader. The first TexturePass is OK but the second one is blinking like a stroboscope. The result can be seen here: https://codepen.io/anon/pen/jYKqyj?editors=0010#0
And here is the code :
THREE.Custom = THREE.Custom || {};

// Taken from https://github.com/stemkoski/stemkoski.github.com/blob/master/Three.js/js/shaders/AdditiveBlendShader.js
THREE.Custom.AdditiveShader = {
    uniforms: {
        tDiffuse: { type: "t", value: null },
        tAdd: { type: "t", value: null },
        fCoeff: { type: "f", value: 1.0 }
    },

    vertexShader: [
        "varying vec2 vUv;",

        "void main() {",
            "vUv = uv;",
            "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
        "}"
    ].join("\n"),

    fragmentShader: [
        "uniform sampler2D tDiffuse;",
        "uniform sampler2D tAdd;",
        "uniform float fCoeff;",

        "varying vec2 vUv;",

        "void main() {",
            "vec4 texel = texture2D( tDiffuse, vUv );",
            "vec4 add = texture2D( tAdd, vUv );",
            "gl_FragColor = texel + add * fCoeff, 1.0;",
        "}"
    ].join("\n")
};

var TestBlending = (function (){

    var canvasWidth, canvasHeight, canvasRatio;

    var clock = new THREE.Clock();
    var container, camera, scene1, scene2, renderer;

    var stats, statsDisplay = true;
    var box1, box2;

    var composerFinal, composerScene1, composerScene2, composerBlending, renderTarget;
    var composerDebugScene1, composerDebugScene2;

    var delta;

    function createScene1 () {

        scene1 = new THREE.Scene();
        scene1.name = "scene1";

        var light = new THREE.DirectionalLight( 0xffffff, 1 );
        light.position.set( 0, 10, 20 );
        light.name = "light1";

        scene1.add(light);

        var material = new THREE.MeshPhongMaterial( { color: 0xcc00cc } );
        var geometry = new THREE.BoxGeometry( 1, 1, 1 );
        box1 = new THREE.Mesh( geometry, material );
        scene1.add( box1 );

    }
    function createScene2 () {

        scene2 = new THREE.Scene();
        scene2.name = "scene2";

        var light = new THREE.DirectionalLight( 0xffffff, 1 );
        light.position.set( 0, 10, 20 );
        light.name = "light2";

        scene2.add(light);

        var material = new THREE.MeshPhongMaterial( { color: 0x33cc33 } );
        var geometry = new THREE.BoxGeometry( 1, 1, 1 );
        box2 = new THREE.Mesh( geometry, material );
        scene2.add( box2 );

    }

    function init() {

        container = document.getElementById('test_blending');

        updateCanvasSize();

        // RENDERER
        renderer = new THREE.WebGLRenderer( {
            antialias: true,
            alpha: true
        } );
        renderer.setPixelRatio( (window.devicePixelRatio) ? window.devicePixelRatio : 1 );
        renderer.setSize(canvasWidth, canvasHeight);
        renderer.setClearColor( new THREE.Color(0x0), 0 );
        renderer.autoClear = false;

        // CAMERA
        camera = new THREE.PerspectiveCamera( 10, canvasRatio, 1, 10000 );
        camera.position.set(0, 0, 30);
        camera.lookAt(new THREE.Vector3(0,0,0));

        createScene1();
        createScene2();

        window.addEventListener( 'resize', onWindowResize, false );

    }

    function updateCanvasSize () {
        canvasWidth = window.innerWidth;
        canvasHeight = window.innerHeight;
        canvasRatio = canvasWidth / canvasHeight;
    }

    function initProcessingPasses () {

        var parameters = {
            minFilter: THREE.LinearFilter,
            magFilter: THREE.LinearFilter,
            format: THREE.RGBAFormat,
            stencilBuffer: true
        };
        renderTarget = new THREE.WebGLRenderTarget( canvasWidth, canvasHeight, parameters );

        processing = { pass: {}, texture: {} };

        processing.pass.clear = new THREE.ClearPass();

        processing.pass.renderScene1 = new THREE.RenderPass( scene1, camera );
        processing.pass.renderScene1.clear = true;
        processing.pass.renderScene1.renderToScreen = false;
        processing.pass.renderScene1.clearDepth = true;

        processing.pass.renderScene2 = new THREE.RenderPass( scene2, camera );
        processing.pass.renderScene2.clear = true;
        processing.pass.renderScene2.renderToScreen = false;
        processing.pass.renderScene2.clearDepth = true;

        processing.pass.blending = new THREE.ShaderPass( THREE.Custom.AdditiveShader );
        //processing.pass.blending.needsSwap = true;
        processing.pass.blending.clear = true;
        processing.pass.blending.renderToScreen = false;

        processing.pass.output = new THREE.ShaderPass( THREE.CopyShader );
        processing.pass.output.renderToScreen = true;

        setPostProcessingPasses();

    }
    function setPostProcessingPasses () {

        console.log('setPostProcessingPasses');

        composerScene1 = null;
        composerScene1 = new THREE.EffectComposer( renderer, renderTarget );
        composerScene1.addPass( processing.pass.clear );
        composerScene1.addPass( processing.pass.renderScene1 );
        processing.texture.renderedScene1 = new THREE.TexturePass(composerScene1.renderTarget2.texture);

        composerScene2 = null;
        composerScene2 = new THREE.EffectComposer( renderer, renderTarget );
        composerScene2.addPass( processing.pass.clear );
        composerScene2.addPass( processing.pass.renderScene2 );
        processing.texture.renderedScene2 = new THREE.TexturePass(composerScene2.renderTarget2.texture);

        composerBlending = null;
        composerBlending = new THREE.EffectComposer( renderer, renderTarget );
        composerBlending.addPass( processing.pass.clear );
        composerBlending.addPass( processing.texture.renderedScene1 );
        processing.pass.blending.uniforms[ 'tAdd' ].value = composerScene2.renderTarget2.texture;
        composerBlending.addPass( processing.pass.blending );
        processing.texture.renderedBlending = new THREE.TexturePass(composerBlending.renderTarget2.texture);

        composerFinal = null;
        composerFinal = new THREE.EffectComposer( renderer, renderTarget );
        composerFinal.addPass( processing.pass.clear );
        composerFinal.addPass( processing.texture.renderedBlending );
        composerFinal.addPass( processing.pass.output );

        composerDebugScene1 = new THREE.EffectComposer( renderer, renderTarget );
        composerDebugScene1.addPass( processing.pass.clear );
        composerDebugScene1.addPass( processing.texture.renderedScene1 );
        composerDebugScene1.addPass( processing.pass.output );
        composerDebugScene2 = new THREE.EffectComposer( renderer, renderTarget );
        composerDebugScene2.addPass( processing.pass.clear );
        composerDebugScene2.addPass( processing.texture.renderedScene2 );
        composerDebugScene2.addPass( processing.pass.output );
    }

    function addStats (container) {
        stats = new Stats();
        if (statsDisplay) container.appendChild( stats.dom );
    }

    function addToDOM() {
        var canvas = container.getElementsByTagName('canvas');
        if (canvas.length>0) {
            container.removeChild(canvas[0]);
        }
        container.appendChild( renderer.domElement );
        addStats(container);
    }

    function animate() {
        window.requestAnimationFrame(animate);

        var time = performance.now() * 0.001;
        var cDelta = clock.getDelta();

        box1.rotation.y = time / 5;
        box1.rotation.x = 10;

        box2.rotation.z = time / -5;
        box2.rotation.x = time / -5;
        box2.rotation.y = 5;

        stats.update();

        render();
    }

    function render() {

        delta = clock.getDelta();;

        renderer.setViewport( 0, 0, canvasWidth, canvasHeight );

        composerScene1.render(delta);
        composerScene2.render(delta);
        composerBlending.render(delta);
        composerFinal.render(delta);

        // DEBUG
        renderer.setViewport( 0, 0, canvasWidth/3, canvasHeight/3 );
        composerDebugScene1.render(delta);
        renderer.setViewport( canvasWidth/3*2, canvasHeight/3*2, canvasWidth/3, canvasHeight/3 );
        composerDebugScene2.render(delta);

    }

    function onWindowResize() {
        camera.aspect = canvasRatio;
        camera.updateProjectionMatrix();
        renderer.setSize( canvasWidth, canvasHeight );
        composerScene1.setSize( canvasWidth, canvasHeight );
        composerScene2.setSize( canvasWidth, canvasHeight );
        composerBlending.setSize( canvasWidth, canvasHeight );
        composerFinal.setSize( canvasWidth, canvasHeight );
    }

    return {
        init: function () {
            init();
            initProcessingPasses();
            addToDOM();
            animate();

        }
    }

})();

TestBlending.init();

Any help would be greatly appreciated. Thanks

A: The major issue is that the target texture of processing.pass.renderScene1 is added twice. It is added as a separate pass to composerBlending and it is also used in processing.pass.blending.
Create a blending shader, which does not use the default diffuse texture tDiffuse:
THREE.Custom.AdditiveShader = {
  uniforms: {
      tBase:  { type: "t", value: null },
      tAdd:   { type: "t", value: null },
      fCoeff: { type: "f", value: 1.0 }
  },

  vertexShader: [
      "varying vec2 vUv;",

      "void main() {",
          "vUv = uv;",
          "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
      "}"
  ].join("\n"),

  fragmentShader: [
      "uniform sampler2D tBase;",
      "uniform sampler2D tAdd;",
      "uniform float fCoeff;",

      "varying vec2 vUv;",

      "void main() {",
          "vec4 texel = texture2D( tBase, vUv );",
          "vec4 add = texture2D( tAdd, vUv );",
          "gl_FragColor = texel + add * fCoeff;",
      "}"
  ].join("\n")
};

and set the 2 textures, which are created by the scene passes, manually to the unifor sampler variables of the blending pass.
composerBlending = new THREE.EffectComposer( renderer, renderTarget );
processing.pass.blending.uniforms[ 'tBase' ].value = composerScene1.renderTarget2.texture;
processing.pass.blending.uniforms[ 'tAdd' ].value = composerScene2.renderTarget2.texture;
composerBlending.addPass( processing.pass.blending );

See the code snippet:

THREE.Custom = THREE.Custom || {};

// Taken from https://github.com/stemkoski/stemkoski.github.com/blob/master/Three.js/js/shaders/AdditiveBlendShader.js
  THREE.Custom.AdditiveShader = {
      uniforms: {
          tBase: { type: "t", value: null },
          tAdd: { type: "t", value: null },
          fCoeff: { type: "f", value: 1.0 }
      },

      vertexShader: [
          "varying vec2 vUv;",

          "void main() {",
              "vUv = uv;",
              "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
          "}"
      ].join("\n"),

      fragmentShader: [
          "uniform sampler2D tBase;",
          "uniform sampler2D tAdd;",
          "uniform float fCoeff;",

          "varying vec2 vUv;",

          "void main() {",
              "vec4 texel = texture2D( tBase, vUv );",
              "vec4 add = texture2D( tAdd, vUv );",
              "gl_FragColor = texel + add * fCoeff;",
          "}"
      ].join("\n")
  };

var TestBlending = (function (){

    var canvasWidth, canvasHeight, canvasRatio;

    var clock = new THREE.Clock();
    var container, camera, scene1, scene2, renderer;

    var stats, statsDisplay = true;
    var box1, box2;

    var composerFinal, composerScene1, composerScene2, composerBlending, renderTarget;
    var composerDebugScene1, composerDebugScene2;

    var delta;

    function createScene1 () {

        scene1 = new THREE.Scene();
        scene1.name = "scene1";

        var light = new THREE.DirectionalLight( 0xffffff, 1 );
        light.position.set( 0, 10, 20 );
        light.name = "light1";

        scene1.add(light);

        var material = new THREE.MeshPhongMaterial( { color: 0xcc00cc } );
        var geometry = new THREE.BoxGeometry( 1, 1, 1 );
        box1 = new THREE.Mesh( geometry, material );
        scene1.add( box1 );

    }
    function createScene2 () {

        scene2 = new THREE.Scene();
        scene2.name = "scene2";

        var light = new THREE.DirectionalLight( 0xffffff, 1 );
        light.position.set( 0, 10, 20 );
        light.name = "light2";

        scene2.add(light);

        var material = new THREE.MeshPhongMaterial( { color: 0x33cc33 } );
        var geometry = new THREE.BoxGeometry( 1, 1, 1 );
        box2 = new THREE.Mesh( geometry, material );
        scene2.add( box2 );

    }

    function init() {

        container = document.getElementById('test_blending');

        updateCanvasSize();

        // RENDERER
        renderer = new THREE.WebGLRenderer( {
            antialias: true,
            alpha: true
        } );
        renderer.setPixelRatio( (window.devicePixelRatio) ? window.devicePixelRatio : 1 );
        renderer.setSize(canvasWidth, canvasHeight);
        renderer.setClearColor( new THREE.Color(0x0), 0 );
        renderer.autoClear = false;

        // CAMERA
        camera = new THREE.PerspectiveCamera( 10, canvasRatio, 1, 100 );
        camera.position.set(0, 0, 30);
        camera.lookAt(new THREE.Vector3(0,0,0));

        createScene1();
        createScene2();

        window.addEventListener( 'resize', onWindowResize, false );

    }

    function updateCanvasSize () {
        canvasWidth = window.innerWidth;
        canvasHeight = window.innerHeight;
        canvasRatio = canvasWidth / canvasHeight;
    }

    function initProcessingPasses () {

        var parameters = {
            minFilter: THREE.LinearFilter,
            magFilter: THREE.LinearFilter,
            format: THREE.RGBAFormat,
            stencilBuffer: true,
        };

        var parameters2 = {
            minFilter: THREE.LinearFilter,
            magFilter: THREE.LinearFilter,
            format: THREE.RGBAFormat,
            stencilBuffer: true,
        };
        renderTarget = new THREE.WebGLRenderTarget( canvasWidth, canvasHeight, parameters );

        processing = { pass: {}, texture: {} };

        processing.pass.clear = new THREE.ClearPass();

        processing.pass.renderScene1 = new THREE.RenderPass( scene1, camera );
        processing.pass.renderScene1.clear = true;
        processing.pass.renderScene1.renderToScreen = false;
        processing.pass.renderScene1.clearDepth = true;

        processing.pass.renderScene2 = new THREE.RenderPass( scene2, camera );
        processing.pass.renderScene2.clear = true;
        processing.pass.renderScene2.renderToScreen = false;
        processing.pass.renderScene2.clearDepth = true;

        processing.pass.blending = new THREE.ShaderPass( THREE.Custom.AdditiveShader );
        processing.pass.blending.renderToScreen = false;
        processing.pass.blending.clear = true;

        processing.pass.output = new THREE.ShaderPass( THREE.CopyShader );
        processing.pass.output.needsSwap = true;
        processing.pass.output.renderToScreen = true;

        setPostProcessingPasses();

      }

      function setPostProcessingPasses () {

        console.log('setPostProcessingPasses');

        composerScene1 = new THREE.EffectComposer( renderer, renderTarget );
        composerScene1.addPass( processing.pass.clear );
        composerScene1.addPass( processing.pass.renderScene1 );
        processing.texture.renderedScene1 = new THREE.TexturePass(composerScene1.renderTarget2.texture);

        composerScene2 = new THREE.EffectComposer( renderer, renderTarget );
        composerScene2.addPass( processing.pass.clear );
        composerScene2.addPass( processing.pass.renderScene2 );
        processing.texture.renderedScene2 = new THREE.TexturePass(composerScene2.renderTarget2.texture);

        composerBlending = new THREE.EffectComposer( renderer, renderTarget );
        processing.pass.blending.uniforms[ 'tBase' ].value = composerScene1.renderTarget2.texture;
        processing.pass.blending.uniforms[ 'tAdd' ].value = composerScene2.renderTarget2.texture;
        composerBlending.addPass( processing.pass.blending );
        processing.texture.renderedBlending = new THREE.TexturePass(composerBlending.renderTarget2.texture);

        composerFinal = new THREE.EffectComposer( renderer, renderTarget );
        composerFinal.addPass( processing.texture.renderedBlending );
        composerFinal.addPass( processing.pass.output );

        composerDebugScene1 = new THREE.EffectComposer( renderer, renderTarget );
        composerDebugScene1.addPass( processing.pass.clear );
        composerDebugScene1.addPass( processing.texture.renderedScene1 );
        composerDebugScene1.addPass( processing.pass.output );
        composerDebugScene2 = new THREE.EffectComposer( renderer, renderTarget );
        composerDebugScene2.addPass( processing.pass.clear );
        composerDebugScene2.addPass( processing.texture.renderedScene2 );
        composerDebugScene2.addPass( processing.pass.output );
    }

    function addStats (container) {
        //stats = new Stats();
        //if (statsDisplay) container.appendChild( stats.dom );
    }

    function addToDOM() {
        container.appendChild( renderer.domElement );
        addStats(container);
    }

    function animate() {
        window.requestAnimationFrame(animate);

        var time = performance.now() * 0.001;
        var cDelta = clock.getDelta();

        box1.rotation.y = time / 5;
        box1.rotation.x = 10;

        box2.rotation.z = time / -5;
        box2.rotation.x = time / -5;
        box2.rotation.y = 5;

        //stats.update();

        render();
    }

    function render() {

        delta = clock.getDelta();

        renderer.setViewport( 0, 0, canvasWidth, canvasHeight );

        composerScene1.render(delta);
        composerScene2.render(delta);
        composerBlending.render(delta);
        composerFinal.render(delta);

        // DEBUG
        renderer.setViewport( 0, 0, canvasWidth/3, canvasHeight/3 );
        composerDebugScene1.render(delta);
        renderer.setViewport( canvasWidth/3*2, canvasHeight/3*2, canvasWidth/3, canvasHeight/3 );
        composerDebugScene2.render(delta);

    }

    function onWindowResize() {
        updateCanvasSize();
        camera.aspect = canvasRatio;
        camera.updateProjectionMatrix();
        renderer.setSize( canvasWidth, canvasHeight );
        composerScene1.setSize( canvasWidth, canvasHeight );
        composerScene2.setSize( canvasWidth, canvasHeight );
        composerBlending.setSize( canvasWidth, canvasHeight );
        composerFinal.setSize( canvasWidth, canvasHeight );
    }

    return {
        init: function () {
            init();
            initProcessingPasses();
            addToDOM();
            animate();

        }
    }

})();

TestBlending.init();


text:
Q: Reference variable in one event handler, in another event handler I have the following event handlers chained.
The code is used for detecting if user has scrolled, but thats not important. More a question on scope.
this.myElement.on('touchstart', (e) => {
    const startY = window.pageYOffset;
  }).on('touchend', (e) => {
    const endY = window.pageYOffset;
    if (startY === endY) {
      //do stuff
    }
  })

How can i reference startY variable defined in first event handler (touchstart), in touchend?

A: You'll have to move it outside the handler (into a higher scope).
let startY;

this.myElement.on('touchstart', (e) => {
    startY = window.pageYOffset;
}).on('touchend', (e) => {
    const endY = window.pageYOffset;
    if (startY === endY) {
      //do stuff
    }
});


text: Q: R: is it possible to draw a diagram with SemPlot without fitting a model? The documentation for the SemPlot package doesn't appear to show any way to build a path diagram without passing a model object and the model objects appear to only be the output of fit models in e.g. lavaan. Any way to specify nodes and paths similar to Diagrammar without fitting a model to data?


text:
Q: JavaScript For loop vs for in does not work I wrote two functions named some and every to expect to get results shown as below:
console.log(every([NaN, NaN, NaN], isNaN));
// → true

console.log(every([NaN, NaN, 4], isNaN));
// → false

console.log(some([NaN, 3, 4], isNaN));
// → true

console.log(some([2, 3, 4], isNaN));
// → false

My functions are:
function every(array,predicate){
  for (var element in array){
    if (!predicate(element))
      return false;
  }
  return true;
}

function some(array, predicate){
  for (var element in array){
    if (predicate(element))
      return true;
  }
  return false;
}

But the results are all false
Once I change the for...in to for loop, the answers are correct.
function every(array, predicate) {
  for (var i = 0; i < array.length; i++) {
    if (!predicate(array[i]))
      return false;
  }
  return true;
}

function some(array, predicate) {
  for (var i = 0; i < array.length; i++) {
    if (predicate(array[i]))
      return true;
  }
  return false;
}

Why for..in can not result in the correct answer?

A: for..in iterates through the property names of the object you are iterating over.
In this case, those would be 0, 1, 2, so your attempt is calling the predicate on those and not the actual array elements.
Don't use for..in with arrays. The order of iteration is not guaranteed and it can wind up iterating over non-index properties.

A: If you don't want to use a traditional for loop, consider using a for…of loop, which iterates through the elements in an array. for…in iterates through the keys.
function every (array, predicate) {
    for (var element of array) {
        if (!predicate(element)) {
            return false;
        }
    }
    return true;
}

docs for for…of
Note: per the documentation, this requires an implementation that runs the ES6 Harmony proposal.


text:
Q: Using Powershell to migrate folder rights to another server I am interested in finding Powershell scripts that can be used\tweaked to migrate folder permissions across servers\environments.
Is this a feasible approach? I would like to automate our deployment process a little more.
Can someone point me to an example?
Thanks

A: I am not sure if you want to use PowerShell or if you need to use PowerShell.
If you dont need to, just use Robocopy.
This script would copy files;
robocopy.exe "\\SOURCESRV\ShareName" "\\DESTSRV\ShareName" /E /SEC /R:1

The /R:1 switch is not essential, just stops the program from hanging if it cannot read a file.
Maybe enable a log to monitor in case this happens? /Log:C:


text:
Q: пожете помочь с cmake? В общем как я понял надо два cmake файла, один в главной директории, другой в исходниках. на этапе линковки становиться понятно, что библиотеки не линкуются, ну вроде понятно, как мне кажется. вот два файла.
src
cmake_minimum_required (VERSION 3.16)
project (game)
include_directories (/usr/include/freetype2)

add_executable (game
    main.cpp
    game.cpp
    gl_gl_3_3.cpp
    scene-manager.cpp
    scene.cpp
    scene-load-start-menu.cpp
    sprite.cpp
    shader-proceed.cpp
    animator.cpp
    animate.cpp
    actor.cpp
    fontController.cpp
    fontBuffer.cpp
    button.cpp
    sound-system.cpp
    sound.cpp
    language.cpp
    isometric.cpp
    tile.cpp
    isometric-sprite.cpp
    item-board.cpp
    event-system.cpp
    search-path.cpp
    programmer.cpp
    object-manager.cpp
    item-refrigerator.cpp
    item-door.cpp
    human-manager.cpp
    time-manager.cpp
    task-manager.cpp
    item-indoor-plant.cpp
    palette.cpp
    item-dinner-board.cpp
    timer.cpp
    scene-level-home.cpp
    item-bed.cpp
    item-cupboard.cpp
    top-panel.cpp
    clock-item-top-panel.cpp
    )

find_package (PkgConfig REQUIRED)

pkg_check_modules (SDL2 sdl2)
pkg_check_modules (GL gl)
pkg_check_modules (FREETYPE freetype2)
pkg_check_modules (OPENAL openal)

find_library (AUDIO audio /usr/lib/x86_64-linux-gnu/)

target_link_libraries (game PUBLIC ${SDL2} ${GL} ${FREETYPE} ${OPENAL} ${AUDIO} )

и в root каталоге.
cmake_minimum_required (VERSION 3.16)
project (game)

add_subdirectory (src)

find_package (PkgConfig REQUIRED)

pkg_check_modules (SDL2 sdl2)
pkg_check_modules (GL gl)
pkg_check_modules (FREETYPE freetype2)
pkg_check_modules (OPENAL openal)

find_library (AUDIO audio /usr/lib/x86_64-linux-gnu/)

target_link_libraries (game PUBLIC ${SDL2} ${GL} ${FREETYPE} ${OPENAL} ${AUDIO} )

вот пример ошибок
[ 97%] Building CXX object src/CMakeFiles/game.dir/clock-item-top-panel.cpp.o
[100%] Linking CXX executable game
/usr/bin/ld: CMakeFiles/game.dir/game.cpp.o: in function `Game::run()':
game.cpp:(.text+0x44): undefined reference to `SDL_Init'
/usr/bin/ld: game.cpp:(.text+0x55): undefined reference to `SDL_GetDesktopDisplayMode'
/usr/bin/ld: game.cpp:(.text+0x6d): undefined reference to `SDL_GL_SetAttribute'
/usr/bin/ld: game.cpp:(.text+0x7c): undefined reference to `SDL_GL_SetAttribute'
/usr/bin/ld: game.cpp:(.text+0x8b): undefined reference to `SDL_GL_SetAttribute'
/usr/bin/ld: game.cpp:(.text+0x9a): undefined reference to `SDL_GL_SetAttribute'
/usr/bin/ld: game.cpp:(.text+0xc7): undefined reference to `SDL_CreateWindow'
/usr/bin/ld: game.cpp:(.text+0xdd): undefined reference to `SDL_GL_CreateContext'
/usr/bin/ld: game.cpp:(.text+0x13e): undefined reference to `SDL_GL_SetSwapInterval'

A: вроде как надо
target_link_libraries (game ${SDL2_LIBRARIES} ...

в файнд макросах либ обычно есть инструкция подключения
советую написать добавление исходников по маске
file(GLOB SOURCE &{CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
add_executable(game ${SOURCE}

в рут сmake удали все что после add_subdirectory, а то дубляж
в src удали project()


text:
Q: Is there any Customizable Sniff Properties for classes/traits/interfaces? is there any Customizable Sniff Properties for classes/traits/interfaces to do the followings;

*

*not allow a blank line before the first content

*One blank line after the last content

I am expecting a rule for something like this.
example

Valid code

Class Example()
{
  /** Content */

}

Invalid Code: After the content it does not have a blank line & before the content there is a space allowed

Class Example()
{

 /** Content */
}

A: Please refer Squiz.WhiteSpace.FunctionSpacing sniff.
Not completely it matches, but as most classes will have functions at the end, the "One line after last" can be enforced and if the class content starts with a function, the "No blank line before first" as well.
Refererance: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Customisable-Sniff-Properties#squizwhitespacefunctionspacing
found this solution form different source