text:
Q: Link with hover overlay is opened on first click on mobile device I have a div that displays another content on hover using css transitions.
There is one text element
Another Text
 that overlays link email adress. On desktop browser it's working correctly - I can click the link after hover is activated. On phone device where hover is replaced by clicking on the element, there's a problem - If I activate the hover by clicking on "Another Text" it opens the link right away.
My question is if there is any way how to restrict link opening on first click.
Ideal scenario on phone device is:

*

*user clicks on "Another text"

*hover is activated, link is displayedbut not fired

*user click link and link is fired

Here is the code: https://jsfiddle.net/9bc0bcja/2/

A: I've partially solved it using javscript:
$(".team-social")
.bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",
 function(e){
    if($(this).hasClass("pointerA")){
     if(is_touch_device()){
        $(this).removeClass( "pointerA" );
     }
    }
    else{
     $(this).addClass( "pointerA" );
    }
 });
$('.team-social a').click(function() {
if(is_touch_device()){
  $(this).parent().removeClass("pointerA");
}
});

It activates pointer-events after transition finishes, so it is not fired right away when I click overlay on phone device.
https://jsfiddle.net/9bc0bcja/4/

*

*added javascript + jquery link

*added class .pointerA

*added pointer-events:none; to class .team-social

A: Try this Fiddle.
I simplified your code, keeping only the necessary elements.
This script only operates if you're using a mobile device, which is what you should want for performance reasons.
This code watches the hover event rather than transitionEnd, that way the function trigger timing is not dependent on the length of the transition.
if (is_touch_device()) {
    var $wrap = $(".wrap"),
        $pw = $wrap.find(".pointer-watch"),
        $tc = $pw.find(".transition-container");

    $pw.addClass("pointerN");
    $('.wrap').hover(function wrapHovered() {
        if ($pw.hasClass("pointerN")){
            setTimeout(function enablePE() {
                $pw.removeClass("pointerN");
            }, 0);
        }
        else if (!$wrap.is(":hover")) {
            $pw.addClass("pointerN");
        }
   });
}


text:
Q: If else statement not working properly in Jenkins pipeline script (groovy) I have the pipeline script (groovy) where i m trying to use if and else condition but its not behaving normally. Seems it always returns false.
Here is my sample (snip of) pipeline script:
def branch_exists_in_node = 1
def branch_exists_in_common = 0
def branch_exists_in_extra = 0
                if(branch_exists_in_node == 1) {
                    NODE_BRANCH = env.BRANCH_NAME
                }else {
                    NODE_BRANCH = "master";
                }
                if(branch_exists_in_common == 1) {
                    COMMON_BRANCH = env.BRANCH_NAME
                }else {
                    COMMON_BRANCH = "master"
                }

But here it always evaluating to false even if the value is 1. Is there any issue with the syntax?
when i do echo of above variables, it prints well..
                    echo "${branch_exists_in_angular}" //0
                    echo "${branch_exists_in_node}" //1
                    echo "${branch_exists_in_common}" //0

UPDATE:
Here is my minimal jenkins pipeline script, please help
def EXTRA_BRANCH
def ANGULAR_BRANCH
def NODE_BRANCH
def COMMON_BRANCH
def branch_exists_in_angular
def branch_exists_in_node
def branch_exists_in_common
def branch_exists_in_extra

pipeline {
    agent {
        label 'nimbus-cloud'
    }
    options {
        gitLabConnection('gitlab')
        timeout(time:1, unit: 'HOURS')
    }
    environment {
        WORK_DIR = "${WORKSPACE}/${BUILD_NUMBER}"
        EXTRA_REPO = "git@gitlab.example.com:tools/extra.git"
        COMMON_REPO = "git@gitlab.example.com:tools/common.git"
        ANGULAR_REPO = "git@gitlab.example.com:tools/angular.git"
        NODE_REPO = "git@gitlab.example.com:tools/node.git"
        EXTRA_BRANCH = "${env.BRANCH_NAME}"
    }
    stages {
        stage('PREDEPLOYMENT: Cleanup and Setting up the VM. '){
            steps {
                running("${JOB_NAME}")
                echo "Deleting previous images. "
                sh 'docker rmi -f $(docker images -a -q) | echo "Not able to delete some images"'
                dir("$WORKSPACE"){
                    sh 'rm -rf *'
                }
                // setting up
                echo "BRANCH NAME IS ${env.BRANCH_NAME}"
                script {
                    EXTRA_BRANCH = env.BRANCH_NAME // this will be different across all the repos
                // Check if above branch is already there on every repo -- for angular
                    try {
                        sshagent(['my-git-ssh']){
                            branch_exists_in_angular = sh(script: 'git ls-remote --heads $ANGULAR_REPO $EXTRA_BRANCH | wc -l', returnStdout: true)
                            echo "${branch_exists_in_angular}"
                            branch_exists_in_node = sh(script: 'git ls-remote --heads $NODE_REPO $EXTRA_BRANCH | wc -l', returnStdout: true)
                            echo "${branch_exists_in_node}"
                            branch_exists_in_common = sh(script: 'git ls-remote --heads $COMMON_REPO $EXTRA_BRANCH  | wc -l', returnStdout: true)
                            echo "${branch_exists_in_common}"
                        }
                    } catch(Exception e){
                        echo "WARN: something unexpected occured. "
                        echo "${e}"
                    }
                    // below lines prints as expected
                    echo "${branch_exists_in_angular}" // 0
                    echo "${branch_exists_in_node}" // 1
                    echo "${branch_exists_in_common}" //0
                    if(branch_exists_in_angular) {
                        ANGULAR_BRANCH = env.BRANCH_NAME
                    }else {
                        ANGULAR_BRANCH = "master";
                    }
                    if(branch_exists_in_node) {
                        NODE_BRANCH = env.BRANCH_NAME
                    }else {
                        NODE_BRANCH = "master";
                    }
                    if(branch_exists_in_common) {
                        COMMON_BRANCH = env.BRANCH_NAME
                    }else {
                        COMMON_BRANCH = "master"
                    }
                }
                echo ANGULAR_BRANCH // prints master = expected
                echo NODE_BRANCH // prints master but expected is checkout branch name feature-test
                echo COMMON_BRANCH // prints master expected
            }
            post {
                success {
                    echo "Success: VM Cleaned up for testing. "
                }
                failure {
                    echo "Error: Some error  occured while cleaning up the system. "
                    failure("${JOB_NAME}")
                }
            }
        }
    }
}

A: Keep in mind that sh(returnStdout: true, script: ...) returns String so variables like branch_exists_in_angular are strings and not numbers. In Groovy (including Jenkins Groovy CPS environment) following expressions always evaluate to true:
if ('0') {
    echo "0 is 0"
}

if ('1') {
    echo "1 is 1"
}

Cast the result of sh step to an integer using (expr) as Integer:
branch_exists_in_angular = sh(script: 'git ls-remote --heads $ANGULAR_REPO $EXTRA_BRANCH | wc -l', returnStdout: true) as Integer

It will make your variables to be a type of Integer and then if (0) will evaluate to false and if (1) will evaluate to true.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing a List of objects from Razor View to Controller only passes one item instead of the whole list I want to pass a List of VoedingBindingModel to my controller by using an Editor Template, however I only receive the first entry of the List in the Controller, never all the entries.
The Controller:
public ActionResult Create()
    {
        ViewBag.fk_customVoedingId = new SelectList(customvoeding.GetAllCustomvoeding(), "customVoedingId", "customVoedingNaam");
        ViewBag.fk_standaardVoedingId = new SelectList(standaardvoeding.GetAllStandaardvoeding(), "standaardVoedingId", "standaardVoedingNaam");

        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Datum,Tijd,VoedingCollection")]AgendaBindingModel agendaBindingModel)
    {
        //Do something
    }

The Model:
public class AgendaBindingModel
    {
      [Required]
       public List<VoedingBindingModel> VoedingCollection { get; set; }
       //More properties
    }

The View:
@using Website.Models
@model AgendaBindingModel

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

agenda

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Datum, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.TextBoxFor(m => m.Datum, "{0:dd-MM-yyyy}", new { @class = "form-control-datepicker", placeholder = "DD-MM-YYYY", maxlength = "10" })

            @Html.ValidationMessageFor(model => model.Datum, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Tijd, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Tijd, "{0:hh:mm}", new { htmlAttributes = new { @class = "form-control-timepicker", placeholder = "hh:mm", maxlength = "5" } })
            @Html.ValidationMessageFor(model => model.Tijd, "", new { @class = "text-danger" })

        @Html.EditorFor(x => x.VoedingCollection[0])

        @Html.EditorFor(x => x.VoedingCollection[1])

        @Html.EditorFor(x => x.VoedingCollection[2])

            <input value="Add" class="btn btn-default" onclick="ShowVoeding()" /> <input value="Remove" class="btn btn-default" onclick="HideVoeding()" />

            <input type="submit" value="Create" class="btn btn-default" />

}

@Html.ActionLink("Back to List", "Index")

