text:
Q: AngularJS + ArcGIS I am trying to use ArcGIS JavaScript API inside an Angular application. As I see, it uses Dojo. So, I am trying to initialize ArcGIS from Angular directive like this:
  link: function (scope, element, attrs) {
    dojo.require('esri.map');
    var init = function () {
      console.log('dojo is ready');
      var map = new esri.Map("map-container", {
        center: [-111.3797, 56.7266 ],
        zoom: 16,
        basemap: "streets"
      });
      map.enableScrollWheelZoom()

    };
    dojo.addOnLoad(init);
  }

Looks like this way is not 100% correct because when I try to zoom by scrolling mouse wheel,  I get this error:
Uncaught TypeError: Cannot call method 'apply' of null

My question, is how to properly to inject ArcGIS functionality inside an Angular app?

A: It looks like you are trying to build your map inside a directive element. That's a legitimate use, but I would make sure that you utilize the AMD loader of Dojo to load your modules and then bootstrap your Angular app after all the Dojo goodness is ready.
I recently put together a write-up on Angular/Esri dev, and the source code for a sample project can be found here.
What I actually do is build the map from a Controller, but the process should be similar to building it in the directive.
define([
    'angular',
    'esri/map'
], function(angular, Map) {
    function mapConfigs() {
        return {
            basemap: 'streets',
            center: [-118.1704035141802,34.03597014510993],
            zoom: 15
        };
    }
    function mapGen(elem) {
        return new Map(elem, mapConfigs());
    }
    function AppController($scope) {
        $scope.map = mapGen('map');
    }
    function init(App) {
        App.controller('AppCtrl', ['$scope', AppController]);
        return AppController;
    }
    return { start: init };
});

I use a bootstrap module to build all my Angular bits using the Esri/Dojo bits before bootstrapping the Angular application.
define([
    'angular',
    'controllers/AppController',
    'widgets/search/SearchBootstrap'
], function(angular, AppController, SearchBootstrap) {
    function init() {
        var App = angular.module('app', ['ui.bootstrap']);
        AppController.start(App);
        SearchBootstrap.start(App);
        // need to bootstrap angular since we wait for dojo/DOM to load
        angular.bootstrap(document.body, ['app']);
        return App;
    }
    return { start: init };
});

Hope that helps a bit.

