text:
Q: How to filter/ add CSS class to an HTML table based on a user's input to HTML form using Java script of JQUERY I am very new to java script/ JQUERY and would appreciate some help.
Basically I have a table with maybe 50-100 entries.
I'm trying to build a website where a user inputs their data into a form and I want the website to hide the table results that doesnt meet their requirements specified on the form OR to add a CSS style class like a green or red border to signal yes or no.
Similar to this website
https://www.prospectivedoctor.com/medical-school-chance-predictor-2/
I'm really struggling
Also, I can appreciate that my solution is quite clunky so would appreciate it if anyone has shorter/ more elegant way to code it so that I can expand it easily to multiple categories.
This is my (truncated) HTML:
<form>
    <select id = "courset" name = "coursetype">
        <option value = "PBL"> PBL</option>
        <option value = "Integrated">Integrated</option>
        <option value = "Traditional">Traditional</option>
        <option value = "Unsure">Not Sure</option>
    </select>

            <input type = "Submit">

</form>

            University
            Course Type
            GSCE Requirements
            A Level Requirements
            Admissions Test

                Uni1
                Integrated
                 5 As
                AAA
                UCAT

                Uni2
                Traditional
                 10 As
                CCC
                None

This is my JQuery and JS:
$(document).ready(function() {
$('#submit').click(
    function submission(){
        var results = $("form").serializeArray();
        function admission () {
                function showTableData() {
                    var myTab = document.getElementById('empTable');
                    // LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
                    for (i = 1; i < myTab.rows.length; i++) {
                        // GET THE CELLS COLLECTION OF THE CURRENT ROW.
                        var objCells = myTab.rows.item(i).cells;
                        // LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
                        for (var j = 0; j < objCells.length; j++) {
                            objCells.item(j).innerHTML
                            if (objCells.item(j).innerHTML === results[16].coursetype){
                                myTab.rows.item(i).style.borderColor = 'green';
                            }

                        }
                    }
                }
        }
    }
);

})

note that I used results[16] because imagine that coursetype is the 17th input item. I couldn't work out a better way to target the input.
*** UPDATE ***
So I amalgamated your solutions which worked pretty well. However, I've hit a block with this particular criteria. Note:  I needed a way for the JQuery to recognise that if someone selects value = 8, then they're also eligible for any unis with entry criteria <8.
Here's my HTML
<form>
    <select id = "Agrad" name = "A Level Grades">
        <option value = "8">A*A*A* </option>
        <option value = "7">A*A*A</option>
        <option value = "6">A*AA</option>
        <option value = "5">AAA</option>
        <option value = "4">AAB</option>
        <option value = "3">ABB</option>
        <option value = "2">BBB</option>
        <option value = "1">BBC</option>
        <option value = "0">BCC or lower</option>
     </select>

             <input type = "button" Value = "Submit">

</form>

                University
                Course Type
                GSCE Requirements
                A Level Requirements
                Admissions Test

                    Uni1
                    Integrated
                     5 As
                    AAA
                    UCAT

                    Uni2
                    Traditional
                     10 As
                    CCC
                    None

                    Uni3
                    Integrated
                     5 As
                    A*A*A*
                    UCAT

Here's my JQuery
$(document).ready(function() {
    $('input[type=button]').click(function() {
// A Grades
        var selected_agrade = $("#Agrad").val();
        $("tr").each(function(tr_index, tr) {
            var needed_agrade = $("tr").attr("agrade");
            if(needed_agrade.includes(selected_agrade)) {
                $(tr).addClass('fit');
            } else {
                $(tr).removeClass('fit');
            }
        });

    });
});

Can you see any obvious reason why it's not working?
Thanks!

A: I've edited your html a little(maybe typo fixed, courset -> course) and rewritten your js code. If you use jQuery, you can easily find dom elements and manipulate it. Also if you use each of jQuery, it's easy to iterate through elements. Note that it's only working with this truncated html so you may need to handle selectors like tr.

$('input[type=button]').click(function() {
    var selected_course = $("#course").val();

    $("tr").each(function(tr_index, tr) {
        var course = $(tr).find(".tabcourse").text();
        if(selected_course == course) {
            $(tr).addClass('green_background');
        } else {
            $(tr).removeClass('green_background');
        }
    });
});
.green_background {
  background-color:green;
}

<form>
  <select id = "course" name = "coursetype">
    <option value = "PBL"> PBL</option>
    <option value = "Integrated">Integrated</option>
    <option value = "Traditional">Traditional</option>
    <option value = "Unsure">Not Sure</option>
  </select>

    <input type = "button" Value="Submit" >

</form>

       University
       Course Type
       GSCE Requirements
       A Level Requirements
       Admissions Test

      Uni1
      Integrated
       5 As
      AAA
      UCAT

      Uni2
      Traditional
       10 As
      CCC
      None

A: There are two tried and true ways that many people might approach this problem. One way is to filter based on the value of a text node in a table cell someValue	 (the literal way of doing this), or filtering based on meta data embedded in the table cell opening tag using the data-something="value") convention.
My inclination is to avoid dealing with text nodes in a situation like this due to various anomalies that can make dealing with them trickier than you might think. For instance, what if a table cell has an empty text node. What if the table cell  failed to materialize for some reason. I say go up one level and deal with the table row,
.
First, you might think about embedding some useful attribute into each table row:

`

You will have to decide what you think is best. Using numbers for the attribute value is convenient, because then you can change the value attribute of the <option> tags in your <select> list to say something like:
<option value="1">PBL</option>
<option value="2">Integrated</option>
<option value="3">Traditional</option>
<option value="4">Not Sure</option>

However, for code clarity, this might be better.
<select id="courset" name="coursetype">
    <option value="All">All</option>
    <option value="PBL">PBL</option>
    <option value="Integrated">Integrated</option>
    <option value="Traditional">Traditional</option>
    <option value="Not_Sure">Not Sure</option>
</select>

`

With each row containing essential meta information, your task becomes much easier than dealing with text nodes. Simply ...
var tbody = document.getElementById('idOfTbody');
var tableRows = tbody.getElementsByTagName('tr');
Now that you have all of the table rows in a variable, the game is a foot!
I might note that in situations like this, you end up needing to toggle on and off the rows depending on which option you pick from the select list. Be sure to have a way for all of the rows to show (hence, the all option or something similar).
Now, all you must do is loop through the table rows, and change the CSS to display:none. I would define a class in my CSS and use something like.
 someTableRow.className="remove";

Yes, you can do something like ...
 someTableRow.style.display="none";

... but, you really should take advantage of CSS classes in a case like this. However, if you bump into a complex situation in which there is already a class on the row, and you don't know how to deal with (add and remove) multiple classes in the .className string, just use the second way.
You pick the kind of loop you want. Here's a basic outline of what to do.
Note, there are various array functions (.filter(), .map(). blah, blah) that might enable you to do a .foreach() and what have you, but here is the most fundamental way to do this.
function filterTableRowsByAttribute (tableRows, rowAttribute, filterValue)
{
    var i,
        row;

    for (i=0; i < tableRows.length; i++) {
        row = tableRows[i];

        if (row.getAttribute(rowAttribute) !== filterValue) {
            removeElement(row);
        } else {
            showTableRow(row);
        }
    }
}

function removeElement(element)
{
    element.style.display="none";
}

function showTableRow (element)
{
    element.style.display="table-row";
}

var filterValue = "Integrated"; // Grab that value from the selection list.
var tbody = document.getElementById('tbodyId'); // Give your tbody an id
var tableRows = tbody.getElementsByTagName('tr');
var targetAttribute = "data-type"

filterTableRowsByAttribute(tableRows, targetAttribute, filterValue);

Conclusion
Making decisions about table rows by an attribute is simpler than dealing with text nodes, or fiddling with the innerHTML. Nested loops are not necessary. Break the problem down into steps. Don't let jQuery bamboozle you. :-) Filtering table rows is easier when the table row elements themselves have enough information to filter by.
The alternative would be to examine the text node in the appropriate table data cell, and then walk up the down to hide the table row.
Gather all table data cells to be examined.
var tableCells = document.getElementsByClassName("tabcourse");

Inspect and test the value of the text node inside of table data cell.
function filterTableRowsByCell(tableCells, filterValue)
{
    let i,
        cell,
        tableRows,
        row;

    tableRows = getTableRowsFromCells(tableCells)

    for (i = 0; i < tableCells.length; i++) {
        cell = tableCells[i];
        row = tableRows[i];

        if (cell.nodeValue !== filterValue) {
            removeElement(row);
        } else {
            showTableRow(row);
        }
    }
}


text:
Q: Error 500 SonataAdmin: Cannot use object of type Symfony\Component\Form\FormRenderer as array I get the error "Cannot use object of type Symfony\Component\Form\FormRenderer as array" when I try to create a new entity in my Sonata Admin Bundle with Symfony. I didn't have that issue before and I haven't changed anything in the Admin file.
Environment
Php 7.0, Mysql

Sonata packages
$ composer show --latest 'sonata-project/*'
sonata-project/admin-bundle 3.x-dev 51387ad dev-master cd61e55
sonata-project/block-bundle 3.x-dev 033f4e1 dev-master 64a897b
sonata-project/cache 1.x-dev adb8f3e 1.x-dev adb8f3e
sonata-project/core-bundle 3.x-dev 16c7611 dev-master 3ac1797
sonata-project/datagrid-bundle 2.x-dev 66dcb36 2.x-dev 66dcb36
sonata-project/doctrine-extensions 1.x-dev b07f636 dev-master b969484
sonata-project/doctrine-orm-admin-bundle 3.x-dev b06d010 dev-master 66219fe
sonata-project/easy-extends-bundle 2.x-dev 60edcd3 2.x-dev 60edcd3
sonata-project/exporter 1.x-dev 2aa197e 1.x-dev 2aa197e
sonata-project/media-bundle dev-master 504b500 dev-master 504b500
sonata-project/notification-bundle 3.x-dev e27bbc2 dev-master 84e6c0b

Symfony packages
$ composer show --latest 'symfony/*'
symfony/monolog-bundle dev-master c9fb33a dev-master c9fb33a
symfony/phpunit-bridge 3.4.x-dev 5ddca7a dev-master 9c5da0f
symfony/polyfill-apcu dev-master cec3239 dev-master cec3239
symfony/polyfill-intl-icu dev-master 4aa0b65 dev-master 4aa0b65
symfony/polyfill-mbstring dev-master 7c8fae0 dev-master 7c8fae0
symfony/polyfill-php56 dev-master e85ebde dev-master e85ebde
symfony/polyfill-php70 dev-master b6482e6 dev-master b6482e6
symfony/polyfill-util dev-master 67925d1 dev-master 67925d1
symfony/security-acl dev-master ab4dfe2 dev-master ab4dfe2
symfony/swiftmailer-bundle 2.6.x-dev 11555c3 dev-master d31de92
symfony/symfony 3.4.x-dev 30e3b6d 3.4.x-dev 30e3b6d

PHP version
$ php -v
PHP 7.0.23-1+020170902060934.6+stretch1.gbpa985da (cli) (built: Sep 2 2017 06:09:36) ( NTS )