Partial class:
(customvoeding and standaardvoeding do the same thing, only customvoeding returns a collection of customvoeding and standaardvoeding returns a collection of standaardvoeding.
public partial class customvoeding
{
    private static foodtrackerEntities1 db = new foodtrackerEntities1();

    public static List<customvoeding> GetAllCustomvoeding()
    {
        db.Configuration.LazyLoadingEnabled = false;
        return db.customvoeding.ToList();
    }
}

A: Your second and third html are broken.

remove hidden

A: You don't seem to be initializing the model and passing it to the view. In the action methods of your controller try adding:
var viewModel = new AgendaBindingModel();
viewModel.VoedingCollection = // TODO: Fill the list from your data source

return View(viewModel );

A: Try like this. I could not test, but if you like we can advance is this way:
To show all items:

@for(int i = 0; i < AgendaBindingModel.VoedingCollection.Count; i++)
{
    @Html.EditorFor(x => x.VoedingCollection[i])
}
To add new item:
<button onclick=newItem() >+</button>

A: I found out what was preventing me from receiving more than one result:
You can NOT use @Html.EditorFor template for more than 1 value when you specify a template. It does not matter if you use different models or different templates, it just simply does not work.
To fix it, you have to use 'Html.BeginCollectionItem' library, which can be found here.


text:
Q: How to find the length of a apex string variable inside visualforce page using javascript? I have a visualforce page and an apex controller class. There is a string variable inside the apex class and i want to find the length of that string from visualforce page using javascript.
global with sharing class SampleClass{
     public String sampleString{get; set;}

     /***rest of the code**/
}

<apex:page showHeader="false"
           controller="SampleClass">

     <!--rest of the code-->

     <script type="text/javascript">

          /**code**/

         console.log('LENGTH: ' + ({!sampleString}).length);

    </script>

</apex:page>

When I run the above code, this: LENGTH: undefined is what i am getting. And I have already checked whether there is value inside the string.  sampleString is not null and it has value inside it. So, what am i doing wrong? Is there any other way to do it?

A: If you wanted the actual string:
let sampleString = "{!JSENCODE(sampleString)}";
console.log(sampleString.length);

You need to make sure you put the string in quotes, and also use JSENCODE to make sure it doesn't get encoded incorrectly.

A: I believe you can use {!LEN(sampleString)}


text:
Q: What is Name meaning for Belinda My name is Belinda. In my locality, it is a rare name. So, everyone asks for its meaning. I know that it is the heroine name of "Rape of the lock". When i googled, I found that it has the meaning of a Serpent. Really I felt bad about it. Did anyone give a serpent name to a child?. Or Whether it has any other meaning...
Please clarify

A: My name is Belinda as well. I have a 1974 edition of Funk and Wagnalls Encyclopedic Dictionary with name meanings and origins.
Belinda  Serpent: Title of an oracular priestess. (Germanic).
Remember that that your personal opinions and ideas about snakes may be completely different than the culture which this association comes from.

A: I believe this is a name that has an obscure origin, and may have spontaneously originated in multiple cultures with different meanings.
For example it can be double name with latin roots.  Bella and linda in Italian mean beautiful and clean respectively.  (In Spanish linda means cute instead of clean.)
Alternatively, it can be derived from a Germanic root meaning "Bright serpent" or even "Bright Linden Tree".
To be honest, I would lean toward the Latin origin.  It's certainly a lot nicer!
Sources:
Wikipedia-Belinda
Wikipedia-Linda
Educated guessing


text:
Q: How tu use a custom validator with a service in Angular I try to use a custom validator to check if email is already taken.
According to the documentation and some articles I came up with this code:
in my auth.service.ts
checkEmail(email) {
    const r$ = of(true);
    const x$ = of(false);
    return this.http.post<any>(`${config.apiUrl}/users/email`, email)
    .pipe(
      mergeMap(v =>
        iif(
          () => v,
          r$,
          x$
        )
      )
    );
  }

in my component
  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      email: ['', [
        Validators.required,
        Validators.email,
        this.checkEmail.bind(this)
      ]]
    });
  }

checkEmail(control: AbstractControl) {
    if (control.value) {
      return this.authService.checkEmail({email: control.value}).toPromise()
      .then(response => {
        return response ? { forbiddenName: {value: control.value}} : null;
        });
    }
  }

But it's not working, how can I make the checkEmail() function return the right data for the validator

A: you need the following mods:
  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      email: ['', [
        Validators.required,
        Validators.email
      ], [this.checkEmail.bind(this)]] // async validators go separate after sync validators
    });
  }

  checkEmail(control: AbstractControl) {
    if (control.value) {
      return this.authService.checkEmail({email: control.value}).pipe(
        map(response => {
          return response ? { forbiddenName: {value: control.value}} : null;
         }) // use observables, don't convert to promises
       );
    }
    return of(null); // gotta return an observable for async
  }

not needed but this can also be simpler / cleaner:
  checkEmail(email) {
    return this.http.post<any>(`${config.apiUrl}/users/email`, email)
    .pipe(
      map(v => !!v) // map and coerce to bool
    );
  }


text:
Q: Sequence contains no elements in linq? I'm trying to get lowest and highest values in key of a dictionary below
public static Dictionary<SimulationResult, List<Student>> SimulationOutput { get; set; } = new Dictionary<SimulationResult, List<Student>>();

this is the class in the key
internal class SimulationResult
{
    public int Unsolved { get; set; }
    public int ValuePreferences { get; set; }
    public int Index { get; set; }
}

I'm getting the error in the Sequence contains no elements on the lines below
int bestResult = SimulationOutput.Keys.Where(x=> x != null).Select(x => x.ValuePreferences).Max();

also on these lines
int bestResult = SimulationOutput.Keys.Select(x => x.ValuePreferences).Max();
int LowestUnsonved = SimulationOutput.Keys.Select(x => x.Unsolved).Min();

The dictionary is filled in a Parallel for loop.
Parallel.For(1, verwerken.Gegevens.AantalIteraties + 1, i =>
{
    PracticumCollectie practicumCollectie = verwerken.Data.PracticumCollectie.Copy();
    StudentCollectie studentCollectie = verwerken.Data.StudentCollectie.Copy();
    studentCollectie.OrderStudentByPreference();
    studentCollectie.AssiningStudentToPracticum(practicumCollectie);

    practicumCollectie.Oplossing.Index = i;
    practicumCollectie.ZetAantalOnopgeloste(studentCollectie);
    practicumCollectie.ZetWaardeVoorkeuren(studentCollectie);

    bool schrijfOplossing = verwerken.Keuze.IsSimuleren ? verwerken.VoldoetAanOndergrenzen(practicumCollectie.Oplossing) : true;

    if (schrijfOplossing)
    {
        SimulationOutput.Add(verwerken.GetBestandsnaam(practicumCollectie.Oplossing), new List<Student>(studentCollectie.Items));
    }
});

A: you have to use ConcurrentDictionary if you are working with Parallel.
normal dictionaries aren't threadsafe.


text:
Q: Weird root of an equation I was doing this math and I found myself dealing with this equation:
$$(5-y)^{2}=(1-y)^{2}$$
Now, square rooting both sides we get,
$$5-y=1-y...(i)$$ or,
$$5-y=-1+y...(ii)$$
Now, (ii) gives us a reasonable root, which is $y=3$. However, (i) gives us a weird result, which is $5=1$. Why do I get this weird result by square rooting both sides?

A: @user already posted a good answer. However, I would like to add to it. The equation that you/I have posted is a simple/linear equation. It can only have one acceptable root/solution. If you attempt to solve the equation as you would for a quadratic equation, you get 2 roots, but one of the roots is unacceptable. So, you are left with only one acceptable root as it is a linear equation.

A: The "weird" result doesn't depend on the manipulation you did but on the original equation itself.
Another way to solve it is by zero-product property, that is:
$$A^2-B^2=(A+B)(A-B)=0 \iff A+B=0 \,\lor\, A-B=0$$
and in your equation the case $A-B$ leds to no solution and we only keep the solution for the case $A+B=0$.

A:
$$(5-y)^{2}=(1-y)^{2}$$
Square-rooting both sides:
$$5-y=1-y...(i)$$ or
$$5-y=-1+y...(ii)$$
Now, (ii) gives us a reasonable root $y=3$. However, (i)
gives us a weird result  $5=1$. Why do I get this weird
result by square-rooting both sides?

You weird result is due to performing an invalid step and taking square root the incorrectly: $$\sqrt{(5-y)^2}=|5-y|\not\equiv5-y.$$ (Try $y=7,$ for example.)
Here are two correct solutions:
Method A
$$(5-y)^2=(1-y)^2\\|5-y|=|1-y|$$
Continuing graphically:

$$y=3.$$
Method B
$$(5-y)^2=(1-y)^2\\25-10y=1-2y\\y=3.$$

