text:
Q: How do I simplify this piece of React code? (Progressive input form) The purpose of the sample of React code below is to create progressive form which only displays one question to begin with and then reveals the next question when the user clicks a button (while keeping the previous questions visible). The actual piece of code I've written contains 12 questions - the number, content and order of which could change over time.  Currently the code works but it's very long and difficult to update and so I'm sure there must be a better more dynamic way of doing this.  One way I've experimented with is having a sperate .js file containing an array of variables for each question but I've not been able to keep the "progressive" aspect of the form working with is method.
Any thoughts or advice would be greatly appreciated!
import React, { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';

import classes from './InputForm2.module.css';

const InputForm2 = () => {
  const dateOfBirthInputRef = useRef();
  const membershipTypeInputRef = useRef();
  const dateOfJoiningInputRef = useRef();

  let navigate = useNavigate();
  function routeChange() {
    let path = '/results';
    navigate(path);
  }

  function dataHandler() {
    const enteredDateofBirth = dateOfBirthInputRef.current.value;
    const enteredMembershipType = membershipTypeInputRef.current.value;
    const enteredDateOfJoining = dateOfJoiningInputRef.current.value;

    const inputData = {
      dateOfBirth: enteredDateofBirth,
      membershipType: membershipTypeRef,
      dateOfJoining: enteredDateOfJoining,
    };
    console.log(inputData);
  }

  function submitHandler(event) {
    event.preventDefault();
    dataHandler();
    routeChange();
  }

  const [q2IsOpen, setQ2IsOpen] = useState(false);
  const [q3IsOpen, setQ3IsOpen] = useState(false);

  const btn1ClickHandler = (event) => {
    event.preventDefault();
    setQ2IsOpen(true);
  };

  const btn2ClickHandler = (event) => {
    event.preventDefault();
    setQ3IsOpen(true);
  };

  const btn3ClickHandler = (event) => {
    event.preventDefault();
    setQ4IsOpen(true);
  };

  return (

      <form>
        <section className={`${classes.active}`}>

            Question 1

What is your date of birth?

            <input
              className={classes.input}
              type="date"
              required
              ref="dateOfBirthInputRef"
            ></input>

            <button className={classes.button} onClick={btn1ClickHandler}>
              Next
            </button>

        <section className={`${q2IsOpen ? classes.active : classes.inactive}`}>

            Question 2

              What is your membershiptype?

            <select
              className={classes.input}
              required
              ref="membershipTypeInputRef"
            >
              <option></option>
              <option value="Platinum">Platinum</option>
              <option value="Gold">Gold</option>
              <option value="Basic">Basic</option>
            </select>

            <button className={classes.button} onClick={btn2ClickHandler}>
              Next
            </button>

        <section className={`${q3IsOpen ? classes.active : classes.inactive}`}>

            Question 3

What date did you start your membership?

            <input
              className={classes.input}
              type="date"
              required
              ref="dateOfJoiningInputRef"
            ></input>

            <button className={classes.button} onClick={btn3ClickHandler}>
              Next
            </button>

          <button
            className={`${classes.submitbutton} ${
              q4IsOpen ? classes.active : classes.inactive
            }`}
            onClick={submitHandler}
          >
            Calculate
          </button>

      </form>

  );
};

export default InputForm2;

A: This isn't fully working code, just an idea of how you would structure this. As you suggested yourself, making an array of question objects is a good idea. You could also break out the question structure into it's own component:
const Question = ({thisIndex, currentIndex, title, text, ref, handler}) => {

    return(
        <section className={`${thisIndex >= currentIndex-1 ? classes.active : classes.inactive}`}>

                {title}

{text}

                <input
                  className={classes.input}
                  type="date"
                  required
                  ref=ref
                ></input>

                <button className={classes.button} onClick={handler}>
                  Next
                </button>

    )
}

The props input to Question component can be mapped from a QUESTIONS object array, assuming an object structure like {title: 'Question 1', text: 'Why are we here?', //and so on}.
I would keep track of visibility simply by keeping track of the index of the last answered question in the main form, and passing that in to each question in the array - that way it only becomes visible when the question before is answered.
const InputForm2 = () => {

    const [currentIndex, setCurrentIndex] = useState(0);

    //all your other code

    const handler = (i) => {
        setCurrentIndex(i)
        //do more stuff
    }

    const questions = QUESTIONS.map((question, i) => {
        return(
            <Question key={i}
                thisIndex=i currentIndex={currentIndex}
                title={question.title} text={question.text}
                handler={handler(i)}
                //and so on
            />
        )
    });

    return (

{questions}

    )
}

Then, in your form you can return the questions array of components.
EDIT
In a similar way, since you have different types of input / select for different questions, you can make separate components and pass those as props to you question.
const QSelector = ({options}) => {
   const optionElements = options.map((option, i) => {
    return(
        <option //get your data from option element
    )
})
   return(
        <selector>
           {options}
        </selector>
   )
}

Obviously for three different input types and three questions, this isn't super useful but as you go in, if you have 5 selector q's, 5 inputs, you'll find you can reuse a lot of structures, just passing in any data that is different.
Below, I'm updating the Question component to receive this as an 'answer' prop.
const Question = ({thisIndex, currentIndex, title, text, ref, handler, answer}) => {

return(
    <section className={`${thisIndex >= currentIndex-1 ? classes.active : classes.inactive}`}>

            {title}

{text}

            {answer}

            <button className={classes.button} onClick={handler}>
              Next
            </button>

)

}


text:
Q: Dojo - how to submit data using a Dialog form I would like to submit some values that a user enters in a Dialog-form. He clicks on the button, gives his name, first name, email and submit.
When he submits, I would like to store these values in a DB. I have a php script that is supposed to get these values from the user... but I don't know how to send these values once submitted to my php script.
Thanks for your help.
---php script------> so far just printing, no DB storing but printing is not working
    <?php
$name= $_POST["name"];

$firstName= $_POST["firstName"];

$email = $_POST["email"];

print("$name+ $firstName+ $email
");
?>

-----------------------HTML page------------------------
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <meta name="generator" content="HTML Tidy for Windows (vers 14 February 2006), see www.w3.org">
        <title>
            Dojo
        </title>
        <meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
        <link rel="stylesheet" type="text/css" href="../js/dojo/resources/dojo.css">
        <link rel="stylesheet" type="text/css" href="../js/dijit/themes/claro/claro.css">

`enter code here`

                        Name:

                        <input dojotype="dijit.form.TextBox" type="text" name="name" id="name">

                        FirstName:

                        <input dojotype="dijit.form.TextBox" type="text" name="firstName" id="firstName">

                        Email :

                        <input type="text" name="mail" id="mail" dojotype="dijit.form.ValidationTextBox"
                        regexpgen="dojox.validate.regexp.emailAddress">

                        <button dojotype="dijit.form.Button" type="submit" onclick="return dijit.byId('subscription').isValid();">OK</button>
                        <button dojotype="dijit.form.Button" type="button" onclick="dijit.byId('subscription').hide();">Annuler</button>

                <button id="button1" dojotype="dijit.form.Button" type="button">Sign</button>

A: You don't have an actual <form> tag within the dialog.  You need something like:

  <form action="PATH_TO_PHP_PAGE" method="POST">

  </form>

If you want to use the dijit form with  the nice validating functionality, you'll need to require dijit.form.Form and put that on your form tag:
<form dojoType="dijit.form.Form">

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create a pop up window asking for input using jquery My index.html code is
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Ember Starter Kit</title>
  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/one.css">

and app.js code is
App = Ember.Application.create();

App.Router.map(function()
{
    this.resource('HOME');
    this.resource('DINESH');
    this.resource('CLICK');
});

If i click it should display a pop-up window asking for my name ("Enter your name").
I am a student who is very new to programming. So kindly explain me as simple as you can.

A: You can do this in pure javascript. prompt() method will do this for you.
Check here
If you want to do this in Ember.js, you need to open a modal, on the user click.
Created a Fiddle http://jsfiddle.net/rocky_217/uxa38xjz/4/

A: You can use prompt() function in jquery or js to receive input in popup. check out the code -:


text:
Q: Count the number of ways in which these stamps can be posted on the envelope. The postal stamps of three different valuations viz $2$ cents, $3$ cents and $4$ cents are available. If the number of ways in which these stamps can be posted on envelope one after the other so that the total valuation of stamps on the envelope is $10$ cents is $N$. Find $N$.
I have actually solved the problem using the method given below.
Consider the function $$f(n)=f(n-2)+f(n-3)+f(n-4)$$ where $f(n)$ represents the ways in which stamps so arranged give the sum as $n$ on the envelope.  Hence we need to find $f(10)$. Now on quick brute force we get $f(2)=1, f(3)=1, f(4)=2$ and $f(5)=2$.
Using these I got $f(10)$ as $17$ which is the correct answer.
But I want to solve this problem using the binomial coefficient method.  For example the answer to this question must be equal to the coefficient of $x^{10}$ in the expansion of $$(x^0+x^2+x^4+x^6+x^8+x^{10})(x^0+x^3+x^6+x^9)(x^0+x^4+x^8)$$
But using this I get the coefficient of $x^{10}$ as $5$ which isn't the correct answer. Can someone please check my method and place your suggestions over how should I continue in this method.
Note : I think that many similar questions might have been asked on MSE but I am focusing on just one particular method to solve such problem. So please don't mark it as duplicate.

A: Five two-cents; one four-cent and three two-cents; two four-cents and one two-cent; two three-cents and two two-cents; two three-cents and one four-cent.
Those are the five combinations of denominations, which you got from the $x^{10}$ coefficient.
As for arranging the stamps, that's a different problem entirely. The number of arrangements for each case above are $1,4,3,6,3$, respectively, which gives your $17$.
Looks like the two methods are meant for different problems.


text:
Q: Top Infected Machines - Dealing with Threats? I printed out a list of the top 25 infected machines (associate machines only)
a bit of detail.
Associate machines are only for sales associate. The domain login is the same for every machine, associates are provided internet, email, and in-house programs to complete CRMS, web leads, in-store sales and so on. They are allowed to go to vendor websites and research diamond information online.
On the report that I have, there are some associate used machines that have 100+ threat counts for one month (this is high threats to low threats).
For the use of the computers, we have determined that 50 threats (this includes tracking cookies) should be more than what they receive in one month...there are only 10 - 15 vendor websites that they should be accessing.
What is a good way to control and reduce the threat count on these machines? I use opendns to block specific categories of websites (there are a lot of categories blocked).

*

*I use SunBelt's VIPRE enterprise, and have antivirus agents installed on every machine in the company doing a quickscan at 12AM, and then a deep scan at 9PM daily.

*Group polices are in-place to prevent certain changes and so forth. Some of the machines allow the domain logon as administrator, some do not. There have been some issues with this.

*we have McAfee mxlogic spam filters as a 'cloud' that filters all incoming and outgoing email from our exchange server, delivering it to outlook mailbox with in-house spam policies as well (content and so forth).

*WSUS runs updates every Tuesday from the server.

Looking for some feedback on how to control these threat counts.

A: This is almost a HR issue but without detail it's difficult to say.
Here you'd need to look at what the threats are that are being listed. There is an IT/change management issue here if activities are being characterised as threats incorrectly by the software and another if something is characterised as a threat but the employee is not misusing resources.
Beyond that I agree with Robert that this is a HR issue

A: In similar situation I finally blocked everything but those 10-15 vendor sites. Can you do that to your associates?
It is strange that your anti-virus is able to find threats only after PC got infected.

A: I know that my outlook is pretty different than most in IT - I work at a university, we have zero control over client machines, everything we do is network-based.
How about just putting those associates machines in their own VLAN, and then creating rules on the router or firewall to block traffic to EVERYTHING but the sites they should be getting to? Even a simple open source router/firewall like Vyatta, with Squid URL filter, should do the job fine...


text:
Q: State if it's an equivalence relation or not I have the following problem

Let $X$ be $Z×Z$, i.e. $X$ is the set of all ordered pairs of the form $(x,
 y)$ with $x, y ∈ Z$. Define the relation $R$ on $X$ as follows: $(x_1, x_2)\mathrel{R}(y_1, y_2)$ if $x_1^2 + x_2^2 = y_1^2 + y_2^2$.

And I have to state whether it's an equivalence relation or not.
I proved that it's reflexive because
$(x_1,x_2)\mathrel{R}(x_1,x_2)$
$x_1^2 + x_2^2=x_1^2 + x_2^2$
It's symmetric
$(x_1,x_2)\mathrel{R}(x_2,x_1)$
$x_1^2 + x_2^2=x_2^2 + x_1^2$
And also transitive
if $(x_1,x_2)\mathrel{R}(y_1,y_2)$ and $(y_1,y_2)\mathrel{R}(z_1,z_2)$ then $(x_1,x_2)\mathrel{R}(z_1,z_2)$
Therefore, it's an equivalence relation,
but I'm nut sure if I have proved it the right way.

A: You're wrong about the symmetric property. You have to prove:

if $(x_1,x_2)\mathrel{R}(y_1,y_2)$, then $(y_1,y_2)\mathrel{R}(x_1,x_2)$

This is rather easy, because it just amounts to switching sides in an equality.
You stated right the transitive property, but didn't prove it.
Hint: from the hypotheses we get $x_1^2+x_2^2=y_1^2+y_2^2$ and $y_1^2+y_2^2=z_1^2+z_2^2$. Then …


text:
Q: SSRS Subscription adding a space around the 1000th character I have an SSRS subscription that runs off a stored procedure.
When the email is sent it is adding a space around the 1000th character of the email.
Unfortunately, there is a href in that space causing the link to fail.
The email has a few dynamic parts so the space comes up in different parts of the link. My users are very strict about formatting and want the link in that exact position.
Does anyone know of a way to stop the space from appearing? I have tried using a no-wrap tag but it still fails.
I apologize for the messy code. I havent posted to StackOverflow much.
 declare @Instructions nvarchar(max) = 'Instructions'

'DATE: ' + CONVERT(varchar(10),@parmReportDate, 101) + '

To: ' + r.pi_name + '

From: nameaa aaaaaaaaaa

The UAB/VA Memorandum of Understanding (VA-MOU) defines the formal          arrangement between UAB and the Birmingham VAMC when a UAB investigator receives or applies for NIH funding, directly or by subaward through a UAB appointment, and that investigator also has a VA appointment.

Per the '+ @NIHPolicy+ ', the MOU must be updated with each significant change or at least one year from the last revision if there were no
significant changes.  Significant changes include such things as a change in VA appointment or a change in research commitment of 25% or greater.'
+
' This notification is a reminder that annual certification of your VA-MOU is due in ' +
CASE
    WHEN @parmreportdate = DATEADD (Day, -60, p.app_end_dt) THEN '60' --and p.app_end_dt
    WHEN @parmreportdate = DATEADD (Day, -30, p.app_end_dt) THEN '30'
    WHEN @parmreportdate = DATEADD (Day, -15, p.app_end_dt) THEN '15'
    WHEN @parmreportdate = DATEADD (Day, 0, p.app_end_dt)   THEN '0'
END
+ ' days. Use the ' + @Instructions+ ' below to complete the annual certification '+ @VAMOUForm+ '. (This MOU is maintained in IRAP by OSP with an OSP Assigned Number of ' + r.inst_no + '.  You will need to reference this number when you complete the form.)

Please direct any questions to the Office of Sponsored Programs at email or phonenumber.'

A: Your code has some hidden characters / white space in. Remove and all will be fine..
declare @Instructions nvarchar(max) = 'Instructions'

becomes
declare @Instructions nvarchar(max) = 'Instructions'


text:
Q: Wordpress Select Files button not working on iPhone Not only does the Safari browser button on iOS work, but it works in chrome.
What can be the problems for 2 days I can not understand this
IOS version 13.4.1
Wordpress version 5.4

A: You're going to have to leave this for the time being.  This is now a known bug in WordPress Core, there appears to be a fix available and will be part of 5.4.1.
You can follow along with the debugging, investigation and updates here:
https://core.trac.wordpress.org/ticket/49753#comment:22
The problem was identified about three weeks and the test release is due today, so an update can be expected in the next few weeks. (Based on what I read, don't hold me to those timelines.)
In earnest, I'd shelf this as an issue and move on to other development work you've got to do - no point in working on this when the fix is already complete and will be pushed shortly.
I know this isn't a solution but at least now you know the cause and that it's being handled.


text:
Q: Resources for animations in WPF/Silverlight? I'm looking for some good resources to ramp up on the animation/storyboard concepts used in WPF/Silverlight. Any pointers?

A: The one link posted was WPF specific. For Silverlight here are a few other resources.

*

*MSDN Animation Overview

*Silverlight SDK Blog

*Adam Kinney Animations Hands on Lab

*Nikhil's Effects and Transitions (Advanced)

There a lots more out there, but these are a few goods ones I found.

A: This site had some good resources that covered some of the information I was looking for.


text:
Q: How to make dictionary of column names in PySpark? I am receiving files and for some files columns are named differently.
For example:

*

*In file 1, column names are: "studentID" , "ADDRESS", "Phone_number".

*In file 2, column names are: "Common_ID", "Common_Address", "Mobile_number".

*In file 3, column names are: "S_StudentID", "S_ADDRESS", "HOME_MOBILE".

I want to pass a dictionary after loading the file data into dataframes and in that dictionary I want to pass values like:
StudentId -> STUDENT_ID
Common_ID -> STUDENT_ID
S_StudentID -> STUDENT_ID

ADDRESS -> S_ADDRESS
Common_Address -> S_ADDRESS
S_ADDRESS  -> S_ADDRESS

The reason for doing this because in my next dataframe I am reading column names like "STUDENT_ID", "S_ADDRESS" and if it will not find "S_ADDRESS", "STUDENT_ID" names in the dataframe, it will throw error for files whose names are not standardized. I want to run my dataframe and get values from those files after renaming in the above DF and one question when in run the new df will it pick the column name form dictionary having data in it.

A: You can have the dictionary as you want and use toDF with a list comprehension in order to rename the columns.
Input dataframe and column names:
from pyspark.sql import functions as F

df = spark.createDataFrame([], 'Common_ID string, ADDRESS string, COL3 string')
print(df.columns)
# ['Common_ID', 'ADDRESS', 'COL3']

Dictionary and toDF:
dict_cols = {
    'StudentId':    'STUDENT_ID',
    'Common_ID':    'STUDENT_ID',
    'S_StudentID':  'STUDENT_ID',
    'ADDRESS':        'S_ADDRESS',
    'Common_Address': 'S_ADDRESS',
    'S_ADDRESS':      'S_ADDRESS'
}
df = df.toDF(*[dict_cols.get(c, c) for c in df.columns])

Resultant column names:
print(df.columns)
# ['STUDENT_ID', 'S_ADDRESS', 'COL3']

A: Use dict and list comprehension. An easier way and which would work even if some of the columns are not in the list is
 df.toDF(*[dict_cols[x]  if x in dict_cols else x for x in  df.columns ]).show()

+----------+---------+----+
|STUDENT_ID|S_ADDRESS|COL3|
+----------+---------+----+
+----------+---------+----+


text:
Q: Angular6. Proper way of error handling in httpClient I'm wondering about error handling from observable streams. I read article about using rxjs and async pipe in Angular. It was written here we should avoid to use subscribe operator and try to replace it with async pipe. But now when I try to write some post/put request we have to subscribe so i'm little bit confused where i should modify my component state.
submitForm() {
  this.restService.add(this.user.id, this.form.value)
    .pipe(
      tap(() => { this.isAdded = true }),
      catchError((error: HttpErrorResponse) => {
          this.responseMsg = 'Something went wrong'
          return throwError('notFound')
        }
      )
    ).subscribe();
  }

Or should i handle this in subscribe
submitForm() {
      this.restService.add(this.user.id, this.form.value)
        .pipe(
          tap(() => { this.isAdded = true }),
        ).subscribe(
            () => {},
            () => {this.responseMsg = 'Something went wrong'}
       );
 }

Which solution is better?

A: This is how you do a proper use of async pipe. When you use async pipes you don't have to subscribe because they do the lifcycle of an observable for you. The subscribe and destroy the subscription to avoid memory leaks. If you don't use async pipes you have to do this manually.
SERVICE.TS
import { EquipmentID } from './../../../shared/model/equipmentID.model';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { PickupAvailability } from '../models/pickup-availability.model';
import { catchError } from 'rxjs/operators';
import { ErrorHandlingService } from '../../../shared/services/error-handling.service';
@Injectable()
export class PickupAvaibilityService {
  BASE_URL = '/sxrw-ship/api/v1';
  AMOUNT_DUE_URL = '/shipments/search';

  constructor(
    private http: HttpClient,
    private errorHandler: ErrorHandlingService
  ) {}

  getAmountDue(equipmentID: EquipmentID[]): Observable<PickupAvailability> {
    return this.http
      .post<PickupAvailability>(
        this.BASE_URL + this.AMOUNT_DUE_URL,
        equipmentID
      )
      .pipe(catchError(this.errorHandler.handleError));
  }
}

Then in my custom error handler service you will have something like this:
ERRORHANDLER.SERVICE.TS
import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { _throw } from 'rxjs/observable/throw';
@Injectable()
export class ErrorHandlingService {
  constructor() {}

  handleError(error: HttpErrorResponse) {
    //To know the version of RxJS npm list --depth=0 (I for this example im on version 5.5)
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred: ', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}` + ` body was: ${error.message}`
      );
    }
    // return an observable with a user-facing error message
    return _throw('Something bad happened; please try again later.');
  }
}

The way I did my error handler is the way it is done on the Angular's official website https://angular.io/guide/http
Now, in the component that will be using the service that calls us http you declare a variable of type Observable (it's good practice to use the $ sing)
COMPONENT.TS
pickupAvailability$: Observable<PickupAvailability>;

  getPickupDate(pa: PickupAvailability) {
    let id = pa.equipmentInitial + pa.equipmentNumber;
    this.equipmentSummary$ = this.pickupDateService
      .getPickupDate(id)
      .pipe(
        map(
          pd =>
            new EquipmentSummary(
              id,
              pd.pickupDate,
              'TODO',
              pa.totalPremiseCharges
            )
        )
      );
  }

HTML
<div *ngIf="(pickupAvailability$ | async) as pickupAvailability">
  <!-- TODO move to table -->
  <div *ngFor="let pa of pickupAvailability">
    <button pButton type="button" label="Pay ${{ pa.totalPremiseCharges }}" class="x-primary-gray-100" (click)='getPickupDate(pa)'>
    </button>
  </div>
  <div *ngIf="(equipmentSummary$ | async) as es">
    <app-pay-storage [equipmentSummary]="es"></app-pay-storage>
  </div>
</div>

You can test it by doing this:
{{pickupAvailability$ | async | json}}

when you are actually going to use it remove the json pipe

A: You can consider using HttpClient interceptor.
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

       return next.handle(request)
            .pipe(catchError(err => {
                 // handle your logic there
             }));
   }
}

Doing, all your Http requests will be handled the same way at the same place. You won't need to inject error management services.
More infos there: Angular httpClient interceptor error handling

A: If you want to handle just the errors from a backend API (HTTP error) you can just handle them in a subscribe function.
Also you can use a custom error handler to handler all your HTTP errors:
import {ErrorHandler} from "@angular/core";
import {UNAUTHORIZED, BAD_REQUEST, FORBIDDEN} from "http-status-codes";
import {Router} from "@angular/router";
import {ToastsManager, Toast, ToastOptions} from "ng2-toastr";

@Injectable()
export class myAppErrorHandler implements ErrorHandler {

  static readonly REFRESH_PAGE_ON_TOAST_CLICK_MESSAGE: string = "An error occurred: Please click this message to refresh";
  static readonly DEFAULT_ERROR_TITLE: string = "Something went wrong";

  constructor(private router: Router,private toastManager: ToastsManager){};

  public handleError(error: any) {
    console.error(error);
    let httpErrorCode = error.httpErrorCode;
    switch (httpErrorCode) {
      case UNAUTHORIZED:
          this.router.navigateByUrl("/login");
          break;
      case FORBIDDEN:
          this.router.navigateByUrl("/unauthorized");
          break;
      case BAD_REQUEST:
         this.showError(error.message);
          break;
      default:
         this.showError(REFRESH_PAGE_ON_TOAST_CLICK_MESSAGE);
    }
  }

  private showError(message:string){
    this.toastManager.error(message, DEFAULT_ERROR_TITLE, { dismiss: 'controlled'}).then((toast:Toast)=>{
            let currentToastId:number = toast.id;
            this.toastManager.onClickToast().subscribe(clickedToast => {
                if (clickedToast.id === currentToastId) {
                    this.toastManager.dismissToast(toast);
                    window.location.reload();
                }
            });
        });
  }
}

Then tell angular to use it instead of the default error handler, to do that add to your providers section in your app.module.ts the following:
  providers: [
      {provide: ErrorHandler, useClass: myAppErrorHandler }
  ]


text:
Q: airflow spark-submit operator - No such file or directory I am trying to schedule a spark job in airflow, here is my dag,
from __future__ import print_function
import airflow
from airflow.contrib.operators.spark_submit_operator import SparkSubmitOperator
from airflow.models import DAG
from datetime import datetime, timedelta
import os

APPLICATION_FILE_PATH = "/home/ubuntu/airflow/dags/scripts/"

default_args = {
    'owner': 'Airflow',
    'depends_on_past': False,
    'retries': 0,
    }

dag = DAG('datatodb', default_args=default_args, start_date=(datetime(2018,7,28)),schedule_interval='0 5 * * *')

data_to_db = SparkSubmitOperator(
    task_id='data_to_db',
    application=APPLICATION_FILE_PATH+"ds_load.py",
    dag=dag,
    run_as_user='ubuntu',
    application_args=["{{ ds }}"]
)

data_to_db

And my python script is this,
from pyspark import SparkContext
from pyspark.sql import SQLContext, SparkSession
from datetime import datetime, timedelta
import sys

def write_to_db(previous_day,spark_session):

  drop_cols = ['created_date','Year','Month']
  datapath = "s3a://***/"
  s3path = datapath + 'date=' + str(previous_day)
  data_to_load_df = spark_session.read.parquet(s3path).drop(*drop_cols).withColumn('date',lit(previous_day))

  data_to_load_df.write.format('jdbc').options(url='jdbc:mysql://servername:3306/dbname',
       driver='com.mysql.jdbc.Driver',
       dbtable='report_table',
       user='****',
       password="***").mode('append').save()

def main(previous_day,spark_session=None):
  if spark_session is None:
        spark_session = SparkSession.builder.appName("s3_to_db").getOrCreate()

  write_to_db(previous_day,spark_session)

if __name__ == "__main__":
    previous_day = sys.argv[1]
    main(previous_day)

Not sure what is wrong with this, I keep getting this error,
[2018-08-01 02:08:37,278] {base_task_runner.py:98} INFO - Subtask: [2018-08-01 02:08:37,278] {base_hook.py:80} INFO - Using connection to: local
[2018-08-01 02:08:37,298] {base_task_runner.py:98} INFO - Subtask: Traceback (most recent call last):
[2018-08-01 02:08:37,299] {base_task_runner.py:98} INFO - Subtask:   File "/home/ubuntu/anaconda2/bin/airflow", line 27, in <module>
[2018-08-01 02:08:37,299] {base_task_runner.py:98} INFO - Subtask:     args.func(args)
[2018-08-01 02:08:37,299] {base_task_runner.py:98} INFO - Subtask:   File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/airflow/bin/cli.py", line 392, in run
[2018-08-01 02:08:37,299] {base_task_runner.py:98} INFO - Subtask:     pool=args.pool,
[2018-08-01 02:08:37,299] {base_task_runner.py:98} INFO - Subtask:   File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/airflow/utils/db.py", line 50, in wrapper
[2018-08-01 02:08:37,299] {base_task_runner.py:98} INFO - Subtask:     result = func(*args, **kwargs)
[2018-08-01 02:08:37,300] {base_task_runner.py:98} INFO - Subtask:   File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/airflow/models.py", line 1493, in _run_raw_task
[2018-08-01 02:08:37,300] {base_task_runner.py:98} INFO - Subtask:     result = task_copy.execute(context=context)
[2018-08-01 02:08:37,300] {base_task_runner.py:98} INFO - Subtask:   File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/airflow/contrib/operators/spark_submit_operator.py", line 145, in execute
[2018-08-01 02:08:37,300] {base_task_runner.py:98} INFO - Subtask:     self._hook.submit(self._application)
[2018-08-01 02:08:37,300] {base_task_runner.py:98} INFO - Subtask:   File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/airflow/contrib/hooks/spark_submit_hook.py", line 231, in submit
[2018-08-01 02:08:37,300] {base_task_runner.py:98} INFO - Subtask:     **kwargs)
[2018-08-01 02:08:37,301] {base_task_runner.py:98} INFO - Subtask:   File "/home/ubuntu/anaconda2/lib/python2.7/subprocess.py", line 394, in __init__
[2018-08-01 02:08:37,301] {base_task_runner.py:98} INFO - Subtask:     errread, errwrite)
[2018-08-01 02:08:37,301] {base_task_runner.py:98} INFO - Subtask:   File "/home/ubuntu/anaconda2/lib/python2.7/subprocess.py", line 1047, in _execute_child
[2018-08-01 02:08:37,301] {base_task_runner.py:98} INFO - Subtask:     raise child_exception
[2018-08-01 02:08:37,301] {base_task_runner.py:98} INFO - Subtask: OSError: [Errno 2] No such file or directory