Here's what my Admin file looks like:
use Doctrine\ORM\EntityRepository;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

class TeamAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->with('Infos')
            ->add('name', 'text');
        $formMapper->add('manager', 'sonata_type_model_list', array(
            'class' => 'UserBundle:User',
            'required' => true,
            'by_reference' => false,
            'required' => false
        ), array(
            'edit' => 'inline',
            'inline' => 'table',
        ))
            ->end()
            ->with('General')
            ->add('members', 'sonata_type_collection', array(
                'required'=> false
            ), array(
                'edit' => 'inline',
                'inline' => 'table',
                'sortable' => 'position'

            ))
            ->add('comexAdmins',
                null,
                array(
                    'label' => 'Admin Comex',
                    'expanded' => true,
                    'by_reference' => false,
                    'multiple' => true,
                    'query_builder' => function(EntityRepository $er)
                    {
                        return $er->createQueryBuilder('u')
                            ->where('u.level = 3');
                    }
                ))
            //            ->add('title')
//            ->add('abstract')
//            ->add('content')
            ->end();

    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper->add('name');
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper->addIdentifier('name');
        $listMapper->add('manager');
        $listMapper->add('comexAdmins');

        $listMapper->add('_action', null, array(
            'actions' => array(
                'show' => array(),
                'edit' => array()
            )
        ));
    }

    public function prePersist($team)
    {
        $this->preUpdate($team);
    }

    public function preUpdate($team)
    {
        $team->getManager();
    }
}

This is the Team Entity
class Team
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, unique=true)
     */
    private $name;

    /**
     * One Team has One Manager.
     * @ORM\OneToOne(targetEntity="User", inversedBy ="managerOf", cascade={"persist"})
     * @ORM\JoinColumn(name="manager_id", nullable =true)
     */
    private $manager;

    /**
     * @ORM\ManyToMany(targetEntity="UserBundle\Entity\User", inversedBy="comexTeams", cascade={"persist"})
     */
    private $comexAdmins;

    /**
     * One Team has many members.
     * @ORM\ManyToMany(targetEntity="User", mappedBy ="teams", cascade={"persist"})
     */
    private $members;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Team
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    public function __toString()
    {
        return $this->name;
    }

    /**
     * Set manager
     *
     * @param \UserBundle\Entity\User $manager
     *
     * @return Team
     */
    public function setManager(\UserBundle\Entity\User $manager = null)
    {
        $this->manager = $manager;

        return $this;
    }

    /**
     * Get manager
     *
     * @return \UserBundle\Entity\User
     */
    public function getManager()
    {
        return $this->manager;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->members = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add member
     *
     * @param \UserBundle\Entity\Team $member
     *
     * @return Team
     */
    public function addMember(\UserBundle\Entity\User $member)
    {
        $this->members[] = $member;

        return $this;
    }

    /**
     * Remove member
     *
     * @param \UserBundle\Entity\Team $member
     */
    public function removeMember(\UserBundle\Entity\User $member)
    {
        $this->members->removeElement($member);
    }

    /**
     * Get members
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMembers()
    {
        return $this->members;
    }

    /**
     * Add comexAdmin
     *
     * @param \UserBundle\Entity\User $comexAdmin
     *
     * @return Team
     */
    public function addComexAdmin(\UserBundle\Entity\User $comexAdmin)
    {
        $this->comexAdmins[] = $comexAdmin;
        $comexAdmin->addComexTeam($this);

        return $this;
    }

    /**
     * Remove comexAdmin
     *
     * @param \UserBundle\Entity\User $comexAdmin
     */
    public function removeComexAdmin(\UserBundle\Entity\User $comexAdmin)
    {
        $this->comexAdmins->removeElement($comexAdmin);
    }

    /**
     * Get comexAdmins
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getComexAdmins()
    {
        return $this->comexAdmins;
    }

    /**
     * Returns Members ids
     * @return array
     */
    public function getMembersIds()
    {
        $ids = array();
        foreach($this->getMembers() as $member)
        {
            $ids[] = $member->getId();
        }
        return $ids;
    }
}

A: Add this setting to your app/config/services.yml
twig.form.renderer2:
    class: Symfony\Bridge\Twig\Form\TwigRenderer
    tags:
        - { name: twig.runtime }
    arguments: [ '@twig.form.engine', '@security.csrf.token_manager']

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hermite Interpolation I am trying to interpolate between 4 points using a Hermite spline. However my spline seems to always start on the second point and only interpolate to the 3rd point. I have tried this with several differnt calculations and keep getting the same result.
Can anyone give me insight on this? Here is my code.
public ControlPoint Get(float t)
{
    //speed multiplyer
    //t = t * 10;

    return new ControlPoint(
        new Vector3(Hermite(points[0].pos.x,  points[1].pos.x, points[2].pos.x, points[3].pos.x, t)
        , Hermite(points[0].pos.y, points[1].pos.y, points[2].pos.y, points[3].pos.y, t)
        , Hermite(points[0].pos.z, points[1].pos.z, points[2].pos.z, points[3].pos.z, t)
        ),
        new Quaternion(Hermite(points[0].rot.x, points[1].rot.x, points[2].rot.x, points[3].rot.x, t)
        , Hermite(points[0].rot.y, points[1].rot.y, points[2].rot.y, points[3].rot.y, t)
        , Hermite(points[0].rot.z, points[1].rot.z, points[2].rot.z, points[3].rot.z, t)
        , Hermite(points[0].rot.w, points[1].rot.w, points[2].rot.w, points[3].rot.w, t)
        )
        );
}

float Hermite(
    float y0, float y1,
    float y2, float y3,
    float mu,
    float tension = 0,
    float bias = 0)
{
    float m0, m1, mu2, mu3;
    float a0, a1, a2, a3;

    mu2 = mu * mu;
    mu3 = mu2 * mu;
    m0 = (y1 - y0) * (1 + bias) * (1 - tension) / 2;
    m0 += (y2 - y1) * (1 - bias) * (1 - tension) / 2;
    m1 = (y2 - y1) * (1 + bias) * (1 - tension) / 2;
    m1 += (y3 - y2) * (1 - bias) * (1 - tension) / 2;
    a0 = 2 * mu3 - 3 * mu2 + 1;
    a1 = mu3 - 2 * mu2 + mu;
    a2 = mu3 - mu2;
    a3 = -2 * mu3 + 3 * mu2;

    return (a0 * y1 + a1 * m0 + a2 * m1 + a3 * y2);
}

A: I'm not an expert Hermite Splines by any stretch of the imagination, but from what I've seen is that the expected behavior would be to interpolate between the second and third point. It looks to me like you just hardcoded in each coordinate to your Get function, so it makes sense that you only get a single interpolation when a Hermite Spline is a function. Think of the second and third points as the two points you want to interpolate between, and the first and fourth points just help to create a better curve.
Since it appears you only have four points total, to interpolate between the first and second points, and third and fourth points, try repeating your first coordinates and last coordinates.
//Interpolate between 1st and 2nd points' x coord
Hermite(points[0].pos.x, points[0].pos.x, points[1].pos.x, points[2].pos.x);
//Interpolate between 3rd and 4th points' x coord
Hermite(points[2].pos.x, points[3].pos.x, points[4].pos.x, points[4].pos.x);
To interpolate between the first and second points points[0] is repeated twice because there is no points[-1]. For interpolation between the third and fourth points, points[4] is repeated because there is no points[5].
To reiterate, do not hardcode in coordinates unless you only want a single interpolation. You'll have to modify your Get function and call it a few times to adjust for the behavior you want. Check out how Snea implemented a Hermite Spline in his DrawGraph function, it helped me to better understand Hermite Spline behavior: Cubic Hermite Spline behaving strangely


text:
Q: Gráfico do Python não mostra todos os valores no eixo X Usei a biblioteca pandas para ler um arquivo csv e criar um gráfico utilizando matplotlib:
import pandas as pd
import matplotlib.pyplot as plt

brazil_dataset = pd.read_csv('/content/states.csv')

fig, ax = plt.subplots()
brazil_dataset.plot('UF', 'Population', ax=ax)
plt.show()

Entretanto, não aparece todos os estados no eixo x do gráfico e os valores de y estão simplificados. Gostaria de saber como gerar o gráfico completo.

A: Imports:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Estados Brasileiros:
estados = np.array(['AC','AL','AP','AM','BA','CE',
                    'DF','ES','GO','MA','MT','MS',
                    'MG','PA','PB','PR','PE','PI',
                    'RJ','RN','RS','RO','RR','SC',
                    'SP','SE','TO'])

Dados fictícios:
populacao = np.random.randint(1000, size = 27)

Criando o dataset:
brazil_dataset = pd.DataFrame({'UF': estados, 'Population' : populacao})

Plotando o gráfico:
fig, ax = plt.subplots()
brazil_dataset.plot('UF', 'Population', ax = ax)
ax.set_xticks(range(len(brazil_dataset['UF'])))
ax.set_xticklabels(brazil_dataset['UF'])
plt.xticks(rotation = 45)
plt.show()

Em ax.set_xticks setamos quantos labels(rótulos) irão existir no gráfico.
Em ax.set_xticklabels setamos os labels(rótulos), as strings.
Você também pode plotar sem ser diretamente pelo dataframe:
plt.figure(figsize=(14,10))
plt.plot('UF','Population', data = brazil_dataset)
plt.xticks(rotation = 45)
plt.show()


text:
Q: C# calling native method without allocating memory for required structure parameter I have a working C# wrapper class for a native library.
Almost all the native methods are expecting a pointer to structure as a parameter, for example:
returntype1 method1(struct1** param1, ...); // yes, there is one method with double reference parameter
returntype2 method2(struct1* param2, ...); // most of the methods expects simple pointer to struct
returntype3 method3(struct1* param3, ...); // most of the methods expects simple pointer to struct

The required structure parameter is defined in the C library header file.
My wrappers are following:
[DllImport(LibraryName, CharSet = Charset.Ansi)]
public static extern int WrapperMethod1(ref IntPtr struct1, ...);

[DllImport(LibraryName, CharSet = Charset.Ansi)]
public static extern int WrapperMethod2(IntPtr struct1, ...);

What is not clear for me, how can the wrapper even work, when I simply do NOT define and use the managed version of the native structure? But it works! Tested all the methods and they work exactly as expected.
I simply call them like:
var ptr = IntPtr.Zero;
WrapperClass.WrapperMethod1(ref ptr, ...);
WrapperClass.WrapperMethod2(ptr, ...);

Why I do not need to allocate memory for the structure using for example Marshal.AllocHGlobal or Marshal.StructureToPtr ? Why it simply works just by specifying a simple IntPtr without any structre defintion and allocation?


text:
Q: Attempting to pass flag to use Chrome via RemoteApp I'm new to VBS but attempting to figure this out on my own but I'm getting to the end of my rope. I have a VBS script that I am using from another poster to open Chrome via RemoteApp on 2008 R2. The script I'm using is:
Dim iURL
Dim objShell

iURL = "www.google.com"

set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "chrome.exe", iURL, "", "", 1