A:
Another way in which this question is interpreted is to consider what taking square-roots does to the pair of equations.  The system $ \ x \ = \ (5 - y)^2 \ , \ x \ = \ (1 - y)^2 \  $ is a pair of "horizontal" parabolas, both of which "open to the right" and have their vertices at $ \ (0 \ , \ 5) \ $ and $ \ (0 \ , \ 1) \ \ . $  Upon taking square-roots, each equation produces a pair of equations, each of which is represented by one "arm" of each parabola:
$$ x \ = \ (5 - y)^2 \ \ = \ \ \left\{ \begin{array}{c} \sqrt{x} \ = \ 5 - y \ \ \text{[red]} \\ \sqrt{x} \ = \ -(5 - y) \ \ \ \text{[orange]} \end{array} \right.   , $$
$$ x \ = \ (1 - y)^2 \ \ = \ \ \left\{ \begin{array}{c} \sqrt{x} \ = \ 1 - y \ \ \text{[blue]} \\ \sqrt{x} \ = \ -(1 - y) \ \ \ \text{[green]} \end{array} \right.   . $$
(ryang shows these equations expressed in terms of absolute-value curves, which appear as "V"-shapes.)
There are then four possible pairings of these equations for the arms of the two parabolas:
$$ 5 - y \ \ = \ \ 1 - y \ \ \text{[red/blue]} \ \ , \ \  5 - y \ \ = \ \ -1 + y \ \ \text{[red/green]} \ \ , $$ $$ -5 + y \ \ = \ \ 1 - y \ \ \text{[orange/blue]} \ \ , \ \ -5 + y \ \ = \ \ -1 + y \ \ \text{[orange/green]} \ \ .  $$
We use both the positive and negative square-roots here because they are both consistent with the original set of equations,  $ \ x \ = \ (5 - y)^2 \ , \ x \ = \ (1 - y)^2 \ \ . $
The intersection equation that is sensible in "standard algebra" is the "red/green" equation, $ \ 5 - y \ = \ -1 + y \ \ $ because it produces the finite value $ \ y \ = \ 3 \ \ $ [the intersection point $ \ (4 \ , \ 3) \ ] \ \ . $  We accept this solution because $ \ \sqrt4 \ = \ 5 - 3 \ = \ -1 + 3 \ \ . $
The "red/blue" and "orange/green" equations do not have solutions in standard algebra because there is no finite number that will make the left and right sides of $ \ 5 - y \ = \  1 - y \ \ $ or $ \ -5 + y \ = \ -1 + y \ \ $ equal.  We see this on the graph as the lack of intersections between the corresponding arms of the parabolas: this can be understood as the result of $ \  \sqrt{x} \ = \ 5 - y \ $ and $ \ \sqrt{x} \ = \ 1 - y \ $ being different "vertical shifts" of the single curve $ \ \sqrt{x} \ = \ -y \ \ . $  (We can say something similar for the differing "shifts" of $ \ \sqrt{x} \ = \ y \ \  $ for the orange and green curves.)
Now there is a resolution to this in more advanced practice (algebraic geometry).  If we allow $ \ y \ $ to take on a "value larger than any finite number", then the two sides of these equations can "become equal".  Mathematicians introduce the "extended plane" which includes the "point at infinity":  it is there that the red and blue or the orange and green arms intersect.  But "infinity" is not a number in standard algebra, so we say there that these equations "have no solution".
The fourth pairing  $ \ -5 + y \   = \   1 - y \ $ of the orange and blue curves appears to have the solution $ \ y = 3 \ \ , $ but this is genuinely "spurious".  Since the range for the blue curve is $ \ 1 - y \ \ge \ 0 \ \Rightarrow \ y \le 1 \ \ $ and that for the orange curve is $ \ -5 + y \ \ge \ 0 \ \Rightarrow \ y \ge 5 \ \ , \ \ y = 3 \ \ $ cannot be in the solution set for this equation.  (The "point at infinity" is where the two parabolic arms intersect, but again that is not admissible in standard algebra.)
The "safest" method of solving the original set of equations for the interpretation in standard algebra is that shown as "Method B" by ryang, as the "squared" terms conceal these complications with the square-roots.

A: $\sqrt{x^2}$ is $|x|$, not $x$.
Because eventually the only solution is $y = 3$, the RHS $1 - y$ is negative ($1 - 3 = -2$), so taking the square root of $(1 - y)^2$ is actually $y - 1$, which is exactly what $(ii)$ gives you.


text:
Q: Resize iframe height on local page when remote page is reloaded I've followed the advice here and gotten it to work as it should. However, it doesn't accomplish exactly what I'm after. I'm pulling in a form from another url, and when the user submits the form it serves up a confirmation page. Is there any sort of way to dynamically check when a page reload has occurred inside the iframe, and then in real time (I'd assume using AJAX) update the height of it to reflect the new calculated height of the confirmation page?
I'm guessing this is not doable, but I wanted to check :)


text:
Q: Python combining setattr and getattr I would like to update the attributes of a class dynamically, but it seems that the combination of setattr and getattr does not work as I would like to use it.
Here is my main class:
class Container(object):
    def __init__(self):
        pass
container = Container()
attributes = ['a', 'b', 'c', 'd']
values = [[1, 2, 3, 4, 5], [True, False], ['red', 'blue', 'green'], [0, 1, -1, -5, 99]]

Please note that for the purpose of that example I explicitly constructed the list of attributes and their respective values. However, in the real application of this code, I do not know anything in advance. Neither their numbers, name, or values. This calls for the need to do that dynamically.
Here is the rest of the code:
for key, value in zip(attributes, values):
    setattr(container, key, [])
    for val in value:
        setattr(container, key, getattr(container, key).append(val))

this part does not work when I run the code. I could save the getattr part in a tmp variable and then call the append method for the list before calling the setattr, but I would like to condense it if possible.
Anyone could explain me why this does not work? What alternative(s) do I have?
Thanks for your help

A: You are appending to a list in-place. Like all in-place mutation functions, .append() returns None, so your final line:
setattr(container, key, getattr(container, key).append(val))

ultimately evaluates to:
setattr(container, key, None)

Just set a copy of the list on the class:
for key, value in zip(attributes, values):
    setattr(container, key, values[:])

where the [:] creates a copy of values by slicing from 0 to len(values) in a short-hand notation without needing to loop.
If all you want to do is create an object that provides the keys and values as attributes (much like a dict would yet with attribute access instead of item access), you could also use:
class Container(object):
    def __init__(self, names, values):
        self.__dict__.update(zip(names, values))

then run:
Container(attributes, values)

which removes the need to call setattr() in a loop.

A: It might help you understand what's going on if you can watch the progress of each step:
class Container(object):
    def __init__(self):
        pass
    def __str__(self):
        return '%s(%s)' % (self.__class__.__name__,
            ', '.join(['%s = %s' % (attr, getattr(self, attr))
                for attr in self.__dict__]))

Now you can print container.  If you do this in the nested loop you'll see that after the first attempt to setattr you've clobbered the original list stored in container.a (as Martijn noted):
for key, value in zip(attributes, values):
    setattr(container, key, [])
    for val in value:
        print 'before:', container
        setattr(container, key, getattr(container, key).append(val))
        print 'after:', container

before: Container(a = [])
after: Container(a = None)
before: Container(a = None)
Traceback (most recent call last): ...

The "best" way to do this obviously depends on the real problem—given the shrunken problem Martijn's version is quite appropriate, but perhaps you have to append one item, or extend with multiple items, at some point well after creating some initial container instance.


text:
Q: Why can't I directly modify a component's state, really? I understand that React tutorials and documentation warn in no uncertain terms that state should not be directly mutated and that everything should go through setState.
I would like to understand why, exactly, I can't just directly change state and then (in the same function) call this.setState({}) just to trigger the render.
E.g.: The below code seems to work just fine:
const React = require('react');

const App = React.createClass({
  getInitialState: function() {
    return {
      some: {
        rather: {
          deeply: {
            embedded: {
              stuff: 1,
            },
          },
        },
      },
    },
  };
  updateCounter: function () {
    this.state.some.rather.deeply.embedded.stuff++;
    this.setState({}); // just to trigger the render ...
  },
  render: function() {
    return (

        Counter value: {this.state.some.rather.deeply.embedded.stuff}

        <button onClick={this.updateCounter}>Increment</button>

    );
  },
});

export default App;

I am all for following conventions but I would like to enhance my further understanding of how ReactJS actually works and what can go wrong or is it sub-optimal with the above code.
The notes under the this.setState documentation basically identify two gotchas:

*

*That if you mutate state directly and then subsequently call this.setState this may replace (overwrite?) the mutation you made. I don't see how this can happen in the above code.

*That setState may mutate this.state effectively in an asynchronous / deferred way and so when accessing this.state right after calling this.setState you are not guaranteed to access the final mutated state. I get that, by this is not an issue if this.setState is the last call of the update function.

A: The React docs for setState have this to say:

NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

Basically, if you modify this.state directly, you create a situation where those modifications might get overwritten.
Related to your extended questions 1) and 2), setState() is not immediate. It queues a state transition based on what it thinks is going on which may not include the direct changes to this.state. Since it's queued rather than applied immediately, it's entirely possible that something is modified in between such that your direct changes get overwritten.
If nothing else, you might be better off just considering that not directly modifying this.state can be seen as good practice. You may know personally that your code interacts with React in such a way that these over-writes or other issues can't happen but you're creating a situation where other developers or future updates can suddenly find themselves with weird or subtle issues.

A: It surprises me that non of the current answers talk about pure/memo components (React.PureComponent or React.memo). These components only re-render when a change in one of the props is detected.
Say you mutate state directly and pass, not the value, but the over coupling object to the component below. This object still has the same reference as the previous object, meaning that pure/memo components won't re-render, even though you mutated one of the properties.
Since you don't always know what type of component you are working with when importing them from libraries, this is yet another reason to stick to the non-mutating rule.
Here is an example of this behaviour in action (using R.evolve to simplify creating a copy and updating nested content):

class App extends React.Component {
  state = { some: { rather: { deeply: { nested: { stuff: 1 } } } } };

  mutatingIncrement = () => {
    this.state.some.rather.deeply.nested.stuff++;
    this.setState({});
  }
  nonMutatingIncrement = () => {
    this.setState(R.evolve(
      { some: { rather: { deeply: { nested: { stuff: n => n + 1 } } } } }
    ));
  }

  render() {
    return (

        Normal Component: <CounterDisplay {...this.state} />

        Pure Component: <PureCounterDisplay {...this.state} />

        <button onClick={this.mutatingIncrement}>mutating increment</button>
        <button onClick={this.nonMutatingIncrement}>non-mutating increment</button>

    );
  }
}

const CounterDisplay = (props) => (
  <React.Fragment>
    Counter value: {props.some.rather.deeply.nested.stuff}
  </React.Fragment>
);
const PureCounterDisplay = React.memo(CounterDisplay);

ReactDOM.render(<App />, document.querySelector("#root"));

A: This answer is to provide enough information to not change/mutate the state directly in React.
React follows Unidirectional Data Flow. Meaning, the data flow inside react should and will be expected to be in a circular path.
React's Data flow without flux

To make React work like this, developers made React similar to functional programming. The rule of thumb of functional programming is immutability. Let me explain it loud and clear.
How does the unidirectional flow works?

*

*states are a data store which contains the data of a component.

*The view of a component renders based on the state.

*When the view needs to change something on the screen, that value should be supplied from the store.

*To make this happen, React provides setState() function which takes in an object of new states and does a compare and merge(similar to object.assign()) over the previous state and adds the new state to the state data store.

*Whenever the data in the state store changes, react will trigger an re-render with the new state which the view consumes and shows it on the screen.

This cycle will continue throughout the component's lifetime.
If you see the above steps, it clearly shows a lot of things are happening behind when you change the state. So, when you mutate the state directly and call setState() with an empty object. The previous state will be polluted with your mutation. Due to which, the shallow compare and merge of two states will be disturbed or won't happen, because you'll have only one state now. This will disrupt all the React's Lifecycle Methods.
As a result, your app will behave abnormal or even crash. Most of the times, it won't affect your app because all the apps which we use for testing this are pretty small.
And another downside of mutation of Objects and Arrays in JavaScript is, when you assign an object or an array, you're just making a reference of that object or that array. When you mutate them, all the reference to that object or that array will be affected. React handles this in a intelligent way in the background and simply give us an API to make it work.
Most common errors done when handling states in React
// original state
this.state = {
  a: [1,2,3,4,5]
}

// changing the state in react
// need to add '6' in the array

// bad approach
const b = this.state.a.push(6)
this.setState({
  a: b
})

In the above example, this.state.a.push(6) will mutate the state directly. Assigning it to another variable and calling setState is same as what's shown below. As we mutated the state anyway, there's no point assigning it to another variable and calling setState with that variable.
// same as
this.state.a.push(6)
this.setState({})

Many people do this. This is so wrong. This breaks the beauty of React and is bad programming practice.
So, what's the best way to handle states in React? Let me explain.
When you need to change 'something' in the existing state, first get a copy of that 'something' from the current state.
// original state
this.state = {
  a: [1,2,3,4,5]
}

// changing the state in react
// need to add '6' in the array

// create a copy of this.state.a
// you can use ES6's destructuring or loadash's _.clone()
const currentStateCopy = [...this.state.a]

Now, mutating currentStateCopy won't mutate the original state. Do operations over currentStateCopy and set it as the new state using setState().
currentStateCopy.push(6)
this.setState({
  a: currentStateCopy
})

This is beautiful, right?
By doing this, all the references of this.state.a won't get affected until we use setState. This gives you control over your code and this'll help you write elegant test and make you confident about the performance of the code in production.
To answer your question,

Why can't I directly modify a component's state?

Well, you can. But, you need to face the following consequences.

*

*When you scale, you'll be writing unmanageable code.

*You'll lose control of state across components.

*Instead of using React, you'll be writing custom codes over React.

Immutability is not a necessity because JavaScript is single threaded, but it's a good to follow practices which will help you in the long run.
PS. I've written about 10000 lines of mutable React JS code. If it breaks now, I don't know where to look into because all the values are mutated somewhere. When I realized this, I started writing immutable code. Trust me! That's the best thing you can do it to a product or an app.

A: the simplest answer to "

Why can't I directly modify a component's state:

is all about Updating phase.
when we update the state of a component all it's children are going to be rendered as well. or our entire component tree rendered.
but when i say our entire component tree is rendered that doesn't mean that the entire DOM is updated.
when a component is rendered we basically get a react element, so that is updating our virtual dom.
React will then look at the virtual DOM, it also has a copy of the old virtual DOM, that is why we shouldn't update the state directly, so we can have two different object references in memory, we have the old virtual DOM as well as the new virtual DOM.
then react will figure out what is changed and based on that it will update the real DOM accordingly .
hope it helps.

A: To avoid every time to create a copy of this.state.element you can use update with $set or $push or many others from immutability-helper
e.g.:
import update from 'immutability-helper';

const newData = update(myData, {
  x: {y: {z: {$set: 7}}},
  a: {b: {$push: [9]}}
});

A: setState trigger re rendering of the components.when we want to update state again and again we must need to setState otherwise it doesn't work correctly.

A: My current understanding is based on this and this answers:
IF you do not use shouldComponentUpdate or any other lifecycle methods (like componentWillReceiveProps, componentWillUpdate, and componentDidUpdate)  where you compare the old and new props/state
THEN
It is fine to mutate state and then call setState(), otherwise it is not fine.


text:
Q: Google Map Marker not working recently i found "FusedLocationApi" is deprecated, so i try fix my apps regarding google doc. my code working fine, and my activity get location, but when i try to set marker, it's not working. i'm so confuse, can anyone help me to find where i missing ?
Here my code.
class DealerMapsActivity : FragmentActivity(),
    OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener{

private val TAG = "DealerMapsActivity"
private var mMap: GoogleMap? = null
private var mGoogleApi: GoogleApiClient? = null
private lateinit var binding: ActivityDealerMapsBinding
private var myLastLocation: Location? = null
private var myMarker: Marker? = null
private var mFusedLocationClient: FusedLocationProviderClient? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    Log.d(TAG,"onCreate")
    binding = DataBindingUtil.setContentView(this,R.layout.activity_dealer_maps)
    val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}

in this case i use LocationCallback to get location.
private var mLocationCallback: LocationCallback = object : LocationCallback() {
    override fun onLocationResult(locationResult: LocationResult?) {

        for (location in locationResult!!.locations) {
            Log.i(TAG, "accuracy: "+ location.accuracy + " Location: " +
                    location.latitude + " " + location.longitude)
            myLastLocation = location
        }
        SetMapMarker()
        if(myLastLocation!!.accuracy > 0) {
            Log.i(TAG, "set accuracy into text: "+ myLastLocation!!.accuracy)
            binding.vAccurate.text =
                    "Accurate to "+myLastLocation!!.accuracy.toInt().toString()+ " meters"
        }
    }

}

and here my code to set Map Marker.
fun SetMapMarker(){
    Log.i(TAG, "set marker")
    if(myMarker != null){
        myMarker!!.remove()
    }
    val latlng = LatLng(myLastLocation!!.latitude, myLastLocation!!.longitude)
    if(myMarker == null){
        myMarker = mMap!!.addMarker(
                MarkerOptions()
                        .position(latlng)
                        .icon(BitmapDescriptorFactory
                                .defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
        )
    }
    myMarker!!.snippet = "ok"
    myMarker!!.title = "i'm here"

    val camera = CameraPosition
            .builder()
            .target(latlng)
            .zoom(16.0F)
            .build()
    mMap!!.animateCamera(CameraUpdateFactory.newCameraPosition(camera))
}

}

A: as @J Ramesh suggest, very funny. i just replace with this.
fun SetMapMarker(){
val latlng = LatLng(myLastLocation!!.latitude, myLastLocation!!.longitude)
Log.i(TAG, "set marker")
if(myMarker != null){
    myMarker!!.position = latlng
}

if(myMarker == null){
    myMarker = mMap!!.addMarker(
            MarkerOptions()
                    .position(latlng)
                    .icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
    )

// you can set title and message only one time not required all time (if you want to change message every time then write these line outside if statement)
 myMarker!!.snippet = "ok"
 myMarker!!.title = "i'm here"
}

val camera = CameraPosition
        .builder()
        .target(latlng)
        .zoom(16.0F)
        .build()
mMap!!.animateCamera(CameraUpdateFactory.newCameraPosition(camera))
}

hope help someone.


text:
Q: Is MySQL's `ORDER BY` distinct on multisets? Assuming a table with a column where integers are stored.
-----------------------------
id    |  some_int  | some_other_value
-----------------------------
1        5           hello
2        9           how
3        987         are
4        5           you
5        9           thanks
6        1           for
7        5           answering. :-)