I checked the python script in its path, its there, also checked the mysql driver, its in the jars folder. This error message does not give me much information on which file is missing. Can anyone help me with this?

A: Answering my own question, since I resolved it. My bad, I just had to restart the airflow webserver and scheduler after placing the driver jars in spark/jar folder. It worked fine then.


text:
Q: Load library from MemoryClassLoader? I've been working on a sort of bootstrapper for an application I am writing. It buffers an application from a website and runs it. It works very well up to the point that I call the main method of the main class of the application, which requires libraries, which are also streamed. The LIBs and the Application are in the same classloader, but it says it was unable to locate the library due to an unsatisfied link. I searched for help, but could not find any.

A: I assume you're getting an UnsatisfiedLinkError because you haven't done a Runtime.loadLibrary to bring in native code to support native methods.  Such libraries need to be on the local file-system and are independent of any class loader.  Javadoc:

public void loadLibrary(String libname)

Loads the dynamic library with the specified library name. A file containing native code is loaded from the local file system from a place where library files are conventionally obtained. The details of this process are implementation-dependent. The mapping from a library name to a specific filename is done in a system-specific manner.

and obviously, Runtime.getRuntime() is independent of any particular class loader.
If a network class load could cause a network load of native code, that would be a huge remote code execution vulnerability because native code cannot be constrained by a SecurityManager the way java bytecode can be.
If you trust the website that produces the application, and are fetching it over a secure channel (encrypted to prevent MITM and tampering), then you can fetch the libraries, dump them to the local file system, verify any signatures or checksums, then call Runtime.loadLibrary or System.loadLibrary to load the native libraries before causing the class to initialize.
If you don't trust the authors of the website that produces the application, or that website hosts third-party content, then don't load JARs much less system libraries from it.
Even if the website authors are trustworthy, loading system libraries or other native code that you haven't vetted and tested can be dangerous.  Process sandboxing via chroot and system call interception can help mitigate this risk somewhat but be careful.


