text:
Q: I need assistance with signin method I was coding along with Zero To Mastery web dev course. The app is called smartbrain. There is a signin method which doesn't run when I'm adding if statement, it should go to homepage, but its bouncing back to signin page. It only goes to homepage if put the routing function outside the if loop.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const database = {
    users: [
        {
            id: '123',
            name: 'john',
            email: 'john@gmail.com',
            password: 'cookies',
            entries: 0,
            joined: new Date(),
        },
        {
            id: '124',
            name: 'sally',
            email: 'sally@gmail.com',
            password: 'bananas',
            entries: 0,
            joined: new Date(),
        },
    ],
};
app.get('/', (req, res) => {
    res.json(database.users);
});
app.post('/signin', (req, res) => {
    if (
        req.body.email === database.users[0].email &&
        req.body.password ===
            database.users[0].password
    ) {
        res.json('success');
    } else {
        res.status(400).json('error logging in');
    }
});

app.post('/register', (req, res) => {
    const { name, email, password } = req.body;
    database.users.push({
        id: '125',
        name: name,
        email: email,
        password: password,
        entries: 0,
        joined: new Date(),
    });
    res.json(
        database.users[database.users.length - 1]
    );
});

app.get('/profile/:id', (req, res) => {
    let found = false;
    const { id } = req.params;
    database.users.forEach((user) => {
        if (user.id === id) {
            found = true;
            return res.json(user);
        }
    });
    if (!found) {
        res.status(400).json('user not found');
    }
});

app.post('/image', (req, res) => {
    let found = false;
    const { id } = req.body;
    database.users.forEach((user) => {
        if (user.id === id) {
            found = true;
            user.entries++;
            return res.json(user.entries);
        }
    });
    if (!found) {
        res.status(400).json('user not found');
    }
});

app.listen(3001, () => {
    console.log('App is running');
});

signin.js
import { React, Component } from 'react';

class Signin extends Component {
    constructor(props) {
        super(props);
        this.state = {
            signInEmail: '',
            signInPassword: '',
            // validUser: false,
        };
    }
    onEmailChange = (event) => {
        this.setState({
            signInEmail: event.target.value,
        });
    };
    onPasswordChange = (event) => {
        this.setState({
            signInPassword: event.target.value,
        });
    };

    onSubmitSignIn = () => {
        // console.log(this.state);

        fetch('http://localhost:3001/signin', {
            method: 'post',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                email: this.state.signInEmail,
                password: this.state.signInPassword,
            }),
        })
            .then((response) => response.json())
            .then(data => {
                if (data==='success'){
                    this.props.onRouteChange('home');
                }
            })
        // this.props.onRouteChange('home');
    };
    render() {
        const { onRouteChange } = this.props;
        // console.log(this.state);
        return (

                    <form className='measure center'>
                        <fieldset
                            id='sign_up'
                            className='ba b--transparent ph0 mh0'>
                            <legend className='f2 fw6 ph0 mh0 center'>
                                Sign In
                            </legend>

                                    Email

                                <input
                                    className='pa2 input-reset ba bg-transparent hover-bg-black hover-white w-80'
                                    type='email'
                                    name='email-address'
                                    id='email-address'
                                    onChange={this.onEmailChange}
                                />

                                    Password

                                <input
                                    className='b pa2 input-reset ba bg-transparent hover-bg-black hover-white w-80'
                                    type='password'
                                    name='password'
                                    id='password'
                                    onChange={this.onPasswordChange}
                                />

                            {/*
                                <input type='checkbox' /> Remember
                                me
                             */}
                        </fieldset>

                            <input
                                className='b ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib'
                                type='submit'
                                value='Sign in'
                                onClick={this.onSubmitSignIn}
                            />

                                    onRouteChange('register')
                                }
                                className='f6 link dim black db pointer'>
                                Register

                            {/*
                                Forgot your password?
                             */}

                    </form>

        );
    }
}

export default Signin;

See the commented code
 this.props.onRouteChange('home');

If I uncomment this and comment the one in if loop, I get a success response from my server and it goes to home page. Another thing is that if the this.props.onRouteChange('home'); is inside the if loop I can see my username password on url bar as a query string. Any solution???
app.js
import React, { Component } from 'react';
import Navigation from './Components/Navigation';
import Logo from './Components/Logo';
import ImageLinkForm from './Components/ImageLinkForm';
import Rank from './Components/Rank';
import FaceRecognition from './Components/FaceRecognition';
import Signin from './Components/Signin';
import Register from './Components/Register';
import Particles from 'react-particles-js';
import Clarifai from 'clarifai';
import './App.css';

const particlesConfig = {
    particles: {
        number: {
            value: 40,
            density: {
                enable: true,
                value_area: 500,
            },
        },
    },
};

const app = new Clarifai.App({
    apiKey: 'c14191b446b14919afd059c9a0666edf',
});

class App extends Component {
    constructor() {
        super();
        this.state = {
            input: '',
            imageURL: '',
            box: {},
            route: 'signin',
            isSignedIn: false,
        };
    }

    // componentDidMount() {
    //  fetch('http://localhost:3001/')
    //      .then((response) => response.json())
    //      .then((data) => console.log(data));
    // }

    calculateFaceLocation = (data) => {
        const clarifaiFace =
            data.outputs[0].data.regions[0].region_info
                .bounding_box;
        const image =
            document.getElementById('inputimage');
        const width = Number(image.width);
        const height = Number(image.height);
        // console.log(width, height);
        return {
            leftCol: clarifaiFace.left_col * width,
            topRow: clarifaiFace.top_row * height,
            rightCol:
                width - clarifaiFace.right_col * width,
            bottomRow:
                height - clarifaiFace.bottom_row * height,
        };
    };

    displayFaceBox = (box) => {
        console.log(box);
        this.setState({
            box: box,
        });
    };

    handleInput = (event) => {
        this.setState({
            input: event.target.value,
        });
    };
    handleDetect = () => {
        this.setState({
            imageURL: this.state.input,
        });
        app.models
            .predict(
                Clarifai.FACE_DETECT_MODEL,
                this.state.input
            )
            .then((response) =>
                this.displayFaceBox(
                    this.calculateFaceLocation(response)
                )
            )
            .catch((err) => console.log(err));
    };

    onRouteChange = (route) => {
        if (route === 'signout') {
            this.setState({ isSignedIn: false });
        } else if (route === 'home') {
            this.setState({ isSignedIn: true });
        }
        this.setState({ route: route });
    };

    render() {
        return (

                <Particles
                    params={particlesConfig}
                    className='particles'
                />

                <Navigation
                    onRouteChange={this.onRouteChange}
                    isSignedIn={this.state.isSignedIn}
                />
                {this.state.route === 'home' ? (

                        <Logo />

                            <Rank />
                            <ImageLinkForm
                                handleInput={this.handleInput}
                                handleDetect={this.handleDetect}
                            />

                            <FaceRecognition
                                imageURL={this.state.imageURL}
                                box={this.state.box}
                            />

                ) : this.state.route === 'signin' ? (
                    <Signin
                        onRouteChange={this.onRouteChange}
                    />
                ) : (
                    <Register
                        onRouteChange={this.onRouteChange}
                    />
                )}

        );
    }
}

export default App;

A: The only reason it would be failing is because the data response you're getting through fetch inside the if block (not loop) is certainly not equal to 'success'.
Try console logging the response.
Also, in your signin route, you're only checking the email and password are equal to the first user's in database array, so maybe you are only checking with the second user.

A: It actually the  tag that was causing the problem. Removed it and now everything is fine. Its still in testing phase so i was only checking for the first user. Thanx a lot though for replying


text:
Q: Facebook Friend Dialog Replacement Looking for a way to add a friend using the Facebook API. (Add Friend Request)
Seems on April 30th the Friends Dialog was https://developers.facebook.com/docs/apps/changelog "The friends dialog is no longer available."
Even though in the API docs it says "The Friends Dialog should be used if you want to integrate the ability to add someone as a friend in your app."
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/friends
Does anyone know of an alternative to this using the API or a dialog? Any help would be so appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to merge different files that have the same header but slightly different file name? I have a problem in merging files for a big data sets like below.
I want you help me to let me know the script that can do such task.
fine name: fluxes_year_lat_long
I have 30 years of daily fluxes files for more that 100 location(lat_long)
I want to merge from year 1 to year 30 of each point files.
my file looks like this
file name1: fluxes_2000_50_70
2000 1 1 5000 ....
2000 1 2 2000 ....
.
.
.
2000 12 31 5000
YYYY M D Fluxes

file name2: fluxes_2001_50_70
2001 1 1 5000
YYYY M D Fluxes
.
.
.

all the way to:
file name30: fluxes_2030_50_70
2030 1 1 5000
YYYY M D Fluxes
.
.
.

The number of rows for each file is the same.
I want the output to be merging the daily fluxes from year 2000 to 2030 for each point's
location like
output file: fluxes_lat_long
YYYY MM DD Fluxes value.

In addition, I want the script read and merge file starting with  the name fluxes_.
I appreciate your response.

A: I think you are asking that given files:
fluxes_2000_10_10   fluxes_2001_10_10    fluxes_2003_10_10

and
fluxes_2000_20_10   fluxes_2001_20_10    fluxes_2003_20_10

You create a "total" file for each of the above files at latitude 10_10 and then 20_10 etc.
In which case:
bash$ for lat in $(ls -1 fluxes_* | sed 's/fluxes_[0-9]*_\([0-9]*_[0-9]*\)/\1/' |sort|uniq )
do
    echo "processing $lat ..."
    cat fluxes_[0-9]*_${lat} > fluxes_TOT_${lat}
done

ls -1 fluxes_* | sed 's/fluxes_[0-9]*_\([0-9]*_[0-9]*\)/\1/' | sort | uniq  finds all the unique latitudes (x_y) number pairs, we then step through them with a for loop and cat the contents of the files at that latitude (all the years) and outputs them to fluxes_TOT_x_y.