Opening browser on a variable page using vbscript
After getting this to initially launch Chrome via RemoteApp, I found that Chrome crashes without loading the page (doesn't matter what the URL is). Further research led me to this page, which recommended including the flag --allow-no-sandbox-job when launching Chrome via RemoteApp.
What I can't seem to figure out is how to include the above flag within the initial VBScript.

A: Try this:
objShell.ShellExecute "chrome.exe", iURL & " --allow-no-sandbox-job"  , "", "", 1


text:
Q: Undefined method 'stringify_keys' error when using many to many association There are lots of stringify_keys questions here, but i can't find proper match to my problem, so i'll appreciate at least any example matching it.
I have three models named Song, Mixtape and MixtapeSong.
class Song < ActiveRecord::Base
  attr_accessible :duration, :name, :order

  belongs_to :album

  has_many :mixtape_songs
  has_many :mixtapes, :through => :mixtape_songs
end

class Mixtape < ActiveRecord::Base
  attr_accessible :description, :image, :name

  has_many :mixtape_songs
  has_many :songs, :through => :mixtape_songs
end

class MixtapeSong < ActiveRecord::Base
  attr_accessible :mixtape_id, :order, :song_id
  belongs_to :mixtape
  belongs_to :song
end

When i tried below commands through rails console, i succeed to add a record to mixtape_songs table with mixtape_id and song_id values but also with an 'order' NULL:
mtape = Mixtape.find(1)
song  = Song.find(3)
mtape.songs << song

Also executing an update_attributes was failed with 'Undefined method signify_keys' error.
params = [:mixtape_id => 1, :song_id => 3, :order => 2]
mts = MixtapeSong.find(1)
mts.update_attributes(params)

What i need to do is adding this association through Mixtape model with specifying an 'order' value or through MixtapeSong model without 'Undefined method signify_keys' error.
I guess the right way is adding through Mixtape model but i can't figure out how to set 'order'? Any help is appreciated.

A: Fetching:
mtape = Mixtape.find(1)
songs_in_proper_order = mtape.songs.order(mixtape_songs: :created_at)

Swapping:
MixtapeSong.transaction do
    ms1 = MixtapeSong.find(1)
    ms2 = MixtapeSong.find(2)

    ms1.created_at, ms2.created_at = ms2.created_at, ms1.created_at

    ms1.save
    ms2.save
end


text:
Q: Avalonia UI, creating a custom control by drawing things One could create a control by starting from a container control (like panel) and add other existing controls (like buttons, textbox, etc) on it. But in some cases, there are no such suitable primitive controls and one has to draw things from scratch.
Avalonia UI's Visual Studio extension has a UserControl template, and it seems that it allows adding existing controls using XAML, which is the former case of the previous paragraph. But how to draw from scratch? Where is WinForm's OnPaint() equivalent or WPF's OnRender() equivalent? Is there any example of creating a control from scratch in Avalonia UI?

A:
or WPF's OnRender() equivalent

It's called Render, the name is pretty much the only difference, DrawingContext's API closely resembles WPF one.


text:
Q: Operator overload of typedef type I'm trying to use the QVM and ODEINT library. I'm using the qvm::vec<double,n> through a typedef as my state_type.  I would like to use the subscript operator for ´state_type´. (To my knowledge ODEINT requires the subscript operator.) My problem is that QVM access operator is ´A(v)´ and doesn't implement the subscript operator. How would you overload the operator or solve this problem?
#include<bits/stdc++.h>
#include <boost/numeric/odeint.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/qvm.hpp>

using namespace std;

typedef boost::multiprecision::cpp_dec_float_50 value_type;

typedef boost::qvm::vec<value_type,3> triple;

int main()
{
 \\some code
}


text:
Q: Faster Find Method and filter position comparison? Issue:  I'm having to search a large sheet for specific policy numbers.  The find function takes quite a while when there are nearly 75,000 rows.  Any suggestions on how to compare these two sheets of 75,000 rows?  A solution i thought might work would be to sort each sheet and then take the policy number needed to be found and compare it to the middle row.  Is there a way to compare that policy number and see if in the simple sort function it would be greater or less than?  After finding that comparison, i would reset the upper and lower bounds and find the middle again.  ...Would this be quicker? Are there any other suggestions?
Thank you
Current Code:
Sub policyComment()

Dim x As Integer
Dim endRow As Variant
Dim polSer As String
Dim foundVal As String
Dim commentVar As Variant

Windows("SuspenseNoteMacro.xlsm").Activate
Sheets("Main").Select

Range("A2").Select
endRow = ActiveCell.End(xlDown)

x = 2

Do
    polSer = Range("A" + CStr(x)).Value

    Windows("010713 Suspense ALL.xlsm").Activate
    Sheets("Sheet1").Select

    Set foundRange = Sheets("Sheet1").Cells.Find(what:=polSer, LookIn:=xlFormulas, lookat:=xlWhole)

   'foundRange = ActiveCell.Value
    If foundRange Is Nothing Then
        Windows("SuspenseNoteMacro.xlsm").Activate
        Sheets("Main").Select
        Range("J" + CStr(x)).Value = "Not Found"
    ElseIf foundRange <> "" Then
        Sheets("Sheet1").Cells.Find(what:=polSer, LookIn:=xlFormulas, lookat:=xlWhole).Activate
        commentVar = Range("J" + CStr(ActiveCell.Row)).Value
        Windows("SuspenseNoteMacro.xlsm").Activate
        Sheets("Main").Select
        Range("J" + CStr(x)).Value = commentVar
    End If

    x = x + 1
    Range("A" + CStr(x)).Select
    foundRange = ""
Loop Until (x = endRow)

End Sub

A: Scott already provided an answer, but FYI here is some sample code illustrating the difference between using Find() and using a Dictionary to look up 10k individual values in an unsorted range containing the same 10k values.
Output on my PC:
50.48828 sec using Find()
0.078125 sec to load dictionary (10000 keys)
0.015625 sec using Dictionary

Code (requires a reference to "Microsoft Scripting Runtime" library):
Sub TestFind()

    Dim arrToFind
    Dim numRows As Long, r As Long
    Dim f As Range, rngSrc As Range
    Dim t
    Dim d As Scripting.Dictionary

    Set rngSrc = Worksheets("Source").Range("A2:A10001")

    arrToFind = Worksheets("Dest").Range("A2:A10001").Value
    numRows = UBound(arrToFind, 1)

    t = Timer
    Debug.Print "Starting test using Find()"
    For r = 1 To numRows
        If r Mod 1000 = 0 Then Debug.Print "Row " & r
        Set f = rngSrc.Find(arrToFind(r, 1), , xlValues, xlWhole)
        If Not f Is Nothing Then
        'do something based on f
        End If
    Next r
    Debug.Print Timer - t & " sec using Find()"

    t = Timer
    Set d = UniquesFromRange(rngSrc)
    Debug.Print Timer - t & " sec to load dictionary (" & d.Count & " keys)"

    t = Timer
    Debug.Print "Starting test using Dictionary"
    For r = 1 To numRows
        If r Mod 1000 = 0 Then Debug.Print "Row " & r
        If d.Exists(arrToFind(r, 1)) Then
        'use value from dictionary
        End If
    Next r
    Debug.Print Timer - t & " sec using Dictionary"

End Sub

Function UniquesFromRange(rng As Range) As Scripting.Dictionary

    Dim d As New Scripting.Dictionary
    Dim c As Range, tmp

    For Each c In rng.Cells
       tmp = Trim(c.Value)
       If Len(tmp) > 0 Then
            If Not d.Exists(tmp) Then d.Add tmp, c.Offset(0, 1).Value
       End If
    Next c

    Set UniquesFromRange = d
 End Function

A: Your code is slow for a few reasons, but mainly because of how you are looping through each cell individually (the actual Find function is not what is slowing it down).
Below, I've put your search column into an array and looped through that, which will be much, much faster. I've also taken out all your select and activate statements, as they are extraneous 99% of the time in VBA, and can also slow down your code a bit. Lastly, I turned off ScreenUpdating which helps as well.
If I missed something in the refactoring, let me know.
Option Explicit

Sub policyComment()

Dim x As Long, endRow As Long, polSer As String, foundRange As range, commentVar As String
Dim varArr() As Variant
Dim wksMain As Worksheet, wks1 As Worksheet

Set wksMain = Sheets("Main")
Set wks1 = Sheets("Sheet1")

Application.ScreenUpdating = False

With wksMain

    endRow = .range("A" & .Rows.Count).End(xlUp).Row
    varArr = .range("A2:A" & endRow)

    For x = LBound(varArr) To UBound(varArr)

        polSer = varArr(x, 1)

        With wks1

            Set foundRange = .Cells.Find(polSer, LookIn:=xlFormulas, lookat:=xlWhole)

            If foundRange Is Nothing Then

                wksMain.range("J" & x + 1).Value = "Not Found" 'need to add 1 to x because arrays are zero based

            Else

                commentVar = .range("J" & foundRange.Row)
                wksMain.range("J" & x + 1).Value = commentVar ''need to add 1 to x because arrays are zero based

            End If

        End With

    Next

End With

Application.ScreenUpdating = True

End Sub


text:
Q: How to create simpliest PHP Get API with UTF-8 support? How to create simpliest *(less lines of code, less strange words) PHP Get  API *(so any programm made in .Net C# could call url like http://localhost/api.php?astring=your_utf-8_string&bstring=your_utf-8_string ) with UTF-8 support?
What I need Is PHP API with one function - concatinate 2 strings so that a simple .net client like this would be able to use it:
    public string setStream(string astring, string bstring)
    {
string newAstring =Uri.EscapeDataString(astring);
string newBstring = Uri.EscapeDataString(bstring);
        WebClient client = new WebClient();
        var result = client.DownloadString(("http://localhost/api.php?" + string.Format("astring={0}&bstring={1}", newAstring, newBstring)).ToString());
        return result;
    }

A: public string SetStream(string astring, string bstring)
{
    using (var client = new WebClient())
    {
        var values = new NameValueCollection() {
            "astring", astring,
            "bstring", bstring
        };
        var result = client.UploadValues(
            "http://localhost/api.php",
            "GET",
            values
        );
        return Encoding.Default.GetString(result);
    }
}

A: Dunno if I'm missing something, but:
<?php

function concatinateStrigs($a, $b){
    return $a . $b;
}

echo concatinateStrigs($_GET['astring'], $_GET['bstring']);

?>


text:
Q: How to get canGoBack functionality in Ionic 5? I'm trying to put a back button in Ionic app and to hide the back button when it's in the root, which the root is not fixed and can be changed based on the flow. I found the following code here:
...
constructor(
    private router: Router,
    private ionRouterOutlet: IonRouterOutlet
) {

}

ngOnInit() {
    this.canGoBack    = this.ionRouterOutlet.canGoBack();
...

It would be nice if it works but IonRouterOutlet is component and cannot be injected to another component like this. Any idea about how can it be done in Ionic 5 with angular?

A: @ViewChild(IonRouterOutlet, { static : true }) routerOutlet: IonRouterOutlet;

    // if (this.routerOutlet.canGoBack()) or whatevet...


text:
Q: Excel 365 Formulas - How to save LAMBDA function permanently (for all existing and new files)? I would like a global solution every time I start Excel365 with my key add-in also firing up.
I defined several LAMBDA custom functions, saved them in my add-in, and I would like to make them available globally - not just only for the current workbook. Is it possible? I tried saving a workbook with definition as an add-in (.xlam) but the formulas are not available.   The don't seem to be available when as an add-in.   When I am in the add-in parent file on the desktop, all is good and everything is running.  But once I post the file back for your as an add-in, The Lambda(s) and the defined name space go away.

A: You might try creating a template for excel to load when it is opened.
Customizing how Excel starts so it utilized the template.

A: My additional work around is also simple. If the LAMBDAs were saved in the original Workbook with "Workbook" as the saved parameter. Then each of those worksheets in the original LAMBDA workbook is "infected" with all of the workbook LAMBDAs. Therefore, I simply copy a blank worksheet from the original Workbook to the "new" workbook. Then by virtue of "infection" the new workbook is also newly infected with all of the new LAMBDAs. It works just like COVID, who knew?


text:
Q: Your child might do better Consider this sentence, please:
Your child might do better with a different teacher.
Can I paraphrase "might" with "it is possible that...would..."? For example:
It is possible that Your child would do better with a different teacher.

A: Yes, that is exactly what the first phrase means. However, your paraphrase is not as good because it ends with "would," which implies virtual certainty. It is true that you have previously qualified this with "it is possible," which negates any implication of certainty, but the formulation is still slightly contradictory and so may be interpreted differently from what you intend. The first sentence unambiguously implies possibility; it does not even formally imply probability although in practice people may use this formulation to indicate their opinion that it is not merely possible but probable.
Personally, I would use "might perhaps" to imply "not probable but possible," use "might" to mean possibility without any implication that it was more probable than not, use "might well" to indicate at least an even chance, "probably would" to indicate a much better than even chance, and "would" to indicate close to certainty, but not everyone uses the modals in the exact same way.
In short, "might" here indicates possibility unambiguously without implying much of anything about probability except that it is materially less than 100%.

A: You could use the alternative you suggest as it is correct and conveys the same meaning.
However, 'might' as a modal verb works well to be succinct in expressing possibility.
'It is possible that...' is a more wordy alternative.
You don't tell us the exact context of your sentence, but I would prefer using 'might' as it's more succinct and allows you to keep 'your child' as the subject (rather than a general 'it is'), thus keeping the focus on the human subject. It sounds more natural to me with 'might'.
Note that both alternatives allow the speaker to give additional information with 'if' if desired. For example:

Your child might do better with another teacher if you wanted
It's possible your child would do better with another teacher if you wanted


text:
Q: Handling multiple requests in a loop causes sync issues I call getLogs() through a post request and get a list of LogFileID(filename) from a DB and then I pass this LogFileID to do an additional request by calling _getLogFileUrls which gives me a signed url for that ID in response. I push all of them one by one into a global array and return it the end response.
I know it's incorrect to use setTimeout but the problem is not using, it gives me a different result into the array every time. What could I do to resolve this issue? How do I correct this code so that the loop iterates to the next only when the signed url is stored into the global array.
function _getLogFileUrls(logFileId, callback){

var request = require('request'),
    config = require('../../config.js');

var fileParams = {
    fileName: 'xyzdirectory/' + logFileId
};
request.post({
          url: config.filesServiceUrl + 'get-logfile-urls',
          json: fileParams
        },function(error, response, body) {

        if (!error && response.statusCode === 200) {
            callback(body);
        } else {
            res.status(400).send('Error requesting file service for logs:');
        }
    }).on('error', function(err) {
        console.log('File service error for Logs: ' + err);
    });
}

function getLogs(req, res){

        if(!req.body.id){
            return res.status(400).send('Please check the params!');
        }

        var date;

        if(req.body.date){
            date = req.body.date;
        } else {
            date = new Date().toISOString().slice(0,10);
        }

        var sqlQuery = "SELECT `LogFileID` FROM `logs_data` WHERE `EmpID` = '" + req.body.id + "' AND DATE(`Timestamp`) = '" + date + "'",
        resArray= [];

        hitThisQueryForMe(sqlQuery, res, function(rows){

            if(!rows.length) res.json(rows);

            _.each(rows, function(item){
                console.log('item: ' + item.LogFileID);
                _getLogFileUrls(item.LogFileID, function(response){
                    resArray.push(response);
                });
            });

            setTimeout(function(){
                res.send(resArray);
                resArray = [];
            }, 4000);

        });

    }

A: SQL injection alert
First of all, your code has a serious SQL injection vulnerability. Never use string concatenation to create SQL using user-provided data or otherwise anyone will be able to read, modify and delete anything in your database. This is very serious security issue. For more details see those answers:

*

*cannot use backtick when using nodejs 7.3.0

*How to escape mysql special characters with sockets.io/node.js/javascript
The answer
Now to answer your question. To handle what you try to do here you should either stick to callbacks and use a good module to handle concurrency like Async:

*

*https://caolan.github.io/async/
Or you can use promises with a good module to help with concurrency like Q or Bluebird:

*

*http://documentup.com/kriskowal/q/

*http://bluebirdjs.com/
Additionally when working with promises you can use generator-based coroutines with tools like co or Bluebird.coroutine:

*

*https://github.com/tj/co

*http://bluebirdjs.com/docs/api/promise.coroutine.html
Or you can use ES8 async/await:

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Those are the main ways to handle cases like yours. Reinventing the wheel of concurrency handling can lead (as you can see here) to error-prone, hard to maintain code.
I recommend using the right tool for the job.

A: Use async/await
Install asyncawait library and its dependency bluebird:
npm install asyncawait --save
npm install bluebird --save

Your edited code should look like:
const async = require('asyncawait/async');
const await = require('asyncawait/await');
const Promise = require('bluebird');
const request = require('request');
const config = require('../../config.js');

function _getLogFileUrls(logFileId) {
    return new Promise((resolve, reject) => {
        var fileParams = {
            fileName: 'xyzdirectory/' + logFileId
        };

        request.post({
            url: config.filesServiceUrl + 'get-logfile-urls',
            json: fileParams
        }, function (error, response, body) {
            if (!error && response.statusCode === 200) {
                resolve(body);
            } else {
                reject('Error requesting file service for logs:');
            }
        }).on('error', function (err) {
            console.log('File service error for Logs: ' + err);
        });
    });
}

function getLogs(req, res) {

    if (!req.body.id) {
        return res.status(400).send('Please check the params!');
    }

    var date;

    if (req.body.date) {
        date = req.body.date;
    } else {
        date = new Date().toISOString().slice(0, 10);
    }

    var sqlQuery = "SELECT `LogFileID` FROM `logs_data` WHERE `EmpID` = '" + req.body.id + "' AND DATE(`Timestamp`) = '" + date + "'",
        resArray = [];

    hitThisQueryForMe(sqlQuery, res, function (rows) {

        if (!rows.length) res.json(rows);

        _.each(rows, (async function (item) {
            console.log('item: ' + item.LogFileID);
            var logFileUrlResponse = await (_getLogFileUrls(item.LogFileID));
            resArray.push(logFileUrlResponse);
        }));

        res.send(resArray);
        resArray = [];
    });
}


text:
Q: WPF TargetInvocationException when trying to change textbox text in SelectionChanged method So my code gives me a TargetInvocationException
link to screenshot of exception details
This is my code
public partial class MainWindow
    {
        Double totalPrice = 0;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void txtDiscount_SelectionChanged(object sender, RoutedEventArgs e)
        {
           Double newTotalPrice = 0;
           if (!String.IsNullOrEmpty(txtDiscount.Text))
           {
               newTotalPrice = totalPrice - Double.Parse(txtDiscount.Text);

           }
           txtFullAmount.Text = newTotalPrice.ToString();

        }

The last line is the one thats making it crash, Im trying to assign a textbox to change whenever a different textbox changes.
The funny part is that this works perfectly if I change the title instead
this.Title = newTotalPrice.ToString();

Edit: Also my original code works if used with a button instead.
Edit <TextBox Background="#ecf0f1" IsReadOnly="True" Text="" Name="txtFullAmount" SelectionChanged="txtDiscount_SelectionChanged" HorizontalAlignment="Left" Height="23" Margin="505,511,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="85"/>

A: I think you set a SelectedIndex in your XAML. In this case, the SelectionChanged event is raised before the window is completly initialized. Before the initialisation, the member variables for the controls are always null.
The easiest way is to check if the TextBox exists and return if it is null:
private void txtDiscount_SelectionChanged(object sender, RoutedEventArgs e)
{
    if(txtFullAmount == null) return;
    //your code
}

The assignment to the Title works, because this exists already at this moment.


text:
Q: Capture TAB/SHIFT-TAB on onblur event of a dropdown in javascript I want to capture Tab and Shift-Tab in the onblur event of a dropdownlist in javascript. Is it possible?
thanks,
Kishore

A: For what purpose?
I'm not sure if there's a better way to do it but you could have a couple of global boolean variables for Tab and Shift. Add keydown and keyup methods to toggle the booleans accordingly. Then during the Blur you can just do a logical check on the two.

A: onblur is not enough... You need to capture KeyEvents and check and store if tab/shift-tab are pressed. Then you can check for those keys in the blur-handler.


text:
Q: Change source address based on destination IP: NAT or routing? I have a router/host with multiple public IP addresses. I want to change the source ip depending on some destination addresses. This has already been asked here:
If the traffic originates from some internal/other host, then the source address has already been selected and we are forced to use NAT, fine.
So we're with local originated traffic. The answer to the above question suggests, that this only works using appropiate ip route entries using src.

*

*Can one create that entry without replicating the default route (which might change for example)?

Another answer on the contrary says, that NAT also works for local originated traffic.

*

*Does NAT work for local traffic?

*IF it works, is there any recommendations whether NAT or routing should be used? My current thoughts go like this:

*

*NAT has the pro, that it handles both local and non-local traffic in one rule (one place to maintain config is good!)

*NAT has all the cons of NAT.

*Routing makes things more obvious (and possibly goes into IGP easier).


text:
Q: Array from a jsonDecoder object This might be a very easy question (sorry!).
I would like to links a mySQL database to a Quiz App in Swift 4.
Therefore I connected to a service.php and got the information with decodable.
How can I access this information to show in a label? Do I have to make a new Array and append the objects?
import UIKit

struct Question: Codable {

let id: String?
let frage: String?
let antwort1: String?
let antwort2: String?
let antwort3: String?
let antwort4: String?
let correct: String?
let notiz: String?
let lernsektorID: String?
let lerneinheitID: String?
let lernbereichID: String?
let schwierigkeitID: String?
let redakteur: String?
let createdAt: String?

enum CodingKeys: String, CodingKey {
    case id = "ID"
    case frage = "Frage"
    case antwort1 = "Antwort1"
    case antwort2 = "Antwort2"
    case antwort3 = "Antwort3"
    case antwort4 = "Antwort4"
    case correct = "Correct"
    case notiz = "Notiz"
    case lernsektorID = "LernsektorID"
    case lerneinheitID = "LerneinheitID"
    case lernbereichID = "LernbereichID"
    case schwierigkeitID = "SchwierigkeitID"
    case redakteur = "Redakteur"
    case createdAt = "created_at"
}
}

var fragen = [Question]()

let url = "https://redaktion.pflegonaut.de/service.php"
let urlObj = URL(string: url)

URLSession.shared.dataTask(with: urlObj!) { (data, response, error) in
do {
     self.fragen = try JSONDecoder().decode([Question].self, from: data!)
// can I use .append() here?
// maybe in a for loop?

} catch {
    print(error)
}
}.resume()

So I can use the elements like:
//
// let randomizedQuestion = fragen.frage.randomElement()
//
// questionOutlet.text = randomizedQuestion

Thanks!

A:
// NECESSARY?
  var QuestionBankJson: [QuestionJson] {
  var questionListJson = [QuestionJson]()
  }

No, just declare one array and name the struct simply Question
var questions = [Question]()

and assign
do {
  self.questions = try JSONDecoder().decode([Question].self, from: data!)
  print(self.questions[1].Frage!)
} catch {
    print(error) // never print something meaningless like "we got an error"
}

Notes:

*

*Please conform to the naming convention that variable names start with a lowercase letter.

*If you are responsible for the JSON declare also the keys lowercased otherwise use CodingKeys.

*Declare the struct members as much non-optional as possible.

*Never print a meaningless literal string when catching Codable errors. Print always the error instance.

*Use a better date string format than this arbitrary German format. UNIX time stamp, SQL date string or ISO8601 are sortable and can be even decoded to Date.


text:
Q: How to close login.html file after user login, using flask? When a button is clicked on main.html page. It then redirects to login.html, In login.html when submit is pressed it has action="{ (login) }". In flask i have route for login. So, Now can i close that login.html page using flask(in route("/login"))

A: Instead of passing action="{(login)}" try using
action="{{url_for('login')}}"

The url_for function is used to refer to URLs based on their functions.


text:
Q: Most efficient way to look up multiple values in separate table I have two tables:
Table 1-
Gender<-c("M","F","M","M","F")
CPTCodes<-c("15777, 19328, 19342, 19366, 19370, 19371, 19380","15777, 19357","19367, 49568","15777, 19357","15777, 19357")
Df<-tibble(Gender,CPTCodes)

Table 2-
Code<-c(19328,19342,15777,49568,12345)
Value<-c(0.5,7,9,35,2)
Df2<-tibble(Code,Value)

I would like to create a third column in table 1 that has the sum of the value (from table 2) of all of the codes from the "CPTCodes" column in table 1.  So in theory I would be first separating the numbers in the CPTCodes column (as some rows have more codes than others), converting to numeric, then searching for that particular code in table 2's "Code" column, grabbing the corresponding value in table 2 and summing them to put back in table 1.  For instance, for the very first row of table 1 I would be finding the corresponding value of 15777, adding it to the corresponding value of 19328, added to value of 19342.. etc.. etc..
I had thought about first using tidyverse's "separate" to split the cptcodes column into multiple columns with one code in each column, but not every row has the same number of codes and often there are 10+,  is this the best way?
If this has already been answered somewhere please point me in the right direction.


text:
Q: Commit a file previously deleted from git I'm using XCode, SourceTree and i accidentally removed the Podfile.lock from the repository, but I have it in my pc. How can I add it again or unmarked it as removed in the repository?

A: If it's ok for you to go back in time to "remove the removal" of the file from history (as if it had never been deleted in the first place), then this is what you do. Let's assume the file was removed on master~3.
git checkout master~3
git checkout HEAD~1 -- Podfile.lock # get the file back from previous revision
git commit --amend --no-edit # commit (file should not be deleted on this revision)
git cherry-pick master~3..master # replay history of master after the revision we modified
# at this point you should verify that everything is ok
# if everything is ok, then we need to move master pointer
git branch -f master
git checkout master # checkout new "fixed" master

That should be enough. This is rewriting the history of the branch.... it has costs associated with it (other developers are already working on the old branch? They will have to rebase/cherry-pick their work on top of the new branch, for example).


text:
Q: php exec() in unicode mode? I need to execute command line commands and tools that accept ut8 as input or generate an ut8 output.
So i use cmd an it works, but when i try this from php with exec it doesn't work.
To make it simple i tried simple output redirection.
When i write direct in command prompt:

chcp 65001 > nul && echo цчшщюя-öüäß>utf8.txt

The uft8.txt is created an the content is correct.

цчшщюя-öüäß

When i use the exec function from php:
$cmd = "chcp 65001 > nul && echo цчшщюя-öüäß>utf8.txt";
exec($cmd,$output,$return);
var_dump($cmd,$output,$return);

the content in the utf8.txt is messed up:

¥Å¥Î¥^¥%¥Z¥?-ÇôǬÇÏÇY

I am using Win7,64bit with (Console) Codepage 850.
What should i do to fix that?
Additional Infos:
I am trying to overcome some issues with reading and writing of utf8 filenames on windows.
PHP file functions fail: glob, scandir, file_exists can't handle utf8 filenames correctly. File are invisible, skipped, names are changed ...
Therefore i want to avoid php file functions and i am looking for some php extern filehandling.

A: Since i couldn't find an easy, fast and reliable internal php solution, i am ending with using that i know it's work. Cmd-Batch-File.
I make a small function that generate a cmd batch file in runtime.
Its just prepends the the chcp (change the codepage) command in order to switch to unicode.
And parse the output.
function uft8_exec($cmd,&$output=null,&$return=null)
{
    //get current work directory
    $cd = getcwd();

    // on multilines commands the line should be ended with "\r\n"
    // otherwise if unicode text is there, parsing errors may occur
    $cmd = "@echo off
    @chcp 65001 > nul
    @cd \"$cd\"
    ".$cmd;

    //create a temporary cmd-batch-file
    //need to be extended with unique generic tempnames
    $tempfile = 'php_exec.bat';
    file_put_contents($tempfile,$cmd);

    //execute the batch
    exec("start /b ".$tempfile,$output,$return);

    // get rid of the last two lin of the output: an empty and a prompt
    array_pop($output);
    array_pop($output);

    //if only one line output, return only the extracted value
    if(count($output) == 1)
    {
        $output = $output[0];
    }

    //delete the batch-tempfile
    unlink($tempfile);

    return $output;

}

Usage: just like php exec():

utf8_exec('echo цчшщюя-öüäß>utf8.txt');

OR

uft8_exec('echo цчшщюя-öüäß',$output,$return);


text:
Q: Validação dos 2 últimos dígitos de CPF em um único laço for Eu fazendo a verificação dos dois últimos dígitos para validação de CPF.
Fiz o código, mas só está calculando o primeiro dígito. Não estou conseguindo, incluir no mesmo laço para calcular o segundo dígito:

    while True:

    #CPF deve ser inserido sem formatação Ex.16695835009
    cpf = input("Informe o seu CPF: ")

    if len(cpf) != 11 or not cpf.isnumeric():
        print("Dados inseridos incorretamente.\nDigite novamente.")
        continue

    novo_cpf = cpf[:-2]
    soma_digitos = 0
    lista_digitos = []

    for key, index in enumerate(novo_cpf):
        key_reverso = len(novo_cpf) + 1 - key
        lista_digitos.append(key_reverso * int(index))
        soma_digitos += lista_digitos[key]

    d = 11 - (soma_digitos % 11)

    if(d > 9):
        d = 11 - d

    '''
    Os prints abaixo é só para verificação da saída do código.
    '''
    print(lista_digitos)
    print(soma_digitos)
    print(d)

A: Até dá para fazer tudo com um único laço, só não sei se faz tanta diferença assim. Mas antes vamos tentar fazer com dois laços, aí comparamos com a versão "um-laço-só".

Antes dos laços em si, você já poderia converter a string em uma lista de números, na qual cada elemento desta lista é um dígito. Para isso podemos usar map e int:
def validar_cpf(cpf):
    if len(cpf) != 11:
        return False

    try:
        digitos = list(map(int, cpf))
    except ValueError:
        return False

    # restante da validação...

Assim, se algum caractere da string não puder ser convertido para número, ele cai no bloco except e a função já retorna False. Fiz assim porque posteriormente eu vou precisar converter esses caracteres para número, para poder fazer os cálculos do dígito verificador. Ao mesmo tempo, eu já valido se a string de fato contém dígitos.
Também escolhi desta forma porque isnumeric() pode retornar True para vários caracteres que dão erro ao serem convertidos para número com int(), como por exemplo o ½ (VULGAR FRACTION ONE HALF) - veja aqui a lista completa - então eu acho essa verificação melhor do que simplesmente usar isnumeric() (com a vantagem de que já cria a lista com os caracteres convertidos para números, pois vou precisar desses números posteriormente). Como é o usuário que está digitando os dados, existe a possibilidade dele digitar algum desses caracteres, então já fazemos esta verificação logo no início.

Agora sim, aos cálculos. Primeiro vamos fazer a versão com 2 loops (o algoritmo pode ser facilmente buscado na internet, eu usei este site como fonte):
def validar_cpf(cpf):
    if len(cpf) != 11:
        return False

    try:
        digitos = list(map(int, cpf))
    except ValueError:
        return False

    def calcula_digito(multiplicador):
        total = 0
        for d in digitos:
            if multiplicador >= 2:
                total += d * multiplicador
                multiplicador -= 1
            else: break
        resto = total % 11
        if resto < 2:
            return 0
        else:
            return 11 - resto

    # primeiro dígito não bate, CPF inválido
    if digitos[9] != calcula_digito(10):
        return False

    # segundo dígito não bate, CPF inválido
    if digitos[10] != calcula_digito(11):
        return False

    return True

Eu criei a inner function calcula_digito, que contém o loop para calcular o dígito verificador. Para o primeiro dígito verificador, começamos com 10, que é multiplicado pelo primeiro dígito do CPF, depois multiplicamos o segundo dígito por 9, o terceiro por 8, etc (parando no 2, por isso o if multiplicador >= 2, e um break para interromper o loop caso o multiplicador seja menor que 2).
No segundo dígito verificador, eu faço o mesmo algoritmo, mas começando a multiplicar por 11. A lógica do loop é a mesma, e por isso eu reaproveitei o código da função interna calcula_digito. Mas como essa função é chamada duas vezes, então estou fazendo dois laços.

Repare que o que muda de um loop para outro é somente o valor inicial do multiplicador (10 para o primeiro, 11 para o segundo), e a condição de parada é a mesma (vou até o valor do multiplicador ser 2). Sendo assim, seria possível fazer tudo em um único loop:
def validar_cpf(cpf):
    if len(cpf) != 11:
        return False

    try:
        digitos = list(map(int, cpf))
    except ValueError:
        return False

    def calcula_resto(resto):
        if resto < 2:
            return 0
        else:
            return 11 - resto

    total1 = total2 = 0
    multiplicador = 11
    for d in digitos:
        if multiplicador >= 2:
            if multiplicador >= 3:
                total1 += d * (multiplicador - 1)
            total2 += d * multiplicador
            multiplicador -= 1
        else: break

    # primeiro dígito não bate, CPF inválido
    if digitos[9] != calcula_resto(total1 % 11):
        return False

    # segundo dígito não bate, CPF inválido
    if digitos[10] != calcula_resto(total2 % 11):
        return False

    return True

Eu aproveito o mesmo loop para calcular o somatório referente a ambos os dígitos verificadores (tanto iniciando com 11 quanto com 10), e em seguida calculo os respectivos dígitos usando o resto da divisão segundo as regras do algoritmo.

Neste comentário você disse que queria fazer tudo em um único loop, pois assim "seria menos código". Bom, olhe novamente para as funções acima e veja se o ganho foi realmente significativo (na minha opinião, não foi, é praticamente a mesma quantidade de código).
Mas o ponto não é "escrever menos código". Um código mais curto não é necessariamente "melhor", assim como um código mais longo não é necessariamente "pior". Primeiro procure escrever um código claro e correto, e depois você pensa nessas otimizações.
Se está preocupado com o desempenho, sinceramente, esses loops não são tão custosos assim e para a grande maioria dos casos a diferença será irrelevante. Em sistemas reais você faz testes de desempenho para ver onde estão os gargalos e não se preocupa com essas micro-otimizações (até porque em sistemas reais, na grande maioria das vezes, provavelmente o gargalo não estará nesses loops menores).
Pense também na manutenção do código: futuramente pode ser que uma outra pessoa (ou até mesmo você) tenha que mexer no código, então o melhor é que ele esteja claro quanto ao que é feito. Claro que pode ser uma questão de opinião se o algoritmo fica melhor expresso com um loop ou dois, mas você não deveria escrever um código que fica confuso e difícil de entender e manter, só porque ficou menor (o tamanho do código não deve ser um objetivo em si, há outros pontos a se considerar).

Conforme comentado pelo Bacco, daria para otimizar o segundo loop, pois o primeiro elemento é multiplicado por 11, sendo que no final pegamos o resto da divisão por 11, então este elemento não influencia no resultado final. Portanto, o segundo loop poderia começar do segundo dígito em diante:
def validar_cpf(cpf):
    if len(cpf) != 11:
        return False

    try:
        digitos = list(map(int, cpf))
    except ValueError:
        return False

    # incluir o índice no qual começa o loop
    def calcula_digito(multiplicador, inicio = 0):
        total = 0
        for d in digitos[inicio:]:
            if multiplicador >= 2:
                total += d * multiplicador
                multiplicador -= 1
            else: break
        resto = total % 11
        if resto < 2:
            return 0
        else:
            return 11 - resto

    # primeiro dígito não bate, CPF inválido
    if digitos[9] != calcula_digito(10):
        return False

    # segundo dígito não bate, CPF inválido
    if digitos[10] != calcula_digito(10, 1): # começa o loop do segundo elemento
        return False

    return True

Agora a função calcula_digito pode receber o índice no qual o loop será iniciado (ou zero, se nenhum for indicado - lembrando que listas começam no índice zero).
digitos[inicio:] constrói uma sub-lista a partir do índice inicio. Claro que eu poderia fazer um if inicio == 0: faço o for em digitos, e se inicio for um valor diferente, aí eu crio a sub-lista (assim evito de criar uma sub-lista à toa, quando o índice for zero).
Outra alternativa é usar um while:
def calcula_digito(multiplicador, inicio = 0):
    total = 0
    indice = inicio
    while True:
        if multiplicador >= 2:
            total += digitos[indice] * multiplicador
            multiplicador -= 1
            indice += 1
        else: break
    resto = total % 11
    if resto < 2:
        return 0
    else:
        return 11 - resto

Assim, evito a criação de sub-listas. De qualquer forma, repare que as alterações são mais no sentido de criar ou não novas estruturas à toa, se isso faz mais sentido ou não de acordo com o contexto, etc, e o que menos importa aqui é se o código vai ficar menor.


text:
Q: getFile Method invokes error callback with weird error code (1000) - eventhough the file exists window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
  fileSystem.root.getFile(localPath, { create: false }, function(fileEntry) {
      doSomethingGood();
  }, function(err) {
      alert(err.code);
  });
});

the file specified in localPath exists in my Filesystem. I still get the error Callback. It alerts the code: 1000. This is strange, because, according to the dcoumentation, the errorcode should be one of those in FileError which equal 1 to 12 (http://cordova.apache.org/docs/en/2.5.0/cordova_file_file.md.html#FileError). So what does the errorcode 1000 want to tell me? And why is the error Callback thrown if the file exists?

A: Code 1000 seems to be used for invalid addresses.
Check out the following examples (extract from my log file, on an Android device):
Read /storage/emulated/0/Android/data/com.my.app/cache/repositories/0001/summary.jpg  not found
=> FileError code: 1

Read cache/repositories/0001/summary.jpg  not found
=> FileError code: 1

Read file:///repositories/0001/summary.jpg  not found
=> FileError code: 5

Read file:///cache/repositories/0001/summary.jpg  not found
=> FileError code: 5

Read //cache/repositories/0001/summary.jpg  not found
=> FileError code: 1000

Read /cache/repositories/0001/summary.jpg  not found
=> FileError code: 1000

Read //repositories/0001/summary.jpg  not found
=> FileError code: 1000

Read /repositories/0001/summary.jpg  not found
=> FileError code: 1000

Read //storage/emulated/0/Android/data/com.my.app/cache/repositories/0001/summary.jpg  not found
=> FileError code: 1000


text:
Q: R equivalent of bash's set -x; echo all commands being executed? In bash, if you enable set -x, the script will echo the evaluated form of all commands to the stderr logs. In tcsh, this same is accomplished with set echo. Is there something similar for R? It would help debugging if I had more verbose output of what the script commands look like as they are being run, without having to manually print or cat every single one.

A: This answer assumes command-line.
The script is:
1 + 1

3 + 3

100 + 100

This it running:
$ Rscript -e 'source("/tmp/run.R", echo=TRUE)'
##
## > 1 + 1
## [1] 2
##
## > 3 + 3
## [1] 6
##
## > 100 + 100
## [1] 200

It shld be trivial to make a wrapper script for that. littler might even have an option like this.


text:
Q: How to populate test data programmatically for integration tests in Spring? I am looking for the recommended approach for populating test data programmatically in integration tests using spring / spring boot. I am using HSQLDB (inmemory).
There is the possibility to execute SQL scripts in spring for integration tests like this:
@Test
@Sql({"/test-schema.sql", "/test-user-data.sql"})
public void userTest {
    // execute code that relies on the test schema and test data
}

Instead of writing SQL scripts I would like to insert data for multiple test methods in one integration test programmatically like this:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BookstoreApp.class)
@IntegrationTest
public class BookRepositoryTest {
    @Autowired
    private BookRepository bookRepository;

    @Before // not working
    public void setUp() throws Exception {
        bookRepository.save(new Book("Donald Duck 1", "Walt Disney", "0-14-020652-3"));
        bookRepository.save(new Book("Donald Duck 2", "Walt Disney", "0-14-020652-4"));
        bookRepository.save(new Book("Micky Mouse", "Walt Disney", "0-14-020652-5"));
    }

    @Test
    public void findByTitle() {
        List<Book> books = bookRepository.findByTitle("Duck");
        Assert.assertEquals(2, books.size());
    }

    @Test
    public void getByIsbn() {
        Book book = bookRepository.getByIsbn("0-14-020652-4");
        Assert.assertEquals("0-14-020652-4", book.getIsbn());
        Assert.assertEquals("Donald Duck 2", book.getTitle());
    }

}

Each Test of this example runs just fine when being executed separately. But the second one (getByIsbn) will fail, when running them together. So obviously @Before is the wrong annotation to use here, since the books will be inserted twice.
How can I enforce the database setup being executed only once?

A: Replacing @IntegrationTest with @Transactional (at the class level) should likely solve your problem.
Reasoning:

*

*@IntegrationTest launches your entire Spring Boot application, but this appears to be overkill for your scenario.

*@Transactional will cause your tests to execute within a test-managed transaction that will be rolled back after the test completes; code executed within the @Before method will be executed inside the test-managed transaction.


text:
Q: Как проскроллить элемент в selenium В Дискорде есть список участников с полосой прокрутки, когда мы ее опускаем вниз участники на странице обновляются.
Мне нужно парсить всех участников канала, Но у меня не получается скроллить этот элемент.

A: Ответ на похожий вопрос уже был дан - ТУТ.
Задача решается разными способами:

*

*Вызов JavaScriptExecutor

*Нажатие ctrl+end

*Использование Java Robot class

Примеры

A: Я сделал для вас рабочее решение, но оно достаточно костыльное.
Import
import time
from selenium import webdriver

Code
pathToWebdriver = ''
driver = webdriver.Chrome(executable_path=pathToWebdriver)

channelUrl = ''
driver.get(channelUrl)
time.sleep(5)

def getOnline():
    online = driver.find_elements_by_xpath('//*[@id="members-697179618699903006"]/div/h2/span')
    data = online[0].text
    data = data.split('—')
    return data[1]

def getOffline():
    while True:
        xpath = "//span[@class='roleColor-rz2vM0']"
        elements = driver.find_elements_by_xpath(xpath)
        rangeOfList = len(elements)
        driver.execute_script('arguments[0].scrollIntoView()',
                              elements[rangeOfList - 1])

        offline = driver.find_elements_by_xpath(
            '//*[@id="members-697179618699903006"]/div/h2/span')

        if offline != []:
            data = offline[0].text
            data = data.split('—')
            return data[1]

def main():
    users = []
    usersCount = int(getOnline()) + int(getOffline())
    while True:
        xpath = "//span[@class='roleColor-rz2vM0']"
        elements = driver.find_elements_by_xpath(xpath)
        rangeOfList = len(elements)
        for element in elements:
            print(element.text)
            if element.text not in users:
                users.append(element.text)
        driver.execute_script('arguments[0].scrollIntoView()',
                              elements[rangeOfList - 1])
        time.sleep(1)
        if len(users) == usersCount:
            break
    print(users)

if __name__ == '__main__':
    main()

A: Я решил свой вопрос.
Я получал скроллбар и скроллил его таким образом на 1500 пикселей вниз.
Потом я обходил в цикле всех видимых участников сервера и если селениум не может найти его на странице, я скроллил список пользователей и искал участников заново по data-list-item-id:
user = driver.find_element_by_xpath(f'//div[@data-list-item-id="members-802881024991690792___{i}"]')

element_list = driver.find_element_by_xpath("/html/body/div/div[2]/div/div[2]/div/div/div/div[2]/div[2]/div[2]/div/div")

driver.execute_script("arguments[0].scrollTop = arguments[0].scrollTop + 1500", element_list)


text:
Q: java.lang.NoClassDefFoundError: scala/collection/GenTraversableOnce$class I am try to implement Apache kafka and spark streaming Integration
here is my python code:
from __future__ import print_function
import sys
from pyspark.streaming import StreamingContext
from pyspark import SparkContext,SparkConf
from pyspark.streaming.kafka import KafkaUtils

if __name__ == "__main__":
#conf = SparkConf().setAppName("Kafka-Spark").setMaster("spark://127.0.0.1:7077")
conf = SparkConf().setAppName("Kafka-Spark")
#sc = SparkContext(appName="KafkaSpark")
sc = SparkContext(conf=conf)
stream=StreamingContext(sc,1)
map1={'demo':1}
kafkaStream = KafkaUtils.createStream(stream, 'localhost:2181', "test-consumer-group", map1)

# kafkaStream = KafkaUtils.createStream(stream, 'localhost:2181', "name", map1) #tried with localhost:2181 too
lines = kafkaStream.map(lambda x: x[1])
counts = lines.flatMap(lambda line: line.split(" "))
     .map(lambda word: (word, 1)) \
     .reduceByKey(lambda a, b: a+b)
counts.pprint()

stream.start()
stream.awaitTermination()

when I run above program then it display output on terminal :
16/10/24 15:27:20 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)
java.lang.NoClassDefFoundError: scala/collection/GenTraversableOnce$class
    at kafka.utils.Pool.(Pool.scala:28)
    at kafka.consumer.ZookeeperConsumerConnector.(ZookeeperConsumerConnector.scala:91)
    at kafka.consumer.ZookeeperConsumerConnector.(ZookeeperConsumerConnector.scala:143)
    at kafka.consumer.Consumer$.create(ConsumerConnector.scala:94)
    at org.apache.spark.streaming.kafka.KafkaReceiver.onStart(KafkaInputDStream.scala:100)
    at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
    at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:131)
    at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:597)
    at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:587)
    at org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:1993)
    at org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:1993)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70)
    at org.apache.spark.scheduler.Task.run(Task.scala:86)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: scala.collection.GenTraversableOnce$class
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 17 more
16/10/24 15:27:20 ERROR SparkUncaughtExceptionHandler: Uncaught exception in thread Thread[Executor task launch worker-0,5,main]
java.lang.NoClassDefFoundError: scala/collection/GenTraversableOnce$class
    at kafka.utils.Pool.(Pool.scala:28)
    at kafka.consumer.ZookeeperConsumerConnector.(ZookeeperConsumerConnector.scala:91)
    at kafka.consumer.ZookeeperConsumerConnector.(ZookeeperConsumerConnector.scala:143)
    at kafka.consumer.Consumer$.create(ConsumerConnector.scala:94)
    at org.apache.spark.streaming.kafka.KafkaReceiver.onStart(KafkaInputDStream.scala:100)
    at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
    at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:131)
    at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:597)
    at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:587)
    at org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:1993)
    at org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:1993)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70)
    at org.apache.spark.scheduler.Task.run(Task.scala:86)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: scala.collection.GenTraversableOnce$class
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 17 more
16/10/24 15:27:20 INFO StreamingContext: Invoking stop(stopGracefully=false) from shutdown hook
16/10/24 15:27:20 WARN TaskSetManager: Lost task 0.0 in stage 0.0 (TID 0, localhost): java.lang.NoClassDefFoundError: scala/collection/GenTraversableOnce$class
    at kafka.utils.Pool.(Pool.scala:28)
    at kafka.consumer.ZookeeperConsumerConnector.(ZookeeperConsumerConnector.scala:91)
    at kafka.consumer.ZookeeperConsumerConnector.(ZookeeperConsumerConnector.scala:143)
    at kafka.consumer.Consumer$.create(ConsumerConnector.scala:94)
    at org.apache.spark.streaming.kafka.KafkaReceiver.onStart(KafkaInputDStream.scala:100)
    at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
    at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:131)
    at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:597)
    at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:587)
    at org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:1993)
    at org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:1993)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70)
    at org.apache.spark.scheduler.Task.run(Task.scala:86)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: scala.collection.GenTraversableOnce$class
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 17 more
16/10/24 15:27:20 ERROR TaskSetManager: Task 0 in stage 0.0 failed 1 times;