text:
Q: Ionic Framework Data offline sync I am Trying to get some data to show in an ionic application,my problem that i want to know how to be able to get the data online,and then save them when iam offline,so i can consult some of them.
Any proposed solution?

A: If your goal is to have a database on the phone that automatically syncs with an online database when the phone has signal then you should look at PouchDB and CouchDB. There is an excellent tutorial at https://www.joshmorony.com/offline-syncing-in-ionic-2-with-pouchdb-couchdb/ that you could read.


text:
Q: What is this component next to the IR LEDs on an Amcrest Camera? I recently disassembled an Amcrest IP Camera and found this sensor next to the IR LEDs.  It doesn't look like a photosensitive resistor which has a zig-zag pattern.
Can someone explain what it is?

A: Appears to a light sensor phototransistor (could be a chip too). As in this Kingbright one:

Datasheet here
The ones with light blue epoxy roll off to 20% response at around 750nm vs. 470nm for clear epoxy, so they are mainly sensitive to IR.
Clear epoxy phototransistor

Blue epoxy phototransistor

The style of CdS light sensor with a serpentine pattern that you are referring to looks like this (image from here):

They are prohibited in many jurisdictions (and have been for many years now) because they contain toxic cadmium and there are viable alternatives.


text:
Q: If there are "arbitrarily efficient" paths in a given direction, is there always a "best" path in that direction? $\newcommand{\ep}{\epsilon}$
$\newcommand{\al}{\alpha}$
$\newcommand{\be}{\beta}$
Let $M$ be a Riemannian manifold, $S \subset M,p \in M \setminus{S}$, and $v \in T_pM$ be a unit vector. Let $d_S$ be the distance function from $S$.