A: I think a very 'AngularJS' style approach to this would be something like the following. (fiddle here http://jsfiddle.net/technicolorenvy/2Ke62/4/)
I like using angular-ui-router, but this approach would also work w/ Angular's $routeProvider. The magic here is in the resolve object which will optionally 'wait' until a promise is resolved before continuing.
angular.module('webApp', ['ui.router'])
    // module (app) config
    .config(function ($stateProvider, $urlRouterProvider) {

        $urlRouterProvider.otherwise('/map');

        $stateProvider.state('map', {
            url: '/map',
            template: '

',
            controller: 'MapCtrl',
            resolve: {
                promiseObj: function ($q, $rootScope, wish) {
                    var deferred = $q.defer(),
                        deps = {
                            Map: 'esri/map',
                            FeatureLayer: 'esri/layers/FeatureLayer',
                            InfoTemplate: 'esri/InfoTemplate',
                            SimpleFillSymbol: 'esri/symbols/SimpleFillSymbol',
                            SimpleRenderer: 'esri/renderers/SimpleRenderer',
                            SimpleMarkerSymbol: 'esri/symbols/SimpleMarkerSymbol',
                            ScaleDependentRenderer: 'esri/renderers/ScaleDependentRenderer',
                            Color: 'dojo/_base/Color'
                        };

                    wish.loadDependencies(deps, function () {
                        deferred.resolve();
                        if (!$rootScope.$$phase) {
                            $rootScope.$apply();
                        }
                    });

                    return deferred.promise;
                }
            }
        });
    });

As you can see above, we have a map state that has a resolve prop. You can then build an object that represents your ArcGIS/Dojo dependencies and pass that on to your wish.loadDependencies (see below).
Using q we will return a promise that gets resolved once all the dependencies are loaded via dojo's require
angular.module('webApp')
     // service that deals w/ our dojo require
    .service('wish', function () {

        // it's not require... it's a wish?
        var wish = {};

        function _loadDependencies(deps, next) {
            var reqArr = _.values(deps),
                keysArr = _.keys(deps);

            // use the dojo require (required by arcgis + dojo) && save refs
            // to required obs
            require(reqArr, function () {
                var args = arguments;

                _.each(keysArr, function (name, idx) {
                    wish[name] = args[idx];
                });

                next();
            });
        }

        return {
            loadDependencies: function (deps, next) {
                _loadDependencies(deps, next);
            },

            get: function () {
                return wish;
            }
        };
    });

after that, in your MapCtrl, you can call all the ArcGIS/Dojo fns directly (as you would normally), by the keys you used in the deps object that was constructed during app config, as they are now attached to the object returned by wish.get().
What follows is a modified version of the example found here (https://developers.arcgis.com/en/javascript/jssamples/renderer_proportional_scale_dependent.html)
angular.module('webApp')
    // our map controller
    .controller('MapCtrl', function ($rootScope, $scope, wish) {

        var w = wish.get(),
            greenFill = new w.Color([133, 197, 133, 0.75]),
            greenOutline = new w.Color([133, 197, 133, 0.25]),
            layer,
            markerSym,
            renderer1,
            renderer2,

            CROPS_URL = 'http://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/USA_County_Crops_2007/FeatureServer/0';

        $scope.map = new w.Map('map', {
            center: [-98.579, 39.828],
            zoom: 4,
            basemap: 'gray'
        });

        layer = new w.FeatureLayer(CROPS_URL, {
            outFields: ['STATE', 'COUNTY', 'M086_07', 'AREA'],
            infoTemplate: new w.InfoTemplate('${COUNTY}, ${STATE}', '
The percentage of the area of the county that represents farmland is ${M086_07}%.
')
        });
        layer.setDefinitionExpression('AREA>0.01 and M086_07>0');

        markerSym = new w.SimpleMarkerSymbol();
        markerSym.setColor(greenFill);
        markerSym.setOutline(markerSym.outline.setColor(greenOutline));
        renderer1 = new w.SimpleRenderer(markerSym);
        renderer1.setProportionalSymbolInfo({
            field: 'M086_07',
            minSize: 1,
            maxSize: 10,
            minDataValue: 0,
            maxDataValue: 100
        });

        //for the second renderer increase the dot sizes and set a backgroundFillSymbol
        renderer2 = new w.SimpleRenderer(markerSym);
        renderer2.setProportionalSymbolInfo({
            field: 'M086_07',
            minSize: 5,
            maxSize: 15,
            minDataValue: 0,
            maxDataValue: 100
        });

        layer.setRenderer(new w.ScaleDependentRenderer({
            rendererInfos: [{
                'renderer': renderer1,
                    'minScale': 50000000,
                    'maxScale': 10000000
            }, {
                'renderer': renderer2,
                    'minScale': 0,
                    'maxScale': 5000000
            }]
        }));

        $scope.map.addLayer(layer);
    });

working fiddle demonstrating the above code, found here http://jsfiddle.net/technicolorenvy/2Ke62/4/


text:
Q: JOOQ:How to use alias in complex Select statement? Here is my select statement
SelectQuery<Record> selectQueryPayment = transaction.selectQuery();
    selectQueryPayment.addSelect(AccountPayment.ACCOUNT_PAYMENT.PAYMENT_NUMBER,AccountPayment.ACCOUNT_PAYMENT.PAYMENT_AMOUNT,AccountPayment.ACCOUNT_PAYMENT.PAYMENT_TYPE,
                     AccountPayment.ACCOUNT_PAYMENT.PAYMENT_DATE,AccountPayment.ACCOUNT_PAYMENT.PAYMENT_AMOUNT,AccountPayment.ACCOUNT_PAYMENT.PAYMENT_AMOUNT.subtract(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_REFUNDED.add(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_APPLIED)));

Here you can see a complex select with some calculation
ACCOUNT_PAYMENT.PAYMENT_AMOUNT.subtract(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_REFUNDED.add(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_APPLIED))

How to create Alias for this? And then get back data from it?

A: Ok I got the solution we can use this
AccountPayment.ACCOUNT_PAYMENT.PAYMENT_AMOUNT.subtract(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_REFUNDED.add(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_APPLIED)).as("OverPayment")

We have to add as("Alias Name") and getting value back we have to use
     Result<Record> resultPayment = selectQueryPayment.fetch();
           for(Record record : resultPayment){
           feeAmount =  resultPayment.getValues("OverPayment");

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Has Google pushed an update to their OAuth2.0 flow that breaks multiple accounts? Up until last week, when ever I was logged into multiple accounts in Google and I invoked the OAuth2.0 flow I would get to an ugly screen (looked like it had been hit repeatedly with the ugly stick) that was functional. It would display a list of radio buttons with all the accounts I am logged in as, you select the one and continue through the flow.
This week I now get a beautiful screen that is non-functional (does not list accounts and the signin button only adds an additional account to the list of accounts I am signed in as) I should point out that I am logged into 4 different Google accounts at the same time. The OAuth2.0 for my app appears to be working fine as if I start an in-cognito window in Chrome, or start a new session and only have one account logged in, my OAuth flow continues normally.
Is this just me or is everyone hit by it?

A: We (google) are rolling back the new page and within a few minutes it should return to the previous behavior.
Any chance you could let us know what kinds of accounts those 4 you were logged in to were? SAML? Google Apps? Plain gmail?

A: We're also experiencing this. Hope someone at Google takes note and gets this fixed soon!
EDIT: To clarify, I've only experienced the problem when logged into both a personal Google account AND a Google apps account. Haven't tested other situations at present.

A: FYI, we just rolled out the new UI, so you may begin to see the "beautiful screen" that is now functional. :-) Thanks for the bug report.


text:
Q: Performance Issue when Single row in Hbase exceeds hbase.hregion.max.filesize In Hbase, I have configured hbase.hregion.max.filesize as 10GB. If the Single row exceeds the 10GB size, then the row will not into 2 regions as Hbase splits are done based on row key
For example, if I have a row which has 1000 columns, and each column varies between 25MB to 40 MB. So there is chance to exceed the defined region size. If this is the case, how will it affect the performance while reading data using rowkey alone or row-key with column qualifier?

A: First thing is Hbase is NOT for storing that much big data 10GB in a single row(its quite hypothetical).
I hope your have not saved 10GB in a single row (just thinking of saving that)
It will adversely affect the performance. You consider other ways like storing this much data in hdfs in a partitioned structure.
In general, these are the tips for generally applicable batch clients like Mapreduce Hbase jobs
Scan scan = new Scan();
scan.setCaching(500); //1 is the default in Scan, which will be bad for MapReduce jobs
scan.setCacheBlocks(false);  // don't set to true for MR jobs

Can have look at Performance


text:
Q: Opening 2 dialogs in Scene2D-dialog LibGdx I'm using Scene2d dialog in my game to create pop-ups. They are supposed to be questions and the player has to answer them. After the player has answered the question it's supposed to create another pop-up to give feedback. The answering part is working correctly as is identifying the correct answer. However I can't create the feedback button correctly. Currently the player gets asked a question. Then he answers and nothing. When he gets asked another question the feedback pops up on top of the next question. TLDR: Question -> answer -> feedback in one loop is what I'm looking for. Here's the code for the part that is not working properly:
do{
    if(DialogOma.wasClicked) {
        if (DialogOma.wasTheAnswerCorrect) {
            int ID = friendlyNPCs.get(j).getID();
                if(GameScreen.isEnglish) {
                    diaTest = new DialogOma("Questionjabs", disTestSkin, 1, myBundleEn, ID, "resultoikein", "ok");
                                         }
                else{
                    diaTest = new DialogOma("Vastausmies", disTestSkin, 1, myBundleFi, ID, "resultoikein", "ok");
                    }
                    diaTest.getSkin().getFont("default-font").getData().setScale(3f, 3f);
                    diaTest.show(stage);
                    DialogOma.wasTheAnswerCorrect = false;
                    Player.rightAnswer = true;
                    DialogOma.wasClicked = false;
                    Player.hasAnswered = true;
                                            }
                    else if (!DialogOma.wasTheAnswerCorrect) {
                        int ID = friendlyNPCs.get(j).getID();
                            if(GameScreen.isEnglish){
                                diaTest = new DialogOma("Vastausmies", disTestSkin, 1, myBundleEn, ID, "resultvaarin", "ok");
                                                    }
                            else{
                                diaTest = new DialogOma("Vastausmies", disTestSkin, 1, myBundleFi, ID, "resultvaarin", "ok");
                                }
                     diaTest.getSkin().getFont("default-font").getData().setScale(3f, 3f);
                     diaTest.show(stage);
                     DialogOma.wasTheAnswerCorrect = false;
                     Player.rightAnswer = false;
                     DialogOma.wasClicked = false;
                     Player.hasAnswered=true;
                        }
                    }
                }while(!Player.hasAnswered&&!diaTest.isVisible());

Most of the code is just to check the language pack to be used.
DialogOma.wasTheCorrectAnswer is used to determine which pop-up screen should be used after answering
Player.rightAnswer is used to handle the answer outside of dialog
Player.hasAnswered and DialogOma.wasClicked are there from my testings. Haven't found aything by Googling it yet. Would really appreciate help here guys :)
EDIT: Here's what happens in the result method of dialog:
        if(object.equals("correct")) {
        ChangeScreens.gameIsOn = true;
        wasTheAnswerCorrect = true;
        wasClicked = true;
    }
    else{
        ChangeScreens.gameIsOn = true;
        wasTheAnswerCorrect = false;
        wasClicked = true;
    }
}

A: Okay, I managed to solve this by myself after sleeping over it. I had to make the first piece of code run as its own method which is controlled by the variable "wasClicked". Previously my buttons could be assigned with values "right" or "wrong" but I had to make it accept also value "ok" in order to get out of the loop. Probably not the best possible way to handle this but at least it works.


text:
Q: Saving the auth token and using it Having trouble figuring out how to save the auth token from the authorization request response and use it for making an authorized request so that I can pull database information. Appreciate any advice!
When I run $node index on the code below, I get this status 403 response.

$ node index
STATUS: 403
STATUS: 200
HEADERS: {"x-gs-rid":"notsureifthisinfoisconfidentialornot","content-type":"application/json;charset=utf-8","cache-control":"no-ca
che, no-store, max-age=0, must-revalidate","pragma":"no-cache","expires":"0","strict-transport-security":"max-age=31536000 ; inc
ludeSubDomains, max-age=15768000","x-xss-protection":"1; mode=block","x-frame-options":"DENY","x-content-type-options":"nosniff"
,"connection":"close","set-cookie":["mesosphere_server_id=notsureifthisprivatetoo; path=/"]}
BODY: {"country":"US","username":"myemailaddress","expiresAt":1511230469149,"X-GSAccessToken":"LotsofNumbersandLettersandPeriodsforTokenGoeshere"}

My issue is that I'm trying to save this auth token and use it properly so that I can make the next request(that's now authorized) to config2.gamesparks.net databases but can't figure out how.

var config     = require( "./config.json" );

var gameSparks = require( "./GameSparks" );

var https = require('https');
var options = {
  host: 'auth.gamesparks.net',
  path: '/restv2/auth/user',
  headers: {
      'Authorization':'Basic PRIVATEGSAUTHCODEHERE'
  }
};

var req = https.get(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));

  // Buffer the body entirely for processing as a whole.
  var bodyChunks = [];
  res.on('data', function(chunk) {
    // You can process streamed parts here...
    bodyChunks.push(chunk);
  }).on('end', function() {
    var body = Buffer.concat(bodyChunks);
    console.log('BODY: ' + body);
    // ...and/or process the entire body here.
  })
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});

var gsrequest = {
  host: 'config2.gamesparks.net',
  path: '/restv2/game/GSAPIKEYHEREcipm/endpoints/',
  }
};
var req = https.get(gsrequest, function(res) {
  console.log('STATUS: ' + res.statusCode);
});

A: If what you are posting is JSON, then it looks like the access-token is accessible via
body.X-GSAccessToken


text:
Q: Python - Copy several files from several locations to one folder based on a excel file Good day
We need to copy data from one server to another server for a migration. I have received an Excel list in which I have the following columns.

All contained files must be copied. Unfortunately, the new path where the documents should be copied should also be written into the DataFrame and finally the whole thing should be exported as CSV.
The export is no problem.
But I have problems with the loop.
In my imagination:
I have a basic destination path
 - I work per line
 - I copy the file using the file path
 - I add the "destination path + file name" in new path in the data frame
 - Repeat on the next line
So i started with:
import os
import glob
import shutil
import numpy as np
import pandas as pd

Docdf = pd.read_excel('S:\Test_MSC.xlsx')

destpath = 'S:\\Test_dest\\'

for f in Docdf:
[...] *problem*

Docdf .to_csv("enchanced_file.csv", sep = ";", encoding = "utf-8")

How do I best build the loop?
Many thanks for the support

A: for f in Docdf: is wrong, it will iterate over column names. You need to iterate over rows or just use the apply method:
from shutils import copyfile

def copying(row):
    oldpath = row[4] # column E
    newpath = destpath + row[1] # column B
    copyfile(oldpath, newpath)
    return newpath

Docdf['new_path'] = Docdf.apply(copying, axis=1)


text:
Q: add custom UIView and xib into storyboard I have a custom UIView and xib called DialPad and I'm trying to use this object in my storyboard, but the custom DialPad isn't being add as a subview with the buttons
my custom DialPad :UIView
@implementation DialPad

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

my custom xib called DialPad

and my view controllers look like this
#import <UIKit/UIKit.h>
#import "DialPad.h"

@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIView *dial;
@end