A: I would use sort -u fluxes_*_lat_long > fluxes_lat_long`, it is by far the simplest solution.
EDIT: use in a script
for file in $(ls -1 fluxes_20*_*_*) ; do
    export ll="$(echo $file |cut -d _ -f 3,4)"  # extract lat & long
    echo "sort -u fluxes_*_$ll"  "> fluxes_$ll" # create sort instruction
done | uniq | sh

A: If I understood your requirements, you want to merge all the flux data for one point in fluxes_lat_long with the format
01 01 Fluxes total_fluxes_for_Jan_1_over_30_years
01 02 Fluxes total_fluxes_for_Jan_2_over_30_years
...

If that's the case, here's a Perl script that should help:
#!/usr/bin/perl

use strict;
use warnings;

my @files = glob 'fluxes_*_*_*';
my %points;
$files[$_] =~ /_([0-9]+_[0-9]+)\Z/ and $points{$1}++ for (0..$#files);

for my $point (sort keys %points){
    my @point_files = grep { /_$point\Z/ } @files;
    my %days;
    for my $file (@point_files){
        open my $f,'<',$file or die "Failed to open file $file : $!\n";
        <$f>; #Discard the header
        while(<$f>){
            my ($year,$month,$day,$number) = split;
            $days{"$month $day"}+=$number;
         }
         close $f;
     }

     open my $of,'>',"fluxes_$point";
     for (sort by_date keys %days){
         print $of "$_ Fluxes $days{$_}\n";
     }
 }

 sub by_date{
    my ($month_a,$day_a) = split /\s*/,$a;
    my ($month_b,$day_b) = split /\s*/,$b;
    my $month_sort = $month_a <=> $month_b;
    my $day_sort = $day_a <=> $day_b;
    return $month_sort ? $month_sort : $day_sort
}

A: If you want to concatenate, you can do it easily:
cat fluxes_2001_50_70 >> fluxes_2000_50_70

But you do it when your files don't increase their volumne.
However , your question is behind of set of other question such as:
"second file should be update after merging?"

A: tail -qn +2 will remove the headers and start from the second line for every file, fluxes_* will glob all the files that starts with that string, and > fluxes_2000_2030 will pipe all data to a single output file:
tail -qn +2 fluxes_* > fluxes_2000_2030


text:
Q: Does the chaining of multiple then on a Promise mean that multiple steps will be executed once the Promise is resolved? I'm reading up on bluebird and what problems it solves for the native Promise API and currently learning and I keep seeing this pattern with them:
Promise.promisifyAll(needle);
var options = {};

var current = Promise.resolve();
Promise.map(URLs, function (URL) {
    current = current.then(function () {
        return needle.getAsync(URL, options);
    });
    return current;
}).map(function (responseAndBody) {
    return JSON.parse(responseAndBody[1]);
}).then(function (results) {
    return processAndSaveAllInDB(results);
}).then(function () {
    console.log('All Needle requests saved');
}).catch(function (e) {
    console.log(e);
});

Does this all mean that once the map is done (which is weird because map doesn't return a Promise but I guess that's another question), it'll execute 2 then with the second waiting for the first one to complete?


text:
Q: Objects are not valid as a React child (found: object with keys {seconds, nanoseconds}) firebase I keep getting this nasty error:

Error: Objects are not valid as a React child (found: object with keys {seconds, nanoseconds}). If you meant to render a collection of children, use an array instead.

Here is my code:
const [notifications, setNotifications] = useState([]);

  useEffect(() => {
    if (user) {
      db.collection("users")
        .doc(user)
        .collection("notifications")
        .onSnapshot((snapshot) =>
          setNotifications(snapshot.docs.map((doc) => doc.data()))
        );
    } else {
      console.log("No Notifications");
    }
  }, [user]);

I have no clue what is wrong with my code. Help would be appreciated!


text:
Q: How to perform operation for all matrix elements in Scilab? I'm trying to simulate the heat distribution on an infinite plate over time. For this purpose, I've wrote a Scilab script. Now, the crucial point of it, is calculation of temperature for all plate points, and it has to be done for every time instance I want to observe:
for j=2:S-1
    for i=2:S-1
        heat(i, j) = tcoeff*10000*(plate(i-1,j) + plate(i+1,j) - 4*plate(i,j) + plate(i, j-1) + plate(i, j+1)) + plate(i,j);
    end;
end

The problem is, that, if I'd like to do it for a 100x100 points plate, it means, that here (it's only for inner part, without boundary conditions), I would have to loop 98x98 = 9604 times, at every turn calculating the heat at a given i,j point. If I'd like to observe that for, say 100 secons, with a 1 s step, I have to repeat it 100 times, giving 960,400 iterations in total. Which takes quite a long time, and I'd like to avoid it. Up to 50x50 plate, it all happens in a reasonable, 4-5 seconds time frame.
Now my question is - is it necessary to do all this using for loops? Is there any built-in aggregate function in Scilab, that will let me do this for all elements of a matrix? The reason I haven't found a way yet, is that the result for every point depends on the values of other matrix points, and that made me do it with nested loops. Any ideas on how to make it faster appreciated.

A: It seems to me that you want to compute a 2D intercorrelation of your heat field and a certain diffusion pattern. This pattern can be thought as a "filter" kernel, which is a common way to modify images with a linear filter matrix. Your "filter" is:
F=[0,1,0;1,-4,1;0,1,0];

If you install the Image Processing Toolbox (IPD) you will have a MaskFilter function to do this 2D intercorrelation.
S=500;
plate=rand(S,S);
tcoeff=1;

//your solution with nested for loops
t0=getdate();
for j=2:S-1
  for i=2:S-1
    heat(i, j) = tcoeff*10000*(plate(i-1,j)+plate(i+1,j)-..
    4*plate(i,j)+plate(i,j-1)+plate(i, j+1))+plate(i,j);
  end
end
t1=getdate();
T0=etime(t1,t0);
mprintf("\nNested for loops: %f s (100 %%)",T0);

//optimised nested for loop
F=[0,1,0;1,-4,1;0,1,0];   //"filter" matrix
F=tcoeff*10000*F;
heat2=zeros(plate);
t0=getdate();
for j=2:S-1
  for i=2:S-1
    heat2(i,j)=sum(F.*plate(i-1:i+1,j-1:j+1));
  end
end
heat2=heat2+plate;
t1=getdate();
T2=etime(t1,t0);
mprintf("\nNested for loops optimised: %f s (%.2f %%)",T2,T2/T0*100);

//MaskFilter from IPD toolbox
t0=getdate();
heat3=MaskFilter(plate,F);
heat3=heat3+plate;
t1=getdate();
T3=etime(t1,t0);
mprintf("\nWith MaskFilter: %f s (%.2f %%)",T3,T3/T0*100);

disp(heat3(1:10,1:10)-heat(1:10,1:10),"Difference of the results (heat3-heat):");

Please note, that MaskFilter pads the image (the original matrix) before applying the filter, and as far as I know it uses a "mirror" array across the border. You should check whether this behaviour is appropriate for you or not.
The speed increase is about *320 (the execution time is 0.32% of your original code). Is that fast enough?
In theory it could be done with two 2D Fourier Transform (with Scilab builtin mfft maybe) but it might not be faster than this. See here: http://mailinglists.scilab.org/Image-processing-filter-td2618144.html#a2618168

A: Please consider that there is a big difference between vectorizing an operation and parallel computation, as I have explained here. Although vectorizing might improve performance a little bit, that's not comparable to what you can achive through GPU computing for example (e.g. OpenCL). I will try to explain a vectorized form of your code without going too much into the details. Consider these as given:
S = ...;
tcoeff = ...;

function Plate = plate(i, j)
    ...;
endfunction

function Heat = heat(i, j)
    ...;
endfunction

Now you could define a meshgrid:
x = 2 : S - 1;
y = 2 : S - 1;
[M, N] = meshgrid(x,y);
Result = feval(M, N, heat);

The feval is the key here which will broadcast the feval function over the M and N matrices.

A: Your scheme is a finite differences scheme of the Laplacian operator applied to a rectangular grid. If you choose a row-wise or column-wise numbering of your degrees of freedom (here the plate(i,j)) in order to treat them as vectors, then applying your "discrete" Laplacian can be done by multiplying a sparse matrix on the left (it is very fast) This is particularly well explained in the following document:
https://www.math.uci.edu/~chenlong/226/FDMcode.pdf.
The implementation is described in Matlab but is easily translated in Scilab.


text:
Q: How do I install webpack version 4.19.1? My system already has webpack version 4.27.5, but I need to uninstall this version and then use an older version 4.19.1, instead. I'm using Ubuntu.
I've run the command:
npm uninstall <web package>

but my issue was not resolved.

A: I recommend you to create a .npmrc file and add it
save-exact=true

This will prevent you from get packages like "^4.19.1", which AFAIK this means, get any package above 4.19.1
and then just install the needed package using the following command
npm install webpack@4.19.1 --save-dev


text:
Q: CMFormatDescriptionRef and CMVideoFormatDescriptionGetDimensions After updating to ios 8, I cant seem to get CMFormatDescriptionRefs Dimensions
it always return 0,0 dimension. already looked at apples Documents but I really cant understand how to apply it.
Here's my existing codes which is working with ios 7 (already tested it with my device with ios 7)
   NSArray *ports = [input ports];
AVCaptureInputPort *usePort = nil;
for ( AVCaptureInputPort *port in ports )
{
    if ( usePort == nil || [port.mediaType isEqualToString:AVMediaTypeVideo] )
    {

        usePort = port;
        break;
    }
}

CMVideoFormatDescriptionRef format = [usePort formatDescription];
CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(format);
cameraSize = CGSizeMake(dim.width, dim.height);

A: Solved my problem by adding an observer for the AVcapture port formatDescription
since in the ios 8 version gives you a "0" value with the old way of getting the ports format description.
the first line adds an observer for AVCapture
[[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(avCaptureInputPortFormatDescriptionDidChangeNotification:)
                                                     name:AVCaptureInputPortFormatDescriptionDidChangeNotification object:nil];`

the next line will give you the ports description if the AVCapture changes
- (void)avCaptureInputPortFormatDescriptionDidChangeNotification:(NSNotification *)notification {
[self initializeAPI];
NSArray *ports = [deviceInput ports];
AVCaptureInputPort *usePort = nil;
for ( AVCaptureInputPort *port in ports )
{
    if ( usePort == nil || [port.mediaType isEqualToString:AVMediaTypeVideo] )
    {

        usePort = port;
        break;
    }
}

CMFormatDescriptionRef formatDescription = usePort.formatDescription;
if (formatDescription) {
    CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
    if ((dimensions.width == 0) || (dimensions.height == 0)) {

        return;
    }
    CGFloat aspect = (CGFloat)dimensions.width / (CGFloat)dimensions.height;
    BOOL is7x = floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1;
    if (is7x) {
    }else{
        aspect = 1.f / aspect;

        dimensionForIOS8Above = CGSizeMake(dimensions.width, dimensions.height);
        //NSLog(@"8DIMENSION %f",dimensionForIOS8Above.width);

    }

}

}


text:
Q: How to set base line of inline-block element equal to the base line of its last child I have the following HTML:

A

B

X

Y

And the following CSS:
.horizontal > div {
    display : inline-block;
}

.vertical > div {
    display : block;
}

Currently I have
    X
A B Y

But I want to have
A B X
    Y

I tried setting vertical-align: text-top, but it doesn't align in exact way, there are a couple of pixels missing which looks really ugly.
P.S. I have jsfiddle for this: http://jsfiddle.net/Lr8W4/10/

A: The following seems to work:
.horizontal > div {
    display : inline-block;
    border: 1px dotted gray;
    vertical-align: text-top;
    font-size: 50px;
}

I exaggerated the font-size to illustrate the alignment.
See fiddle at: http://jsfiddle.net/audetwebdesign/FqEqh/


text:
Q: i want sum of 4 textfield in 5th one on change of values of above 4 fields in flutter this is code. for 4 textfield and one for adding those values also take switch case for getting the values from the label of textfield but didn't get any output. my switch case also work but didn't get any output in totalSum variable.
this is code. for 4 textfield and one for adding those values also take switch case for getting the values from the label of textfield but didn't get any output. my switch case also work but didn't get any output in totalSum variable.
  @override
  State<StatefulWidget> createState() => _AmountEdit();
}
class _AmountEdit extends State<AddAmount> {
  final amount = new TextEditingController();
  final amount1 = new TextEditingController();
  final amount2 = new TextEditingController();
  final amount3 = new TextEditingController();
  final amount4 = new TextEditingController();
  final total = new TextEditingController();