Suppose that for every unit speed path $\be(t)$ starting at $p$, there exists $\ep_{\beta}>0$ and a unit speed path $\al_{\beta}:(-\ep_{\beta},\ep_{\beta}) \to M$ also starting at $p$, such that $\dot \al_{\beta}(0) = v$ and
  $$
d_S(\al_{\beta}(t)) \le  d_S(\be(t)) \quad \text{ for all } t \in (-\ep_{\beta},\ep_{\beta}).
$$

Does there exist a single unit speed path $\al:(-\ep,\ep) \to M$ starting at $p$ with velocity $v$, that "beats" all the different $\beta$'s at once?
i.e. I want $\al(0)=p , \dot \al(0) = v,$ such that for every
unit speed path $\be(t)$ starting at $p$,
$$
d_S(\al(t)) \le  d_S(\be(t)) \quad \text{ for all } t \in \left( -\tilde \ep_{\beta},\tilde \ep_{\beta}  \right).
$$
(I allow $\tilde \ep_{\beta} <  \ep_{\beta}$.) Informally, I am assuming that $v$ is a "preferred direction of movement towards $S$ from $p$", and I ask if there is a single path in that direction, which beats all other paths for short times. My guess is that the geodesic $t \to \exp_p(tv)$ should do the job, but I am not sure how to prove that.