A: The collection API is different between Scala 2.10 and 2.11
<dependency>
                     <groupId>org.scala-lang</groupId>
                     <artifactId>scala-library</artifactId>
                     <version>2.10.6</version>
  </dependency>

A: I can confirm the fix is validation dependencies.
My problem was SpringBoot/Java related. For a Python project look into using the pip install pipdeptree command: https://www.geeksforgeeks.org/dependency-tree-of-a-python-module
For me I upgraded my SpringBoot version which changed my spring-kafka-test version which intern included kafka 2.13.x which finally included scala libs.
I used mvn dependency:tree on my project's build file and searched for '2.12' to find where the old dependency was coming from. Example dependency tree (unrelated dependencies removed). Notice org.apache.kafka:kafka_2.11:jar:0.10.0.0 included as part of my.company.riptide.api:ness-logger:jar:1.0.0 but org.springframework.kafka:spring-kafka-test:jar:2.7.9 includes a newer version org.apache.kafka:kafka_2.13:jar:2.7.2
My solution was to exclude kafaka_2.11 from my ness-logger dependency like this:
<dependency>
  <groupId>my.company.riptide.api</groupId>
  <artifactId>ness-logger</artifactId>
  <version>1.0.0</version>
  <exclusions>
    <exclusion>
      <groupId>org.apache.kafka</groupId>
      <artifactId>kafka_2.11</artifactId>
    </exclusion>
  </exclusions>