  final FocusNode _focusNode = FocusNode();
  final FocusNode _focusNode1 = FocusNode();
  final FocusNode _focusNode2 = FocusNode();
  final FocusNode _focusNode3 = FocusNode();
  final FocusNode _focusNode4 = FocusNode();
  final FocusNode _focusNode5 = FocusNode();

  void initState() {
    super.initState();
    _focusNode.addListener(() {
      print("Has focus: ${_focusNode.hasFocus}");
      if (_focusNode.hasFocus == false) {
        print(test);
      }
      if (test.contains(",00")) {
        print("perfect amount");
      } else {
        String finalAmount = test + append;
        print("the final amount ${finalAmount}");
        amount.text = finalAmount;
      }
    });
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  String append = ",00";
  String test;

  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;

    return Scaffold(
      appBar: AppBar(
        title: Text('Retrieve Text Input'),
      ),
      body: Column(
        children: <Widget>[
          TextBox1(
            controllerText: amount,
            focusNode: _focusNode,
            label: "amount",
          ),
          TextBox1(
            controllerText: amount1,
            focusNode: _focusNode1,
            label: "amount1",
          ),
          TextBox1(
            controllerText: amount2,
            focusNode: _focusNode2,
            label: "amount2",
          ),
          TextBox1(
            controllerText: amount3,
            focusNode: _focusNode3,
            label: "amount3",
          ),
          TextBox1(
            controllerText: amount4,
            focusNode: _focusNode4,
            label: "amount4",
          ),
          TextBox1(
            controllerText: total,
            focusNode: _focusNode5,
          ),
        ],
      ),
    );
  }
}

class TextBox1 extends StatefulWidget {
  var controllerText;
  var focusNode;
  String label;

  TextBox1({this.controllerText, this.focusNode, this.label});

  @override
  State<StatefulWidget> createState() => _TextBox();
}

class _TextBox extends State<TextBox1> {
  String test;
  int test1;
  String append = ",00";
  String finalAmount;

  @override
  void initState() {
    super.initState();
    widget.focusNode.addListener(() {
      if (widget.focusNode.hasFocus == false) {
        print(test);
        if (test == "") {
          finalAmount = "";
        } else {
          if (test.contains(",")) {
          } else {
            finalAmount = test + append;
            widget.controllerText.text = finalAmount;
          }
        }
      }
    });
  }

  @override
  void dispose() {
    widget.focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    double screenWidth = MediaQuery.of(context).size.width;
    return TextField(
        onChanged: (value) {

          print("widget label ${widget.label}");

          print("onchangecallback");
          test = value;
          print("printng value ${value}");

          test1 = int.parse(value);
          sum(value, widget.label);
//          print("printing test1 ${test1}");
        },
//        inputFormatters: [
//          WhitelistingTextInputFormatter.digitsOnly,
//          CurrencyInputFormatter(),
//        ],
        controller: widget.controllerText,
        focusNode: widget.focusNode,
        keyboardType: TextInputType.number,
        decoration: InputDecoration(
          disabledBorder:
              OutlineInputBorder(borderSide: BorderSide(color: Colors.white)),
          border: OutlineInputBorder(),
        ));
  }

  dynamic a;
  dynamic b;
  dynamic c;
  dynamic d;
  dynamic e;
  dynamic totalSum;

  sum(value, type) {
//    print("print value ${widget.controllerText}");
//    print("print amount text field ${value}");
    switch (type) {
      case "amount":
        {
          setState(() {});

          a = value;
          print("value of A ${a}");
        }
        break;

      case "amount1":
        {setState(() {});
          b = value;
          print("value of B ${b}");
        }
        break;

      case "amount2":
        {setState(() {});
          c = value;
          print("value of C ${c}");
        }
        break;

      case "amount3":
        {setState(() {});
          d = value;
          print("value of D ${d}");
        }
        break;

      case "amount4":
        {setState(() {});
          e = value;
          print("value of E ${e}");
        }
        break;

    }
    print("value of A outside the switch ${a}");
    print("value of B outside the switch ${b}");
  totalSum = a + b + c + d + e;
    print("this is total ${totalSum}");
  }
}```

A: Why not using TextEditingController.fromValue controller?
    new TextField(
      controller: new TextEditingController.fromValue(
          new TextEditingValue(
              text: field1,
              selection:
      onChanged: (content) {
        setState(() {
        sum = field1+field2+field3+field4;
      });
      },
      onTap: (() {}),
      onSubmitted: ((s) {
        setState(() {
        });
      }),
    ),


text:
Q: Find all NaN slice in numpy array I have a four dimensional Numpy ndarray (time, pressure level, latitude, longitude), and I want to check for each time and pressure level (dimensions 0 and 1) if there is an all-NaN slice along the latitude or longitude dimenstion (2 and 3).
I'd like to to it in a vectorized way, so without looping over the array, but I can't figure out how.
import numpy as np
a=np.ones([2,3,5,5])
a[0,2,:,2]=np.nan*np.ones_like(a[0,2,:,2])
a[0,1,1,:]=np.nan*np.ones_like(a[0,1,1,:])
a[0,0,1,2]=np.nan
a[1,1,:,2]=np.nan*np.ones_like(a[0,2,:,2])
a[1,1,1,:]=np.nan*np.ones_like(a[0,1,1,:])
print(a)

The array now holds ones (i.e. numbers), and in some locations slices of only NaNs. I'd like to know these locations. So in this case, I need to find that the NaN slices are at [0,2,:,2], [0,1,1,:], [1,1,:,2], and a[1,1,1,:].

A: You should use the np.isnan function which creates a boolean matrix of the same size as your original matrix. Then just use boolean reduction operations like np.all. Thus the following code stores in idx the index of the lines (axis=1) of which all the elements are equal to np.nan.
arr = np.array([[0, 0, 0], [np.nan, np.nan, np.nan], [1, np.nan, 1]])
arr_isnan = np.isnan(arr)
idx = np.argwhere(arr_isnan.all(axis=1))

Output:
>>>print(idx)
[[1]]

Following your example this methods gives you this output :
arr_isnan = np.isnan(a)
idx = np.argwhere(arr_isnan.all(axis=2))

>>>print(idx) #[0,2,:,2] and [1,1,:,2] because axis=2
array([[0, 2, 2],
       [1, 1, 2]], dtype=int64)

>>>print(a[idx[:,0], idx[:,1], :, idx[:,2]])
[[nan nan nan nan nan]
 [nan nan nan nan nan]]

So you just have to adjust the position of ":" according to the axis.


text:
Q: Google Authentication error Ruby on Rails I'm trying to implement Google authentication on my Rails app but I'm having some trouble.
Following https://richonrails.com/articles/google-authentication-in-ruby-on-rails/, I created my initializer with the keys I got from Google's developer console 'omniauth.rb'
OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, '*****', '*****', {client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}
end

I added some routes
  # GOOGLE AUTH
  get 'auth/:provider/callback', to: 'sessions#create'
  get 'auth/failure', to: redirect('/')
  get 'signout', to: 'sessions#destroy', as: 'signout'

My sessions' create action
def create
    user = User.from_omniauth(env["omniauth.auth"])
    sign_in user
    flash[:success] = 'Logged in!'
    redirect_to root_path
end

And the User.from_omniauth method in user's model
def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.password = user.password_confirmation = user.password_digest =  SecureRandom.urlsafe_base64(n=6)
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end

I set a random password because I'm using also bcrypt authentication and it forces that every user has one password
Lastly, in my view I have a button for login
= link_to "Sign in with Google", "/auth/google_oauth2", id: "sign_in", class: "btn btn-primary"

The problem is that it doesn't work, when I click it an error shows on sessions' create user = User.from_omniauth(env["omniauth.auth"]):
NameError at /auth/google_oauth2/callback
undefined local variable or method `env' for #<SessionsController:0x956eb90>

Other times it throws SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError) in another line but I guess that's a different mistake.

A: There is no env method available.
Instead of this, use
user = User.from_omniauth(request.env["omniauth.auth"])
in your create method as request.env["omniauth.auth"] object has the information sent by google after authentication of user to your application.


text:
Q: Trying to use AlertDialog but the app crashes at launch I am trying to use AlertDialog widget in my app, but whatever I do the app crashes at launch. I know something is messed up or not defined but can't seem to find it.I have defined a button for triggering the alert dialog and set 'yes' and 'no' options for the dialog. Selecting 'yes' will result in exiting the app and showing a toast and Selecting 'no' will close the alert dialog and return to app by showing a toast. This is how it should work on paper but as I said the app will crash on launch.
My code:
package com.example.togglebutton;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

   private Button bt;
   AlertDialog.Builder builder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bt = (Button) findViewById(R.id.btn);
        builder = new AlertDialog.Builder(this);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                builder.setMessage("Do you want to close this application ?")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id, ) {
                                finish();
                                Toast.makeText(getApplicationContext(), "you chose yes",
                                        Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                dialog.cancel();
                                Toast.makeText(getApplicationContext(), "you chose no ",
                                        Toast.LENGTH_SHORT).show();
                            }
                        });

                AlertDialog alert = builder.create();

                alert.setTitle("AlertDialogExample");
                alert.show();
            }

        });
}
}

A: Because you forgot this line
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);

A: Add setContentView(R.layout.activity_main)  below super.onCreate(savedInstanceState);

A: SOLUTION OF YOUR PROBLEM
You need to set the layout of the activity and in the above-posted code what we can see that it is missing. So just add the line below super.onCreate(savedInstanceState);
setContentView(R.layout.YOUR_LAYOUT_NAME);

NOTE: Replace YOUR_LAYOUT_NAME with the name of the layout file which you have defined for MainActivity.


text:
Q: javascript set className property for Internet Explorer I set className property of a dinamically generated select control with the following code:
oField.className ="select";

It works for Firefox not for Internet Explorer. How can I set this property on IE?
The code:
var oField = document.createElement("select");
if(browser == "IE"){
    oField.size = 1;
    oField.setAttribute("name","sele"+num);
    oField.onChange = function(){
        AggiungiRiga(oField.name,oField.value)
    };
}
else{
   oField.setAttribute("size",1);
   oField.setAttribute("name","sele"+num);
   oField.setAttribute("onChange","AggiungiRiga(this.name,this.value)");
}
oField.className ="select";

Here I add it to the document:
oTd1.appendChild(oField);

(oTd1 is the  element where the select control must be place). I know the code is not of good quality cause is legacy code.

A: I see no appendChild() method, where are you appending the select element?
not appending the oField to the document could be causing you issues.
eg:
document.body.appendChild(oField);

Also where are the variables browser and num declared from? i guess if its working in FF num is declared.
 var oField = document.createElement("select");

 oField.size = 1;
 oField.name = "sele" + num;

 oField.onChange = function(){AggiungiRiga(oField.name,oField.value)};

 oField.className = "select";

 document.getElementById('tabella').getElementsByTagName('TBODY')[0].childNodes[0].firstChild.appendChild(oField)

Do you know what would of made it easy i had a id for the TD and it worked, i would be easer if you had a TD id="" any way if you wanted the select to be placed in the first TD this will do it compleate example shown above
   document.getElementById('tabella').getElementsByTagName('TBODY')[0].childNodes[0].firstChild.appendChild(oField)

you would however need to have the table as compact