Is SELECT * FROM mytable ORDER BY some_int; distinct? Meaning will it always return the rows in the same order, after each query?

A: To the best of my knowledge if there are duplicates in the order by clause, there is no guarantee for the order in which the duplicates are presented.
If this is a concern, you could modify the order by to include the primary key (id I am assuming).
ORDER BY some_int, id

Since id is a primary key, it should also be indexed.  Thus the performance difference will be minimal.

A: Doing this order by does not always have to give you the same result order. It is not frequent that the order will be different but it's not a 100% safe to assume that the order will always be the same as it is not an unique value that you're ordering by. To achieve this you should also include the primary key after the initial order.
SELECT * FROM mytable ORDER BY some_int, id

A: Use this:
SELECT * FROM mytable ORDER BY some_int,id;

So it will sort for 'some_int' and then using 'id' Duplicates for 'some_id' will be set to fixed position using 'id' column


text:
Q: Надо поэлементо сложить и вычесть трехмерные массивы 3x3(и найти среднее всех элементов) Написал вот такой вот код, вроде все приавильно, но в консоле пустые массивы. Помогите разобраться, что не так

let arr = [
                [1, 2, 3],
                [4, 5, 6],
                [7, 8, 9],
            ];

            let arr2 = [
                [1, 2, 3],
                [4, 5, 6],
                [7, 8, 9],
            ];

function Massives(arr, arr2){

                function ArrSum(arr, arr2){

                    let ArrSum = [
                        [],
                        [],
                        [],
                    ];

                    for(i=0; i<arr.lenght; i++){
                        let PodArr = arr[i];
                        let PodArr2 = arr2[i];
                        for(k=0; k < PodArr.lenght; k++){
                            let sum = PodArr[k];
                            let sum2 = PodArr2[k];
                            let endSum = sum + sum2;
                            ArrSum[i].push(endSum);

                        }
                    }
                    return ArrSum;

                };

                function ArrSub(arr, arr2){

                let ArrSub = [
                    [],
                    [],
                    [],
                ];
                    for(i=0; i<arr.lenght; i++){
                        let PodArr = arr[i];
                        let PodArr2 = arr2[i];
                        for(k=0; k < PodArr.lenght; k++){
                            let sub = PodArr[k];
                            let sub2 = PodArr2[k];
                            let endSub = sub - sub2;
                            ArrSub[i].push(endSub);

                        }
                    }
                    return ArrSub;

                };

                function ArrMid(arr, arr2){
                    for(i=0; i<arr.lenght; i++){
                        let PodArr = arr[i];
                        let PodArr2 = arr2[i];
                        for(k=0; k < PodArr.lenght; k++){
                            let mid = PodArr[k];
                            let mid2 = PodArr2[k];
                            var EMid =+ mid + mid2;
                            let endMid = EMid/(PodArr.lenght * arr.lenght);
                            return endMid;
                        }
                    }
                };

                console.log(ArrSum(arr, arr2));
                console.log(ArrSub(arr, arr2));
                console.log(ArrMid(arr, arr2));

            }

            console.log(Massives(arr, arr2));

A: Внимательнее надо
lenght -> length


text:
Q: dapper -multi-mapping: flat sql return to nested objects I have a company that contains an address object. The SQL return is flat, and I'm tring to get Query<> to load all the objects.
cnn.Query<Company,Mailing,Physical,Company>("Sproc",
                    (org,mail,phy) =>
                    {
                        org.Mailing = mail;
                        org.Physical = phy;
                        return org;
                    },
                    new { ListOfPartyId = stringList }, null, true, commandTimeout: null,
                    commandType: CommandType.StoredProcedure, splitOn: "MailingId,PhyscialId").ToList();

I'm not sure if i have the SplitOn correct either. I'm getting the message:

When using the multi-mapping APIs ensure you set the splitOn param if
  you have keys other than Id Parameter name: splitOn

Suggestions would be great.
The examples in the Test.cs are not what the code asks for as parameters for the queries. These need to be updated

A: for me this works perfect ... perhaps a typo?
I see PhyscialId which definitely looks like one.
class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Mailing Mailing { get; set; }
    public Physical Physical { get; set; }
}

class Mailing
{
    public int MailingId { get; set; }
    public string Name { get; set; }
}

class Physical
{
    public int PhysicalId { get; set; }
    public string Name { get; set; }
}

public void TestSOQuestion()
{
    string sql = @"select 1 as Id, 'hi' as Name, 1 as MailingId,
       'bob' as Name, 2 as PhysicalId, 'bill' as Name";
    var item = connection.Query<Company, Mailing, Physical, Company>(sql,
                (org, mail, phy) =>
                {
                    org.Mailing = mail;
                    org.Physical = phy;
                    return org;
                },
                    splitOn: "MailingId,PhysicalId").First();

    item.Mailing.Name.IsEqualTo("bob");
    item.Physical.Name.IsEqualTo("bill");

}


text:
Q: What does the third parameter in CONVERT() do? Query
Get the Joining year,Joining Month and Joining Date from employee table
This is my query which I have to perform. For this I write the following script:
select
    SUBSTRING (convert(varchar,joining_date,103),7,4) ,
    SUBSTRING (convert(varchar,joining_date,100),1,3) ,
    SUBSTRING (convert(varchar,joining_date,100),5,2)
from
    EMPLOYEE

The result is: http://d.pr/i/vObI
But when I changed convert(varchar,joining_date,100) to convert(varchar,joining_date,101)
Result is like this: http://d.pr/i/G5fZ
Can anyone please explain what this parameter means?