A: Assuming $M$ is complete, choose a sequence $x_i \in S$ for which $d(p,x_i)$ approaches $D = \text{inf}\{d(p,x) \mid x \in S\}$.
It follows that the set $Q = \{q \in \overline D \mid d(p,q)=D\}$ is not empty. The property of your vector $v$ that you state will be true if and only if $v$ is the initial direction of some unit speed geodesic $\alpha$ from $p$ to some $q \in Q$.
The point is that if $\alpha$ does have that form then $d_S(\alpha(t)) = D-t$, and $d_S(\beta(t)) \ge D-t$ for each of your $\beta$ paths.
If on the other hand if $\alpha$ does not have that form then you can take $\beta$ to be a path which does have that form.

A: The answer is positive. Since for every unit speed path starting from $p$ at time $t=0$, we always have $d_S(\alpha(t)) \ge d_S(p)-t$ for every $t$, and since we there always exist an "optimal" unit speed path $\alpha(t)$, satisfying $d_S(\alpha(t)) = d_S(p)-t$ for sufficiently small $t$, a path that beats (weakly) this optimal path,  must be optimal itself. So, we can take as a challenge $\beta:=$ an "optimal path"-and conclude that there exist an optimal path in the $v$ direction, as required.


text:
Q: last value of sublist in freemarker I have a long date list with corresponding price values.
out of this list I need the last price of every month.
I sliced the list and tried to get the last value but cant!
please help.
here is part of the list:

here is my code:
<#assign new_list><#list reportData.daily as list><#if list?string('M')?number=6 && list?string('Y')?number=2017>${list?string("dd/MM/yyyy")}</#if></#list></#assign>${new_list?last}

if I remove the "?last" it will show me a sublist for all dates for June-2017 but once i add "?last" i get:
For "?last" left-hand operand: Expected a sequence, but this has evaluated to a string (wrapper: f.t.SimpleScalar):

A: You get that error because <#assign new_list>...</#assign> captures the raw output printed, which is not a sequence. If you really have to do this in template, put an #if inside the #list which only prints the current item if the next one is in a different month. (You can peek at the next item inside <#list xs as x>...</#list> like xs[x?index + 1]) But, you aren't supposed to do such data processing in a template...


text:
Q: 3-d game programming what programming language/languages do they use to produce games lik Bioware's Dragon Age Origins and some other 3-d games like Call of Duty?
If I would like to do 3d-game programming, where do I start? Are there even simple tutorials for this? I would like to do 3-d game programming for PC games:)

A: C++ is a solid start.
Game Institute has decent courses (for a fee). This is by no means trivial. Start with the basics (object oriented programming, 3d animation, threading, etc) and you'll get somewhere.
Remember to have fun. It makes learning easier.

A: Most major games are written in C++.  This does not mean that you have to use C++.  For indy games you can also consider C# with XNA if you're more familiar with that (or want to play your eventual creations on your xbox 360 relatively easily).  XNA also has the benefit of being free.
GarageGames also makes a relatively well-respected series of games engines (which are not free, but are very affordable compared to most), including one which adds the standard capabilities to XNA so you don't have to write it all from scratch.
MPelletier's advice is good, though.  Game development is very complex, and even a simple game is a huge undertaking.  Get a good grasp on the basics first, and I'd strongly suggest starting out with 2-D games.