A: Why don't you  try do it with jquery:
$('#idElement').attr('class', 'classname');

Or just with javascript :
document.getElementById("idElement").setAttribute("class", "className");


text:
Q: Filling a new vector by sampling without replacement from an old one Is there a good and efficient algorithm in C++ for sampling without replacement that could easily be applied to the following function?
It takes two vectors, new and old, and fills the latter in a loop by repeatedly sampling from the former (rng.i0 is a random number generator function that I use to return a random integer between 0 and given value).
void diluationexpansionstep(std::vector<long> &oldpopulation,
                            std::vector<long> &newpopulation,
                            long newpopsize)
{
    for (int i = 1; i <= newpopsize;i++) {
        int index_a = rng.i0(oldpopulation.size());
        newpopulation.push_back(oldpopulation[index_a]);
    }
}

Update::
Thank you for helpful responses. Because i want to use my own RNG rather than the inbuilt one in C++ i ended constructing the following Fisher Yates based function where rng.i0 is a function that returns a random intiger between 0 and integer parameter.
void FisherYatesShuffle(vector<long> &indices){
    for (int k = 0; k < indices.size(); k++) {
        int r = k + rng.i0(indices.size()-k);
        swap(indices[k], indices[r]);
        }
    }

void diluationexpansionstep(std::vector<long> &oldpopulation,
                            std::vector<long> &newpopulation,
                            long newpopsize){
    vector<long> indices(oldpopulation.size());
    std::iota(std::begin(indices),std::end(indices),0);
    FisherYatesShuffle(indices);
    for (int i = 0; i <= newpopsize-1;i++){
        newpopulation.push_back(oldpopulation[indices[i]]);
        }
    }

As far as i can tell this work accurately and reasonably quickly.

A: A "good and efficient" algorithm for minimizing developer time and maximizing correctness, using std::random_shuffle from <algorithm>:
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>

using namespace std;

vector<long> random_sample_without_replacement(const vector<long>& source, int newpopsize)
{
    assert(newpopsize >= 0 && newpopsize <= source.size());
    auto result { source };
    std::random_shuffle(result.begin(), result.end());
    result.resize(newpopsize);
    return result;
}

int main() {
    vector<long> test { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    auto result { random_sample_without_replacement(test, 5) };
    for (auto& e : result) cout << e << " ";
    cout << endl;
    return 0;
}

Working example here.


text:
Q: Как переместить элементы ресурсов из string массива в int массив У меня есть int массив который хранит нужные мне элементы и у меня есть ArrayList типа String который хранит подобные элементы.
Как мне передавать эти элементы в int массив? По поводу первого массива, как я понимаю хранить он эти значения может, так как это классифицируется как id ресурса, как мне узнать эти id или есть другое решение?


text:
Q: adding jQuery UI bounce effect I am trying to use jquery ui to have images bounce in and out of a div. I have all the images loaded in a hidden div. I have a recursive jquery function that displays the images in a separate div in an infinite loop. I would like to add the effect of the image bouncing in and then out.
Currently I have:
jQuery(document).ready(function(){

var imgarray = jQuery('img','#hide');

(function recurse(counter) {
    var imgobj = imgarray[counter];
    jQuery('.slides_container img').remove();
    jQuery('.slides_container').delay('1200').prepend(
        ''
    );
    delete imgarray[counter];
    imgarray.push(imgobj);
    setTimeout(function() {
        recurse(counter + 1);
    }, 2000);
})(0);

});

and

How can I add the bounce in effect?

A: You are pretty close your use of the delay is not doing anything because jquery is executing you next block of code and removing that image before it can transition out. You have a couple of options to fix this.
Wrap your ease out animation with the rest in a time out like:
http://jsfiddle.net/32cxA/22/
setTimeout(function() {
    jQuery('.slides_container img').animate({
        top: '-=700'
    }, 1500, 'easeInBounce');
    delete imgarray[counter];
    imgarray.push(imgobj);
    setTimeout(function() {
        recurse(counter + 1);
    }, 2000);
}, 2000);

Or keep your .delay() and just wrap the rest of the code in a setTimeout equal to the total transition time like:
http://jsfiddle.net/32cxA/25/
jQuery('.slides_container img').animate({
        top: '+=700'
    }, 1200, 'easeOutBounce').delay(2000).animate({
            top: '-=700'
        }, 1500, 'easeInBounce');
    setTimeout(function() {
        delete imgarray[counter];
        imgarray.push(imgobj);
        setTimeout(function() {
            recurse(counter + 1);
        }, 2000);
    }, 4700);

A: I have updated the code a bit, and it might not be what you're looking for, but instead of using an array to number whichever you want, I've used the modulus sign (%) to get which number the element is and then I use an increasing integer (You can also use a for loop if you need more control).
Here's the code I have and you can use this however you want.
$(document).ready(function(){
    var numBalls = $('#hidden img').length; //Find out how many images are in queue.
    i = 0; //Start a counter
    setInterval(function(){ //Every (3000) ms run this action
        i++; //Up the counter by 1
        $('img:nth-of-type(' + (i%numBalls + 1) + ')').animate({top: '+=700'}, 1000, 'easeOutBounce').delay(1000).animate({top: '-=700'}, 1000, 'easeOutBounce') //animate the image.  The correct image is selected by (i%numBalls+1)
    },3000);
});

If you have to use an array count, I can work around this, but here is the fiddle to show what I believe you're looking for.  Take a look at the comments here as well to explain what is happening.
http://jsfiddle.net/wxBck/
Also, by using your code, I edited your fiddle to work:
http://jsfiddle.net/32cxA/27/
I added a delay in between the two animations, you may not have seen this working if you tried this because your setTimeout delay was shorter than the entirety of the animation


text:
Q: Dynamic SQL declaration executed by batch file I'm not a proficient coder for SQL queries so I need some help with this one.
Here is my attempt:

DECLARE @ID AS varchar(max) = 'SELECT ID FROM Price WHERE ID = ''123456''';
DECLARE @VALUE as varchar(max) = 'SELECT TOP 1 Value FROM PriceData WHERE PriceID=''@ID' ORDER BY UpdatedOn DESC';

INSERT INTO PriceData VALUES (@ID,CAST(GETDATE() AS DATE),@VALUE,GETDATE())

So essicently I have two tables PRICE and PRICEDATA. PRICE has the PriceID I want from the ID '123456' so I decalre that as @ID and then the VALUE is the most recent value from PriceData by the ID '123456' so I order by the descending order and get the first element, then i insert into PriceData with the new values for today. Obviously this does not work I tried playing around with EXEC(@SQL) after i keep appending to the script but that also didn't work. What am I doing wrong here?
PS: @ID has to be BIGINT and @VALUE has to be FLOAT but since i'm declaring SQL statement I had to make them varchar for the moment
PSS: Also im saving this sql script as an SQL file and running this command in a batch file
 sqlcmd -S "db" -i "C:\MYSQL.sql"

A: I don't think you need a dynamic SQL or any variables here. Just an Insert from select should work
INSERT INTO PriceData
SELECT TOP 1 P.ID,
             Cast(Getdate() AS DATE),
             Value,
             Getdate()
FROM   PriceData PD
       JOIN Price P
         ON P.ID = PD.PriceID
WHERE  ID = '123456'
ORDER  BY PD.UpdatedOn DESC


text:
Q: Appending same div multiple times without reducing performance Good day all, I'm trying to make a game with jquery where a space-ship will be shooting bullets. All are working fine except when it fires multiple bullets performance gets slower. I understand that it is the problem of jquery .append() because I used it to generate bullets when spacebar is pressed. But I can't figure it out how to solve this. These are the codes for bullet generating and animation,
function generateBullet(objectid, bulletid, bulletclass, left, top) {
    var objectID = $('#' + objectid);
    var bulletID = bulletid;
    var bulletClass = bulletclass;
    var adjust_left = left;
    var adjust_top = top;
    var objectLeft = objectID.offset().left - adjust_left;
    var objectTop = objectID.offset().top - adjust_top;
    var appendingValue = "

";
    $("#content").append(appendingValue);
}

function animateBullet(bulletid) {
    var bulletID = $("." + bulletid);
    bulletID.each(function() {
        var nowTop = $(this).offset().top;
        $(this).css("top", nowTop - 55);
    });
}

If there is any other way to generate bullets then please let me know. Again your help will be much appreciated. Tnx!


text:
Q: Struct remains unedited after function I have defined some structs and I have created a function that reads the data from a XML and inserts it into a DialogueRules struct.
Everything should work, but after the execution some values remain untouched, even if they should. I have debugged and I have discovered that they are set properly, but when I exit the dialogue_load funcion they lose their values. (I runned Valgrind and it does not find anything weird)
After more debugging, I have discovered that some pointers, like dr->l_topic[1].name, point to a direction in the main, point to another one inside dialogue_load, and they point to the original function when I go back to the main.
I do not have a single clue about why it fails, what is the cause?
The code is as follows:
DialogueRules * dr=create_dialog();  //Reserve memory for the pointer
printf("t0: %d \n",dr->l_topic[1].name); //The pointer has the original value
dialogue_load("rules.xml",dr);  //Loads the xml
printf("t2: %d \n",dr->l_topic[1].name); //The pointer has the original value

Dialogue_load is
STATUS dialogue_load(char * file_name,DialogueRules *dr){
printf("t1: %d \n",dr->l_topic[1].name);//The pointer has another value!

//Load the xml
 xmlDocPtr doc;
xmlNodePtr node;

if (!file_name) {
    return ERROR;
}

if ((doc = xmlParseFile(file_name))== NULL) {
    fprintf(stderr,"File %s has not XML format.\n", file_name);

    return ERROR;
}

node = xmlDocGetRootElement(doc);
if (node == NULL) {
    fprintf(stderr, "Empty document\n");
    xmlFreeDoc(doc);
    return ERROR;
}

if (xmlStrcmp(node->name, (const xmlChar*) ROOT)) {
    fprintf(stderr,"Expected <%s>, instead of %s\n", ROOT, node->name);
    xmlFreeDoc(doc);
    return ERROR;
}

node = node->xmlChildrenNode;
while(node != NULL) {

    if (!xmlStrcmp(node->name, (const xmlChar*) RULES)) {
        dreader_process_rules(doc, node->xmlChildrenNode, dr);
    }
    else if (!xmlStrcmp(node->name, (const xmlChar*) TOPICS)) {
        dreader_process_topics(doc, node->xmlChildrenNode, dr);
    }

    node = node->next;
}
xmlFreeDoc(doc);
return OK;

}

Create_dialog is
DialogueRules *create_dialog() {
 DialogueRules * dialog = (DialogueRules*)malloc(sizeof(DialogueRules));
 dialog->num_rules=0;
 dialog->num_topic=0;
 return dialog;
}

The structs are the following:
typedef struct _Topic
{
Id id;
char name[WORD_SIZE+1]; /* topic name */
Set * topic_rules; /* set of rule indexes associated with a topic */
} Topic;

typedef struct _Rule
{
Id id; /* rule identifier */
char * pattern [MAX_PATTERNS];/* If the string matches any of these input patterns,    then executes this rule */
int num_patterns;/* number of patterns */
char * template [MAX_PATTERNS]; /* List of pos sible templates that can be used as a    response */
int num_templates; /* number of possible answers */
int last; /* Last used template */
} Rule;

typedef struct _DialogueRules
{
Rule l_rule[MAX_RULES]; /* vector to store rules */
int num_rules; /* number of rules stored in l_rule */
Topic l_topic[MAX_TOPICS]; /* vector to store topics */
 int num_topic; /* number of topicsstored in l_topic */
} DialogueRules;

EDIT:
The output when using %p is:
t0: 0x7f57d20afe98
t1: 0x7f57d20afe80
t2: 0x7f57d20afe98
Edit 2:
The makefile rule for main is:
main.o: main.c
 $(CC) ${CFLAGS} ${CXML2} -c main.c -o main.o

and for dialoguerrulesreader(which contains dialog_rule) is
 DialogueRulesReader.o: DialogueRulesReader.c DialogueRulesReader.h
   ${CC}  ${CXML2} -c  $< ${LXML2}

(Take in account that
CC=gcc  -ggdb
CFLAGS=-Wall -pedantic -ansi
CXML2=`xml2-config --cflags`
LXML2=`xml2-config --libs`

)

A: As discovered in comments; you should use the same CFLAGS to build all units. It turned out that using different flags (particularly -ansi on one file, and no standard specification on the other) caused the structs to have different sizes in two different units.


text:
Q: Error in Processing Request Code 502 Text : OK somebody know how to fix this??
I've search for the same problem and it doesn't work.
PHPmyAdmin work fine before.
message shows:
Error in Processing request
Error Code : 502
Error Text : OK


text:
Q: Python svgpathtools scaled method strange results I have converted the following path-d to a Path object using the parse_path of the svgpathtools module:
M 0.0,36.0 C 0.0,164.082 96.0,250.0 251.0,250.0 C 404.639,250.0 544.0,213.0 544.0,-14.0 C 544.0,-234.0 385.95,-339.976 290.0,-405.0 C 169.0,-487.0 89.75200000000001,-522.634 -49.0,-576.0 C -54.93907,-578.28437 -60.3166,-579.27496 -64.9795,-579.27496 C -76.9143,-579.27496 -84.1666,-572.78519 -84.1666,-564.88956 C -84.1666,-557.8411199999999 -78.38711,-549.6723599999999 -65.0,-543.99996 C 53.0,-493.99996 160.0,-457.99996 251.0,-343.99996 C 342.0,-230.99996 376.0,-138.08695999999998 376.0,6.000040000000013 C 376.0,141.00004 343.0,230.00004 231.0,230.00004 C 184.385,230.00004 153.548,217.40704000000002 119.0,186.00004 C 110.90765999999999,178.64337 107.6879,172.97044000000002 107.6879,168.59784000000002 C 107.6879,155.13934 138.1906,154.00004 151.0,154.00004 C 220.0,154.00004 274.0,89.11334000000001 274.0,18.000040000000013 C 274.0,-56.99995999999999 226.0,-113.99995999999999 135.0,-113.99995999999999 C 55.841800000000006,-113.99995999999999 0.0,-39.99995999999999 0.0,36.00004000000001 L 0.0,36.0 M 572.0,128.0 C 572.0,163.0 601.0,192.0 636.0,192.0 C 671.0,192.0 699.0,163.0 699.0,128.0 C 699.0,93.0 671.0,65.0 636.0,65.0 C 601.0,65.0 572.0,93.0 572.0,128.0 M 572.0,-131.0 C 572.0,-96.0 601.0,-67.0 636.0,-67.0 C 671.0,-67.0 699.0,-96.0 699.0,-131.0 C 699.0,-166.0 671.0,-194.0 636.0,-194.0 C 601.0,-194.0 572.0,-166.0 572.0,-131.0

When I get the d attribute of the scaled Path object however:
parse_path("M 0.0,36.0 C 0.0,164.082 96.0,250.0 251.0,250.0 C 404.639,250.0 544.0,213.0 544.0,-14.0 C 544.0,-234.0 385.95,-339.976 290.0,-405.0 C 169.0,-487.0 89.75200000000001,-522.634 -49.0,-576.0 C -54.93907,-578.28437 -60.3166,-579.27496 -64.9795,-579.27496 C -76.9143,-579.27496 -84.1666,-572.78519 -84.1666,-564.88956 C -84.1666,-557.8411199999999 -78.38711,-549.6723599999999 -65.0,-543.99996 C 53.0,-493.99996 160.0,-457.99996 251.0,-343.99996 C 342.0,-230.99996 376.0,-138.08695999999998 376.0,6.000040000000013 C 376.0,141.00004 343.0,230.00004 231.0,230.00004 C 184.385,230.00004 153.548,217.40704000000002 119.0,186.00004 C 110.90765999999999,178.64337 107.6879,172.97044000000002 107.6879,168.59784000000002 C 107.6879,155.13934 138.1906,154.00004 151.0,154.00004 C 220.0,154.00004 274.0,89.11334000000001 274.0,18.000040000000013 C 274.0,-56.99995999999999 226.0,-113.99995999999999 135.0,-113.99995999999999 C 55.841800000000006,-113.99995999999999 0.0,-39.99995999999999 0.0,36.00004000000001 L 0.0,36.0 M 572.0,128.0 C 572.0,163.0 601.0,192.0 636.0,192.0 C 671.0,192.0 699.0,163.0 699.0,128.0 C 699.0,93.0 671.0,65.0 636.0,65.0 C 601.0,65.0 572.0,93.0 572.0,128.0 M 572.0,-131.0 C 572.0,-96.0 601.0,-67.0 636.0,-67.0 C 671.0,-67.0 699.0,-96.0 699.0,-131.0 C 699.0,-166.0 671.0,-194.0 636.0,-194.0 C 601.0,-194.0 572.0,-166.0 572.0,-131.0").scaled(.4, .4).d()

the result string seems segmentated:

This is however not the case by scaling with numbers like 0.5 or above, but with numbers < ca. 0.45 in my experience! I can not understand why is this happening. Any help is highly appreciated!


text:
Q: Is there an equivalent of Junit assetEquals with delta in Scalacheck I am porting some Junit tests(for Java code) into Scalacheck. One of the Junit tests is using
http://junit.sourceforge.net/javadoc/org/junit/Assert.html#assertEquals(double, double, double)
Now when I write Scalacheck property for the same is there a way to provide delta how Junit API offers?

A: Comparing doubles sucks :). Here is how ScalaTest helps you with it:
import org.scalatest._