A: There are several different ways that you can format date using convert(varchar....  These are well documented on the MSDN site or different sites online.
Using convert(varchar..., date, 100) places the date in the format:
mon dd yyyy hh:mmAM (or PM)
May 10 2013 12:55PM

Using convert(varchar...date, 101) puts the date in the format:
mm/dd/yyyy
05/10/2013

See Demo
My suggestion would be whenever you implement these conversions, be sure to give a length on the varchar(10), etc.
Based on what it looks like you are returning, you can eliminate some of the convert/substring statements that you are using and implement some other functions to get the same result:
select year(joining_date) as [year] ,
  convert(varchar(3),joining_date,100) as [month] ,
  day(joining_date) as [day]
from EMPLOYEE

A: I think there is a better approach to split and get datetime parts using DATEPART:
  select DATEPART(YEAR, [joining_date]),
  DATEPART(MONTH, [joining_date]),
  DATEPART(DAY, [joining_date]) from EMPLOYEE

or if you are interested for example in names use DATENAME:
 select DATEPART(YEAR, [joining_date]),
 DATENAME(MONTH, [joining_date]),
 DATEPART(DAY, [joining_date]) from EMPLOYEE

However according to MSDN for DATENAME: "The return value depends on the language environment set by using SET LANGUAGE".
Regarding your initial question - these parameters are basically styles or I would call them Regional specific codes as described here, and you can just run the different queries against the DB and you will see the strings returned - and you will figure why you get unexpected results. For more infos refer to MSDN: CAST and CONVERT


text:
Q: Javascript function in angular 2 I am new to angular2. I am converting an html website into angular 2. There is a javascript smoothscroll function and its in an external js file. The problem is that this code and function is running fine in html but not running in angular. Maybe, I am doing some mistakes. Please guide me .

/*!
 * Start Bootstrap - New Age v3.3.7 (http://startbootstrap.com/template-overviews/new-age)
 * Copyright 2013-2016 Start Bootstrap
 * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE)
 */
 //scroll funtion code
!function(t){"use strict";t("a.page-scroll").bind("click",function(a){var o=t(this);t("html, body").stop().animate({scrollTop:t(o.attr("href")).offset().top-50},1250,"easeInOutExpo"),a.preventDefault()}),t("body").scrollspy({target:".navbar-fixed-top",offset:100}),t(".navbar-collapse ul li a").click(function(){t(".navbar-toggle:visible").click()}),t("#mainNav").affix({offset:{top:50}})}(jQuery);
<!doctype html>

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

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

  <link href="assets/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">

  <link rel="stylesheet" href="assets/lib/font-awesome/css/font-awesome.min.css">

  <link href="assets/css/hover-min.css" rel="stylesheet">
  <link href="assets/css/animate.min.css" rel="stylesheet">
  <link href="assets/css/animate.css" rel="stylesheet">
 <link rel="stylesheet"
          href="https://fonts.googleapis.com/css?family=Work+Sans">

  <app-root></app-root>

          HOME


text:
Q: Can a vector reference a 2-D array in Java? Basically, I want to create a 2-D array that grows in size at runtime. Could I do this using a vector in Java?
Would these be right then?
int [] [] x = new x [100] [100];
Vector x= new Vector();
To add elements into the array-
for i=0 to 99
   for j=0 to 99
   x.addElement(x[i] [j]);

essentially, it would be just the same like referencing any other object, only here, I've to specify the index numbers as well, right?
I'm a novice at Java. So I'd appreciate any help!

A: It's hard to know what to suggest to you without knowing the cases you need to optimize for.
For example, this simple wrapper around a map is a sparse 2D matrix optimized for setting and getting specific indices (doesn't need to "grow" at all), but bad for iterating over all indices.
public class SparseMatrix<T> {
    private final Map<Coordinates, T> map = new HashMap<Coordinates, T>();
    private final T defaultValue;

    public SparseMatrix(T defaultValue) {
       this.defaultValue = defaultValue;
    }

    private static class Coordinates {
        private final int[] coordinates;

        Coordinates(int... coordinates) {
            this.coordinates = coordinates;
        }

        @Override
        public boolean equals(Object o) {
            return Arrays.equals(coordinates, ((Coordinates)o).coordinates);
        }

        @Override
        public int hashCode() {
            return Arrays.hashCode(coordinates);
        }
    }

    public T get(int x, int y) {
        T value = map.get(new Coordinates(x, y));
        if ( value == null ) {
            return defaultValue;
        }
    }

    public T set(int x, int y, T val) {
        return map.put(new Coordinates(x, y), val);
    }
}

Usage:
SparseMatrix<Integer> matrix = new SparseMatrix<Integer>(0);
matrix.set(3, 5, 7);
int seven = matrix.get(3, 5);
int zero = matrix.get(3, 6); //not set yet, uses default

It can also be very easily adapted to N-dimensions.  Of course in production code you wouldn't roll your own, you'd use a library that does a better job.

A: You can use ArrayList which is equivalent to dynamic array.
ArrayList<ArrayList<Integer>> aDynamicArray = new ArrayList<ArrayList<Integer>>(2);
aDynamicArray.add(new ArrayList<Integer>());
aDynamicArray.add(new ArrayList<Integer>());

Now you can use you for loop as following:
int [] [] x = new x [2] [100];
for i=0 to 1
   for j=0 to 99
       aDynamicArray.get(i).add(x[i] [j]);

EDIT:

if i wanted to access x[2] [3] , how would i do that in the arraylist?

x[2][3] means value at 3rd row and 4th column. So, Fisrt line of code will change as follows: (to accomodate 3 rows)
ArrayList<ArrayList<Integer>> aDynamicArray = new ArrayList<ArrayList<Integer>>(3);
for(int i=0; i<3, i++)
{
    aDynamicArray.add(new ArrayList<Integer>());
}

then following line will give you access to x[2][3]:
aDynamicArray.get(2).get(3);

A: Unfortunately, Java has neither 2D arrays nor 2D growing vectors.
It has array of arrays or vector of vectors.
In your example, you created 1D vector of Objects:
Vector x= new Vector();

is similar to growing array of type Object[] x
So, when you do
y.addElement(x[i][j]);

Java does "boxing", i.e. it does
y.addElement(new Integer(x[i][j]));

Since you added 100x100 elements into 1D array, you will need to calculate location yourself
y.get(i*numcols+j)

So, to avoid all this, use vector of vectors like example below. The example copies newly fixed size array into vector of vectors:
   // creates fixed size 2D array with zeros
    int [] [] x = new int [50][50];

    // creates empty vector of vectors of integers
    // y is of type Vector<Vector<Integer>>
    // y.get(row) is of type Vector<Integer>>
    // y.get(row).get(col) is of type Integer
    Vector<Vector<Integer>> y = new Vector<Vector<Integer>>();

    // set the size of vector of vectors (number of rows)
    // each row will be null for now
    y.setSize(x.length);

    // enumerating rows
    for(int row=0; row<x.length; ++row) {

        log.info("row {}", row);

        // assign empty vector for row
        y.set(row, new Vector<Integer>());

        // set row size (number of columns)
        y.get(row).setSize(x[row].length);

        // enumerating columns of current row
        for(int col=0; col<x[row].length; ++col) {

            // setting the value for a cell
            y.get(row).set(col, x[row][col]);

        }
    }

A: In java would be something like:
int [][] x = new int [100] [100]

ArrayList <Integer> y = new ArrayList();

y.add(some number);

More information about Arraylist
Java let you have a collection compose by different data types. For Example
ArrayList<Object> list = new ArrayList<Object>();
list.add(1);
list.add("Java");
list.add(3.14);

Thus you can also use ArrayList of ArrayList and so on.

A: If you know the size of array (you have mentioned as 99), you can use int[][] intA = new int[100][100] and If you are familiar in java, you can implement your own Growing int[][] by monitoring array size when adding element.
Assume you are adding last element intA[99][99] = someInt at this time you can create new array int[][] newIntA = new int[intA.length+25][100]; then you need to copy content of existing intA array to newIntA
or you can use ArrayList<ArrayList<Integer>> to add your values or use ArrayList[] its your choice.


text:
Q: EnumResTypeProc blank LPTSTR argument I have the following code to enumerate all the resource files in a given .exe
BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCTSTR lpszType, LPTSTR lpszName, LONG_PTR lParam);
BOOL CALLBACK EnumResTypeProc(HMODULE hModule, LPTSTR lpType, LONG_PTR lParam);

REMOTECONTROL_API BOOL EnumResources(LPCWSTR file1, LPCWSTR file2)
{
    HMODULE hFile = LoadLibrary(file1);

    BOOL bSuccess = EnumResourceTypes(hFile, EnumResTypeProc, NULL);

    FreeLibrary(hFile);

    return bSuccess;
}

BOOL CALLBACK EnumResNameProc(HMODULE hModule, LPCTSTR lpszType, LPTSTR lpszName, LONG_PTR lParam)
{
    return TRUE;
}

BOOL CALLBACK EnumResTypeProc(HMODULE hModule, LPTSTR lpType, LONG_PTR lParam)
{
    MessageBox(NULL, lpType, L"Type", 0);
    return TRUE;
}

But when the EnumResTypeProc callback is called, the argument lpType is a blank string.
Why does this happens?

A: If you read the documentation, it says:

lpszType [in]
  Type: LPTSTR
The type of resource for which the type is being enumerated. Alternately, rather than a pointer, this parameter can be MAKEINTRESOURCE(ID), where ID is the integer identifier of the given resource type.
  ...
If IS_INTRESOURCE(lpszType) is TRUE, then lpszType specifies the integer identifier of the given resource type. Otherwise, it is a pointer to a null-terminated string.

Also this documentation says:

Note that the lpszType in EnumResTypeProc is either a resource ID or a pointer to a string (containing a resource ID or type name); lpszType and lpszName in EnumResNameProc and EnumResLangProc are similar.

That means your callback's lpType parameter is not always a pointer to a string, like you are assuming.  Sometimes it is a number that has been type-casted as a pointer instead.
Try this:
BOOL CALLBACK EnumResTypeProc(HMODULE hModule, LPWSTR lpType, LONG_PTR lParam)
{
    WCHAR szMsg[256];

    if (IS_INTRESOURCE(lpType))
        StringCchPrintfW(szMsg, 256, L"Type: %u", (USHORT)lpType);
    else
        StringCchPrintfW(szMsg, 256, L"Type: %s", lpType);

    MessageBoxW(NULL, szMsg, L"Type", 0);

    return TRUE;
}

REMOTECONTROL_API BOOL EnumResources(LPCWSTR file1, LPCWSTR file2)
{
    BOOL bSuccess = FALSE;

    HMODULE hFile = LoadLibraryExW(file1, NULL, LOAD_LIBRARY_AS_DATAFILE);
    if (hFile != NULL)
    {
        bSuccess = EnumResourceTypesW(hFile, EnumResTypeProc, NULL);
        FreeLibrary(hFile);
    }

    return bSuccess;
}


text:
Q: What do i do if need to change a libraries functionality I have a class in a Java Library(open-m3u) that I need to change just slightly.
The functionality is easy to implement on my own without using the library. The library is open-source so i have access to all of its code. The class is made in such a way that inheriting it or even changing that small part is not possible. My question is should I copy that class and all the classes that it depends on and put them in my own code base and change the functionality or should implement the functionality myself. Or is there another option?

A: Decorator pattern allows you to add new functionality to existing object.
If java library you use has any class like this:
public class LibraryClass implement ILibraryInterface {

    public void someMethod() {
        ...
    }
}

Then you can create Decorator class:
public class LibraryClassDecorator implement ILibraryInterface {

    private LibraryClass libObj;

    public LibraryClassDecorator(LibraryClass libObj) {
        this.libObj = libObj;
    }

    public void someMethod() {
        libObj.someMethod();
        // here you can do whatever you want.
        // Add some additional logic
        // transform result value if there is some
    }

}

Note: you have to implement the same interface to follow Liskov substitution principle

A:
The functionality is easy to implement on my own without using the
  library.

IMHO, then that's the way to go. Your other options are:

*

*Build the functionality around the library: you say that's not possible in your case.

*Create a branch of the library in your own source control system. That means you'll have to keep that repository in sync with the library maintainers, which means a permanent burden. And you have to check what the library's license says about forking.

*Copy the relevant parts into your code base and do the modifications there. Then you won't profit from future enhancements or bug fixes, but still have to maintain code that was created and architected by someone else, and doesn't exactly fit your requirements. And you have to check what the library's license says about copying parts into a foreign code base.

They all have their drawbacks.
As a general remark: in 25 years of professional software development, I've seen both successful usages of external libraries as well as complete failures. Some times, we invested more time into evaluating existing libraries (and then finding out that nothing matched) than we needed for implementing the project-specific solution on our own.
And every library you can do without, makes config management and rollout easier.

A: A solution will be to make a class that extends the one you wanna change and overide the part you wanna change


text:
Q: Is it possible to control the volume of AVMIDIPlayer I would like to use AVMIDIPlayer to play a multi-channel MIDI file in a game as background music, but I want to be able to fade out the background music when the game is over.  Unfortunately, AVMIDIPlayer does not have a volume parameter like AVAudioPlayer does.  Is there some way I can control the volume of AVMIDIPlayer?  (Changing the global volume is not really acceptable)
The only other solution I can see is to figure out how to identify the tracks in a MIDI file, create a multi-instrument AUGraph, and slap a mixer at the end.  I haven't been able to dig up any multi-instrument CoreMIDI examples, and it's looking pretty daunting.

A: Use a MusicSequence to play with a low level core audio AUGraph, then play the sequence with a MusicPlayer. In the AUGraph you can control the mixer node.
This goes into excruciating detail.


text:
Q: how to remove empty line use regex in javascript and c# user input content by text editor, and finally submitted to the database.
before store in database,i want remove empty line in content at begin and end (the middle can not be removed).
i want use JavaScript and C#
sample content is:

    a
bc

te
st

\n\n

i need is:

    a
bc

te
st

who can help me?

A: Well if I understand what you are trying to accomplish, this should solve your problem:
        string input = @"

            a
bc

te
st

\n\n

        ";
        string pattern = @"(
)?(\\n|
)?(
|\\n)(
)?";
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pattern);
        string final = reg.Replace(input, String.Empty);
        Console.WriteLine(final);
    }