</dependency>

Truncated output of mvn dependency:tree:
[INFO] +- my.company.riptide.api:ness-logger:jar:1.0.0:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-validation:jar:2.5.7:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:9.0.55:compile
[INFO] |  |  \- org.hibernate.validator:hibernate-validator:jar:6.2.0.Final:compile
[INFO] |  |     \- jakarta.validation:jakarta.validation-api:jar:2.0.2:compile
[INFO] |  +- commons-io:commons-io:jar:2.7:compile
[INFO] |  +- my.company.eis:ness-logging-package:jar:4.0.1:compile
[INFO] |  |  +- org.apache.avro:avro:jar:1.8.2:compile
[INFO] |  |  |  +- org.codehaus.jackson:jackson-core-asl:jar:1.9.13:compile
[INFO] |  |  |  +- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.13:compile
[INFO] |  |  |  +- com.thoughtworks.paranamer:paranamer:jar:2.7:compile
[INFO] |  |  |  \- org.tukaani:xz:jar:1.5:compile
[INFO] |  |  +- org.apache.avro:avro-compiler:jar:1.8.2:compile
[INFO] |  |  |  +- org.apache.velocity:velocity:jar:1.7:compile
[INFO] |  |  |  \- joda-time:joda-time:jar:2.7:compile
[INFO] |  |  +- org.apache.kafka:kafka_2.11:jar:0.10.0.0:compile
[INFO] |  |  |  +- com.101tec:zkclient:jar:0.8:compile
[INFO] |  |  |  \- org.scala-lang.modules:scala-parser-combinators_2.11:jar:1.0.4:compile
[INFO] |  |  \- com.netflix.hystrix:hystrix-core:jar:1.5.18:compile
[INFO] |  |     +- com.netflix.archaius:archaius-core:jar:0.4.1:compile
[INFO] |  |     \- io.reactivex:rxjava:jar:1.3.8:compile
[INFO] |  +- org.springframework.boot:spring-boot-loader-tools:jar:2.5.7:compile
[INFO] |  |  \- org.apache.commons:commons-compress:jar:1.21:compile
[INFO] |  \- my.company.riptide.springboot:graceful-shutdown:jar:1.0.2:compile