A: I don't want to be discouraging, but I don't want to lie either. Creating even the simplest 2D game is a major feat. Here are some things you'll probably have to learn, if you're going to code a game on your own :

*

*General concepts and techniques used in computer graphics.

*Network programming (if applicable)

*Audio programming and Digital Signal Processing theory.

*Linear algebra, trigonometry and geometry branches in mathematics

*AI concepts like fuzzy logic, finite state machines or neural networks.

Not to mention you need a solid background in programming. Most of the bigger game developers use C++, which is a decent choice when performance is of the essence. But one size doesn't fit all. I recommend you look at C++, Python and Java and figure out which one you like to use.
Now, this might come as a disappointment, but it needs to be said. If you're just starting out with programming, you're not going to make a 3D game for a long time. I learned C++ back in 2002 and I still learn new ways to use the programming language. There's a lot of books named Teach yourself programming language X in Y weeks. Don't believe the lie. There is no way one can learn anything that complex within that timespan. What I'm trying to say is, don't be in a hurry! Patience is everything, and there is no such thing as a free lunch.
And when you finally have the knowledge to make a game, start simple. Even coding a Nethack clone which uses ascii art graphics gives you new experience you can extend on. And your first games should be 2D. Working in two dimensions is much simpler, and a lot of the math involved extends nicely to three dimensions when you are ready to advance further.