That above code will return:

                a
bc

te
st

You could then go about trimming ever line, as it looks like it needs it.

A: It is not mentioned in the question whether you want to clean up your content on the client or server side.
If it should be done on the server please don't use regex for it. Why? See this excellent answer. Use HTML parser instead. E.g. with HtmlAgiltyPack:
var doc = new HtmlDocument();
doc.LoadHtml(html);
foreach(var node in doc.DocumentNode.SelectNodes("//div|//span|//p"))
    if (string.IsNullOrWhiteSpace(node.InnerText.Replace(@"\n", string.Empty)))
        node.Remove();

var result = doc.DocumentNode.OuterHtml;

But it could be done even simplier on the client (without regex too) by using jQuery:
var dom = $(html);
dom.find('p,span,div').each(function() {
    if ($(this).text().trim() == '')
        $(this).remove();
});

var result = dom.wrap('
').parent().html();


text:
Q: Cannnot Assign- must be a instance Django I have a table called job_position and there is a foreign key called region.
position =job_position.objects.get(id=position_id)
position.department= department.objects.get(department_name =request.POST.get("department")),

the "department" is passed from the HTML form, and the value of it is "Asia"
I am quite sure the error is from the second line
Cannot assign "(<region: Asia>,)": "job_position.region" must be a "region" instance.
But when I am trying the code in python shell ,it works fine,ie.e can get the region object and pass it to the position object region attribute and works fine. But somehow it does not works in the web development.
Anyone can help explain? Thanks very much

A: Cannot assign "(<region: Asia>,)"
As you have a comma at the end of your line, it turned it object into a tuple. Simply remove the comma:
position.department = department.objects.get(department_name=request.POST.get("department"))


text:
Q: Rails 3.2.2 Integrating spree in existing rails application. Migration table name conflict I have full featured existing Rails 3.2.2 running application. I want to integrate the spree application with it.
I have followed the steps for adding Spree which are given in the Github http://github.com/spree/spree BUT I already have some tables with the same name which Spree has like 'addresses' and 'users'
The migrations are failing because of name conflict. when I tried
config.active_record.table_name_prefix = "spree_"

It started running all migrations from beginning and prepended spree_ to every table and got in conflict again because original table also get name like spree_addresses.
How should I go ahead for integrating the spree in existing application.?

A: Unfortunately, it will be quite tough. You somehow must merge both spree and your apps user models and addresses models to make them compatible.
Easiest would be to start from scratch and install spree. I was in your situation and ended up with a fresh rails app.


text:
Q: In my application System.data.OracleClient is not coming In my application, on namesapce System.Data.OracleClient is not coming, what to do?

A: To import any namespace, you have to make sure you have added a reference to the appropriate DLL that contains the namespace (and classes within) that you want you use.


text:
Q: IPython/Jupyter Problems saving notebook as PDF So, I've been trying to save a jupyter notebook as PDF but I just can't figure out how to do this. The first thing I try is from the file menu just download as PDF, but doing that results in:
nbconvert failed: PDF creating failed

the next thing I try is try to do the conversion from the Command Prompt like this
$ ipython nbconvert --to latex --post PDF MyNotebook.ipynb

but again, this results in an error message
ImportError: No module named 'PDF'

and if I try
$ ipython nbconvert --to latex MyNotebook.ipynb

this results in
IPython.nbconvert.utils.pandoc.PandocMissing: Pandoc wasn't found:
Please check that pandoc is installed

if I try to install pandoc (pip install pandoc), this gives me
ImportError: No module named 'ConfigParser'

and this is where I get stuck because I just don't know what else to do.
Anyone have idea how to fix whatever is wrong?

A: For converting any Jupyter notebook to PDF, please follow the below instructions:
(Be inside Jupyter notebook):
On Mac OS:
command + P --> you will get a print dialog box --> change destination as PDF --> Click print
On Windows:
Ctrl + P --> you will get a print dialog box --> change destination as PDF --> Click print
If the above steps doesn't generate full PDF of the Jupyter notebook (probably because Chrome, some times, don't print all the outputs because Jupyter make a scroll for big outputs),
Try performing below steps for removing the auto scroll in the menu:-
Credits: @ÂngeloPolotto

*

*In your Jupyter Notebook, click Cell on top of the jupyter notebook

*Next click All output --> Toggle scrolling for removing auto scroll.

A: To make it work, I installed latex, typical latex extra, and pandoc.
With ubuntu:
sudo apt-get install texlive texlive-latex-extra pandoc

it takes some times: several 100 Mb to download. I read somewhere that you can use --no-install-recommends for texlive and extra to reduce to the dl.

A: As the comments to the question say, you will need pandoc and latex (e.g. TeXShop).  I installed pandoc with Homebrew, it took just a second.  Having pandoc and TeXShop, I could generate latex but not pdf (on the command line).
ipython nbconvert --to latex mynotebook.ipynb

Exploring the latex (.tex) file with TeXShop, the failure was due to missing stylesheets and defs.  After installing all of these (adjustbox.sty, adjcalc.sty, trimclip.sty, collectbox.sty, tc-pgf.def, ucs.sty, uni-global.def, utf8x.def, ucsencs.def), it did finally work.
However, the result looks a little too funky for my taste.  It is too bad that printing the html from Safari loses the syntax coloring.  Otherwise, it doesn't look so bad.  (This is all on OS X).

A: I am using Anaconda-Jupyter Notebook on OS: Ubuntu 16.0 for Python programming.
Install Nbconvert, Pandoc, and Tex:
Open a terminal and implement the following commands in it.
Install Nbconvert: though it's part of the Jupyter ecosystem still install it once again
$conda install nbconvert

Or
$pip install nbconvert

But I will recommend using conda instead pip if you are using anaconda
Install Pandoc: since Nbconvert uses Pandoc for converting markdown to formats other than HTML. Type following command
$sudo apt-get install pandoc

Install TeX: For converting to PDF, nbconvert uses the TeX. Type following command
$sudo apt-get install texlive-xetex

After execution of these commands, close the opened notebooks refresh the home page Or restart the kernel of the opened notebook. Now try to download notebook as a pdf :)
Note: For more details, please refer the official documentation:
https://nbconvert.readthedocs.io/en/latest/install.html

A: If you are on a Mac and have Homebrew installed, open a terminal shell and install pandoc typing the command:
brew install pandoc
be patient, time to install and compile can take a while on slow internet connections or older systems.

A: This Python script has GUI to select with explorer a Ipython Notebook you want to convert to pdf. The approach with wkhtmltopdf is the only approach I found works well and provides high quality pdfs. Other approaches described here are problematic, syntax highlighting does not work or graphs are messed up.
You'll need to install wkhtmltopdf:
http://wkhtmltopdf.org/downloads.html
and
Nbconvert
pip install nbconvert
# OR
conda install nbconvert

Python script
# Script adapted from CloudCray
# Original Source: https://gist.github.com/CloudCray/994dd361dece0463f64a
# 2016--06-29
# This will create both an HTML and a PDF file

import subprocess
import os
from Tkinter import Tk
from tkFileDialog import askopenfilename

WKHTMLTOPDF_PATH = "C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf"  # or wherever you keep it

def export_to_html(filename):
    cmd = 'ipython nbconvert --to html "{0}"'
    subprocess.call(cmd.format(filename), shell=True)
    return filename.replace(".ipynb", ".html")

def convert_to_pdf(filename):
    cmd = '"{0}" "{1}" "{2}"'.format(WKHTMLTOPDF_PATH, filename, filename.replace(".html", ".pdf"))
    subprocess.call(cmd, shell=True)
    return filename.replace(".html", ".pdf")

def export_to_pdf(filename):
    fn = export_to_html(filename)
    return convert_to_pdf(fn)

def main():
    print("Export IPython notebook to PDF")
    print("    Please select a notebook:")

    Tk().withdraw() # Starts in folder from which it is started, keep the root window from appearing
    x = askopenfilename() # show an "Open" dialog box and return the path to the selected file
    x = str(x.split("/")[-1])

    print(x)

    if not x:
        print("No notebook selected.")
        return 0
    else:
        fn = export_to_pdf(x)
        print("File exported as:\n\t{0}".format(fn))
        return 1

main()

A: notebook-as-pdfInstall
python -m pip install notebook-as-pdf pyppeteer-install
Use it
You can also use it with nbconvert:
jupyter-nbconvert --to PDFviaHTML filename.ipynb
which will create a file called filename.pdf.
or pip install notebook-as-pdf
create pdf from notebook jupyter-nbconvert-toPDFviaHTML