[INFO] +- org.springframework.kafka:spring-kafka:jar:2.7.9:compile
[INFO] |  +- org.springframework:spring-messaging:jar:5.3.13:compile
[INFO] |  +- org.springframework:spring-tx:jar:5.3.13:compile
[INFO] |  +- org.springframework.retry:spring-retry:jar:1.3.1:compile
[INFO] |  |  \- javax.annotation:javax.annotation-api:jar:1.3.2:compile
[INFO] |  +- org.apache.kafka:kafka-clients:jar:2.7.2:compile
[INFO] |  |  +- com.github.luben:zstd-jni:jar:1.4.5-6:compile
[INFO] |  |  +- org.lz4:lz4-java:jar:1.7.1:compile
[INFO] |  |  \- org.xerial.snappy:snappy-java:jar:1.1.7.7:compile
[INFO] |  \- com.google.code.findbugs:jsr305:jar:3.0.2:compile
[INFO] +- junit:junit:jar:4.13.2:test
[INFO] |  \- org.hamcrest:hamcrest-core:jar:2.2:compile
[INFO] +- io.cucumber:cucumber-spring:jar:7.0.0:test
[INFO] |  \- org.apiguardian:apiguardian-api:jar:1.1.2:test
[INFO] +- io.cucumber:cucumber-core:jar:7.0.0:test
[INFO] |  +- io.cucumber:cucumber-gherkin:jar:7.0.0:test
[INFO] |  +- io.cucumber:cucumber-gherkin-messages:jar:7.0.0:test
[INFO] |  +- io.cucumber:messages:jar:17.1.1:test
[INFO] |  +- io.cucumber:tag-expressions:jar:4.0.2:test
[INFO] |  +- io.cucumber:cucumber-expressions:jar:13.0.1:test
[INFO] |  +- io.cucumber:datatable:jar:7.0.0:test
[INFO] |  +- io.cucumber:cucumber-plugin:jar:7.0.0:test
[INFO] |  +- io.cucumber:docstring:jar:7.0.0:test
[INFO] |  +- io.cucumber:html-formatter:jar:17.0.0:test
[INFO] |  \- io.cucumber:create-meta:jar:6.0.1:test