#import "ViewController.h"
@interface ViewController ()
{
    DialPad  *d;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    d = [[DialPad alloc] initWithFrame:self.dial.frame];

    [self.dial addSubview:d];
}
@end

and my storyboard

but the border around the view looks strange

#import "DialPad.h"
#import <QuartzCore/QuartzCore.h>

@implementation DialPad

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    self.layer.borderColor = [UIColor redColor].CGColor;
    self.layer.borderWidth = 1;
}
@end

A: For loading a view from xib file, you should do this:
d = [[[NSBundle mainBundle] loadNibNamed:@"DialPad" owner:nil options:nil]
                 firstObject];
[self.dial addSubview:d];

Border: try to add border code in - (void)awakeFromNib


text:
Q: Create a column which increments value for changes in another row I have a dataframe with two columns as below:
Var1Var2
a   28
b   28
d   28
f   29
f   29
e   30
b   30
m   30
l   30
u   31
t   31
t   31

I'd like to create a third column with values which increases by one for every change in value of another column.
Var1Var2Var3
a   28  1
b   28  1
d   28  1
f   29  2
f   29  2
e   30  3
b   30  3
m   30  3
l   30  3
u   31  4
t   31  4
t   31  4

How would I go about doing this?

A: Something like this:
(df.Var2.diff() != 0).cumsum()

A: You can compare Var2 with its shifted-by-1 version:
v
   Var1  Var2
a     0    28
b     1    28
d     2    28
f     3    30
f     4    30
e     5     2
b     6     2
m     7     2
l     8     2
u     9     5
t    10     5
t    11     5

i = v.Var2
v['Var3'] = i.ne(i.shift()).cumsum()

v
   Var1  Var2  Var3
a     0    28     1
b     1    28     1
d     2    28     1
f     3    30     2
f     4    30     2
e     5     2     3
b     6     2     3
m     7     2     3
l     8     2     3
u     9     5     4
t    10     5     4
t    11     5     4

A: Using category
df.Var2.astype('category').cat.codes.add(1)
Out[525]:
0     1
1     1
2     1
3     2
4     2
5     3
6     3
7     3
8     3
9     4
10    4
11    4
dtype: int8

Updated
from itertools import groupby
grouped = [list(g) for k, g in groupby(df.Var2.tolist())]
np.repeat(range(len(grouped)),[len(x) for x in grouped])+1


text:
Q: Ionic alert to cant added check box and text filed in same alert I'm try to add input text filed and check box in my alert but I cant do it correctly please help me to fix it,,
I want display text box and check box fields in my alert
This is my code
doPrompts() {
    let prompt = this.alertCtrl.create({
      title: 'Add new add-on',
      message: "",

      inputs: [
        {

          placeholder: 'Select category',

        },
        {
          placeholder: 'Description',

        },
        {
          placeholder: 'Units',

        },
        {
          placeholder: '$ 00.00',

        }
      ],

      buttons: [
        {
          text: 'Cancel',
          handler: data => {
            console.log('Cancel clicked');
          }
        },
        {
          text: 'Add',
          handler: data => {
            console.log('Saved clicked');
          }
        }
      ]
    });
    prompt.present();
  }

A: This is by design.Check the docs.

Alerts can also include several different inputs whose data can be passed back to the app. Inputs can be used as a simple way to prompt users for information. Radios, checkboxes and text inputs are all accepted, but they cannot be mixed.

If you need a form with different types of input. You will need to create an separate component having a form with both textbox input and select input and show as a modal
let modal = this.modalCtrl.create(SelectForm);
modal.present();


text:
Q: How can I control Background Music of other Apps in Swift? First sorry for my English because I'm French.
I work on a connected object which send data to my app to start, pause, start the next music or the precedent and to augment the volume.
My application has to execute these actions on any music emitted by the iPhone. For example, if I listen to music in Spotify or Deezer, the app has to control it.
I don't know how I can do this in Swift. Just I really think that work with AVAudioSession.

A: I'm not sure what you're asking about, but I think this is what you mean. This will control the music playing on you device and the volume.
Here's an article about it : http://www.justindoan.com/tutorials/2016/7/31/mpmedia-tutorial-control-music-playback-in-ios-with-swift
So here's basically what you have to do. Firstly import MediaPlayer.
    import MediaPlayer

then you define the mediaController and prepare to play
    let mediaController = MPMusicPlayerController.systemMusicPlayer()
    mediaController.prepareToPlay()

and to control the media.
    //play
    mediaController.play()

    //pause
    mediaController.pause()

    //go to previous item
    mediaController.skipToPreviousItem()

    //go to start of the item
    mediaController.skipToBeginning()

    //and to go to the next item
    mediaController.skipToNextItem()

Hope this helps.


text:
Q: Python 2.7 - Tweepy - How to get rate_limit_status()? I am working on a twitter App using Python 2.7 and the latest version of the tweepy module.  One thing I cannot figure out is how to use the function rate_limit_status()
Here is my code:
import tweepy, time, sys, random, pickle
import pprint

# argfile = str(sys.argv[1])

#enter the corresponding information from your Twitter application:
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_KEY = ''
ACCESS_SECRET = ''

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)

api = tweepy.API(auth)
public_tweets = api.home_timeline()
user = api.get_user('@MyUserName')

print api.rate_limit_status()

When I print the results of the function it gives me a large dictionary that I cannot decipher.  I have looked at the tweepy documentation but can't find any good examples on using rate_limit_status().
What is the next step I should be doing to troubleshoot something like this?
Is there a tool to format these large dictionaries so I can read them and try to decipher how to access the values in the dictionary?
Edit:
It turns out I didn't have a good understanding of what a Rest API is and how simply it works!  I was expecting something MUCH more complicated in my head.
I actually switched to the twitter Python module twitter library instead of Tweepy and then did a lot of research on how to use the Twitter API.
Two youtube videos that REALLY helped me are:
https://www.youtube.com/watch?v=7YcW25PHnAA
and
https://www.youtube.com/watch?v=fhPb6ocUz_k
The Postman Chrome app was awesome and allowed me to easily test and visualize how my calls to the Twitter API worked and it easily formatted the resulting JSON to so I could read it.
To do quick calculations I also took the JSON from Postman and threw it into this website http://konklone.io/json/ to get a csv that I could then open in Excel and make sure everything was behaving as expected and that I was getting the right now number of results.
After all that, writing the Python code to interact with the Twitter API was easy!
Adding all this in this hopes it will help someone else in the future!  If it does please let me know! :)

A: As per the Tweepy documentation

Returns the remaining number of API requests available to the
  requesting user before the API limit is reached for the current hour.
  Calls to rate_limit_status do not count against the rate limit. If
  authentication credentials are provided, the rate limit status for the
  authenticating user is returned. Otherwise, the rate limit status for
  the requester's IP address is returned.

So in simpler words you can say that, it returns a JSON object in which tells you about the Number of requests you have made and Number of requests remaining, the reason why it is difficult to read at first sight lies in the face that, it contains the count for every type of API call that you have made and not only the current API call you just executed.
So for example if you run the above script, then, you can see that you have made a call to api.home_timeline() Now according to the twitter Rules and Regulations you can only make 15 calls to this method in a given window session, So if you unpack the JSON object returned then you can see that, there is a lot of data but if you analyse the data then, You will find that api.home_timeline() only affects limits of relevant methods, such as when calling above methods you can check the rate limit using:
data = api.rate_limit_status()

print data['resources']['statuses']['/statuses/home_timeline']
print data['resources']['users']['/users/lookup']

However you have to do a little bit of research on the JSON returned and then you can extract the relevant data from the JSON object, as the returned JSON objects are hard to read, you can always use these types of links to make it more user readable and then analyse it.


text:
Q: Are C/C++ library functions and operators the most optimal ones? So, at the divide & conquer course we were taught:

*

*Karatsuba multiplication

*Fast exponentiation

Now, given 2 positive integers a and b is operator::* faster than a karatsuba(a,b) or is pow(a,b) faster than
int fast_expo(int Base, int exp)
{
    if (exp == 0) {
        return 1;
    }
    if (exp == 1) {
        return Base
    }
    if (exp % 2 == 0) {
        return fast_expo(Base, exp / 2) * fast_expo(Base, exp / 2);
    }
    else {
        return base * fast_expo(Base, exp / 2) * fast_expo(Base, exp / 2);
    }
}

I ask this because I wonder if they have just a teaching purpose or they are already base implemented in the C/C++ language

A: Karatsuba multiplication is a special technique for large integers. It is not comparable to the built in C++ * operator which multiplies together operands of basic type like int and double.
To take advantage of Karatsuba, you have to be using multi-precision integers made up of at least around 8 words. (512 bits, if these are 64 bit words). The break-even point at which Karatsuba becomes advantageous is at somewhere between 8 and 24 machine words, according to the accepted answer to this question.
The pow function which works with a pair of floating-point operands of type double, is not comparable to your fast_expo, which works with operands of type int. They are different functions with different requirements. With pow, you can calculate the cube root of 5: pow(5, 1/3.0).  If that's what you would like to calculate, then fast_expo is of no use, no matter how fast.
There is no guarantee that your compiler or C library's pow is absolutely the fastest way for your machine to exponentiate two double-precision floating-point numbers.
Optimization claims in floating-point can be tricky, because it often happens that multiple implementations of the "same" function do not give exactly the same results down to the last bit. You can probably write a fast my_pow that is only good to five decimal digits of precision, and in your application, that approximation might be more than adequate. Have you beat the library? Hardly; your fast function doesn't meet the requirements that would qualify it as a replacement for the pow in the library.