A: To convert notebooks to PDF you first need to have nbconvert installed.
pip install nbconvert
# OR
conda install nbconvert

Next, if you aren't using Anaconda or haven't already, you must install pandoc either by following the instructions on their website or, on Linux, as follows:
sudo apt-get install pandoc

After that you need to have XeTex installed on your machine:

*

*Linux : TeX Live

*Mac : MacTex

*Windows : MikTex
You can now navigate to the folder that holds your IPython Notebook and run the following command:
jupyter nbconvert --to pdf MyNotebook.ipynb

for further reference, please check out this link.

A: 2015-4-22: It looks like an IPython update means that --to pdf should be used instead of --to latex --post PDF. There is a related Github issue.

A: This problem was experienced with both Ubuntu and Mac OSX. After a frantic set of searches and trials, both of them were solved. This requires both tex and pandoc; both jumbo external programs cannot installed by Python's pip.

Mac OSX: using MacPorts installation of pandoc
port install pandoc

This should take nearly an hour to complete (in the usual case). If the problem persists, you might have to install MacTeX distro. of TeXLive.

For Ubuntu: install vanilla TeXLive from the network installer -- not through apt-get. Then install pandoc using apt-get.
sudo apt-get install pandoc

A complete installation of TeXLive would require a upto to 4.4 GB on disk.
To save all this trouble, the recommeded way to use IPython/Jupyter Notebook would be to install Anaconda Python distribution.

A: I had all kinds of problems figuring this out as well. I don't know if it will provide exactly what you need, but I downloaded my notebook as an HTML file, then pulled it up in my Chrome browser, and then printed it as a PDF file, which I saved. It captured all my code, text and graphs. It was good enough for what I needed.

A: If you are using sagemath cloud version, you can simply go to the left corner,
select File --> Download as --> Pdf via LaTeX (.pdf)
Check the screenshot if you want.
Screenshot Convert ipynb to pdf
If it dosn't work for any reason, you can try another way.
select File --> Print Preview and then on the preview
right click --> Print and then select save as pdf.

A: As a brand new member, I was unable to simply add a comment on the post but I want to second that the solution offered by Phillip Schwartz worked for me. Hopefully people in a similar situation will try that path sooner with the emphasis. Not having page breaks was a frustrating problem for quite a while so I am grateful for the discussion above.
As Phillip Schwartz said:
"You'll need to install wkhtmltopdf: [http://wkhtmltopdf.org/downloads.html][1]
and Nbconvert "
You then add a cell of the type "rawNBConvert" and include:

That seemed to do the trick for me, and the generated PDF had the page break at the corresponding locations.
You don't need to run the custom code though, as it seems the "normal" path of downloading the notebook as HTML, opening in browser, and printing to PDF works once those utilities are installed.

A: To convert .ipynb into pdf, your system should contain 2 components,

*

*nbconvert:
Is part of jupyter allows to convert ipynb to pdf

pip install nbconvert
OR
conda install nbconvert

*XeTeX:
Convert ipynb to .tex format and then converting to pdf.

sudo apt-get install texlive-xetex

Then you can use below command to convert to pdf,

ipython nbconvert --to pdf YOURNOTEBOOK.ipynb

In case, it doesn't work, install pandoc and try again.

sudo apt-get install pandoc

A: I had problems correctly displaying some symbols with regular download as pdf. So downloaded as tex jupyter nbconvert --to latex "my notebook.ipynb", made some tweaks with notepad (as an example, in my case I needed these lines for my language
\usepackage{tgpagella}
\usepackage[lithuanian,english]{babel}

) and then exported to pdf with latex --output-format=pdf "my notebook.tex".
But finally, however, to retain the same characters as you see in a browser I ended up using my Chrome browser printing: Ctrl+P Print to pdf. It adds unnecessary header and footer but everything else remains as it is. No more errors processing tqdm progress bar, no more code going out of the page and so on. Simple as that.

A: In any system, the basic steps to correctly setup nbconvert  to convert ipython notebooks to pdf/latex are

*

*Install nbconvert

*Install pandoc

*Install Texlive

Installing nbconvert
pip install nbconvert
or conda install nbconvert
Installing pandoc
sudo apt-get install pandoc for Ubuntu
or sudo yum install pandoc for CentOS
for others visit pandoc-installation
Installing texlive
You can install recommended packages or full install. For Ubuntu
sudo apt-get install texlive texlive-xetex texlive-generic-extra texlive-generic-recommended