[INFO] +- org.springframework.kafka:spring-kafka-test:jar:2.7.9:test
[INFO] |  +- org.apache.kafka:kafka-clients:jar:test:2.7.2:test
[INFO] |  +- org.apache.kafka:kafka-streams:jar:2.7.2:test
[INFO] |  |  +- org.apache.kafka:connect-json:jar:2.7.2:test
[INFO] |  |  |  \- org.apache.kafka:connect-api:jar:2.7.2:test
[INFO] |  |  \- org.rocksdb:rocksdbjni:jar:5.18.4:test
[INFO] |  +- org.apache.kafka:kafka-streams-test-utils:jar:2.7.2:test
[INFO] |  +- org.apache.kafka:kafka_2.13:jar:2.7.2:test
[INFO] |  |  +- org.apache.kafka:kafka-raft:jar:2.7.2:test
[INFO] |  |  +- com.fasterxml.jackson.module:jackson-module-scala_2.13:jar:2.12.5:test
[INFO] |  |  +- com.fasterxml.jackson.dataformat:jackson-dataformat-csv:jar:2.12.5:test
[INFO] |  |  +- net.sf.jopt-simple:jopt-simple:jar:5.0.4:compile
[INFO] |  |  +- com.yammer.metrics:metrics-core:jar:2.2.0:compile
[INFO] |  |  +- org.scala-lang.modules:scala-collection-compat_2.13:jar:2.2.0:test
[INFO] |  |  +- org.scala-lang.modules:scala-java8-compat_2.13:jar:0.9.1:test
[INFO] |  |  +- org.scala-lang:scala-library:jar:2.13.3:compile
[INFO] |  |  +- org.scala-lang:scala-reflect:jar:2.13.3:test
[INFO] |  |  +- com.typesafe.scala-logging:scala-logging_2.13:jar:3.9.2:test
[INFO] |  |  +- org.apache.zookeeper:zookeeper:jar:3.5.9:compile
[INFO] |  |  |  +- org.apache.zookeeper:zookeeper-jute:jar:3.5.9:compile
[INFO] |  |  |  +- org.apache.yetus:audience-annotations:jar:0.5.0:compile
[INFO] |  |  |  \- io.netty:netty-transport-native-epoll:jar:4.1.70.Final:compile
[INFO] |  |  \- commons-cli:commons-cli:jar:1.4:test
[INFO] |  +- org.apache.kafka:kafka_2.13:jar:test:2.7.2:test
[INFO] |  \- org.junit.jupiter:junit-jupiter-api:jar:5.7.2:test
[INFO] |     +- org.opentest4j:opentest4j:jar:1.2.0:test
[INFO] |     \- org.junit.platform:junit-platform-commons:jar:1.7.2:test