A: operator::* and other standard operators usually map to the primitives provided by the hardware. In case, such primitives don't exist (e.g. 64-bit long long on IA32), the compiler emulates them at a performance penalty (gcc does that in libgcc).
Same for std::pow. It is part of the standard library and isn't mandated to be implemented in a certain way. GNU libc implements pow(a,b) as exp(log(a) * b). exp and log are quite long and written for optimal performance with IEEE754 floating point in mind.

As for your sugestions:
Karatsuba multiplication for smaller numbers isn't worth it. The multiply machine instruction provided by the processor is already optimized for speed and power usage for the standard data types in use. With bigger numbers, 10-20 times the register capacity, it starts to pay off:

In the GNU MP Bignum Library, there used to be a default
  KARATSUBA_THRESHOLD as high as 32 for non-modular multiplication
  (that is, Karatsuba was used when n>=32w with typically w=32);
  the optimal threshold for modular exponentiation tending to be
  significantly higher. On modern CPUs, Karatsuba in software tends to
  be non-beneficial for things like ECDSA over P-256 (n=256, w=32 or
  w=64), but conceivably useful for much wider modulus as used in RSA.

Here is a list with the multiplication algorithms, GNU MP uses and their respective thresholds.
Fast exponentiation doesn't apply to non-integer powers, so it's not really comparable to pow.

A: A good way to check the speed of an operation is to measure it.  If you run through the calculation a billion or so times and see how much time it takes to execute you have your answer there.
One thing to note.  I'm lead to believe that % is fairly expensive.  There is a much faster way to check if something is divisible by 2:
check_div_two(int number)
{
    return ((number>>1) & 0x01);
}

This way you've just done a bit shift and compared against a mask.  I'd assume it's a less expensive op.

A: The * operator for built-in types will almost certainly be implemented as a single CPU multiplication instruction. So ultimately this is a hardware question, not a language question. Longer code sequences, perhaps function calls, might be generated in cases where there's no direct hardware support.
It's safe to assume that chip manufacturers (Intel, AMD, et al) expend a great deal of effort making arithmetic operations as efficient as possible.


text:
Q: Updating Customer with REST API results in 500 Internal Server Error I'm updating AR Customer records via the Contract-Based REST API using PHP & Guzzle 6 and am getting a 500 Internal Server Error response back.
The error message in the response is:
{
   "message": "An error has occurred.",
   "exceptionMessage": "Unable to cast object of type 'PX.Api.ContractBased.Models.EntityValueField' to type 'PX.Api.ContractBased.Models.EntitySearchField'.",
   "exceptionType": "System.InvalidCastException",
   "stackTrace": "... see below ..."
}

Stack Trace:
at PX.Api.ContractBased.OData.FilterVisitor.SetNullableCondition(BinaryOperatorNode nodeIn, String nullCondition, String regularCondition)
at PX.Api.ContractBased.OData.FilterVisitor.VisitRoot(SingleValueNode root)
at PX.Api.ContractBased.OData.Helpers.FillRestQueryOptions(IEdmModel edmModel, EntityImpl entity, String filter, String select, String expand, String custom)
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

 My sincerest appologies for adding the entire stack trace, but I thought it might be helpful.

At first, I thought that it might have something to do with the URL of the request, but after looking at this answer from a similar question it does not appear to be related to the parameters passed in the URL?
I have already found a 'solution/workaround' by removing the CustomerID from the request body, but it seems a bit odd that this is needed in order to get the request to work?
I had a look at the documentation for updating a record, but don't see anything related to 'remove the key field when using the filter parameter in the request URL'.
This request returns the 500 Internal Server Error:
PUT entity/Default/18.200.001/Customer?$filter=CustomerID%20eq%20%27100000044%27&$select=CustomerID
{
   "CustomerClass": {
      "value": "CUSTOMER_CLASS"
   },
   "CustomerID": {
      "value": "100000044"
   },
   "CustomerName": {
      "value": "Christiaan Raubenheimer"
   },
   "MainContact": {
      "Address": {
         "AddressLine1": {
            "value": "Street Line 1"
         },
         "AddressLine2": {
            "value": "Stree Line 2"
         },
         "City": {
            "value": "City"
         },
         "Country": {
            "value": "ZA"
         },
         "PostalCode": {
            "value": "0000"
         },
         "State": {
            "value": "State"
         }
      },
      "Attention": {
         "value": "Christiaan Raubenheimer"
      },
      "DisplayName": {
         "value": "Company Name"
      },
      "Email": {
         "value": "...email address..."
      },
      "JobTitle": {
         "value": "Company Name"
      },
      "Phone1": {
         "value": "0000000000"
      }
   }
}

This request returns a 200 Success Response:
PUT entity/Default/18.200.001/Customer?$filter=CustomerID%20eq%20%27100000044%27&$select=CustomerID
{
   "CustomerClass": {
      "value": "CUSTOMER_CLASS"
   },
   "CustomerName": {
      "value": "Christiaan Raubenheimer"
   },
   "MainContact": {
      "Address": {
         "AddressLine1": {
            "value": "Street Line 1"
         },
         "AddressLine2": {
            "value": "Stree Line 2"
         },
         "City": {
            "value": "City"
         },
         "Country": {
            "value": "ZA"
         },
         "PostalCode": {
            "value": "0000"
         },
         "State": {
            "value": "State"
         }
      },
      "Attention": {
         "value": "Christiaan Raubenheimer"
      },
      "DisplayName": {
         "value": "Company Name"
      },
      "Email": {
         "value": "...email address..."
      },
      "JobTitle": {
         "value": "Company Name"
      },
      "Phone1": {
         "value": "0000000000"
      }
   }
}

In summary, it looks like it's required to remove the CustomerID from the request body as demonstrated above, but could it be that I am perhaps missing something?

A: The error is probably due to the fact that you are mixing multiple ways of selecting a record in order to update it.
You are using the 2 following ways:

*

*The Filter parameter in the URL

*The Key field in the body of the record

Please consider only using one of these method.


text:
Q: Error with Ruby and PDFKit on Appfog I'm trying to use PDFkit with Ruby on Rails on Appfog.
I am using the gem wkhtmltopdf-binary and have also tried changing the PDFKit config.wkhtmltopdf  path, as this answer on a related question suggests.
I always get this error:
PDFKit::NoExecutableError (No wkhtmltopdf executable found at ...

Also, whatever path I specify in the PDFKit config.wkhtmltopdf follows the at in the error message.
I'm a begginer at Ruby and RoR. All I did was put the example code given in the PDFKit docs in a welcome controller on the app and then ran it on the browser. Then I received the error in the browser We're sorry, but something went wrong. and finally I checked the logs of my application on Appfog.
What I need help with, and what I think complicates this, is the fact that the application is on Appfog. I can't install the binary of wkhtmltopdf and so I have no idea of how to do this.
Hope someone can help me :)


text:
Q: Current click position on map windows phone I google it many times but can't find a proper solution
i want to get currently clicked position on map in windows phone and add pushpin to that location so that it may be saved as a reminder

A: try this..
private void Map_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
     GeoCoordinate asd = this.Map.ConvertViewportPointToGeoCoordinate(e.GetPosition(this.Map));
}


text:
Q: Linking issues with leptonica and libpng Working through an install of tesseract without sudo permissions and without a standard bevy of prebuilt libraries. The installation I've got to go through as far as I know follows the path of zlib -> libpng -> leptonica -> tesseract.
Each installation by itself is successful, the main issues I'm running into is that for some reason leptonica cannot find the relevant libpng installation. Process below:
zlib:
 ./configure --prefix={dir}/local
 make
 make check
 make install

libpng:
 ./configure --prefix={dir}/local
 make
 make check
 make install

To confirm I check my installs and see that libpng appears to be installed:
JNG* PNG       rw-   JPEG Network Graphics
     MNG* PNG       rw+   Multiple-image Network Graphics (libpng 1.5.13)
     PNG* PNG       rw-   Portable Network Graphics (libpng 1.5.13)
          See http://www.libpng.org/ for details about the PNG format.
   PNG24* PNG       rw-   opaque 24-bit RGB (zlib 1.2.7,1.2.11)
   PNG32* PNG       rw-   opaque or transparent 32-bit RGBA
    PNG8* PNG       rw-   8-bit indexed with optional binary transparency