class MyTest extends FlatSpec with ShouldMatchers {

  ...

  100.0 should be (100.0 plusOrMinus 1e-9)

  ...
}

An alternative for plusOrMinus is +- method.

A: ScalaTest works nicely with ScalaCheck, and the matcher I think you're looking for is at http://www.scalatest.org/user_guide/using_matchers#checkingNumbersAgainstARange


text:
Q: Fast Algorithm for partial sums on a list I have been learning Python for 2 months now. In order to hone my programming skills, I solve problems on Codewars from time to time.
Task
Codewars kata:

Write a program that takes a list of numbers as an argument and return a list of partial sums.

My Attempt
I wrote a solution that I tested and it works:
def parts_sums(ls):
    length=len(ls)+1
    def gen():
        for elt in range(0,length):
            yield sum(ls[elt:])

    result= list(gen())
    return result

Codewars is rejecting this solution because it's too slow for lists with thousands of numbers.
I have spent an embarrassingly huge amount of time trying to come up with a faster solution with no avail.
How can the algorithm be designed more performant?

A: A solution with an explicit loop:
result= ls + [0]
for i in range(len(result)-1, 0, -1):
  result[i-1]= result[i] + result[i-1]

Note that it can also be done in-place in ls.

A: You don't have to compute the sum of a slice at each step, all you have to do is subtract one number from the previous sum.
Here's a pretty naive but straight forward solution, subject to further optimizations.
def part_sums(ls):
    result = [sum(ls)]
    for x in ls:
        result.append(result[-1] - x)
    return result

A: As commented by Yves Daoust, seems like a suffix sum array with additional zero-element (as sum over empty array).
Suffix Sum
Some notes on Suffix Sum:

Given an array 'A' of size N, its suffix sum array is an array of the same size N such that the ith element of the suffix sum array 'Suffix' is the sum of all elements of the given array till ith index from the end, i.e Suffix[i] = A[i] + A[i+1] + A[i+2] + … + A[N-1] - (0-Based indexing).

For Example:
Given A[] = [3, 4, -1, 2, 5], the suffix sum array S[] is given as - S[0] = 13, S1 = 10, S1 = 6, S3 = 7, S[5] = 5.
i.e. S[] = [13, 10, 6, 7, 5]

See also:

*

*Dev.to (2020): Prefix Sum & Suffix Sum - Programming Tools

*Wikipedia: suffix array (might be related, not sure)

Implementation
Following approach uses these concepts for performance:

*

*predefined, fix-sized result array (instead of extending or list-comprehension)

*fix-sized loop for i (instead of recursion) to reverse increment

*explicit fast-returning if-branch for inputs with 0 or 1 elements

def suffix_sum(arr):
    result = arr + [0]   # add the zero as last element for this task (copied input)

    n = len(arr)
    if (n <= 1):  # input with 0 or 1 elements returned as is
        return result

    last = n-1  # the last of the input array stays unmodified

    # iterate by element (last to first):
    for i in range(last, -1, -1):  # step backwards from last to first
        result[i] = result[i+1] + arr[i]   # result-sum = previous-sum + element (increases with each element)

    return result

Results for 3 test-cases:
in: [0, 1, 3, 6, 10]
out:[20, 20, 19, 16, 10, 0]
in: []
out:[0]
in: [1234]
out:[1234, 0]

Notes:

*

*The reverse-for-loop using a range as in Print a list in reverse order with range()?

*the first element is denoted by -1 as second range-argument

Debug-print each iteration with print(f"{i:2}: {result[i]} = {result[i+1]} + {arr[i]}") shows 4 iterations for example-input [0, 1, 3, 6, 10] with length n=5:
 3: 16 = 10 + 6
 2: 19 = 16 + 3
 1: 20 = 19 + 1
 0: 20 = 20 + 0

A: You could setup the resulting list starting with the total sum and progressively extend it reducing the last element by values in the original list:
ls = [1, 2, 3, 4, 5, 6]

r = [sum(ls)]
r.extend(r[-1]-n for n in ls)

print(r)
# [21, 20, 18, 15, 11, 6, 0]

Or, using itertools, accumulate the sum backwards and reverse the result:
from itertools import accumulate

r = [*accumulate([0]+ls[::-1])][::-1]

print(r)
# [21, 20, 18, 15, 11, 6, 0]


text:
Q: How to separate words from a row individually using php and mysql I have a mysql database with a table called keywords -- see below

**** As you can see the row has more than one word listed inside.
MY QUESTION
Is there a way to separate each word on it's own using mysql and php. Right now it combines all the words as one instead of individually.
The picture below is showing you words but one button may contain 3 or more words.

I need for the words to be unique and on their own. Can this be done in MYSQL? If so can you please provide the php coding, thank you.

A: you can separate the keyword by comma and space using PHP.
//Split the keyword into array
$keywords_array = explode(", ", $keywords);

//Use array_unique to remove duplicates
$unique_keywords_array = array_unique($keywords_array);

//Print output
foreach($unique_keywords_array as $key) {
    echo $key . "<br />";
}