text:
Q: Bonferroni correction in independent samples t-test? I have three IVs with two levels/groups. My primary hypothesis is that there will be group differences for all IVs in total score. However, total score is comprised of scores on 7 subscales. Total score difference was hypothesised a priori, while subscale differences testing was done out of curiosity. 2x2x2 anova is out of the question because some groups n<5.
How should I proceed with t-tests regarding the Bonferroni correction? My p is set at 0.01.
It doesn't make sense to divide p with 24 (3x7+3x1) because the value is too low. Maybe for each IV p=0.01/8?


text:
Q: How do I revert a file that has been deleted in master and do not have permission to amend or push to the master?
*

*Ran git log, which showed following

commit on master( in my case, it is develop branch) a867b4af366350be2e7c21b8de9cc6504678a61b`
Author: Me <me@me.com>
Date:   Thu Nov 4 18:59:41 2010 -0400

blah blah blah...

commit 25eee4caef46ae64aa08e8ab3f988bc917ee1ce4
Author: Me <me@me.com>
Date:   Thu Nov 4 05:13:39 2010 -0400

more blah blah blah...

commit 0766c053c0ea2035e90f504928f8df3c9363b8bd
Author: Me <me@me.com>
Date:   Thu Nov 4 00:55:06 2010 -0400

And yet more blah blah...

commit 0d1d7fc32e5a947fbd92ee598033d85bfc445a50
Author: Me <me@me.com>
Date:   Wed Nov 3 23:56:08 2010 -0400

Yep, more blah blah.

*As I'm not able to revert or reset my master branch to certain commit, created a new branch from the old commit, which contains the deleted branch by running following command
git checkout -b "branch_name" 0d1d7fc32e5a947fbd92ee598033d85bfc445a50
USING git hash of 03 November 2010, created a new branch (this commit contains the xyz.java file which does not exist in the latest commit on master (develop) branch)

*Do not have any more changes to make in this new branch (created in step 2 above). purpose of creating this new branch was to revert the xyz.java file, which has been deleted in master. Pushed this new branch to remote.

Git does not allow me to create a PR for this new branch as it shows an error that this new branch does not contain any change, which is not already contained in develop.
If I rebase my new branch with master (develop, in my case) by running following command, it deletes xyz.java file from my new branch.
git pull origin develop

How do you get xyz.java file back in my new branch, which allows git to recognise this new branch contains xyz.java file, which has been deleted in master branch?

A: TL;DR
You need to create a PR from a branch that starts from the latest state of  master and adds the file back in, not from an old branch.
My solution
The fact that you don't have permission to push to master does not mean you cannot add commits to master. It just means you have to use a PR to do so.
Steps to follow:

*

*Create a new branch from master in its latest state.

*On that branch add and commit the file back in (e.g., using @Ivan's answer, or by using git revert on the commit where you deleted it).

*Push that branch to the remote.

*Submit a PR from it, and that will add the file back into master once it's approved and merged.

The point of having push protection on master is not to prevent you from adding commits onto master, but rather to force you to do it through a PR, typically for the purpose of having a review on it before it gets merged.
Why your approach didn't work
In the attempt you describe in the question, you started back from the old branch instead of starting from the latest version of master. The problem with that is that the master branch continues to have a commit that deletes that file, so merging that old branch in again, Git continue to (correctly) say, well, I'm merge a branch with the file into a branch that says delete that file, so that file should stay deleted.
In contrast, a new branch that re-adds is, when merged into main, will re-add it since you're merging one branch that doesn't have it and one branch that's adding it.

A: Find the last commit before deleting this file. Remember the hash. Then checkout this file to your current branch.
git checkout <hash> -- <full/path/to/the/file>

For example:
git checkout 0d1d7fc32e5a947fbd92ee598033d85bfc445a50 -- xyz.java

Then make a commit.


text:
Q: Ошибка при компиляции sass файла Только начинаю изучать sass и gulp. Для верстки использую готовый шаблон. Целью было вывести изображение в фоне header. Для этого в index.html я прописал:

А в файле main.sass:
body
    font-size: 16px
    min-width: 320px
    position: relative
    line-height: 1.75
    font-family: $default-font
    overflow-x: hidden
    opacity: 1
    &.ishome
        .site-header
            min-height: 700px

При запуске gulp, в командной строке появляется ошибка:
gulp-notify: [Error running Gulp] app\sass\main.sass
Error: Illegal nesting: Only properties may be nested beneath properties.
        on line 39 of app/sass/main.sass
>>     &.ishome {
   ----^

Т.к. я только начинаю разбираться, я не смог самостоятельно понять в чем проблема.

A: Проверьте табуляцию. Для sass в отличие от scss важен каждый пробел. Предполагаю, что у вас некоторые отступы совершались табами, а некоторые пробелами. В табах в зависимости от настройки редактора может быть разное кол-во пробелов.

A: была такая же ошибка в SASS - оказалось, что проблема именно в табуляции.
Я редактировал файл с готовыми стилями, в котором отступы делались при помощи Tab (2 пробела). У меня Tab четыре пробельных отступа делал, поэтому я пытался двойным нажатием пробела отступы выставлять, и вылетала ошибка.
В настройках назначил Tab 2 пробельных отступа и ошибка исчезла


text:
Q: How to draw two loops in same vertice in graph I wish to draw a graph with two loops undirected on the same vertice, follows the figure:

I draw the two loops, but got ugly, follows the code:
\begin{tikzpicture}
\draw[fill=black] (2,-1) circle (3pt);
\draw[fill=black] (2,0) circle (3pt);
\draw[fill=black] (2,2) circle (3pt);
\node at (2.5,-1) {$z$};
\node at (2.4,0.1) {$x.y$};
\node at (2,2.3) {$w$};
\draw[thick] (2,0) edge[bend right] (2,2);
\draw[thick] (2,0) edge[bend left] (2,2);
\draw[thick] (2,-1) edge[bend right] (2,0);
\draw[thick] (2,-1) edge[bend left] (2,0);
\draw (2,0) edge [loop left] (2,0);
\draw (2,0) edge [loop below] (2,0);
\end{tikzpicture}

A: Is this what you like?
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\coordinate (W) at (2,2);
\coordinate (XY) at (2,0);
\coordinate (Z) at (2,-1);
\draw[fill=black] (Z) circle (3pt) node[below=1mm] {$z$};
\draw[fill=black] (XY) circle (3pt) node[right=7mm] {$x.y$};
\draw[fill=black] (W) circle (3pt) node[above=1mm] {$w$};
\draw[thick] (XY) edge[bend right] (W);
\draw[thick] (XY) edge[bend left] (W);
\draw[thick] (Z) edge[bend right] (XY);
\draw[thick] (Z) edge[bend left] (XY);
\draw (XY) edge [loop left, min distance=10mm] (XY);
\draw (XY) edge [loop right, min distance=10mm] (XY);
\end{tikzpicture}
\end{document}


text:
Q: UML Diagrams with C If I am using UML diagrams to depict a C program, can I have composition and aggregation or is that reserved just for Object Oriented Languages?
For example if I have a struct or a Buffer in my source that is only used for that particular segment of the code I assume is aggregation, because the lifecycle of that particular piece of code is dependent of the user using that file right?
Should I be using Association and Direct Association?

A: *

*Yes, you can use UML to describe programs in any language.

*When an object (structure, w/e ) has it's lifecycle tight coupled with another object is Composition , not Aggregation

*What you described is neither Composition nor Aggregation. The lifecycle of a particular structure/buffer that's only valid through a certain code segment can be better represented through a Sequence diagram (get buffer , release buffer calls should be shown in the diagram)

*You will have allot of Composition and Aggregation in C. Think about POD structs. Some of them reference other POD structs inside them. If the reference comes with memory ownership it's Composition (eg :pointer which needs to be released). If the reference doesn't come with memory ownership it's Aggregation (eg : pointer which you don't have to release when releasing the structure).


text:
Q: What's the mechanism of locking access to selected applications in Android? I'm trying to find out how applications like Perfect App Protector or Smart Applock Free work.
What mechanism is used?

A: These applications use a service to monitor whether a new application is trying to launch or not.
It can be done in several ways. If running application matched with the configured application then it is sent back to the background by the service and may ask for lock code, password as you configured earlier. If it matches then you will get the application on the foreground. Otherwise it kills the process from being executed.


text: Q: Kickstart script seems to be skipping over %post I have set up a Kickstart script for Fedora 25 Server, and part of that includes some things in the %post section, including generating a root password and calling a Slack webhook to notify me with an encrypted message. When I run the script, I see no errors, but I do not get the message from the server with the GPG-encrypted password. The script is here: https://pastebin.com/raw/HV96vxji (Do note that I have redacted some information for security)


text:
Q: Aurelia - I18N on options of a select I would like to translate the options of my select but I do not know how to do that :
<select>
    <option repeat.for="element of elementList" model.bind="element.id">
      ${element.value}   <== How to translate the value ?
    </option>
</select>

Could you please help me ?

A: The value would have to be a key in your translation file. Then you'd simply use the t binding behavior:
${element.value & t}
This would work for a model.bind expression as well, but that might not be what you want.


text:
Q: Chemistry package for typesetting nuclide Is there a chemistry package with a specific command for typesetting nuclide?
If not, what is the preferred method for typing this?
Here is what I have myself:
\documentclass{article}

\usepackage[version=3]{mhchem}

\begin{document}
$\ce{^{14}_{7}C}$
\end{document}

A: As I mentioned in a comment: I know about a lot of chemistry related packages and maintain a list which I hope is rather complete (if something's missing let me know).
That being said I believe you already made a good choice. The packages mhchem and chemmacros are probably the easiest for this:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{mhchem,chemmacros}

\begin{document}

mhchem: \ce{^{14}_7N}

chemmacros: \ch{^{14}7N}

\end{document}