The issue though is that the libpng library referenced above is not the version I'm installing. For zlib I've installed 1.2.11, so that seems to be working. For libpng I'm installing 1.6.35, so while the make check and make install commands seem to be working, it's not being recognized. I've tried more manual linking. (env is csh and believe me I'd change it if I could.)
setenv PATH $PATH\:{dir}/local/bin
setenv LD_LIBRARY_PATH {dir}/local/lib
setenv LD_RUN_PATH {dir}/local/lib/

However, still not seeing the correct version of libpng show up.
Shows up in leptonica when I run ./configure --prefix={dir}/local:
checking for ZLIB... yes
checking for LIBPNG... no

So outside of versions, it's not finding any libpng library. Installing leptonica 1.74.4.
I'm very used to just installing everything under sudo so this is kind of new territory to me, and I'm unfamiliar with csh so part of me worried that I've mucked up my environment settings somehow. Any clue what's going on and how I can get leptonica to find libpng?


text:
Q: Pyspark RDD filter behaviour when filter condition variable is modified When the following code is run:
A = ss.sparkContext.parallelize(range(1, 100))
t = 50
B = A.filter(lambda x: x < t)
print(B.count())
t = 10
C = B.filter(lambda x: x > t)
print(C.count())

The output is:
49
0

Which is incorrect as there are 39 values between 10 and 49. It seems like changing t to 10 from 50 effected the first filter as well and it got re-evalutated so when both filters are applied consecutively it effectively becomes x<10 which would result in 1, 2, 3, 4, 5, 6 ,7, 8, 9 followed by x>10 resulting in an empty rdd.
But When I add debug prints in the code the result is not what I expect and I am looking for an explanation:
A = ss.sparkContext.parallelize(range(1, 100))
t = 50
B = A.filter(lambda x: x < t)
print(B.collect())
t = 10
print(B.collect())
print(B.count())
C = B.filter(lambda x: x > t)
print(C.collect())
print(C.count())

The output is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
9
[]
0

How come the count is 10 after t=10 but print(B.collect()) shows the expected rdd with values from 1 to 49? If triggering collect after changing t re-did the filter, then shouldn't collect() show values from 1-9?
I am new to pyspark, I suspect this has to do with spark's lazy operations and caching. Can someone explain what is going on behind the scenes?
Thanks!

A: Your assumption is correct, the observed behaviour is related to Spark's lazy evaluation of transformations.
When B.count() is executed, Spark simply applies the filter x < t with t = 50 and prints the expected value of 49.
When C.count() is executed, Spark sees two filters in the excution plan of C, namely x < t and x > t. At this point in time t has been set to 10 and no element of the rdd satiesfies both conditions to be smaller and larger than 10. Spark ignores that fact that the first filter has already been evaluated. When a Spark action is called all transformations in the history of the current rdd are executed (unless some intermediate result has been cached, see below).
A way to examine this behaviour (a bit) more in details is to switch to Scala and print toDebugString for both rdds.1
println(B.toDebugString)

prints
(4) MapPartitionsRDD[1] at filter at SparkStarter.scala:23 []
 |  ParallelCollectionRDD[0] at parallelize at SparkStarter.scala:19 []

while
println(C.toDebugString)

prints
(4) MapPartitionsRDD[2] at filter at SparkStarter.scala:28 []
 |  MapPartitionsRDD[1] at filter at SparkStarter.scala:23 []
 |  ParallelCollectionRDD[0] at parallelize at SparkStarter.scala:19 []

Here we can see that for rdd B one filter is applied and for rdd C two filters are applied.
How to fix the issue?
If the result of the first filter is cached the expected result is printed out. When then t is changed and the second filter is applied C.count() only triggers the second filter based on the cached result of B:
A = ss.sparkContext.parallelize(range(1, 100))
t = 50
B = A.filter(lambda x: x < t).cache()
print(B.count())
t = 10
C = B.filter(lambda x: x > t)
print(C.count())

prints the expected result.
49
39

1 Unfortunately this works only in the Scala version of Spark. PySpark seems to "condense" the output of toDebugString (version 3.1.1).


text:
Q: Filling NaN using groupby dict I am attempting to replace the NaN in the 'cylinders' column using a dictionary with the median model cylinder number. I think it should work easily but I have been getting stuck each way I try.
cylinders_model_med = df.groupby('model').agg({'cylinders': 'median'})

cylinders_model_med=cylinders_model_med.to_dict()

#output:

  'bmw x5': 6.0,
  'buick enclave': 6.0,
  'cadillac escalade': 8.0,
  'chevrolet camaro': 6.0,
  'chevrolet camaro lt coupe 2d': 6.0,
  'chevrolet colorado': 5.0,
  'chevrolet corvette': 8.0,
  'chevrolet cruze': 4.0,
  'chevrolet equinox': 4.0,
  'chevrolet impala': 6.0,
  'chevrolet malibu': 4.0,
  'chevrolet silverado': 8.0,
  'chevrolet silverado 1500': 8.0,
  'chevrolet silverado 1500 crew': 8.0,
  'chevrolet silverado 2500hd': 8.0,
  'chevrolet silverado 3500hd': 8.0,
  'chevrolet suburban': 8.0,
  'chevrolet tahoe': 8.0,
  'chevrolet trailblazer': 6.0,
  'chevrolet traverse': 6.0,
  'chrysler 200': 4.0,
  'chrysler 300': 6.0,
  'chrysler town & country': 6.0,
  'dodge charger': 6.0,
  'dodge dakota': 6.0,
  'dodge grand caravan': 6.0,
  'ford econoline': 8.0,
  'ford edge': 6.0,
  'ford escape': 4.0,
  'ford expedition': 8.0,
  'ford explorer': 6.0,
  'ford f-150': 8.0,
  'ford f-250': 8.0,
  'ford f-250 sd': 8.0,
  'ford f-250 super duty': 8.0,
  'ford f-350 sd': 8.0,
  'ford f150': 8.0,
  'ford f150 supercrew cab xlt': 6.0,
  'ford f250': 8.0,
  'ford f250 super duty': 8.0,
  'ford f350': 8.0,
  'ford f350 super duty': 8.0,
  'ford focus': 4.0,
  'ford focus se': 4.0,
  'ford fusion': 4.0,
  'ford fusion se': 4.0,
  'ford mustang': 6.0,
  'ford mustang gt coupe 2d': 8.0,
  'ford ranger': 6.0,
  'ford taurus': 6.0,
  'gmc acadia': 6.0,
  'gmc sierra': 8.0,
  'gmc sierra 1500': 8.0,
  'gmc sierra 2500hd': 8.0,
  'gmc yukon': 8.0,
  'honda accord': 4.0,
  'honda civic': 4.0,
  'honda civic lx': 4.0,
  'honda cr-v': 4.0,
  'honda odyssey': 6.0,
  'honda pilot': 6.0,
  'hyundai elantra': 4.0,
  'hyundai santa fe': 6.0,
  'hyundai sonata': 4.0,
  'jeep cherokee': 6.0,
  'jeep grand cherokee': 6.0,
  'jeep grand cherokee laredo': 6.0,
  'jeep liberty': 6.0,
  'jeep wrangler': 6.0,
  'jeep wrangler unlimited': 6.0,
  'kia sorento': 4.0,
  'kia soul': 4.0,
  'mercedes-benz benze sprinter 2500': 6.0,
  'nissan altima': 4.0,
  'nissan frontier': 6.0,
  'nissan frontier crew cab sv': 6.0,
  'nissan maxima': 6.0,
  'nissan murano': 6.0,
  'nissan rogue': 4.0,
  'nissan sentra': 4.0,
  'nissan versa': 4.0,
  'ram 1500': 8.0,
  'ram 2500': 6.0,
  'ram 3500': 6.0,
  'subaru forester': 4.0,
  'subaru impreza': 4.0,
  'subaru outback': 4.0,
  'toyota 4runner': 6.0,
  'toyota camry': 4.0,
  'toyota camry le': 4.0,
  'toyota corolla': 4.0,
  'toyota highlander': 6.0,
  'toyota prius': 4.0,
  'toyota rav4': 4.0,
  'toyota sienna': 6.0,
  'toyota tacoma': 6.0,
  'toyota tundra': 8.0,
  'volkswagen jetta': 4.0,
  'volkswagen passat': 4.0}}
#input:
df['cylinders']=df['cylinders'].fillna(cylinders_model_med)
df['cylinders'].isna().sum()
#output
5260

This is the same number of NaN I started with.
I am new here so let me know if you need more (or less) information.
Thank you for your time!

A: Alignment in pandas is based on index, so you need to create defaults which either you explicitly align to your dataframe or which will be aligned automatically. The easiest way to do this would be to create a default series with the same index as df using replace:
defaults = df['model'].replace(cylinders_model_med)
df['cylinders'] = df['cylinders'].fillna(defaults)

See the docs for more info: vectorized operations and label alignment

A: Filling in NaN values from corresponding values is what combine_first does for a living. You could calculate the median cylinder number by model then fill in the original dataframe NaN cylinder numbers by model.
Assume this starting dataframe
            model  cylinders