A: As you didn't share any code, i can give you a simple guess so you can proceed further :-
Get data from your table with php and use explode function to separate each word.

A: the best choice is to use explode function ,
the link below is the reference of explode in php website :
http://php.net/manual/en/function.explode.php


text:
Q: Add target and rel with php Imagine you have this markup:
Original code:

  Google
  Google
  Google
  Google

Desired code:

  Google
  Google
  Google
  Google

Targeting the "p" with the class "Add", how can I with php add:

*

*The "target" property to all nested elements

*The "rel" property to all nested elements

*The class "l" to all nested elements

I need to dynamically change the html structure, the original links are constructed by a module and I cannot change them before the original html is constructed. Before I was doing it with javascript but js is not an option because some users do not have js enabled in the browser.
My previous js code is:
$(".Add a").attr("target", "_blank");
$(".Add a").attr("rel", "noFollow noReferrer");
$(".Add a").addClass("l");

Thank you.

A: Is this what you're looking for? you can make this so that it only prints if a certain condition is met.

    <a href='https://google.com' <?php echo("target='_blank'") ?> <?php echo("rel='noFollow noReferrer'") ?> <?php echo("class='l'") ?>>Google
    <a href='https://google.com' <?php echo("target='_blank'") ?> <?php echo("rel='noFollow noReferrer'") ?> <?php echo("class='l'") ?>>Google
    <a href='https://google.com' <?php echo("target='_blank'") ?> <?php echo("rel='noFollow noReferrer'") ?> <?php echo("class='l'") ?>>Google
    <a href='https://google.com' <?php echo("target='_blank'") ?> <?php echo("rel='noFollow noReferrer'") ?> <?php echo("class='l'") ?>>Google


text:
Q: React: Trying to set an API JSON response to state object and pass it to component for mapping and rendering I have a component where I've set an empty array called customers: [] in this.setState: { }. On load the component fires a POST call to an API which returns a JSON object with the XHR name CustomerOffers. I have logic in place to iterate through the array and map all parts of the JSON object to the UI but every time I load the app I'm getting an Error message stating TypeError: this.state.customers.map is not a function, but when I tested this with dummy data inside the customers array everything rendered properly. I used a console.log statement to print the return response from the API and it's showing as undefined which leads me to believe that somewhere in the return process the app isn't getting the data. I've included my code below, any help on this would be huge!
React
import React, { Component } from 'react';
import './Button.css';
import Grid from '@material-ui/core/Grid';
import axios from 'axios';

class UsersList extends Component {

  constructor(){
        super();
        // this.selectCard  = this.selectCard.bind(this);
        // Define data model object and cardActive
        this.state = {

            cardActive: null,

            dataModel: {
              offerName: null,
              customerId: null
            },

            SessionId: null,

            customers: []
        }

        // this.updateOffer = offerID => {};

        this.submitData = () => {
          let temporalDataModel = this.state.dataModel;

          temporalDataModel.SessionId = this.state.SessionId;

          console.log(
            "Transmitting data...NOW",
            temporalDataModel
          );

          this.setState(
            {
              dataModel: temporalDataModel
            },
            () => {
              let postUrl = "https://myAPI.com";
              axios
                .post(postUrl, this.state.dataModel)
                .then(response => {
                  console.log(response);
                })
                .catch(err => {
                  console.error(err);
                });
            }
          );
        };

        this.selectCard = obj => {
          let temporalDataModel = this.state.dataModel;

        //   console.log("paramenters", obj);
        //   console.log("currentState", temporalDataModel);

          this.state.customers.forEach(c => {
            if (c.CustomerId === obj.customerId) {
              c.Offers.forEach(off => {
                if (off.OfferId === obj.offerId) {
                  console.log("offer", off);
                  temporalDataModel.customerId = obj.customerId;
                  temporalDataModel.offerName = off.Name;
                  temporalDataModel.offerId = off.OfferId;
                  temporalDataModel.products = off.Products;
                  temporalDataModel.sessionId = obj.SessionId;
                }
              });
            }
          });

          console.log("data updated", temporalDataModel);

          this.setState({ cardActive: obj.offerId, SessionId: obj.SessionId,  });
        };
    }

    getCustomerOffers(){
      var search = window.location.search;
      var params = new URLSearchParams(search);
      var customerId = params.get('CUSTOMERID');
      var sessionId = params.get('SESSIONID');
      var data = "{'CustomerId':'1','SessionId':'9636','IsExisting':'true'}";

      var requestOffers = {
        method: 'post',
        url: 'https://myAPI.com',
        data: "{'CustomerId':'" + customerId + "','SessionId':'" + sessionId + "'}"
    };

          axios.post('https://myAPI.com',
               "{'CustomerId':'" + customerId + "','SessionId':'" + sessionId + "'}")
           .then((res) => {
               console.log("RESPONSE RECEIVED: ", res);
               this.setState({
                   customers: res.data
               });
               console.log("Customer: ", this.state.customers.CustomerId);
           })
           .catch((err) => {
               console.log("AXIOS ERROR: ", err);
           });

    }

    componentDidMount(){
      this.getCustomerOffers();

    }

    // selectCard(offerId) {
    //     this.setState({ cardActive: offerId });
    //   }

    render (){
        return (
          this.state.customers != null &&

          {this.state.customers.map((customer, index) => {
              return

Name: {customer.LastName}, {customer.FirstName}

Customer ID: {customer.CustomerId}

                              Address:

                              {customer.Address.Address1}

                              {customer.Address.City}, {customer.Address.State} {customer.Address.Zip}

Available Offers

                              <Grid container spacing={24} justify="center">
                              {customer.Offers.map((Offer,index) => {
                                  return
 {
                                      const obj = {
                                        offerId: Offer.OfferId,
                                        customerId: customer.CustomerId,
                                      };
                                      console.log("Offer ID:",Offer.OfferId, ",Customer ID:",customer.CustomerId,",Offer Name:", Offer.OfferName, ",Session ID:", customer.SessionId);
                                      this.selectCard(obj);
                                    }}>
                                          <Grid item xs={12}>

{Offer.OfferId}

{Offer.Name}

                                                  {Offer.Products.map((Product, index) => {
                                                      return

+ {Product.ProductName}

                                                  })}

{Offer.Price}

                                          </Grid>

                              })}

                              </Grid>

          })}

          <button className="navbuttonSelected" disabled={!this.state.cardActive} onClick={this.submitData}>Submit</button>

        )

    }
}

export default UsersList

A: I don't think you are using Axios (or try and catch) quite how it should be for asynchronous requests.
Try and Catch blocks can only be used on synchronous blocks of code. When you make an api call is it asynchronous (i.e. takes a random amount of time to complete). To catch an error on an asynchronous block, you would normally use a .catch(handlerFunction) attached to a promise.
It should be something like:
axios.post(myurl, mydata).then(res => console.log(res))
   .catch(e => console.log(e))

So getOffer might be rewritten:
const getOffers = (trequest) => {
    return axios(trequest)
      .catch(e => console.log(e) );
}

To get the results, you would then need to do something like:
getOffers('/getmyoffers').then(results => console.log(results) )