`
For others and to full install texlive  follow the instructions given at  tug as per your system and choice.
I downloaded tar.gz file from  tug-texlive-download and followed instructions given at  TeX Live - Quick install. Installation instructions in  summary:

*

*Clean up
rm -rf /usr/local/texlive/2019
rm -rf ~/.texlive2019

*Run installer
unpack the zip file
cd /your/unpacked/directory
perl install-tl
Enter command: i

*Setting path
sudo vi /etc/bash.bashrc and insert
PATH=/usr/local/texlive/2019/bin/x86_64-linux:$PATH; export PATH
MANPATH=/usr/local/texlive/2019/texmf-dist/doc/man:$MANPATH; export MANPATH
INFOPATH=/usr/local/texlive/2019/texmf-dist/doc/info:$INFOPATH; export INFOPATH

*Setting default papersize
tlmgr paper letter
The commands may differ as per your system but the basic steps remains the same.

A: I had this error in Windows 10. I followed these three steps and it solved my problem:

*

*Install nbconvert
pip install nbconvert

*Install pandoc
https://pandoc.org/installing.html

*Install miktex

https://miktex.org/download

Also it is good to update libraries:
pip install jupyter --upgrade
pip install --upgrade --user nbconvert

A: What I found was that the nbconvert/utils/pandoc.py had a code bug that resulted in the error for my machine. The code checks if pandoc is in your environmental variables path. For my machine the answer is no. However pandoc.exe is!
Solution was to add '.exe' to the code on line 69
if __version is None:
    if not which('pandoc.exe'):
        raise PandocMissing()

The same goes for 'xelatex' is not installed.
Add to the file nbconvert/exporters/pdf.py on line 94
    cmd = which(command_list[0]+'.exe')

A: For Ubuntu users, an answer can be found here. I also quote it:

The most probable cause, is that you have not installed the
  appropriate dependencies. Your Ubuntu system has to have some packages
  installed regarding conversion of LaTeX and XeTeX files, in order to
  save your notebook as PDF. You can install them by:
sudo apt-get install texlive texlive-xetex texlive-generic-extra texlive-generic-recommended pandoc

Also, nbconvert is another dependency that is usually automatically
  installed with jupyter. But you can install it just to be sure, while
  having your virtual environment activated:
pip install -U nbconvert

A: You may go for below simple trick (works totally well with all modern browsers; on all recent operating systems - Windows, Mac, Linux) :

*

*Right click anywhere on your ipynb notebook.

*Select Print... . This will take you to the "Print-Preview Wizard" that will show you a PDF form of your python notebook.

*Provide the destination folder name. Click save.

Voila!!
This simple hack shall ofcourse save much of your time of installing nbviewer or miktex, pandoc or LaTex, etc. converter packages. Moreover, actually this hack works in same way, like you try to save an html webpage into PDF format.


text:
Q: Is it better to use dictionary or individually bind every variable in Model (More detail in description) I want to populate all the label text of my application from back end. I have an estimation of 60 labels per page. Is it better to save all the data in the form of a dictionary and and move it to the view or should I create a variable for each of this labels and bind them in the Model and pass as an object.
Which one is better in terms of speed and memory usage?
EDIT 1:

I'm refraining from using resx, since there would be frequent changes in the labels and I don't want to republish the code frequently.

A: In your case, one of the best practices is to use resource files (.resx) and take advantage of Globalization and Localization features provided by the framework.
Resource files are sort of dictionary, but you will be able to benefit from a lot more than doing it by yourself.
Hope it helps.


text:
Q: Is there any ongoing research in transformation geometry? I'm a 3rd year undergrad Math student and totally confused right now on what field I'm gonna choose in my thesis next semester. We we're introduced in Transformation Geometry (Introduction to Symmetries by George Martin, used by our professor as a reference). I'm amazed at how the book approaches geometry algebraically tho seems hard. Really, I'm interested in this topic yet I'm disappointed while searching through the Google if this field really exist for research. I found only that this is a new approach in geometry for highschool. Currently, I already read about half of the book. It's a beautiful book.

*

*Is this a good field to study?

*If this is not a good field to study (i.e., just a new approach in geometry), are there any field of mathematics related to this?


text:
Q: Confusion Matrix for Leave-One-Out Cross Validation in sklearn I know how to draw confusion matrix when I use the train and test split using sklearn but I do not know how to create the confusion matrix when I am using the leave-one-out cross validation as shown in this example:
# Evaluate using Leave One Out Cross Validation
import pandas
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = pandas.read_csv(url, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
num_folds = 10
num_instances = len(X)
loocv = model_selection.LeaveOneOut()
model = LogisticRegression()
results = model_selection.cross_val_score(model, X, Y, cv=loocv)
print("Accuracy: %.3f%% (%.3f%%)" % (results.mean()*100.0, results.std()*100.0))

How should I create the confusion matrix for LOOCV in order to visualize the per-class accuracy?

A: Borrowing your method from here, you can work around the problem via creating a custom scorer that receives the metadata during the iterations. These metadata can be used to find: F1 Score, Precision, Recall, Accuracy as well as the Confusion Matrix!

Here we need another trick that is using GridSearchCV which accepts a custom scorer, so here we go!

Here is an example that you can work on more according to your absolute requirements:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import make_scorer, accuracy_score, confusion_matrix
from sklearn.model_selection import GridSearchCV, StratifiedKFold

# Your method from the link you provided
def cm_analysis(y_true, y_pred, labels, ymap=None, figsize=(10,10)):
    if ymap is not None:
        y_pred = [ymap[yi] for yi in y_pred]
        y_true = [ymap[yi] for yi in y_true]
        labels = [ymap[yi] for yi in labels]
    cm = confusion_matrix(y_true, y_pred, labels=labels)
    cm_sum = np.sum(cm, axis=1, keepdims=True)
    cm_perc = cm / cm_sum.astype(float) * 100
    annot = np.empty_like(cm).astype(str)
    nrows, ncols = cm.shape
    for i in range(nrows):
        for j in range(ncols):
            c = cm[i, j]
            p = cm_perc[i, j]
            if i == j:
                s = cm_sum[i]
                annot[i, j] = '%.1f%%\n%d/%d' % (p, c, s)
            elif c == 0:
                annot[i, j] = ''
            else:
                annot[i, j] = '%.1f%%\n%d' % (p, c)
    cm = pd.DataFrame(cm, index=labels, columns=labels)
    cm.index.name = 'Actual'
    cm.columns.name = 'Predicted'
    fig, ax = plt.subplots(figsize=figsize)
    sns.heatmap(cm, annot=annot, fmt='', ax=ax)
    #plt.savefig(filename)
    plt.show()

# Custom Scorer
def my_scorer(y_true, y_pred):
    acc = accuracy_score(y_true, y_pred)
    # you can either save  y_true, y_pred and accuracy into a file
    # for later use with the info in clf.cv_results_
    # or plot the confusion matrix right here!
    # for labels, you can create a class attribute to make it more dynamic
    # i.e. changes automatically with every new dataset!
    cm_analysis(y_true, y_pred, labels=[0,1], ymap=None, figsize=(10, 10))
    # N.B as long as you have y_true and y_pred from every round here, you can
    # do with them all the metrics that want such as F1 Score, Precision, Recall, A
    # ccuracy and the Confusion Matrix!
    return acc

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
df = pd.read_csv(url, names=names)
array = df.values
X = np.array(array[:,0:8])
Y = np.array(array[:,8]).astype(int)

# I'll make it two just for submitting the result here!
num_folds = 2
skf = StratifiedKFold(n_splits=num_folds, random_state=0)

# this is just a trick because the list contains
# the default parameter only (i.e. useless)
param_grid = {'C': [1.0]}
model = LogisticRegression()
# create custom scorer
custom_scorer = make_scorer(my_scorer)
# pass it to the GridSearchCV
clf = GridSearchCV(model, param_grid, scoring=custom_scorer, cv=skf, return_train_score=True)
# Fit and Go
clf.fit(X,Y)

# cv_results_ is a dict with all CV results during the iterations!
# IDK, you may need it to combine its content with the metrics ..etc
print(clf.cv_results_)

Result
{'mean_score_time': array([0.09023476]), 'split0_train_score':
 array([0.79166667]), 'mean_train_score': array([0.77864583]),
'params': [{'C': 1.0}], 'std_test_score': array([0.01953125]),
'mean_fit_time': array([0.00235796]),
'param_C': masked_array(data=[1.0], mask=[False], fill_value='?',
dtype=object), 'rank_test_score': array([1], dtype=int32),
'split1_test_score': array([0.7734375]),
'std_fit_time': array([0.00032902]), 'mean_test_score': array([0.75390625]),
'std_score_time': array([0.00237632]), 'split1_train_score': array([0.765625]),
'split0_test_score': array([0.734375]), 'std_train_score': array([0.01302083])}

Split 0

Split 1

EDIT
If you strictly want LOOCV, then you can apply it in the above code, just replace StratifiedKFold by LeaveOneOut function; but bear in mind that LeaveOneOut will iterate around 684 times! so it's computationally very expensive. However, that would give you the confusion matrix in details during the iterations (i.e. metadata).
Nevertheless, if you are seeking the confusion matrix of the overall (i.e. final) process then you will still need to use the GridSearchCV but like follow:
......
loocv = LeaveOneOut()
clf = GridSearchCV(model, param_grid, scoring='accuracy', cv=loocv)
clf.fit(X,Y)

y_pred = clf.best_estimator_.predict(X)
cm_analysis(Y, y_pred, labels=[0, 1], ymap=None, figsize=(10,10))

Result


text:
Q: Can console and PC players play together online? I have a gaming PC and plan to buy FIFA 15. My friends already play it on their XBoxes. Is it possible that I join them or does the PC version have its own multiplayer servers?
The only thing I found out about it was that for former versions of FIFA it did not work.

A: No. This is not supported. Each platform is separate.

A: ++ to TZHX for his answer :)
The only thing you can somehow do on PC while your actually playing the game on another platform is access your FUT on the web @ https://www.easports.com/fifa/ultimate-team/web-app


text:
Q: Data Loaded:  Fatal error: Uncaught exception 'PDOException' with message I have searched for solutions but nothing seems to be working. I have added the port 3307 (web africa) south africa.but I still get this error

Data Loaded:  Fatal error:  Uncaught exception
  'PDOException' with message 'SQLSTATE[HY000] [2002] Connection timed
  out' in /home/sea503/public_html/phpsqlinfo_addrow.php:11 Stack trace:
  0 /home/sea503/public_html/phpsqlinfo_addrow.php(11):
  PDO->__construct('mysql:host=mysq...', NULL, NULL) 1 {main}
  thrown in /home/sea503/public_html/phpsqlinfo_addrow.php on
  line 11

My code looks like this
<?php
require("dbinfo.php");// database connections
// Get parameters from URL
$lat = $_GET["lat"];
$lng = $_GET["lng"];
$name = $_GET["name"];
$time = $_GET["time"];
$description = $_GET["description"];
$sighting = $_GET["sighting"];
//Connect to database
$dbh = new PDO("mysql:host=mysql.spri.co.za;port=3307;dbname=kruger_park_live",$sean_sql,$########);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    // Prepare INSERT statement new sigting
        $stmt3 = $dbh->prepare("INSERT INTO tbl_maps (ID, map_client_name, client_time, client_lat, client_lng, client_description, client_sighting)  VALUES (NULL, ?, ?, ?, ?, ?, ?)");
        // Assign parameters
        $stmt3->bindParam(1,$name);
        $stmt3->bindParam(2,$time);
        $stmt3->bindParam(3,$lat);
        $stmt3->bindParam(4,$lng);
        $stmt3->bindParam(5,$description);
        $stmt3->bindParam(6,$sighting);
        $stmt3->execute();
        $data[] = array("name"=>$name, "lat"=>round($lat,6), "lng"=>round($lng,6),"time"=>$time,"description"=>$description,"sighting"=>$sighting);
        //Data for success
        echo json_encode($data);
}
catch(PDOException $e) {
    echo "Error Message.". $e->getMessage() ;// Remove or modify after testing
    file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", phpsqlinfo_addrow.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
//Close the connection
$dbh = null;
?>

and the dbinfo.php like this
<?php
 $host= "****;port=3307"; $username="****"; $password="****"; $database="****"; $dbname="****";

?>

A: You are doing
$dbh = new PDO("mysql:host=...;dbname=...,$s..,$P..);
      // I removed the actual values for your security

but your variables are
$host= "";
$username="...";
$password="...";
$database="...";

I believe you want to do
$dbh = new PDO("mysql:host=$host;dbname=$database",$username,$password);

you set your variable, but were using the values as the variable names
this is apparent when looking at this line in the error message -
PDO->__construct('mysql:host=mysq...', NULL, NULL)
                                       ^^^^  ^^^^

A: I have made "" to single ''
$dbh = new PDO("mysql:host=myhost;port=xxxx;dbname=db_name",$sean_sql,$########);

to
$dbh = new PDO('mysql:host=myhost;port=xxxx;dbname=db_name','$username','$password');


text:
Q: Swift iOS Which View Is On Top In my app I have a background task running that alerts the user when a certain event happens.  What has to happen next depends on which view is currently on top.  How can I determine this?  I thought about writing some indicator into a plist file but that seems a bit clunky especially if there's a system way of doing it.

A: that's how it can be done in objective c
if([self.navigationController.topViewController isKindOfClass:[MYController Class]])
     //then do something

I'm sure you cab find out the swift version easily

A: I can think of two possible ways:

*

*First, you could use NSUserDefaults to set a Bool or String indicator. Assuming you're using Swift, try:
NSUserDefaults.standardUserDefaults().setObject("FirstViewOnTop", forKey:"WhatViewIsOnTop?")
NSUserDefaults.standardUserDefaults().synchronize()
When you want to retrieve the value, use:
let indicatorString = NSUserDefaults.standardUserDefaults().objectForKey("WhatViewIsOnTop?")
You could use an if/else statement from there.

*The way I would go about doing it, though, is to subclass UIView and add a z property and add it to the init(). Then you can access it much more elegantly.

A: This sounds like the perfect opportunity to use NSNotificationCenter.  Have the background task post a notification that your view controllers will listen for.  When the active viewController gets the notification, it can handle it in the way that is appropriate for that viewController.
Send the Notification from the main queue since your task is running in the background:
dispatch_async(dispatch_get_main_queue()) {
    NSNotificationCenter.defaultCenter().postNotificationName("SomethingWonderfulHappened", object: nil)
}

Receive the Notification: For each of your viewControllers that might want to act on the notification, override viewDidAppear to start listening for notifications, and override viewDidDisappear to stop listening for notifications:
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleNotification:", name:"SomethingWonderfulHappened", object: nil)

}

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

Notification Handler: Implement one of these for each of your viewControllers.  Have each one do what is appropriate for that viewController.
func handleNotification(notification: NSNotification) {
    //Action to take when SomethingWonderfulHappened
}


text:
Q: Android:best way for send/get data from php i send and get data from php with this code
public void SendGetData(){
    class GetDataJSON extends AsyncTask<String, Void, String>{

        private ProgressDialog pDialog;
        private InputStream is = null;
        private String url = "http://***/SendGet.php";
        private String page_output = "";

        @Override
        protected String doInBackground(String... args) {

            try {
                    // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("Name", ed_name.getText().toString()));
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            is.close();
            page_output = sb.toString();

            Log.i("LOG", "page_output --> " + page_output); ///<--------------------------|
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        return page_output;
    }

        @Override
        protected void onPostExecute(String result){
            Log.i("LOG", " onPostExecute -> " + result );
            myJSON=result;
            Log.i("LOG", "myJSON" + myJSON);
        }
    }
    GetDataJSON g = new GetDataJSON();
    Log.i("LOG", " GetDataJSON " );
    g.execute();
}

but most code deprecated like

The type NameValuePair is deprecated
The constructor BasicNameValuePair(String, String) is deprecated
The type HttpPost is deprecated
The type HttpEntity is deprecated
The type HttpResponse is deprecated
...

What is the best alternative to the above method?
OkHttp or Apache HttpComponents - HttpClient or is there a better way?
Thank you


text:
Q: How to access a variable from .cpp file in a .h file Consider this scenario:
File1.cpp:
double dir = M_PI/2;

hFile1.h:
void printdir () {
cout << dir;
}

Main.cpp:
#include "hFile1.h"
int main () {
printdir();
}

This obviously will not work because hFile1.h will throw an error: "use of undeclared identifier 'dir'". In this example, I want to be able to access and use the defined dir variable in hFile1.h. Is this possible?
NOTE: I have already tried using extern based on similar posts on this topic and it didn't work, even after I did exactly what they did. Code:
File1.cpp:
extern double dir = M_PI/2;

hFile1.h:
extern double dir;
void printdir () {
cout << dir;
}

Main.cpp:
#include "hFile1.h"
int main () {
printdir();
}

A: You need to use keyword "extern" in hFile1.h as below. I tested, it worked.
extern double dir;

void printdir () {
    cout << dir;
}