0   nissan maxima        6.0
1   nissan maxima        6.0
2   nissan maxima        4.0
3   nissan murano        6.0
4   nissan murano        NaN
5   nissan murano        4.0
6   nissan murano        6.0
7    nissan rogue        4.0
8    nissan rogue        4.0
9    nissan rogue        NaN
10   nissan rogue        6.0
11  nissan sentra        6.0
12  nissan sentra        4.0
13  nissan sentra        4.0
14   nissan versa        4.0
15   nissan versa        4.0
16   nissan versa        NaN
17   nissan versa        4.0

Calculate the median cylinders by model and fill in the NaNs
df.assign(cylinders=df['cylinders'].combine_first(df[['model','cylinders']].groupby('model').transform('median').squeeze()))

Result
            model  cylinders
0   nissan maxima        6.0
1   nissan maxima        6.0
2   nissan maxima        4.0
3   nissan murano        6.0
4   nissan murano        6.0
5   nissan murano        4.0
6   nissan murano        6.0
7    nissan rogue        4.0
8    nissan rogue        4.0
9    nissan rogue        4.0
10   nissan rogue        6.0
11  nissan sentra        6.0
12  nissan sentra        4.0
13  nissan sentra        4.0
14   nissan versa        4.0
15   nissan versa        4.0
16   nissan versa        4.0
17   nissan versa        4.0


text:
Q: Argument of type 'User' is not assignable to parameter of type 'EntityTarget' I'm sending an "Entity" to the function and using it inside the function. But it is giving me this error.
export type Entities = User | Blog | Service

import AppDataSource from '../database'
import { Entities } from '../entity/index'
import User from '../entity/User'

const getList = async (entity: Entities) => {
  const list = (await AppDataSource.manager.find(entity))
}

Argument of type 'Entities' is not assignable to parameter of type 'EntityTarget'.
Type 'User' is not assignable to type 'EntityTarget'.

enter image description here

A: you need to extend from EntityTarget:
export interface User extends EntityTarget<unknown> {}
export interface Blog extends EntityTarget<unknown> {}
export interface Service extends EntityTarget<unknown> {}

export type Entities = User | Blog | Service

import AppDataSource from '../database'
import { Entities } from '../entity/index'
import User from '../entity/User'

const getList = async (entity: Entities) => {
  const list = (await AppDataSource.manager.find(entity))
}

A: I got such an error in the code above "'X' type argument cannot be assigned to 'X' type parameter" I did it this way to solve the problem:
import { EntityTarget } from 'typeorm'
import AppDataSource from '../database'

export type _User = EntityTarget<'User'>
export type _Blog = EntityTarget<'Blog'>
export type _Service = EntityTarget<'Service'>

export type Entities = _User | _Blog | _Service

export const getList = async (entity: Entities) => {
  const list = (await AppDataSource.manager.find(entity))
}

But I'm not sure if it's healthy

A: I solved the problem this way, it seems more logical. Thanks
import { EntityTarget } from 'typeorm'
import AppDataSource from '../database'

const getList = async <E>(entity: EntityTarget<E>) => {
  const list = await AppDataSource.manager.find(entity)
}


text:
Q: DNS issues on a single Wifi - Linux Mint 19.1 I'm having DNS problems with one WiFi network which I've been using for a long time. I tried to do an hotspot with my phone and everything worked as normal, so the issue is only on that network.
ping 8.8.8.8 works, but
nslookup google.com
;; Got SERVFAIL reply from 127.0.0.53, trying next server
;; connection timed out; no servers could be reached

I've tried to install resolvconf and other solutions found online but none of them worked.
This is the content of /etc/resolv.conf (after adding nameserver 8.8.8.8 in /etc/resolvconf/resolv.conf.d/tail):
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
# 127.0.0.53 is the systemd-resolved stub resolver.
# run "systemd-resolve --status" to see details about the actual nameservers.

nameserver 127.0.0.53
search station
nameserver 8.8.8.8

A: The solution I found was to

*

*Make sure Dnsmasq is installed (sudo apt-get install dnsmasq)

*add dns=dnsmasq in the [main] section of /etc/NetworkManager/NetworkManager.conf


text:
Q: Query Firebase for highest id, then add to it I need help with a Firebase query. I'm using AngularFire2 at the moment.
I've been struggling with this for days. Read every document, watched every YouTube video, and asked many people, but I'm getting nowhere..
My Firebase structure is something like this:
ROOT
    jobs
        KYLigf4dFBvTTstR1Wy
            id: "1"
            customer: "Jeff F"
            description: "Repair a chair"
        KYLigACCViJVQffEoRl
            id: "2"
            customer: "Quick G"
            description: "Install a light bulb"
        KYLigSQasdCR3XfQ8WN
            id: "3"
            customer: "Justin S"
            description: "Do everything for everyone"
        KYLiddsfdsgWCKhjoiB
            id: "4"
            customer: "Heather D"
            description: "Have a baby"

So I need to fetch the highest ID. Then I need to add a new entry to the list using the next id. In this case it would be 5. That's it, that's all I need. And I'm pulling my hair out trying to do it.
I've tried a million different ways, but the problem comes when I try to use push(), everything falls apart, so I just can't find the proper path to go down here.
I guess another way of saying this is, that I would like to pull the highest ID from Firebase, then save it to a variable that changes with it. Then I could just access that variable whenever I needed to get the latest id - since the number will always be changing.

A: One possible solution would be to create a second node that tracks the next ID.
When you insert a new Job, follow up the insert with an update to the nextJobId node to increment the ID. This would simplify the need to retrieve the next ID.
Keep in mind that with Firebase the data structure is denormalized. Its okay to create additional nodes to make reads faster.
ROOT
jobs
    KYLigf4dFBvTTstR1Wy
        id: "1"
        customer: "Jeff F"
        description: "Repair a chair"
    KYLigACCViJVQffEoRl
        id: "2"
        customer: "Quick G"
        description: "Install a light bulb"
    KYLigSQasdCR3XfQ8WN
        id: "3"
        customer: "Justin S"
        description: "Do everything for everyone"
    KYLiddsfdsgWCKhjoiB
        id: "4"
        customer: "Heather D"
        description: "Have a baby"
nextJobId: 5 // Create an index that provides the next Id.

A: Use Firebase's weird "KYLigf4dFBvTTst..." keys as your id
We are all more comfortable with conventional id's like 1, 2, 3, and therefore bend over backwards trying to find ways of generating them. However, the need to create a conventional id has created a complicated problem for you.
Firebase's weird-looking auto-generated keys are actually designed to solve your problem. They have the features of an incrementing id, i.e. they tell you the date order of creation, and also effectively provide uniqueness like a UUID.
Importantly, they allow multiple clients who are offline to still generate very-likely time-ordered and unique id's.
Firebase keys can be generated off-line
They are not just strange to look at, they are also magically able to be generated without an internet connection.
The process that generates them,
.push

is a pure client-side operation, that can run (for example) in your browser while you are not connected to the net. It does not send anything to the database.
The relevance of this is that the firebase key can be generated and discarded at will without penalty, and you can generate as many of them as you like: only when you actually write content into the key does anything actually happen in the database.
Let go of 1,2,3
They are from the pre-connected era.
I am  thinking of teaching my baby daughter to count in Firebase Id's instead...


text:
Q: VBA Fax using fax server on server from computer on network I am running Windows Server 2008 R2.  I installed the fax server role on the server.  I am able to fax documents using the external fax modem attached to the server from computers attached to the network by printing the documents and selecting "Fax on MYSERVER".  I am able to fax a .pdf using the following code (which I got from mdsn.microsoft.com) from the server but not from any other computer even when logged into the computer using the administrator account.
Sub fax_report(location_fax_number, report_name, fax_location, fax_file_path)
    Dim objFaxDocument As New FAXCOMEXLib.FaxDocument
    Dim objFaxServer As New FAXCOMEXLib.FaxServer
    Dim JobID As Object

    On Error GoTo Err_Clear

Err_Clear:
    If Err <> 0 Then
        Err.Clear
        Resume Next
    End If

    'Connect to the fax server
    objFaxServer.Connect ("\\MYSERVER")

    'Set the fax body
    objFaxDocument.Body = fax_file_path

    'Name the document
    objFaxDocument.DocumentName = report_name

    objFaxDocument.Recipients.add (location_fax_number)

    JobID = objFaxDocument.ConnectedSubmit(objFaxServer)

    objFaxServer.Disconnect

End Sub

The error I'm getting is:

*

*Description: "Operation failed"

*HelpContext: 1000440

*HelpFile: "C:\Program Files (x86)\Common Files\Microsoft
Shared\VBA\VBA7.1\1033\VbLR6.chm"

*LastDllError: 0

*Number: -2147023741

*Source: "FaxComEx.FaxDocument.1"

Although I am able to fax a .pdf from the server when I try from a computer on the network it fails.  I am able to send a .txt file fro a computer on the network.  It looks like the .pdf isn't automatically being converted to a .tiff file like it is when I run the code on the server.  When I run the code from the server Adobe Acrobat Reader DC opens, the .pdf is opened and converted then faxed without error.  Adobe stays open and I can see a temp file was created, it isn't available to be opened from the recent file lists menu.