Edit - to update the customers state you can do this:
getOffers('/getmyoffers').then(results => this.setState({customers:results.data} )

A: The problem is inside your getCustomerOffers method. In this method you are setting customers state to a promise which causing the render method to be re-executed, at this point, this.state.customers is no longer an array (a promise instead).
So now if you understand the root cause, the fix will be easy like someone already posted:
axios(trequest).then((response) => {
   this.setState({ customers: response.data });
}, e => {
   console.log(e);
});

I strongly recommend reading more about Javascript Asynchronous as it will help you more in the long run.


text:
Q: Using superscript in C# resource file I have some superscript text that I need to define in a C# UI project resource file that will eventually be put in a XAML datatable.
For instance the 2 in this example needs to be superscript:  (kg/m2)
Is there any way to define this right in the Value field of the Resource string...perhaps via a Unicode or HTML tag that a standard Xaml control bound to this value could parse?
I'm not opposed to using a XAML converter, but short of putting some sort of hacky string in the resource (e.g.(kg/mSQUARED)) and using the XAML to look for it, I can't think of an elegant way to that either.
Thanks!

A: Based on your comment above, it sounds like "squared" is the only one you need. So, to amplify my comment:
There's already a Unicode code point for "squared" aka "SUPERSCRIPT TWO". It's called U+00B2, if you want to Google more information about it.
Here it is:

²

Highlight that character in your Web browser, copy it to the clipboard, and paste it into your resource file.

A: Use US International keyboard layout, Press Alt-Gr + 2, that will show
Alt-Gr + 3 = ³


text:
Q: MVVM Light - how to fire command from code behind I need to fire command from WP7 applicationbar. Unfortunately it is not possible, but Laurent published interesting workaround:
private void ApplicationBarMenuItemClick(object sender, System.EventArgs e)
{
  var vm = DataContext as MainViewModel;
  if (vm != null)
     vm.MyCommand.Execute(null);
}

Unfortunately my code behind does not see MainViewModel class or actually any ViewModel class at all! Data binding works well so ViewModel is working fine. What am I doing wrong?

A: Put a breakpoint on that line of code and check what the value of DataContext is when the breakpoint is hit. If it's null you've probably forgotten to set the data context in your view.
If the DataContext isn't null, make sure it's of type MainViewModel or else the line calling vm.MyCommand.Execute(null) won't ever be called.
Based on the code you pasted, your view should look something like this.
<phone:PhoneApplicationPage x:Class="MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    shell:SystemTray.IsVisible="True"
    DataContext="{Binding Path=Main, Source={StaticResource Locator}}"
    >

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <!-- the rest has been ommitted for simplicity -->
    </Grid>

    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem x:Name="appBarMenuItem1" Click="ApplicationBarMenuItemClick" Text="Menu Item 1" />
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>
</phone:PhoneApplicationPage>

This assumes your ViewModelLocator has the property Main of type MainViewModel.


text:
Q: Let arrow marker point in the direction of another marker I'm making a Google Maps application where a user can search for a location. This location must point into the direction of a predefined marker.
Given the following pieces of code:
The predefined marker:
      var station = new google.maps.LatLng(52.375401, 5.218824);

      var stationMarker = new google.maps.Marker({
        position:   station,
        map:        map,
        });

The marker that will be placed on the location that the user searched:
      var direction = new google.maps.LatLng(52.376423, 4.887234);

      var directionMarker = new google.maps.Marker({
        position:   direction,
        map:        map,
        draggable:  false,
        title:      "test"
        });

      directionMarker.setIcon(({
        path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
        scale: 6
        }));

How can I make sure that the direction marker (i.e the marker from the user search result) always points to the predefined marker?
I'm making use of the Google Maps API v3.
I've created a jsFiddle, which you can find here

A: Ok here you go:

*

*Use the google.maps.SymbolPath.FORWARD_CLOSED_ARROW so that it points to the north.

*Add the Geometry library to be able to compute a heading.

*Use the rotation parameter on your direction icon.

Here is how to compute the heading from your direction marker to the station:
var heading = google.maps.geometry.spherical.computeHeading(direction,station);

Then use it to rotate your icon accordingly:
directionMarker.setIcon({
    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
    scale: 6,
    rotation: heading
});

You also had one unnecessary pair of () in the above code which I have removed.
JSFiddle demo


text:
Q: How do I make this button be disabled and say "Booked" when clicked in tkinter So, im designing a restaurant management system using tkinter and im trying to make the table booking system right now ive got a button setup to book the table and i want it so when its clicked it becomes gray and says booked but idk how to do that
can anyone help
thanks
window = Tk()
window.title("Restaurant Manager V2")
window.geometry("600x300")
#setup tkinter label
label1 = Label(window, text="Click button to book table")
label1.grid(row=0, column=1, sticky=W)
#setup tkinter button
def button_click():

button1 = Button(window, text="Table 1", width=5, command=button_click)
button1.grid(row=2, column=0, sticky=W)
window.mainloop()

A: def button_click():
    button1.config(state="disabled", text="Booked")

A: you can this with 2nd way
def button_click():

                 button1 = Button(window, text="Booked !", width=5,
                           state="disabled")
                 button1.grid(row=2, column=0, sticky=W)


text:
Q: Looking for a list of values for $\xi^{(n)}(\frac{1}{2})$ I'm looking for a list of values for ${\xi^{(n)}(\frac{1}{2})}$, where $\xi^{(n)}$ is the $n^{\text{th}}$ derivative of the Riemann's $\xi$ function or, alternatively, some implementation of ${\xi^{(n)}(s)}$, eventually in Mathematica.
Thanks in advance.

A: For numerical values for the first 3 derivatives, see the "Relations and positivity results for the derivatives of the Riemann ξ function" by Coffey. Integral formulas are also given.

A: For computing $\xi^{(2n)}(1/2)$ for only one $n$ you should use  $$\xi(s) =\frac{s (s-1)}{2} \Lambda(s)$$ where
$$\Lambda(s)= \Gamma(s/2)\pi^{-s/2} \zeta(s)= \int_0^\infty (\theta(x)-1) x^{s/2-1}dx\qquad\qquad \\ \qquad = \frac{1}{s-1}-\frac{1}{s}+\int_1^\infty (x^{s/2-1}+x^{(1-s)/2-1})(\theta(x)-1)dx \\ \theta(x) = \sum_{n=-\infty}^\infty e^{-\pi n^2 x} = x^{-1/2} \theta(1/x)\qquad\qquad\qquad\qquad\qquad$$

Also why would you need $\xi^{(2n)}(1/2)$ ?


text:
Q: Twilio StatusCallback not working when modifying a live call I am trying to forward a call in Twilio by modifying the live call. I have a number set up that will get the zip code from the caller and then determine the customer number to forward that call to by searching in a database. For the first part of the call (to get the zip code) I'm using the Gather verb. Once I have the zip code and customer's assigned Twilio number I can forward the call using the REST API to modify the live call.
I need to add some extra parameters to the callback URL with a GET request.
According to Twilio's website I should be able to POST the StatusCallbackURL and Method to the modified call.
https://www.twilio.com/docs/api/rest/change-call-state
However, it is not working. Here is my code:
$url = 'http://xxxx.com/phone/customer?to='.$number;

$call = $this->twilio->account->calls->get($this->request->query->get('CallSid'));
$call->update(array(
  'Url' => $url,
  'Method' => 'GET',
  'StatusCallbackMethod' => 'GET',
  'StatusCallback' => 'http://xxxx.com/phone/log/callback'
));

The "Url" and "Method" optional parameters work but Twilio does not call back to the supplied callback URL.
The new URL that twilio redirects the call to returns TwiML for twilio to process.
The call is initiated by an actual person picking up the phone and calling. I tried to create a call via the REST API and the StatusCallback works but twilio expects TwiML to be returned so I get an error in twilio.


text:
Q: Add columns in vector but not in df I am trying to do the following and was wondering if there is an easier way to use dplyr to achieve this (I'm sure there is):
I want to compare the columns of a dataframe to a vector of names, and if the df does not contain a column corresponding to one of the names in the name vector, add that column to the df and populate its values with NAs.
E.g., in the MWE below:
df <- data.frame(cbind(c(1:6),c(11:16),c(10:15)))
colnames(df) <- c("A","B","C")
names <- c("A","B","C","D","E")

how do I use dplyr to create the two columns D and E (which are in names, but not in df) and populate it with NAs?

A: No need in dplyr, it's just a basic operation in base R. (Btw, try avoiding overriding built in functions such as names in the future. The reason names still works is because R looks in the base package NAMESPACE file instead in the global environment, but this is still a bad practice.)
df[setdiff(names, names(df))] <- NA
df
#   A  B  C  D  E
# 1 1 11 10 NA NA
# 2 2 12 11 NA NA
# 3 3 13 12 NA NA
# 4 4 14 13 NA NA
# 5 5 15 14 NA NA
# 6 6 16 15 NA NA


text:
Q: I want to know the grammar of the following sentence "You'll never guess who they got to replace you at work."
The sentence above is one of dialogue in the series "Big bang theory".
I can guess the meaning is that you will never guess who will work instead of you.
But I want to know what's the meaning of 'got to'.
And what does 'they' indicate?
I think the following sentence is correct grammatically.
You'll never guess who will replace you at work.

A: There are two possibilities:

*

*Get here is probably used in the sense "obtain", equivalent to  "hire" or "engage". If that is the case, to replace you is an infinitival of purpose: it says why who was hired, as your replacement. They is the subject of replace.

*It is also possible that get is used in the sense "induce" or "persuade". If that is the case, then to replace you designates the action which who was induced to undertake. Who (more precisely, the missing value which the variable who points to) is the subject of replace.


text:
Q: Not Displaying Nape Body I had these two in the same Main class. Now there are Main.as and MainChar.as
When compiling doesn't show any errors but it isn't displaying the object either :c
It is the first time I am splitting code into different classes. I just figured what should be in the hero creation class and what should stay in Main.
package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import nape.geom.Vec2;
    import nape.phys.Body;
    import nape.phys.BodyList;
    import nape.space.Space;

    import MainChar;

    public class Main extends Sprite
    {
        public var gravity:Number = 600;
        public var space:Space = new Space(new Vec2(0, gravity));
        public var hero:MainChar = new MainChar();

        public function Main():void
        {
            hero.createMainCharacter(stage.stageWidth/2, stage.stageHeight/2, 50, 50);
            addEventListener(Event.ENTER_FRAME, update);
        }

        private function update(e:Event):void
        {
            space.step(1 / stage.frameRate, 10, 10);
            var bodies:BodyList = space.bodies;
            for (var i:int = 0; i < bodies.length; i++)
            {
                var body:Body=bodies.at(i);
                if (body.userData.sprite != null)
                {
                    body.userData.sprite.x = body.position.x;
                    body.userData.sprite.y = body.position.y;
                    body.userData.sprite.rotation=(body.rotation*180/Math.PI)%360;
                }
            }
        }
    }
}

Hero creator class:
package
{
    import flash.display.Graphics;
    import flash.display.Sprite;
    import nape.geom.Vec2;
    import nape.phys.Body;
    import nape.phys.BodyType;
    import nape.shape.Polygon;
    import nape.space.Space;

    public class MainChar extends Sprite
    {
        public var space:Space = new Space(new Vec2(0, 600));

        public function MainChar():void
        {
        }

        public function createMainCharacter(x:Number, y:Number, width:Number, height:Number):void
        {
            var mainChar:Body = new Body(BodyType.DYNAMIC);
            var mainCharShape:Polygon = new Polygon(Polygon.box(width, height));

            mainChar.shapes.add(mainCharShape);
            mainChar.position.setxy(x, y);
            mainChar.space = space;

            var mainCharSprite:Sprite = new Sprite();
                mainCharSprite.graphics.beginFill(0x000000);
                mainCharSprite.graphics.drawRect( -width/2, -height/2, width, height);
                mainCharSprite.graphics.endFill;
            addChild(mainCharSprite);

            mainChar.userData.sprite = mainCharSprite;
            addChild(mainChar.userData.sprite);
        }

    }
}

A: You need to add your hero as a child of your Main sprite EG:
  public function Main():void
  {
        hero.createMainCharacter(stage.stageWidth/2, stage.stageHeight/2, 50, 50);
        addEventListener(Event.ENTER_FRAME, update);
        addChild(hero);
  }


text:
Q: Calculate new point coordinates after imageview translation I need help calculating new coordinates after an imageview translation.
I am working on an android app that will plot points on a map.
The map is downloaded from a backed service.
The points I need to plot come from the backend, and their positions are relative to the map size (8000w x 4450h).
The app (using glide) sets the image in a custom imageview. When that happens, the map is scaled down to fit the screen.
viewH = 735.
viewW = 1080.
I then need to plot the locations; however, the plotted coordinates need to be translated to match the new scale.
Here is how I am calculating it now...which gets the points in the correct area...but they are not precise (plotting to low on y axis):
newX = oldX / (originalMapHeight / imageviewHeight).
newY = oldY / (originalMapWidth / imageviewWidth).
Can someone help me get a more accurate translation of the x,y coordinates? I cannot find anything regarding this, but it may be due to me not knowing what exactly to search.
Thanks!

A: You can use min-max normalization for this. The formula is

For your case, the formula reduces to
NewX = (oldX * imageViewWidth) / originalMapWidth
NewY = (oldY * imageViewHeight) / originalMapHeight


text:
Q: Excel, count TOTAL duplicate values across multiple columns We are looking at counting duplicate values across multiple columns (30 columns).
Basically we had multiple sessions sign ups, we collected emails, we want to know the total of ALL attendees who attended multiples.  Meaning, repeat session attendees.  We just need a total, not per email address.  We need total repeats across all sessions.
I thought a CountIf forumla might work but I have 30 columns. It might still work, I didn't know if there was a range or something else I should use.  I am far from an Excel guru, but work my way around it.
Sample of our data:

Email - Session 1
Email - Session 2
Email - Session 3
Email - Session 5
Email- Session 6

john.doe@me.com
mac.doe@blah.com
Jane.doe@me.com
sam.smith@me.com
jack.blak@mo.com

Jane.doe@me.com
john.doe@me.com
mac.doe@blah.com
john.doe@me.com
sam.smith@me.com

A: Use SUMPRODUCT with COUNTIF:
=SUMPRODUCT((COUNTIF(A2:E3,A2:E3)>1)/(COUNTIF(A2:E3,A2:E3)))


text:
Q: c++ Win32 Multiple windows doing same action I have this problem. I want to open two same windows which behaviour is mirrored. So if I click on first window same action is executed on second window (mirrored behaviour). Is it possible? How can I do this? My application is in C++ and I use WinApi.
Thanks.

A: Well, you can comunicate between them using socket, shared memory or something like that... Another way is to send all windows messages you recieve from one window to another.


text:
Q: Unknown provider: $scopeProvider <- $scope <- AccountSummaryController I am working on angular JS applicaion to make Banking App but I am stuck at a place where my test cases are giving error tht controller not found.
I dont know where I am going wrong any help will be appriciated'
app.js
(function() {
    'use strict';

    // CONTROLLERS
    angular
        .module('abcbankApp.controllers', []);

    // SERVICES
    angular
        .module('abcbankApp.services', []);

    angular
        .module('abcbankApp', ['ui.router', 'ui.grid', 'abcbankApp.accountSummary', 'abcbankApp.transaction', 'abcbankApp.login'])
        .config(routeConfig);

    function routeConfig($stateProvider,$urlRouterProvider) {
       $urlRouterProvider.when("", "/login");

       $urlRouterProvider.when("", "/login");
        // ROUTES
        // Please use State provoders for routing between login,accountSummary, transactions and search
        // define  $stateProvider(state) with url,templateUrl,controllers and controllerAs
         $stateProvider
          .state("accountSummary", {
            url: "/accountSummary",
            templateUrl: "./templates/account-summary/account-summary.html",
            controller : "AccountSummaryController",
            controllerAs :"ActSumCtrl",
        })
        .state("login", {
            url: "/login",
            templateUrl: "./templates/login/login.view.html",
            controller :"LoginController",
            controllerAs :"LoginCtrl",
        })
}

})();

AccountSummaryController.js
(function() {
    'use strict';
   var appContr = angular.module('abcbankApp.accountSummary', ['abcbankApp.accountSummaryService']);
    appContr.controller('AccountSummaryController', function($scope,AccountSummaryService,$state) {
    var ActSumCtrl = this;
    ActSumCtrl.accountList = [];
    ActSumCtrl.accountList = AccountSummaryService.getAccountSummary();
    });

})();

Acoount service.js
(function() {
    'use strict';

     var appServc = angular.module('abcbankApp.accountSummaryService', []);
appServc.factory('AccountSummaryService', ['$http',
  function($http) {
    return {
      getAccountSummary: function() {
          var data;
          $http.get('./data/account-summary.json')
         .success(function(response) {
           data = response.data;
        });
        return data;
      }
    };
  }]);

})();

But I am getting error like this
 Executed 0 of 12 SUCCESS (0 secs / 0 secs)

[1A[2KNode.js (linux; U; rv:v8.15.1) abcbankApp.accsummary module AccountSummaryController Controller definition FAILED

    Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- AccountSummaryController

A: As per documentation - https://docs.angularjs.org/guide/controller, the second parameter to an controller is an array.
appContr.controller('AccountSummaryController', [$scope, function($scope,AccountSummaryService,$state) {
    // code
}]);


text:
Q: Make Javascript code work on button click How can I make this work on click of a button and disable auto start?

canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;

// création d'un tableau
particle = [];
particleCount = 0,
  gravity = 0.1,
  colors = [
    '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
    '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
    '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
    '#FF5722', '#795548'
  ];

for (var i = 0; i < 90; i++) {

  particle.push({
    x: width / 2,
    y: height / 2,
    boxW: randomRange(5, 20),
    boxH: randomRange(5, 20),
    size: randomRange(2, 8),

    spikeran: randomRange(3, 5),

    velX: randomRange(-8, 8),
    velY: randomRange(-50, -10),

    angle: convertToRadians(randomRange(0, 360)),
    color: colors[Math.floor(Math.random() * colors.length)],
    anglespin: randomRange(-0.2, 0.2),

    draw: function() {

      context.save();
      context.translate(this.x, this.y);
      context.rotate(this.angle);
      context.fillStyle = this.color;
      context.beginPath();
      // drawStar(0, 0, 5, this.boxW, this.boxH);
      context.fillRect(
        this.boxW / 2 * -1, this.boxH / 2 * -1,
        this.boxW, this.boxH
      );
      context.fill();
      context.closePath();
      context.restore();
      this.angle += this.anglespin;
      this.velY *= 0.999;
      this.velY += 0.2;

      this.x += this.velX;
      this.y += this.velY;
      if (this.y < 0) {
        this.velY *= -0.2;
        this.velX *= 0.9;
      };
      if (this.y > height) {
        this.anglespin = 0;
        this.y = height;
        this.velY *= -0.2;
        this.velX *= 0.9;
      };
      if (this.x > width || this.x < 0) {

        this.velX *= -0.5;
      };

    },

  });

}
r1 = {
  x: width / 2 - 150,
  y: height / 2 - 150,
  width: 300,
  height: 300,
  velX: 0,
  velY: -10,
  img: loadImage(
    "http://image.noelshack.com/fichiers/2015/12/1427051642-smiley.png"
  ),
  alphatop: 0
};

function drawScreen() {
  size = 50;
  pFontName = "Lucida Sans Unicode";
  context.font = size + "pt " + pFontName;
  context.fillText("Confetti party !!!", width / 2, 150);
  if (r1.alphatop < 1) {
    r1.alphatop += 0.01;
  } else {
    r1.alphatop = 1;
  }
  context.globalAlpha = r1.alphatop;
  context.drawImage(r1.img, r1.x, r1.y);
  context.textAlign = 'center';

  if (r1.alphatop === 1) {
    r1.velY *= 0.999;
    r1.velY += 0.3;

    r1.x += r1.velX;
    r1.y += r1.velY;
  }

  if (r1.y + r1.height > height) {
    r1.anglespin = 0;
    r1.y = height - r1.height;
    r1.velY *= -0.8;
    r1.velX *= 0.9;
  };

  context.globalAlpha = 1;
  for (var i = 0; i < particle.length; i++) {
    particle[i].draw();

  }

}

function loadImage(url) {
  var img = document.createElement("img");
  img.src = url;
  return img;
}

function update() {

  context.clearRect(0, 0, width, height);

  drawScreen();

  requestAnimationFrame(update);
}

update();

function randomRange(min, max) {
  return min + Math.random() * (max - min);
}

function randomInt(min, max) {
  return Math.floor(min + Math.random() * (max - min + 1));
}

function convertToRadians(degree) {
  return degree * (Math.PI / 180);
}

function drawStar(cx, cy, spikes, outerRadius, innerRadius, color) {
  var rot = Math.PI / 2 * 3;
  var x = cx;
  var y = cy;
  var step = Math.PI / spikes;

  context.strokeSyle = "#000";
  context.beginPath();
  context.moveTo(cx, cy - outerRadius)
  for (i = 0; i < spikes; i++) {
    x = cx + Math.cos(rot) * outerRadius;
    y = cy + Math.sin(rot) * outerRadius;
    context.lineTo(x, y)
    rot += step

    x = cx + Math.cos(rot) * innerRadius;
    y = cy + Math.sin(rot) * innerRadius;
    context.lineTo(x, y)
    rot += step
  }
  context.lineTo(cx, cy - outerRadius)
  context.closePath();
  context.fillStyle = color;
  context.fill();

}
html, body{
padding:0;
margin:0;

  background-image: url(
    "http://image.noelshack.com/fichiers/2015/12/1427051641-geometry.png"
  );
  width: 100%;
  height: 100%;
  cursor: default;   text-align: center;

  font-family: 'PT Sans', sans-serif;
}
canvas{
position:absolute;
 left:0;
 top:0;
 z-index:0;
 border:0px solid #000;
}
<canvas id="canvas"></canvas>

A: Wrap your code in a function and then add a button calling that function.

function RunIt(){
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;

// création d'un tableau
particle = [];
particleCount = 0,
  gravity = 0.1,
  colors = [
    '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
    '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
    '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
    '#FF5722', '#795548'
  ];

for (var i = 0; i < 90; i++) {

  particle.push({
    x: width / 2,
    y: height / 2,
    boxW: randomRange(5, 20),
    boxH: randomRange(5, 20),
    size: randomRange(2, 8),

    spikeran: randomRange(3, 5),

    velX: randomRange(-8, 8),
    velY: randomRange(-50, -10),

    angle: convertToRadians(randomRange(0, 360)),
    color: colors[Math.floor(Math.random() * colors.length)],
    anglespin: randomRange(-0.2, 0.2),

    draw: function() {

      context.save();
      context.translate(this.x, this.y);
      context.rotate(this.angle);
      context.fillStyle = this.color;
      context.beginPath();
      // drawStar(0, 0, 5, this.boxW, this.boxH);
      context.fillRect(this.boxW / 2 * -1, this.boxH / 2 * -1, this.boxW, this.boxH);
      context.fill();
      context.closePath();
      context.restore();
      this.angle += this.anglespin;
      this.velY *= 0.999;
      this.velY += 0.2;

      this.x += this.velX;
      this.y += this.velY;
      if (this.y < 0) {
        this.velY *= -0.2;
        this.velX *= 0.9;
      };
      if (this.y > height) {
        this.anglespin = 0;
        this.y = height;
        this.velY *= -0.2;
        this.velX *= 0.9;
      };
      if (this.x > width || this.x < 0) {

        this.velX *= -0.5;
      };

    },

  });

}
r1 = {
  x: width / 2 - 150,
  y: height / 2 - 150,
  width: 300,
  height: 300,
  velX: 0,
  velY: -10,
  img: loadImage("http://image.noelshack.com/fichiers/2015/12/1427051642-smiley.png"),
  alphatop: 0
};

function drawScreen() {
  size = 50;
  pFontName = "Lucida Sans Unicode";
  context.font = size + "pt " + pFontName;
  context.fillText("Confetti party !!!", width / 2, 150);
  if (r1.alphatop < 1) {
    r1.alphatop += 0.01;
  } else {
    r1.alphatop = 1;
  }
  context.globalAlpha = r1.alphatop;
  context.drawImage(r1.img, r1.x, r1.y);
  context.textAlign = 'center';

  if (r1.alphatop === 1) {
    r1.velY *= 0.999;
    r1.velY += 0.3;

    r1.x += r1.velX;
    r1.y += r1.velY;
  }

  if (r1.y + r1.height > height) {
    r1.anglespin = 0;
    r1.y = height - r1.height;
    r1.velY *= -0.8;
    r1.velX *= 0.9;
  };

  context.globalAlpha = 1;
  for (var i = 0; i < particle.length; i++) {
    particle[i].draw();

  }

}

function loadImage(url) {
  var img = document.createElement("img");
  img.src = url;
  return img;
}

function update() {

  context.clearRect(0, 0, width, height);

  drawScreen();

  requestAnimationFrame(update);
}

update();

function randomRange(min, max) {
  return min + Math.random() * (max - min);
}

function randomInt(min, max) {
  return Math.floor(min + Math.random() * (max - min + 1));
}

function convertToRadians(degree) {
  return degree * (Math.PI / 180);
}

function drawStar(cx, cy, spikes, outerRadius, innerRadius, color) {
  var rot = Math.PI / 2 * 3;
  var x = cx;
  var y = cy;
  var step = Math.PI / spikes;

  context.strokeSyle = "#000";
  context.beginPath();
  context.moveTo(cx, cy - outerRadius)
  for (i = 0; i < spikes; i++) {
    x = cx + Math.cos(rot) * outerRadius;
    y = cy + Math.sin(rot) * outerRadius;
    context.lineTo(x, y)
    rot += step

    x = cx + Math.cos(rot) * innerRadius;
    y = cy + Math.sin(rot) * innerRadius;
    context.lineTo(x, y)
    rot += step
  }
  context.lineTo(cx, cy - outerRadius)
  context.closePath();
  context.fillStyle = color;
  context.fill();

}
}
html, body{
padding:0;
margin:0;

  background-image: url("http://image.noelshack.com/fichiers/2015/12/1427051641-geometry.png");
  width: 100%;
  height: 100%;
  cursor: default;   text-align: center;

  font-family: 'PT Sans', sans-serif;
}
canvas{
position:absolute;
 left:0;
 top:0;
 z-index:0;
 border:0px solid #000;
}
<canvas id="canvas"></canvas>
<button onClick="RunIt();">Run It</button>