A: May I suggest a different approach? Im going to assume that 3D graphics are not essential. I believe that if youre really just starting out, going straight for 3D rendering can be a bit complex. 2D is much simpler.
Therefor, follow these simple steps, expect it to last about two hours or so:

*

*Download (and install) Python

*Download (and install) PyGame

*Download (and install) Notepad++, you will use this to write your code, save it with the .py extension (not .txt)

*Head over to the Line By Line Chimp Tutorial (great tutorial!)

After youve read and experimented with that you should be able to create something of your own with a complexity level of, say, Tetris. I created an asteroids clone.
Dont hesitate to return here on Stackoverflow to ask for help if you run into problems. I have helped a few friends through that tutorial that wanted to "try out game programming" and should be able to help you with anything you can manage to get stuck on.
Now go nuts on the keyboard! Before you know it, you'll have created Dragon Age 2!

A: C++ is the standard language, but no large project uses only one language.  Senior staff will use assembly in some places, graphics programmers will often use whatever shader language is appropriate for the system.  Whoever is working on tools or the build system will typically use scripting languages such as Python, Perl, Bash/Batch scripting or others.  Game programmers will typically also use an in game scripting language that can range from standards like Lua, Python, or UnrealScript, to in house scripting languages created just for that engine.
Game Institute -- I have mixed feelings about this place...  They offer a specialized curriculum you have a hard time finding else where; however a friend showed me some tests from this place that had answers which were at best outdated, or at worst flat out wrong.  I wouldn't suggest against them, but be open minded afterwards.
Gamedev.net -- THE amature game programming website. Great community, tons of articles.  They have some great posts on the forums about how to get started.  Even as a professional I still visit this site.

A: If you want to go the managed route, try the XNA Game Studio from Microsoft. I think it's a good place to start, and you might not get discouraged (as I have) with some of the more powerful and complicated technologies, like pure DirectX or OpenGL programming with C++/WIN32. A lot of that stuff is abstracted away so you can focus on actually creating something. Heck, you could even make something that can end up on Xbox Live. It's free to start developing and there's sure to be a lot of resources out there to get you started.

A: Have a look at irrlicht. Its a very good game engine, its easy to use and best of all its free. The engine is in c++ however I remember I saw a .net wrapper of it also.
Probably its not as powerful engine as the ones used by Call of Duty etc. But assuming you are only starting game development you will never need such advance features. You can build very decent games using irrlicht. The site also has few tutorials and active community.

A: Take a look at the Unreal Development Kit. The same engine that was used to power Unreal Tournament and Gears of War is available free for independent developers and takes care of the truly grueling work in making a game.
It's a great way to get into learning the terminology and concepts, while gradually adjusting you to the realm of software development through scripting. Once you feel comfortable with how geometry, textures, particle effects and lighting is used, then venture into the territory of XNA. In both the case of UDK and XNA, you'll find both excellent communities and dozens of tutorials available.

A: http://www.garagegames.com has good resources for getting started in game development.
http://en.wikipedia.org/wiki/GarageGames

A: There are some great C++ game programming frameworks to get you started. DarkGDK is a great one, I have used it and it takes some of the pain out of making a game in C++.

A: Typically professional games are primarily developed in C++. However, unless you're a veteran C++ developer I'd recommend choosing a language you are more familiar with while learning the nuances of game development otherwise you may find yourself battling the syntax and general nature of C++ more than the conceptual particulars related to game programming. C# and XNA, or even the now-defunct Managed Direct X, is a great way to start as a few have already mentioned. A wealth of information covering game development in C# is readily available on the web and in print and a large number of communities exist to provide you support while you learn, so take advantage of them.
Also take note that while XNA is a more complete game development framework there are many other available libraries such as Ogre, OpenGL, and Irrlicht that cover everything from audio to physics.
Try to gain an understanding of game fundamentals and build up your experience through ever increasingly complex projects. This is not to say it is impossible to take on a large project as your first, but in my experience smaller projects tend to be completed with more regularity. Each game you finish will build your confidence, experience, and skill set.
I'd recommend checking out http://www.GameDev.net, the resources there are invaluable. Riemers.net also contains a some great tutorials on XNA and Direct X.
Finally try not to become disheartened by the vastness of understanding game development requires. Things may seem overwhelming when you're beginning in the field but try to keep in mind that even the industry gurus started with no knowledge at some point. With persistence, passion, and patience you'll master the necessary skills to create truly enjoyable games.
Good luck.

A: Object oriented languages with strong graphics libraries are needed to develop those kinds of games.
Those games can be done with:

*

*C++ : DirectX (with VC++), OpenGL, SDL

*C# : DirectX, OpenGL C# bindings (would not recommend this)

*Java : Java3d (which has bindings to OpenGL), JOGL (Java OpenGL)

If you are interested in learning about 3D Graphics and C++ take a look at this.

A: Try out looking at open sourced games. This game just went open source recently and it's pretty advanced. It already employs great physics, visual effects and cut scenes so this could be a great learning opportunity.