A: I figured out the solution.  I needed to set Adobe Acrobat Reader DC as the default program to handle .pdfs on the remote computers.


text:
Q: Will you/won't you?
Help yourself to a drink, _________?
A. Will you
B. Won't you

According to the answer sheet, B is the answer because the question is in fact an offer made to someone and B is more polite. Does that make A incorrect? What about "would"? That can fit in the sentence too. What difference do these 3 make in the meaning? Plus, is B really more polite? It seems kind of frustrated to me.

A: Well, either is grammatically correct, but they have different meanings.
When using question tags, we use the negative form of what we want/mean. According to this eslbase.com page:

If the auxiliary verb in the sentence is affirmative, the tag is negative.

You're Spanish, aren't you?

If the auxiliary verb in the sentence is negative, the tag is affirmative.

You're not Spanish, are you?

So, "Help yourself to a drink, won't you?" implies the opposite: you should help yourself to a drink. It is therefore a polite offer.
"Help yourself to a drink, will you?" implies the opposite: you shouldn't help yourself to a drink. It might be used in situations such as someone random walking into a private party, and taking a drink. It might be followed up with some aggressive behaviour by the person who said it to the person who took the drink.

Just to make it confusing, I've thought of another meaning of "Help yourself to a drink, will you?". It could be used when the speaker is frustrated that somebody hasn't done something already. It would usually have the word "just"  at the beginning:

Just help yourself to a drink, will you?

I can't think of any grammatical "rule" for this usage. But it certainly isn't a polite offer. In speech you could tell this apart from the "aggressive / you shouldn't have done that" meaning above by the stress, emphasis and speech pattern/timing. I can't work out how to make that clear in writing, as the "will" will be stressed in both versions. In writing the context should make it clear which is used.


text:
Q: Server-Sent Event connections are not closed despite calling `close()` I want to programmatically close the Server-Sent-Events once a user logs out. However when the user logs back in, the browser does not execute any https-requests anymore because it has reached its limit of SSE connections.
I'm using EventSource for listening to events.
This is how I close my connections:
var eventSource;
function onChange(accountId:string, callback){
    var url = "...";

    eventSource = new EventSource(url);

    if(eventSource){
        eventSource.addEventListener("put", callback);
    }
}

function close(){
    this.eventSource.close()
}

When I was observing the network connections on the browser, I realized the connection still exists. The output in Timing is: Caution: request is not finished yet!, the following event-streams are stalled due to limited number of connections.
I'm not sure if EventSource is designed to behave like this, but I could not find anything regarding this issue, since many people don't have the same scenario.
Everytime I reload the page in my browser (chrome) all existing connections are closed, but I don't want to reload the page to workaround this issue.

A: Make sure that this.eventSource is referring to what you think it is. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this  If called from an event handler it won't be the global scope.
After calling xxx.close(), set xxx to null. (I doubt that is the problem, but it might help the garbage collection, and also helps find bugs.)
As a 3rd idea of the problem, avoid giving globals the same name as built-in objects. I normally use es for my event source objects.


text:
Q: Not able to create executable jar for webdriver+TestNg project which does not contain main method in any class I am learning webdriver and I have created one project with TestNg.
I have several classes in my package under src folder.
No class contains public static void main(....). i.e[Entry Point]
My question is :
Can we create Runnable / Executable jar file through eclipse for projects like this[project without main method]. I searched on many sites but unfortunately didnt get solution.
Please suggest me some links OR The way by which we can do this.

A: To create a jar file of the TestNG without main method you have to create another class which contain main method.
Suppose you have a TestNG file name as Sample.java, in the same package create one more class as ExecutableRar and write the below code :
public class ExecutableRar {

public static void main(String[] args) {
    TestNG testng = new TestNG();
     Class[] classes = new Class[]{Sample.class};
     testng.setTestClasses(classes);
     testng.run();

}

Now you can run this class as a Java Application. Then right click on the package --> Export --> Java --> Runnable jar File --> select ExecutableRar in launch configuration --> Browse the file location and enter the name of the file in Export Destination --> Finish.
Please let me know if you are having any issues.


text:
Q: Python – visualise correlation in data I have a dataframe and want to identify how the variables are correlated. I can get the correlation matrix easily using – df.corr(). I know I can easily plot the correlation matrix using plt.matshow(df.corr()) or seaborn's heatmap, but I'm looking for something like this - graph

taken from here. In this image, the thicker the line connecting the variables is, the higher the correlation.
I did a few searches on stack and elsewhere but all of them are correlation matrices where the values have been replaced by colors. Is there a way to achieve the linked plot?


text:
Q: Is there an antenna problem with CAN Bus selectable split termination header pin? I am trying to implement a jumper-selectable CAN Bus termination with a SPLIT configuration, as shown in this Analog Devices example:

https://www.analog.com/media/en/technical-documentation/user-guides/DC2063AF.PDF
It occurred to me that there might be a big antenna when the jumper is removed. The 0.3" header pins on JP2 might radiate at 1Mhz since they are connected to CANH and CANL.
Is this a potential noise problem? If so, would a good way to eliminate the problem be to move the capacitor on SPLIT to the other side of the jumper, so it can attenuate the antenna signal?
Before:

After:

Edit 1 Here is my full "before" schematic to show the rest of the circuit.


text:
Q: Why it returns me segmention fault (core dumbed)? After putting two strings, it returns me
segmention fault (core dumbed)
I'm running the code with gcc. Valgrind writes that there are no errors. Tried to write code that decrypts text using the Caesar method. First I enter the text to be decoded, and the second text shows how far I need to move the letters in the first text. That is, the distance is selected at which there is more correspondence in letters between the received text and the second entered text. I carefully checked everything, for me it seems that there are really no errors, or I'm just not well versed in working with memory.
Here's example
inputs
xUbbemehbT
XYlloworld
should return
Helloworld
I really don't understand why it returns me that, here is code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define INT_MSG_LEN 50;

enum {NO_ERROR = 0,
      ERROR_INPUT = 100,
      ERROR_LEN = 101};

static const char *error_texts[] = { "Error input!",
                                     "Error lenght"};

void shift(char *msgEnc, char *msg, char *msgRes, char *mainMsg, char *alphabet, int offset);
void report_error(int error);
void print_error(int error);
int get_sameletters(char *msg, char *msgRes, int offset);
int get_letter(char letter, char *alphabet);
int compare(char *msgEnc, char *msg, char *msgRes, char *alphabet, int offset);
char *read_Input_Msg(int *msglen);

int main(int argc, char *argv[])
{
    int ret = NO_ERROR;
    char *msgEnc, *msg, *msgRes, *mainMsg, alphabet[53] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int msgEncLen, msgLen;

    msgEnc = msg = msgRes = mainMsg = NULL;
    msgEncLen = msgLen = 0;

    msgEnc = read_Input_Msg(&msgEncLen);
    if (msgEnc)
        msg = read_Input_Msg(&msgLen);

    if (msgEnc == NULL || msg == NULL)
        ret = ERROR_INPUT;
    else if (msgEncLen != msgLen)
        ret = ERROR_LEN;

    if (ret == NO_ERROR)
        shift(msgEnc, msg, msgRes, mainMsg, alphabet, msgEncLen);
    else
        print_error(ret);

    free(msgEnc);
    free(msg);
    free(msgRes);
    free(mainMsg);
    return ret;
}

void shift(char *msgEnc, char *msg, char *msgRes, char *mainMsg, char *alphabet, int offset)
{//function for decoding text by a defined offset
    int dis;
    dis = compare(msgEnc, msg, msgRes, alphabet, offset);
    for (int i = 0; i<offset-1; ++i){
        if ((msgEnc[i] >= 'a' && msgEnc[i] <= 'z') || (msgEnc[i] >= 'A' && msgEnc[i] <= 'Z')){
            mainMsg[i] = msgEnc[i+dis];
            break;
        }
    }
    for(int i = 0; i<offset-1; ++i)
        printf("%c", mainMsg[i]);
}

void report_error(int error)
{//prints error
    if (error >= ERROR_INPUT && error <= ERROR_LEN)
        fprintf(stderr, "%s\n", error_texts[error - ERROR_INPUT]);
}

void print_error(int error)
{//what error it is
    switch (error){
        case ERROR_INPUT:
            report_error(ERROR_INPUT);
            break;
        case ERROR_LEN:
            report_error(ERROR_LEN);
            break;
    }
}

int get_sameletters(char *msg, char *msgRes, int offset)
{//gets count of sameletters between two strings
    int sameLetters = 0;
    for (int i = 0; i<offset-1; ++i){
        if (msg[i] == msgRes[i])
            sameLetters++;
    }
    return sameLetters;
}

int get_letter(char letter, char *alphabet)
{
    int k;
    for (int i=0; alphabet[i]; ++i){
        if (letter == alphabet[i])
            k = i;
    }
    return k;
}

int compare(char *msgEnc, char *msg, char *msgRes, char *alphabet, int offset)
{//calculate a distance between first input string and string what will get after decryption
    int distance, max = 0;
    for (int i = 0; alphabet[i]; ++i){
        for (int j = 0; msgEnc[j]; ++j){
            if ((msgEnc[i] >= 'a' && msgEnc[i] <= 'z') || (msgEnc[i] >= 'A' && msgEnc[i] <= 'Z'))
                msgRes[j] = alphabet[(get_letter(msgEnc[j], alphabet) + i) % 52];
            }
            int sameLetters = get_sameletters(msg, msgRes, offset);
            if (sameLetters > max){
                max = sameLetters;
                distance = i;
        }
    }
    return distance;
}

char *read_Input_Msg(int *msglen)
{//input messages, at the same time counts the length of the entered string
    int capacity = INT_MSG_LEN;
    char *msg = malloc(capacity);
    int c, len = 0;
    while ((c = getchar()) != EOF && c != '\n'){
        if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
            free(msg);
            msg = NULL;
            len = 0;
            break;
        }
        if (len == capacity){
            char *tmp = realloc(msg, capacity * 2);
            if (tmp == NULL){
                free(msg);
                msg = NULL;
                len = 0;
                break;
            }
            capacity *= 2;
            msg = tmp;
        }
        msg[len++] = c;
    }
    *msglen = len;
    return msg;
}

A: You fail because you call shift with msgres == null
msgEnc = msg = msgRes = mainMsg = NULL; <<<<==========
msgEncLen = msgLen = 0;

msgEnc = read_Input_Msg(&msgEncLen);
if (msgEnc)
    msg = read_Input_Msg(&msgLen);

if (msgEnc == NULL || msg == NULL)
    ret = ERROR_INPUT;
else if (msgEncLen != msgLen)
    ret = ERROR_LEN;

if (ret == NO_ERROR)
    shift(msgEnc, msg, msgRes, mainMsg, alphabet, msgEncLen);  <<<<======

A: here is valgrind complaining, I know this is not an answer but you seem to have a problem with your valgrind, maybe this will help
==7662== Invalid write of size 1
==7662==    at 0x1096C9: compare (hello.c:110)
==7662==    by 0x1093CF: shift (hello.c:55)
==7662==    by 0x109338: main (hello.c:41)
==7662==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==7662==
==7662==
==7662== Process terminating with default action of signal 11 (SIGSEGV)
==7662==  Access not within mapped region at address 0x0
==7662==    at 0x1096C9: compare (hello.c:110)
==7662==    by 0x1093CF: shift (hello.c:55)
==7662==    by 0x109338: main (hello.c:41)

110 is this line
msgRes[j] = alphabet[(get_letter(msgEnc[j], alphabet) + i) % 52];


text:
Q: MapFragment with Navigation Drawer I'm following this tutorial to make a navigation drawer :
https://github.com/codepath/android_guides/wiki/Fragment-Navigation-Drawer
One of my fragment is a map defined as below :
XML

<fragment  android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.MapFragment" />

    <FrameLayout android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        /*Some texts and buttons */
    </FrameLayout>
</RelativeLayout>

Java
public class MapsFragment extends Fragment implements AsyncResponse {

    private View mView;
    private GoogleMap mMap;
    private LayoutInflater mInflater;
    private Bundle savedInstanceState;
    private CustomButton mCancelButton;
    private CustomButton mPeekButton;
    private boolean mActivityPaused;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    mPeeks = new ArrayList();
    mGson = new Gson();
    mInflater = inflater;
    mIsPaneOpen = false;
    mMarkerMap = new HashMap();

    if (mView != null) {
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null)
            parent.removeView(mView);
        }
        try {
            mView =  mInflater.inflate(R.layout.activity_maps, container, false);
        } catch (InflateException e) {
            e.printStackTrace();
        }

        setUpMapIfNeeded();

        mCancelButton = (CustomButton) mView.findViewById(R.id.bt_cancel);
        return mView;

    }

    public void setUpMapIfNeeded(){
        if (mMap == null){
            mMap = ((MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.map)).getMap();
            if (mMap != null)
                setUpMap();
        }
    }

    private void setUpMap() {
        mMap.setMyLocationEnabled(true);
        //Some code
    }
}

I voluntarily delete some irrelevant code.
Then i have the main activity :
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.widget.DrawerLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/drawer_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

            <!-- The ActionBar -->
            <include
                    layout="@layout/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

            <!-- The main content view -->
            <FrameLayout
                    android:id="@+id/flContent"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
        </LinearLayout>

        <!-- The navigation drawer -->
        <android.support.design.widget.NavigationView
                android:id="@+id/nvView"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="start"
                android:background="@android:color/white"
                app:menu="@menu/drawer_view" />
    </android.support.v4.widget.DrawerLayout>
</LinearLayout>

Java
public class MainActivity extends AppCompatActivity {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    //Manager de Fragment
    DrawerLayout mDrawer;                                  // Declaring DrawerLayout
    Toolbar mToolbar;
    Fragment currentFrag;
    FragmentManager mFragmentManager;
    Fragment mMapFragment;
    Fragment mUserFragment;
    Fragment mThirdFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFragmentManager =  getSupportFragmentManager();

        mMapFragment = new MapsFragment();
        mUserFragment = new UserFragment();
        mThirdFragment = new ThirdFragment();
        //Initializing the first Fragment
        mFragmentManager.beginTransaction().replace(R.id.flContent, new MapsFragment()).commit();

        // Set a Toolbar to replace the ActionBar.
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        // Set the menu icon instead of the launcher icon.
        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setDisplayHomeAsUpEnabled(true);
        // Find our drawer view
        NavigationView nvDrawer = (NavigationView) findViewById(R.id.nvView);
        // Setup drawer view
        setupDrawerContent(nvDrawer);
    }

    //First We Declare Titles And Icons For Our Navigation Drawer List View
    //This Icons And Titles Are holded in an Array as you can see

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawer.openDrawer(GravityCompat.START);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }
    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        selectDrawerItem(menuItem);
                        return true;
                    }
                });
    }

    public void selectDrawerItem(MenuItem menuItem) {
        // Create a new fragment and specify the planet to show based on
        // position

        Fragment fragment = null;
        switch(menuItem.getItemId()) {
            case R.id.nav_map:
                fragment = mMapFragment;
                break;
            case R.id.nav_profile:
                fragment = mUserFragment;
                break;
            case R.id.nav_nav_settings:
                fragment = mThirdFragment;
                break;
            default:
                fragment = mMapFragment;
        }

        // Insert the fragment by replacing any existing fragment

        mFragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();

        // Highlight the selected item, update the title, and close the drawer
        menuItem.setChecked(true);
        setTitle(menuItem.getTitle());
        mDrawer.closeDrawers();
    }

}

The problem is, When i attach de MapFragment for the first time, no problem, the Activity displays the map. But when i tried to go to another fragment through the navigation drawer then went back to the the map fragment i have this exception :
07-19 16:04:25.710  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ android.view.InflateException: Binary XML file line #12: Error inflating class fragment
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at fr.yougraph.homelesspasseul.fragment.MapsFragment.onCreateView(MapsFragment.java:93)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:739)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.os.Looper.loop(Looper.java:145)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5944)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ Caused by: java.lang.IllegalArgumentException: Binary XML file line #12: Duplicate id 0x7f0e0099, tag null, or parent id 0x7f0e0098 with another fragment for com.google.android.gms.maps.MapFragment
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2135)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.app.Activity.onCreateView(Activity.java:5610)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v7.app.AppCompatDelegateImplV11.callActivityOnCreateView(AppCompatDelegateImplV11.java:41)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:826)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:181)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:732)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ ... 18 more
07-19 16:04:25.740  12380-12380/fr.yougraph.homelesspasseul D/AndroidRuntime﹕ Shutting down VM
07-19 16:04:25.740  12380-12380/fr.yougraph.homelesspasseul E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: fr.yougraph.homelesspasseul, PID: 12380
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
            at fr.yougraph.homelesspasseul.fragment.MapsFragment.onCreateView(MapsFragment.java:123)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5944)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)

The first exception, due to duplicate mapfragment, leads to let mView null and I can't perform a findViewById.
I can't see where i'm wrong with this, i used a pager strip before, and the switch between fragments worked well, so as the map.
Thanks for your help
By the way I tried solutions given in those questions :
Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment
Error inflating class fragment: Duplicate id , tag null, or parent id with another fragment
None worked

A: I think the duplicates come from: In onCreated of MainActivity you call setupDrawerContent, which calls selectDrawerItem which sets up your fragment = mMapfragment by default, but previously in Oncreate you already created another MapsFragment in this line:

*

*mFragmentManager.beginTransaction().replace(R.id.flContent, new
MapsFragment()).commit();

So my suggestion is to try to change initialization to mMapFragment which you already declared:

*

*mFragmentManager.beginTransaction().replace(R.id.flContent,
mMapFragment).commit();