text:
Q: ERROR: Error: Request timed out - InfluxDB sitespeed.io I have a problem saving data in an influxdb database, for information I use a docker machine that contains InfluxDb + Grafana, I do not know where it comes from this error?
Screenshot Error

A: Try create docker network and run sitespeed in this network:
docker network create influxdb
docker run -p 8086:8086  -d --name=influxdb --net=influxdb influxdb
docker run --shm-size=1g --rm -v "$(pwd)":/sitespeed.io --net=influxdb sitespeedio/sitespeed.io https://www.sitespeed.io  --influxdb.host=influxdb --influxdb.username=admin --influxdb.password=admin


text:
Q: Creating TermDocumentMatrix in Python 2.7 with textmining package (attribute error) Im trying to make a TermDocumentMatrix in Python using the textmining package. The following code causes an error:
CODE:
import textmining
tdm = textmining.TermDocumentMatrix()

ERROR:
File "<ipython-input-7-50b739ce2532>", line 1, in <module>
    tdm = textmining.TermDocumentMatrix()

AttributeError: 'module' object has no attribute 'TermDocumentMatrix'

Thank you for the help!

A: I've got the same problem with Python v2.7.
Unfortunately it has to do with an older version this package has been made.
We shouldn't have this problem with Python v2.5 or lower.
I've read somewhere that there must be a way to convert this 'old' package, so it's compatible with the newer versions of Python.
I'll keep you posted when I know more about this compatibility error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular UI Modal causes Infinite Digest Loop I have been struggling with creating a system to allow articles to be retrieved and opened in a modal pop-up window. It has been implemented successfully using the Bootstrap modal, but due to some new requirements I need to convert to using the Angular UI Modal.
I think the issue is stemming from my handling of URL changes by Angular's $location.search(), but I can't pinpoint it.
Since adding the $uibModal.open() call, this infinite digest loop occurs whenever I click on an article, this launching the openModal function in my controller.
I will include my controller code and the error message I receive below. The two points of entry to the controller are near the bottom at the $rootScope.$on and $scope.$watch calls. They allow the modal to respond to changes in the URL.
The end goal is the ability to open an Angular UI modal when the URL changes, so that I can remove the URL params when the modal is dismissed.
Thanks for any help!
My controller:
(function () {
    'use strict';

    //Create the LinkModalController and bind it to the core app. This makes it always available.
    angular
        .module('app.core')
        .controller('LinkModalController', LinkModalController);

    LinkModalController.$inject = ['$location', '$q', '$rootScope', '$scope', '$uibModal', 'contentpartservice', 'logger'];
    /* @ngInject */

    function LinkModalController($location, $q, $rootScope, $scope, $uibModal, contentpartservice, logger) {
        var vm = this;

        /*--------------Variable Definitions--------------*/
        vm.modalData = {};
        vm.isModalLoading = true;
        vm.selectedTab;
        vm.urlHistory;

        /*--------------Function Definitions--------------*/
        vm.selectTab = selectTab;
        vm.openModal = openModal;

        /*Activate Controller*/
        activate();

        /*--------------Functions--------------*/
        /*Announcement clicks are handled separately because the announcement data contains the full article*/
        function handleAnnouncementClick(data) {
            vm.modalData = data;
            $("#announcementModal").modal();
            return;
        }

        /*Set the active tab for the open modal*/
        function selectTab(tab) {
            vm.selectedTab = tab;
            return;
        }

        /*Clicking an article of any content type should be funneled through this function. Eventually to be merged with handleSearchResultClick*/
        function handleContentTypeClick(data) {
            setUrl(data.id, data.contentType.value);
            return;
        }

        function handleUrlParamsModalLaunch(data) {
            console.log('launching modal');
            /*Ensure modal is not displaying any data*/
            vm.modalData = {};
            vm.selectedTab = null;

            /*Show modal loading screen*/
            vm.isModalLoading = true;
            var modalInstance = $uibModal.open({
                templateUrl: 'app/modals/contentTypeModalTemplate.html',
                controller: 'LinkModalController as vm',
            });

            /*Call the content service to return the clicked content article*/
            contentpartservice.getContentItem(data.id, data.type).then(function (contentItem) {
                if (contentItem) {
                    vm.isModalLoading = false;
                    vm.modalData = contentItem;
                    return;
                } else {
                    closeModal("#contentPartModal").then(function () {
                        vm.isModalLoading = false;
                        logger.error('An error occurred while fetching content');
                    });
                    return;
                }
            }, function (error) {
                closeModal("#contentPartModal").then(function () {
                    vm.isModalLoading = false;
                    logger.error('An error occurred while fetching content');
                });
                return;
            });
        }

        /*Close a modal and return a promise object - This allows other code to be executed only after the modal closes*/
        function closeModal(modalId) {
            $(modalId).modal('hide');

            var defer = $q.defer();
            defer.resolve();

            return defer.promise;
        }

        //Function to append information to the URL required to retrieve the displayed article
        function setUrl(contentId, contentType) {
            var urlParams = $location.search();

            if (urlParams.q) {
                $location.search({ q: urlParams.q, type: contentType, id: contentId });
            } else {
                $location.search({ type: contentType, id: contentId });
            }

            console.log($location.search());
            return;
        }

        /*Route link click calls to handle different data structures*/
        function openModal(data, context) {
            switch (context) {
                case 'urlParams':
                    handleUrlParamsModalLaunch(data);
                    break;
                case 'announcement':
                    handleAnnouncementClick(data);
                    break;
                case 'contentType':
                    handleContentTypeClick(data);
                    break;
                default:
                    logger.error('An error occurred while fetching content');
            }

            return;
        }

        /*--------------Listeners--------------*/

        /*Catch links click events broadcast from the $rootScope (shell.controller.js)*/
        $rootScope.$on('openModal', function (event, data, context) {
            vm.openModal(data, context);
            return;
        });

        /*--------------Activate Controller--------------*/
        function activate() {
            /*Create a watcher to detect changes to the URL*/
            $scope.$watch(function () { return $location.search() }, function () {
                alert('url changed');
                /*Wait for modals to render*/
                var urlParams = $location.search();

                if (urlParams.type && urlParams.id) {
                    vm.openModal(urlParams, 'urlParams');
                }

                /*Handle the inital page load. (Must wait until content is loaded to open modal). This code only runs once.*/
                $rootScope.$on('$includeContentLoaded', function () {
                    alert('url changed first laod');
                    /*Wait for modals to render*/
                    var urlParams = $location.search();

                    if (urlParams.type && urlParams.id) {
                        vm.openModal(urlParams, 'urlParams');
                    }
                });
            }, true);
        }
    }
})();

The error message that was logged is a massive block of text, so I've pasted it into a Google Doc: https://docs.google.com/document/d/1esqZSMK4_Tiqckm-IjObqTvMGre2Ls-DWrIycvW5CKY/edit?usp=sharing

A: don't know if you have tried $locationProvider.html5Mode(true); in your app's config module. If you use jquery model to open the popup, it might have conflict between angular and jquery because jquery also watches the change on the url. I used to have similar issue like this.


text:
Q: Getting returned wrong values, but reading in fine in system? Java I am trying to read in this input:
processcount 2     # Read 2 processes
runfor 15          # Run for 15 time units
use rr             # Can be fcfs, sjf, or rr
quantum 2          # Time quantum – only if using rr
process name P1 arrival 3 burst 5
process name P2 arrival 0 burst 9
end

My job is to only parse in the values and not the words, and to keep out the comments (#).
Here is the main file:
public class main {

static String[] token = new String[10];
static List<Schedule> p;

public static void schedule()
{
    for(Schedule c: p)
    {
         System.out.println("ProcessInfo: " + c.getProcess().processName);
            System.out.println("count: " + c.getProcessCount());
             System.out.println("quant: " + c.getQuantum());
              System.out.println("runtime: " + c.getRunTime());
               System.out.println("Type: " + c.getType());
    }
  }

public static void main(String[] args) throws Exception {
   Scanner sc = new Scanner(System.in);
      // sc = new Scanner(new File("processes.in"));
    p = new ArrayList<>();

    while(sc.hasNextLine() && !sc.equals("end"))
    {

        token = sc.nextLine().replace(" ","-").replace("#", "-").split("-");

        System.out.println(token[0].toString());

        if(!token[0].startsWith("#") || !sc.nextLine().startsWith("end"))
        {
            Schedule s = new Schedule();
            int pCount=0, runfor=0, quantum=0, arrival=0, burst=0;
            String type = null, pName = null;

            if(token[0].startsWith("processcount"))
            {
                 s.setProcessCount(Integer.parseInt(token[1]));
                System.out.println(Integer.parseInt(token[1] +""));
            }

            else if(token[0].startsWith("runfor"))
            {
                  s.setRunTime(Integer.valueOf(token[1].toString()));
                 System.out.println(Integer.parseInt(token[1]) +"");
            }

            else if(token[0].startsWith("use"))
            {
                s.setType(token[1].toString());
                System.out.println(token[1] +"");
            }

            else if(token[0].startsWith("quantum"))
            {
                s.setQuantum(Integer.valueOf(token[1].toString()));
                System.out.println(token[1] + "");
            }

            else if(token[0].startsWith("process"))
            {
                Processes pl = new Processes();
                pl.setProcessName(token[2]);
                System.out.println(token[2]+ "");

                pl.setArrivalTime(Integer.valueOf(token[4].toString()));
                System.out.println(""+ Integer.valueOf(token[4]));

                pl.setBurstTime(Integer.valueOf(token[6].toString()));
                System.out.println("" + token[6]);

                s.setProcess(pl);
                // add info
                p.add(s);

            }

            else if(token[0].startsWith("end"))
            {
                schedule();
            }

        }

    }

}

}

Here is the Schedule:
public class Schedule {

int processCount;
int runTime;
String type;
int quantum;
Processes process;

public  int getProcessCount() {
    return processCount;
}

public  void setProcessCount(int processCount) {
    this.processCount = processCount;
}

public int getRunTime() {
    return runTime;
}

public  void setRunTime(int runTime) {
    this.runTime = runTime;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public int getQuantum() {
    return quantum;
}

public void setQuantum(int quantum) {
    this.quantum = quantum;
}

public Processes getProcess() {
    return process;
}

public void setProcess(Processes p) {
    process = p;
}
}

Here is the Process:
public class Processes {

String processName;
int arrivalTime;
int burstTime;

public String getProcessName() {
    return processName;
}

public void setProcessName(String processName) {
    this.processName = processName;
}
public int getArrivalTime() {
    return arrivalTime;
}

public void setArrivalTime(int arrivalTime) {
   this.arrivalTime = arrivalTime;
}

public int getBurstTime() {
    return burstTime;
}

public void setBurstTime(int burstTime) {
    this.burstTime = burstTime;
}
}

Here is the output I am getting with my code:
ProcessInfo: P1
count: 0
quant: 0
runtime: 0
Type: null
ProcessInfo: P2
count: 0
quant: 0
runtime: 0
Type: null

why am I getting returned wrong results?

A: There's couple of issue here. You create a new schedule at each iteration of your while loop; you don't get all the relevant values of your current line before the new iteration plus you have couple of useless variables right after you create a new Schedule() which override the previously collected values.
Also, you use toString on a String element of your array which is meaningless. Personnaly I don't try not to use filters and you don't really need any for this. Always try to KISS(Keep It Simple Stupid)
Here's how I'll go about it without using filters.
public static void main (String args [])
{
     // Will help us identify the key words
     String current_token;

     Scanner sc = new Scanner(System.in);

     String input = sc.nextLine();
     //Remove spaces at the beginning and end of the string
     input = input.trim();

     Schedule s = new Schedule();

     // New source for the scanner
     sc =new Scanner(input);

     p = new ArrayList<>();

     while(sc.hasNext())
     {
          current_token = sc.next();

          if(current_token.equals("end"))
            {schedule(); break;}

          switch(current_token)
          {
                case "processcount":
                    s.setProcessCount(sc.nextInt());
                    System.out.println(s.getProcessCount()+ " ");
                    break;

                case "runfor":
                    s.setRunTime(sc.nextInt());
                    System.out.println(s.getRuntime +" ");

                case "use":
                    s.setType(sc.next());
                    System.out.println(s.getType() +" ");
                    break;

                case "quantum":
                    s.setQuantum(sc.nextInt());
                    System.out.println(s.getQuantum + " ");
                    break;

                case "process":
                    Processes pl = new Processes();

                    pl.setProcessName(sc.next());
                    System.out.println(pl.GetProcessName()+ " ");

                    pl.setArrivalTime(sc.nextInt());
                    System.out.println(" "+ pl.getArrivalTime());

                    pl.setBurstTime(sc.nextInt());
                    System.out.println(" " + pl.getBurstTime());

                    s.setProcess(pl);
                    // add info
                    p.add(s);

                    break;

                default:
                    // the current_token is not what we are looking for
                    break;
           }
      }
}

A: You're having an issue because of the way you split the string. The way you have right now first replaces each space with a dash. For example, the string
"processcount 2   # a comment"

would become
"processcount-2---#-a-comment"

and then splitting that gives you an empty string between every pair of dashes, so you'll end up with
token = ["processcount", "2", "","", ... etc]

I suggest that you do this:
String str = (sc.nextLine().split("#"))[0]; //get the string before the pound sign
str = str.trim(); //remove the leading/trailing whitespace
token = str.split("\\s+"); //split the string by the whitespaces


text:
Q: Uncaught TypeError: Cannot read properties of undefined (reading 'coordinates') for mapbox I keep getting a typeError when using mapbox and trying to do user inputted coordinates for the marker and center.
This is the error:
`showPageMap.js:5 Uncaught TypeError: Cannot read properties of undefined (reading 'coordinates')
    at showPageMap.js:5
(anonymous) @ showPageMap.js:5`

My controller looks like this:
`const Adventure = require('../models/listings');
const mbxGeocoding = require("@mapbox/mapbox-sdk/services/geocoding");
const mapBoxToken = process.env.MAPBOX_TOKEN;
const MapboxClient = require('@mapbox/mapbox-sdk');
const geocoder = mbxGeocoding({ accessToken: mapBoxToken });
const { cloudinary } = require('../cloudinary');
const mapboxgl = require('mapbox-gl');

module.exports.index = async (req, res) => {
    const adventures = await Adventure.find({});
    res.render('adventures', { adventures })
};

module.exports.renderNewForm = (req, res) => {
    res.render('adventures/new')
};

module.exports.createAdventure = async (req, res, next) => {
    const geoData = await geocoder.forwardGeocode({
        query: req.body.adventure.location,
        limit: 1
    }).send()
    const adventure = new Adventure(req.body.adventure);
    adventure.geometry = geoData.body.features[0].geometry;
    adventure.images = req.files.map(f => ({ url: f.path, filename: f.filename}));
    adventure.author = req.user._id;
    console.log(adventure);
    await adventure.save();
    req.flash('success', 'Successfully made adventure');
    res.redirect(`/adventures/${adventure._id}`)
};

module.exports.showAdventure = async (req, res) => {
    const adventure = await Adventure.findById(req.params.id).populate({
        path: 'reviews',
        populate: {
            path:'author'
        }
    }).populate('author');
    if (!adventure) {
        req.flash('error', 'Cannot find that campground!');
        return  res.redirect('/adventures');
    }
    res.render('show', { adventure })
};`

My model looks like this:
`const { number } = require('joi');
const mongoose = require('mongoose');
const { adventureSchema } = require('../schemas');
const review = require('./review');
const Schema = mongoose.Schema;

const ImageSchema = new Schema({
    url: String,
    filename: String
});

ImageSchema.virtual('thumbnail').get(function () {
    return this.url.replace('/upload', '/upload/w_200');
});

const opts = { toJSON: { virtuals: true } };

const adventuresSchema = new Schema({
    title: String,
    images: [ImageSchema],
    geometry: {
        type: {
            type: String,
            enum: ['Point'],
            required: true
        },
        coordinates: {
            type: [Number],
            required: true
        }

    },
    price: Number,
    description: String,
    location: String,
    author: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    reviews: [
        {
            type: Schema.Types.ObjectId,
            ref: 'Review'
        }
    ]
}, opts);

adventuresSchema.post('findOneAndDelete', async function (doc) {
    if(doc){
        await review.remove({
            _id: {
                $in: doc.reviews
            }
        })
    }
});

module.exports = mongoose.model('Adventure', adventuresSchema);
`
The js for the map is: `mapboxgl.accessToken = mapToken;
const map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v10', // stylesheet location
    center: adventure.geometry.coordinates, // starting position [lng, lat]
    zoom: 10 // starting zoom
});

map.addControl(new mapboxgl.NavigationControl());

new mapboxgl.Marker()
    .setLngLat(adventure.geometry.coordinates)
    .setPopup(
        new mapboxgl.Popup({ offset: 25 })
            .setHTML(
                `<h3>${adventure.title}</h3><p>${adventure.location}</p>`
            )
    )
    .addTo(map)`

The code uses mongoose, mongodb, and express.
I have tried most solutions on this and none seem to work for me. I redid the model and everything and it simply won't take coordinates which mapbox docs tell me is allowed and included in the api req.
I've been stuck for many hours and nothing works, please help

A: I realize this is an old question but I wanted to answer just to have it recorded online for people to find easily.
The script at the bottom of your Views Index page and Show should show this -

// Views Show Page EJS
<script>
    const mapToken = '<%- process.env.MAPBOX_TOKEN %>';
    let campground = '<%- JSON.stringify(campground) %>';
    campground = JSON.parse(campground);
  </script>
  <script src="/javascripts/showPageMap.js"></script>
  </script>

// Views Index EJS

    <script>
      const mapToken = '<%- process.env.MAPBOX_TOKEN %>';
      let campgrounds = '<%- JSON.stringify(campgrounds) %>'
      campgrounds = { features: JSON.parse(campgrounds) }
    </script>
    <script src="/javascripts/clusterMap.js"></script>

Also, please remove any seeding that have an apostrophe in the name of the city. In the bootcamp I finished a city "O'Fallon" was throwing off my parsing and I had to remove it from the list, or just delete the campsite.
I kept the structure how I have it set up on my project, but you should be able to work backwards to customize it for yourself.


text:
Q: Is it possible to create a beacon with Classic Bluetooth? I'm attempting to use a classic bluetooth chip to possibly send out signals to another device with a classic bluetooth chip.
Now would it be possible to create a beacon with classic bluetooth?

A: You certainly can.  A Bluetooth LE beacon typically sends out regular advertisements with a unique identifier that can be picked up by a receiving device (typically a mobile phone) doing a Bluetooth LE scan.  Since you can also send out advertisements and do scans with classic Bluetooth, you could build the same thing with this technology.
The main disadvantage is that classic Bluetooth uses much more power, both for transmitting the beacon signal and more importantly for doing the scans.  So if you are using mobile phones to detect the beacons the battery drain will be much higher than if using Bluetooth LE.


text:
Q: Adal-angular app token with secret I have an app that gets bearer token from Azure ad with adal-angular.
I can ask questions to graph-api to get the data i want with that token.
But now i want to change that data. For that i need an app token from azure AD.
Graph api resource is https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/educationschool_update
My app is an React app that uses adal-angular.
My app have an secret to do this.
My question(s) is, can Adal -angular get me this app-token? And if its possible, how can it do that?
below is my config for adal angular. client_secret is what im trying to get to work..
window.authContext = new AuthContext({
  tenant: 'xxxxx',
  clientId: 'xxxx',
  redirectUri: "http://localhost:3000/",
  client_secret : 'APP SECRET HERE!?!?!?!?!?!?',
  cacheLocation: 'localStorage'
});

this is my method to get token for the logged in person.
aquireToken() {
        let header = null;
        window.authContext.acquireToken('https://graph.microsoft.com', (error, token) => {
            header = {
                headers: {
                    Authorization: 'Bearer ' + token
                }
            }
        });
        return header;
    }

A: I think it is not possible from the web client (UI loaded in the browser) because according to Azure AD CORS policy only Authorize endpoint is open to the web clients and you can't send client_secret to the Authorize endpoint. There is no such parameter according to the documentation: https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code
I hope it helps even it came 6 months after asking :)


text:
Q: Using SQL to determine cidr value of a subnet mask I'd like to find a way to do a SQL query that will calculate the cidr (bit representation) of a subnet mask stored in the database.  So for example, I've got either 255.255.255.0 or its decimal value (4294967040) stored in the database.  I'd like to do a select and get back /24 representation via the query.
I've done things like the following to determine the last IP of a subnet so I'm hoping to do something similar to determine the cidr representation of a mask.
select concat(inet_ntoa(ip_addr),'-',
    inet_ntoa(ip_addr+(POWER(2,32)-ip_mask-1))) range
from subnets
order by ip_addr

Preferably this would be a SQL statement that would work under mysql, postgres, oracle etc.

A: I think I have found the solution to my issue.  Here is what I have done:
select CONCAT(INET_NTOA(ip_addr),'/',32-log2((4294967296-ip_mask))) net
from subnets
order by ip_addr

Basically I take my decmial mask and subtract it from the maximum decimal value.  I then to a log2 on that value to get the logarithm value.  Then simply subtract that from 32 (the maximum bit available).
Hope that helps others.
Thanks

A: SQL queries don't have a procedural looping construct (notwithstanding procedural language), but you can compare one set of rows to another set of rows, which is kind of like a loop.
You only have 32 possible subnet masks.  In cases like this, it makes sense to create a small table that stores these 32 masks and the associated CIDR number.
CREATE TABLE cidr (
  bits INT UNSIGNED PRIMARY KEY,
  mask INT UNSIGNED NOT NULL
);

INSERT INTO cidr (bits) VALUES
  ( 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);

UPDATE cidr SET mask = ((POWER(2,32)-1)<<(32-bits)) & (POWER(2,32)-1);

SELECT CONCAT(s.ip_addr, '/', c.bits)
FROM cidr c JOIN subnets s ON (c.mask = inet_aton(s.ip_mask));

A: e.g. you need to convert 255.255.255.252 netmask into bit mask.
I always use this simple query (PostgreSQL) :
SELECT 32-length(trim(((split_part('255.255.255.252','.',1)::bigint*(256^3)::bigint +
                        split_part('255.255.255.252','.',2)::bigint*(256^2)::bigint +
                        split_part('255.255.255.252','.',3)::bigint*256 +
                        split_part('255.255.255.252','.',4)::bigint)::bit(32))::text,'1'));

not as nice as could be, but it's short and working like a charm..

A: --
-- Dumping routines for database
--
/*!50003 DROP FUNCTION IF EXISTS `INET_ATOC` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'ALLOW_INVALID_DATES' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `INET_ATOC`(`paramNETMASK` varchar(15)) RETURNS int(2) unsigned
    DETERMINISTIC
    COMMENT 'Converts an IPv4 netmask in dotted decimal notation to a CIDR integer between 0 and 32'
BEGIN
    DECLARE `netmask` int unsigned;
    DECLARE `cidr` int unsigned;
    SET `netmask` = INET_ATON(`paramNETMASK`);
    IF (`netmask` IS NULL)
    THEN
        RETURN NULL;
    ELSE
        SET `cidr` = 0;
        countNetBits: WHILE (`cidr` < 32)
        DO
            IF ( (0x80000000 & `netmask`) = 0x80000000 )
            THEN
                SET `netmask` = 0xFFFFFFFF & (`netmask` << 1);
                SET `cidr` = `cidr` + 1;
            ELSE
                LEAVE countNetBits;
            END IF;
        END WHILE;
        IF (`netmask` != 0)
        THEN
            RETURN NULL;
        END IF;
        RETURN `cidr`;
    END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `INET_CTOA` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'ALLOW_INVALID_DATES' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `INET_CTOA`(`paramCIDR` int) RETURNS varchar(15) CHARSET utf8
    DETERMINISTIC
    COMMENT 'Converts a CIDR suffix (integer between 0 and 32) to an IPv4 netmask in dotted decimal notation'
BEGIN
    DECLARE `netmask` int unsigned;
    IF  ( (`paramCIDR` < 0) OR (`paramCIDR` > 32) )
    THEN
        RETURN NULL;
    ELSE
        SET `netmask` = 0xFFFFFFFF - (pow( 2, (32-`paramCIDR`) ) - 1);
        RETURN INET_NTOA(`netmask`);
    END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `getSubnet` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `getSubnet`(INOUT `paramADDR` VARCHAR(15), INOUT `paramCIDR` INT, OUT `paramMASK` VARCHAR(15), OUT `paramNETWORK` VARCHAR(15), OUT `paramBROADCAST` VARCHAR(15), OUT `paramNUMHOSTS` INT) CHARSET utf8
    DETERMINISTIC
BEGIN
    DECLARE `numaddrs`  int unsigned;
    DECLARE `ipaddr`    int unsigned;
    DECLARE `netmask`   int unsigned;
    DECLARE `wildcard`  int unsigned;
    DECLARE `network`   int unsigned;
    DECLARE `broadcast` int unsigned;
    DECLARE `numhosts`  int unsigned;

    SET `ipaddr` = INET_ATON(`paramADDR`);

    IF (`ipaddr` IS NULL) OR (`paramCIDR` < 1) OR (`paramCIDR` > 30)
    THEN
        SELECT
            NULL, NULL, NULL, NULL, NULL, NULL
        INTO
            `paramADDR`, `paramCIDR`, `paramMASK`, `paramNETWORK`, `paramBROADCAST`, `paramNUMHOSTS`;
    ELSE
        SET `numaddrs`  = pow( 2, (32-`paramCIDR`) );
        SET `numhosts`  = `numaddrs` - 2;
        SET `netmask`   = 0xFFFFFFFF - (`numaddrs` - 1);
        SET `wildcard`  = 0xFFFFFFFF & (~`netmask`);
        SET `network`   = `ipaddr` & `netmask`;
        SET `broadcast` = `ipaddr` | `wildcard`;

        SELECT
            INET_NTOA(`ipaddr`), `paramCIDR`, INET_NTOA(`netmask`), INET_NTOA(`network`), INET_NTOA(`broadcast`), `numhosts`
        INTO
            `paramADDR`, `paramCIDR`, `paramMASK`, `paramNETWORK`, `paramBROADCAST`, `paramNUMHOSTS`;
    END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;


text:
Q: Getting one hour difference on date Following is the code I am writing to convert UTC time to local time :
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
    [dateFormatter1 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter1 setLocale:locale];
    NSDate *date = [dateFormatter1 dateFromString:dateString];

    dateString = [date descriptionWithLocale:[NSLocale systemLocale]];

    NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
    NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

    NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
    NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
    NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;

    NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date];

    NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
    [dateFormatters setDateFormat:@"HH:mm"];
    [dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
    dateString = [dateFormatters stringFromDate: destinationDate];

But this way I am getting a difference of 1 hour. i.e. if date displayed on web app is 12:30, on the app it is displayed as 13:30. Why is that so ?

A: Try with this code:
- (NSDate *) UTCTimeToLocalTime
{
    NSTimeZone *tz = [NSTimeZone defaultTimeZone];
    NSInteger seconds = [tz secondsFromGMTForDate: yourDate];
    return [NSDate dateWithTimeInterval: seconds sinceDate: yourDate];
}

- (NSDate *) LocalTimeToUTCTime
{
    NSTimeZone *tz = [NSTimeZone defaultTimeZone];
    NSInteger seconds = -[tz secondsFromGMTForDate: yourDate];
    return [NSDate dateWithTimeInterval: seconds sinceDate: yourDate];
}

A: You need to learn and accept the principles of handling times and dates.
NSDate represents points in time, independent of any time zone. If we are talking on the phone, and our computers calculate [NSDate date], they get the exact same date, even if our watches display totally different times.
Calendars with time zone information transform between NSDate and something that a user in one particular part of the world expects. So the same NSDate is converted to a string to match what your watch displays, or what my watch displays, which would be different. There should be no need to modify an NSDate in any of this, as you did.


text:
Q: "Illegal filter on FeedItem" error in soql query im trying to run the following query:
SELECT Id, Parent.RecordTypeId FROM FeedItem WHERE Type='EmailMessageEvent' AND Visibility!='AllUsers' AND Parent.Type = 'Case' AND Parent.RecordTypeId = '01258000000cZYOAA2'

I receive the error

MALFORMED_QUERY - Illegal filter on FeedItem

anyone familiar with this error and how to overcome it?
in case it helps,
that's the code i use the query on:
global class EmailFeeditemBatch implements Database.Batchable<sObject>, Schedulable{

global Database.QueryLocator start(Database.BatchableContext BC){
    RecordType rt = [SELECT ID FROM RecordType WHERE DeveloperName = 'Support' AND SobjectType =  'Case' LIMIT 1]; //PUT THIS UP

    String  query = 'SELECT Id, Parent.RecordTypeId FROM FeedItem WHERE Type=\'EmailMessageEvent\' AND Visibility!=\'AllUsers\' AND Parent.Type = \'Case\' AND Parent.RecordTypeId = \''+rt.Id+'\'';
    System.debug(query);
    return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<FeedItem> scope){

    List <FeedItem> feedItemToUpdateList = new List<FeedItem>();
    for(FeedItem feedItem_i : scope){
            feedItem_i.Visibility = 'AllUsers';
            feedItemToUpdateList.add(feedItem_i);
    }
    if (feedItemToUpdateList.size()>0){
        update feedItemToUpdateList;
    }
}

global void finish(Database.BatchableContext BC){

}

global void execute(SchedulableContext sc) {

    database.executeBatch(new EmailFeeditemBatch(), 5);
}

}

A: I'm afraid you can't filter or Parent.RecordtypeId. I can't find any documentation for this but if I remove it the rest of the query works.
This leaves you with two possibilities. You can use a semi-join in you where clause to filter on the parents with the correct record type:
SELECT Id,
       Parent.RecordTypeId
FROM FeedItem
WHERE Type='EmailMessageEvent'
AND Visibility !='AllUsers'
AND Parent.Type = 'Case'
AND ParentId IN (SELECT Id FROM Case WHERE RecordTypeId = '01258000000cZYOAA2')

You could also query all the FeedItems without filtering on the Parent.RecordtypeId, and than loop over them to select the right ones. However this is less efficient and I'd suggest you use the first solution.


text:
Q: How to calculate eigenvalues of this matrix? I am trying to solve the following equation to get the eigenvalues of this (n + 1 $\times$ n + 1) matrix m:
$$m =
\begin{bmatrix}
a & a1^T \\
a1 & bJ
\end{bmatrix}$$
Where:
$$
a, b \in R, 1^T = [1.....1]^T
$$ and J is a (n $\times$ n) matrix of all $1$s.
so far, I  have done the following(I is the identity matrix here):
$$det(m) =
\begin{bmatrix}
a - \lambda & a1^T \\
a1 & bJ - \lambda I
\end{bmatrix} = 0 \\
abJ - a\lambda I - \lambda bJ + \lambda^2 I - a1^Ta1 = 0 \\ \lambda^2I - \lambda(aI + bJ) + abJ - na^2 = 0
$$
because
$$a1^Ta1 = [a....a][a....a]^T = na^2$$
How do I proceed from here?

A: Your computation of the determinant is not correct: you are treating $J$ as if it were a scalar, when it is a matrix. It should be obvious since you get a degree two equation on $\lambda$ instead of degree $n$.
For this matrix, it is easier to look at the eigenvalues directly. I will assume $a\ne b$ and both nonzero, since it is the non-trivial case.
The equation $mx=\lambda x$ gives the equations
$$\tag1
a\sum_{j=1}^n x_j=\lambda x_1,\ \ ax_1+b\sum_{j=2}^n x_j=\lambda x_2=\cdots=\lambda x_n.
$$
Consider first the case $\lambda=0$. Now the equations are
$$
\sum_{j=1}^n x_j=0,\ \ ax_1+b\sum_{j=2}^n x_j=0.
$$
Solving for $x_1$ in the first equation we get $(b-a)\sum_{j=2}^n x_j=0$. Then $x_1=-\sum_{j=2}^n x_j=0$. So the eigenspace for $\lambda=0$ is the subspace
$$
\{x:\ x_1=0,\ \sum_{j=2}^n x_j=0\},
$$
which has dimension $n-2$.
Now consider the case $\lambda\ne0$. We obtain from $(1)$ that $x_2=\ldots=x_n$. They cannot be zero, because $(1)$ would become $ax_1=\lambda x_1$ and $ax_1=0$, a contradiction. So assume that $x_2=1$. Now $(1)$ becomes
$$
(n-1)=(\lambda-a)x_1, \ \ \ ax_1+b(n-1)=\lambda;
$$
solving for $\lambda$ we obtain a quadratic equation on $\lambda$ that will give us the other two eigenvalues. Solving the quadratic quickly gives me
$$
\lambda =\frac{a+b(n-1)\pm\sqrt{[b(n-1)+a]^2-4(n-1)(b-1)a}}{2}
$$


text:
Q: EmguCV not debug on. NET4.0 I have trouble debugging an application made on. NET 4.0.
A written WPF/.NET4.0 and other in WPF/.NET3.5  both compiled fine, but in .NET4.0 I can not debug, the application abruptly closes, I have seen all the examples and these are brought EmguCV made on .NET3.5.
how i can debug an application with EmguCV over .NET4.0?


text:
Q: How does Network layer knows if it has to fragment the packet I got basic question. Trying to understand the mechanism how network layer identify when it receive packet larger than its interface MTU configured and has to fragment it.
For example. If the data to be transmitted by application is 2000byte where as the NIC on the server is having MTU 1500. Network layer has to do fragmentation now but how it knows it has to do it. Does the Transport layer give the full 2000byte data to network layer and than network layer compares it with the interface MTU configured and decide accordingly

A:
If the data to be transmitted by application is 2000byte

There are transport-layer (L4) protocols (most prominently TCP) that do all the chunking for an application. TCP is MTU-aware and segments its data automatically into the optimal chunks.
Other L4 protocols don't do any chunking of their own (e.g. UDP). Any application data is simply encapsulated into a datagram and passed to the network layer. If necessary, the network layer then fragments the encapsulating IP packet across several data-link-layer frames.


text:
Q: Nice Excel Reports from Python - How At present I have some analytical processes that run in SAS and create excel reports (the client needs excel reports, it is a requirement). Using ODS excel SAS produces nice looking tables with headers and such
I am able to change the processes to Python (some of the reasons are we are emigrating to Hadoop/Spark which we will access through Python), I mean the data extraction from the source, and all the data manipulation and summarization. However I have not found a library (yet) that can easily write to excel a nice report
I see from multiple sources that one can loop through the desired output to be sent to excel and place it in each cell, formatting as needed. And no doubt that this is what ODS excel likely does. Perhaps use pandas to write the data quickly and then use openpyxl to do the formatting (or just use openpyxl for all) - this seems like a lot of work (I guess for the cost of SAS license you get nice utilities that do the hard wrk for you among other things)
My question is if someone can point to a library that automates most of this and creates nice reports (clients do not just like numbers and words in cells - that is the reality). I can of course write my own functions (I can also likely write functions for a lot of stuff I just use modules/libraries). I will be generating the excel files in Unix, hence I do not have access to office in the same system.
I am asking again, because the one question with most answers 7 years old
Thanks


text:
Q: Are 15 reputation points sufficient for accepted answers? If a question has not been answered, it lacks exposure, it becomes forgotten, and consequently, fails to attract upvotes.
By answering these types of questions, a user is providing a service, but due to the question's low views count and number of upvotes, an answer — however good — will naturally be penalized.
I have answered many questions that were left on the heap, and my answers were accepted but none of them had more than 3 upvotes.
In similar cases, wouldn't it be better to increase the number of rep, presently at 15 points, for an accepted answer? By doing so, new users like myself would be encouraged to answer these unanswered questions.

A: Reputation was meant to reflect how many people found your contribution useful — while accepting an answer is the choice of ONE user.
The author can up-vote your post (10 rep), and accepting your answer adds an additional 15 rep over that. Accepting an answer also pins the post to the top of the list, which overrides what everyone actually voted on as the best answer. That gives the post even more exposure still.
I believe the benefits of accepting an answer are over-weighted enough to leave it as is.


text:
Q: How to make mercurial run script on push? I have a server which hosts a mercurial repository with hgwebdir. Is it possible to make mercurial to run a script when someone pushes to this repository?
Currently I use a script that checks the repository state every few minutes, but this is obviously an ugly solution.

A: You have to add a hook to your Mercurial server:

*

*Edit .hg/hgrc (or mercurial.ini on Windows)

*Add or edit the [hooks] section

*Associate a shell command to the hook you are interested in (in your case, the changegroup hook)

Look at Handling repository events with hooks in the Mercurial red-bean book for more details.

A: You might want to take a look at mercurial hooks,
http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html


text:
Q: How to make the labels in different color?
Please see the graph below. They should be very colorful!

A: You will need to manually assign the colours in Neo4j Browser. This is pretty straightforward to do:

*

*Select the Node Label you wish to set a colour to (you will find the node labels at the top of the window when you bring back some results

*You will see a colour selector appears at the bottom of the window, choose your colour, and all nodes of that label will be set to that colour

Details here: https://neo4j.com/developer/neo4j-browser/#browser-styling


text:
Q: NullPointerException with mockito test I am very new at writing tests and I am trying to write a simple one to check that the email the user writes for the login is valid. I got the way to do it from a tutorial and it makes sense the way it works but for some reason I am getting the NullPointerException even though I am not sure why. Any ideas about it would help.
This is the login view model part that I want to test:
class LoginViewModel @ViewModelInject constructor(
    private val loginRepository: LoginRepository,
    private val preference: Preferences
) : ViewModel() {

    private val _loginForm = MutableLiveData<LoginFormState>()
    val loginFormState: LiveData<LoginFormState> = _loginForm

    //validate all login fields
    fun loginDataChanged(email: String, password: String) {
        if (!isEmailValid(email)) {
            _loginForm.value = LoginFormState(emailError = R.string.error_state_msg_invalid_email)
        } else if (!isPasswordValid(password)) {
            _loginForm.value = LoginFormState(passwordError = R.string.error_state_msg_invalid_password_signUp)
        } else {
            _loginForm.value = LoginFormState(isDataValid = true)
        }
    }

    //validate email
    private fun isEmailValid(email: String): Boolean {
        return Patterns.EMAIL_ADDRESS.matcher(email).matches()
    }

    //validate password
    private fun isPasswordValid(password: String): Boolean {
        val PASSWORD_PATTERN = "^(?=.*\\d)(?=.*[a-z])(?=.*[a-zA-Z]).{8,}\$"
        val pattern = Pattern.compile(PASSWORD_PATTERN)
        val matcher = pattern.matcher(password)

        return matcher.matches()
    }
}

This is the testing part:
@RunWith(MockitoJUnitRunner::class)
class LoginViewModelTest {

    @Mock
    private lateinit var repository: LoginRepository

    @Mock
    private lateinit var viewModel: LoginViewModel

    @Mock
    private lateinit var preferences: Preferences

    @Rule
    @JvmField
    val instantTaskExecutorRule = InstantTaskExecutorRule()

    val invalidEmail = ""
    val invalidPassword = ""
    val validEmail = "test@email.com"
    val validPassword = "test12345"

    @Before
    fun setUp() {
        viewModel = LoginViewModel(repository, preferences)
    }

    @Test
    fun `loginDataChanged with invalid email should set loginFormState as error`() {
        viewModel.loginDataChanged(invalidEmail, validPassword)
        assert(viewModel.loginFormState.value?.emailError != null)
    }


text:
Q: Nginx redirect of subdomain routes not working This is my server block in the nginx_conf file:
I'm using cloud66 so I can edit this from my dashboard.
This keeps breaking. I suspect it's because of my conditionals and if statements.
I'm trying to reroute the following urls to the following urls:
http://subdomain.domain.com/notes.php and route it to /dashboard
route it to
http://domain.com/dashboard
http://subdomain.domain.com/contact-us.php and route it to /dashboard
route it to
http://domain.com/contact-us/new
http://subdomain.domain.com/help.php and route it to /dashboard
route it to
http://domain.com/faq
server
{
...
    # redirect old routes on subdomain
    server_name ~^www\.(?<domain>.+)$;

    if ($host ~ "^(.*)$domain") {
      set $subd $1;

      if $1 = 'notes.php'{
        rewrite ^(.*) /dashboard permanent;
      }

      if $1 = 'contact-us.php'{
        rewrite ^(.*) /contact-us/new permanent;
      }

      if $1 = 'help.php'{
        rewrite ^(.*) /faq permanent;
      }
    }
}

I get the following error when I put this:
+ server
+ {
+ server_name secure.inrtracker.com www.secure.inrtracker.com;
+
+ location = /notes.php {
+ rewrite ^ /dashboard permanent;
+ }
+ }

An error occurred.
Sorry, the page you are looking for is currently unavailable.
Please try again later.
If you are the system administrator of this resource then you should check the error log for details.
Faithfully yours, nginx.

A: First up: Obligatory If is evil
Secondly you should separate your subdomain and domain to different server blocks (and / or different files). Then create rewrite rules
server {
    server_name oursubdomain.domain.com www.oursubdomain.domain.com;

    location / {
         rewrite ^/notes.php$ $scheme://domain.com/dashboard permanent;
         rewrite ^/contact-us.php$ $scheme://domain.com/contact-us/new permanent;
         rewrite ^/help.php$ $scheme://domain.com/faq permanent;
    }
}

server {
    server_name domain.com www.domain.com;
    location = /dashboard {
        # Do something here, possibly send to php
    }
    location = /faq {
        # Do something here, possibly send to php
    }
    location = /contact-us/new {
        # Do something here, possibly send to php
    }
}

I hope that helps you on your way!


text:
Q: Difference between uniform initialization vs new operator Let's assume that I have the following class:
Class Foo {
public:
    int j;
    Foo(int i){
        j = i;
        std::cout << j << endl;
    };
}

I am new to C++ and I'm confused about whether the following two blocks of code perform the same activity regarding memory allocation. I remember learning that new allocates memory dynamically but I am not sure about the first block. Is the first block doing the same?
Foo foo{2};

Foo *foo2;
foo2 = new Foo(2);

A: Case 1
Here we consider:
Foo foo{2}; //this will create an object of type `Foo` on the stack

The above statement will create an object of type Foo on the stack using the converting constructor Foo::Foo(int).
Case 2
Here we consider:
Foo *foo2;           //creates a pointer of type `Foo*` on the stack
foo2 = new Foo(2);   //assign foo2 the pointer returned from new Foo(2)

Here first we create a pointer named foo2 of type Foo* on the stack. Note that as of now this pointer is uninitialized.
Next, when we write foo2 = new Foo(2); the following things happen:

*

*Due to new Foo(2) an object of type Foo is created on the heap using the converting constructor Foo::Foo(int).

*Next, a pointer to that dynamically allocated object is returned.

*This returned pointer is assigned to foo2 on the left hand side.

Note also that instead of assigning i to j  inside the constructor you can instead initialize j in the constructor initializer list as shown below:
Class Foo {
public:
    int j;
//--------------vvvv--------------> initialize j in the member initializer list
    Foo(int i): j(i){

        std::cout << j << endl;
    };
}


text:
Q: java lexical analyzer (for mining java code which is able to analyze it semantically) I want a lexical analyzer for java code. Should I write my own or should i use a pre-existing tool?
Is it possible to make my lexical analyzer behave the same as the Java lexical analyzer, without writing my own Regular Expressions?
For example if i have a class like this:
 Class Cat
 {
   public void fun(){
    int a;
     a=3;

     int b=0;

     if((a/b==3)||(a/b==0))
     {
         System.out.println("Test");
     }
   }
 }

I want its output to look like this
class keyword
Cat (id/className)
int a(declaration)
a=3 (assignment)
int b=0 (declaration and assignment)
if (key word)
((a/b==3)||(a/b==0)) (if condition)

Please let me know if you have any ideas..

A: http://www.programcreek.com/2011/01/a-complete-standalone-example-of-astparser/
Eclipse includes a tool for extracting the AST out of Java.


text:
Q: How can I create a dynamic JavaScript constructor name determined at runtime? The issue I have is that I am trying to construct an object in JavaScript, but I don't know what the object will be until runtime.
My code looks something like this:
var modelType = attrs.type;
return new modelType();

attrs.type will contain the name of a valid constructor. So for instance, it might be book, cat or dog. Depending on whatever it is, I want to construct that object. I cannot test what attrs.type is first and then choose the correct constructor because the types might change at any time in the future.
Currently the error I am getting is: Uncaught TypeError: string is not a function. (Since modelType is a string...)
Any help would be greatly appreciated!


text:
Q: Grafana cannot aggregate on String fields as it does not recognize keyword field in Elasticsearch I have an Elasticsearch (5.1.2) data source and am visualizing the data in Kibana and Grafana (4.1.1). For string values in my dataset I am using the keyword feature as described at https://www.elastic.co/guide/en/elasticsearch/reference/5.2/fielddata.html. An example of the mapping for fieldname "CATEGORY":
"CATEGORY": {
  "type": "text",
  "norms": false,
  "fields": {
    "keyword": {
      "type": "keyword"
     }
   }
 }

In Kibana this works fine as I can select "fieldname.keyword" when creating visualizations. However in Grafana it seems like the keyword field is not recognized, as I can only select "fieldname" when creating graphs, which displays the message "fielddata is disabled on text fields by default".
Can anyone give any insight as to why the keyword field is not being recognized in Grafana? Setting fielddata=true is an option too, however I would really prefer get it working using keyword due to the memory overhead associated with setting fielddata=true. Thanks!

A: I found the answer to my question here: http://www.mos-eisley.dk/display/it/Elasticsearch+Dashbord+in+Grafana. You can ignore the parts about setting fieldname=true and instead just set it to query the fieldname.keyword when creating the template.
Just a quick note: Something that took me too long to realise is that when grouping by term, "fieldname.keyword" will not be available for selection in the drop down, so you simply have to type it in.


text:
Q: Boxing of NSString stringWithFormat like NSNumber We can create an NSNumber like this
NSNumber *number = [NSNumber numberWithFloat:4.5];
//or
NSNumber *number = @(4.5);
//or
NSNumber *number = @4.5;

I know we can convert to an NSString with the following statement
NSString *string = @("stuff"); //equivalent of [NSString stringWithUTF8String]

However, can we create an NSString like this?
NSString *string = @(@"Name is:%@",name); //equivalent of [NSString stringWithFormat]

A: This is just off the top of my head.
I do not think there's any syntactic sugar for this.
Though, I believe you could achieve what you are looking for like this:
Put this in your .pch file
#define format(s, ...)
[NSString stringWithFormat:s, ##__VA_ARGS__]

And call it :
NSString *s = format(@"%@, %@", @"a", @"b");


text:
Q: twitter bootstrap box-sizing ruined my layout my layout broken when I implement bootstrap during the half way of my project, fixed that with some css modification, and I had commented out this
/**,
*:before,
*:after {
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
}*/

in bootstrap.css, will that affect its core? I just want to use the grid system in my project..

A: I have the same problem and bootstrap 3 destroys my existing layouts and third party widgets. Here are something things I've tried in order of increasing difficulty and stability.
Easiest Way
Safe only if you don't use other bootstrap components
Add the following css after the bootstrap css is loaded:
*,
*:before,
*:after {
  -webkit-box-sizing: content-box;
     -moz-box-sizing: content-box;
          box-sizing: content-box;
}

.container .row *,
.container .row *:before,
.container .row *:after {
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
}

This will use the border-box sizing only for elements within the grid system. This won't work if you have custom widgets within the grid as they would still have border-box applied.
More targeted approach
Safe only if you don't use other bootstrap components
Alternatively, you could add a custom col class to every column div which already have a col-*-* applied like so:

Grid still works

:)

Then use the following css instead:
*,
*:before,
*:after {
  -webkit-box-sizing: content-box;
     -moz-box-sizing: content-box;
          box-sizing: content-box;
}

.container .row .col,
.container .row .col:before,
.container .row .col:after {
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
}

This works fine if you ONLY need to use the bootstrap grid system in your project. If you intend to use other bootstrap components however, I don't recommend this approach either since other bootstrap components would depend on the border-box being set.
Cherry-pick each containing element to fix
A still better way would be to just override the box-sizing as content-box on a specific parent element for a widget like this:
.your-custom-widget-class *,
.your-custom-widget-class *:before,
.your-custom-widget-class *:after {
  -webkit-box-sizing: content-box;
     -moz-box-sizing: content-box;
          box-sizing: content-box;
}

This approach offers the best forward compatibility with future bootstrap components, even if it seems to be working for you now.

A: Add this in your mixin or variables less and make sure it loads after scaffolding.less
It resets the bs3 box-sizing and applies it again to specific elements and all BS3 required elements.
I found that most mess created by the default BS3 box sizing is when it is applied to
a,ul,li

The magic
* {
  .box-sizing(content-box);
}
form,
div,
img,
table,
th,
tr,
td,
p,
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary,
audio,
canvas,
progress,
video,
[class^="container-"],
[class^="container-"] *,
[class^="col-"],
[class^="col-"] *,
[class^="form-"],
[class^="form-"] *,
[class^="bg-"],
[class^="bg-"] *,
[class^="navbar"],
[class^="navbar"] *,
[class^="nav"],
[class^="nav"] *,
[class^="row"],
[class^="row"] * {
  .box-sizing(border-box);
}

A: Yes, don't do that. Removing the box-sizing: border-box will ruin your grid. See also: Why did Bootstrap 3 switch to box-sizing: border-box?
An example to show what happens:

Content

Content

Content

Content

With:
.nonborderbox *
{
-webkit-box-sizing: content-box;
     -moz-box-sizing: content-box;
      box-sizing: content-box;
}

The above will result in:

With box-sizing: border-box the gutter construct by padding will be out of the calculating of your column's width.
Try to understand Bootstrap's grid and the box-sizing: border-box and figure out why this will ruin your layout. Fix this problems or consider to don't use Bootstrap at all for your project.

A: I used a combination of above solutions to fit my need
(I used only the grid system, everything else was already there)
/* *,
*:before,
*:after {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
*/

[class^="container-"],
[class^="container-"] *,
[class^="col-"],
[class^="col-"] *,
[class^="row"],
[class^="row"] * {
  box-sizing:border-box;
}

The grid was taking too much margin and padding
   so i replaced all the
padding-right:15px;
padding-left:15px;
margin-left=-15px;
margin-right=-15px;

to(I commented out the margins)
.row {
/*  margin-left: -15px;
margin-right: -15px;*/
}

and
.col, .col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
  position: relative;
  min-height: 1px;
  padding-left: 5px;
  padding-right: 5px;
}


text:
Q: taking specific json dictionary and parsing it in javascript i need to take this "Data" block from .json file:
                    {
                        "Info": {
                            "type": "audi",
                            "cost": "3435$"
                        }
                    },
                    {
                        "Info": {
                            "type": "bmw",
                            "cost": "7766$"
                        }
                    },
                    {
                        "Info": {
                            "type": "ford",
                            "cost": "8766$"
                        }
                    },
                    {
                        "Info": {
                            "type": "kia",
                            "cost": "1123$"
                        }
                    }
                ],

and parse it in jscript to receive string like this:
audi;3435$;bmw;7766$;ford;8766$;kia;1123$;...type_n value;cost_n value;
I have a problem with taking specific data from the .json file and correct parsing.
I will be very grateful for any tips

A: You can use reduce and generate the string with the format type_n;const_n

const data = [
 {
     "Info": {
  "type": "audi",
  "cost": "3435$"
     }
 },
 {
     "Info": {
  "type": "bmw",
  "cost": "7766$"
     }
 },
 {
      "Info": {
  "type": "ford",
  "cost": "8766$"
     }
 },
 {
     "Info": {
  "type": "kia",
  "cost": "1123$"
     }
 }
];

const parsedStr = data.reduce((str, {Info:{type, cost}}) => (str += `${type};${cost};`), '');

console.log(parsedStr);


text:
Q: Problemas com o CSS sou novo aqui e estou programando em CSS,me problema é o seguinte:
Eu consigo fazer e colocar os códigos normalmente no sublime text, mas na hora de ver o resultado no navegador ele não aparece. O que eu faço ?

A: Utilize a estrutura abaixo:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Título da página</title>

        <link rel="stylesheet" href="CAMINHO_PARA_ARQUIVO.css">
    </head>
    <body>

    </body>
</html>

Ela funciona perfeitamente! Todas as minhas páginas na web são construidas com esse modelo e nunca tive nenhum tipo de problema. Só linkar de forma CORRETA o css e pronto, tudo funcionando! :D
Tente observar no console de desenvolvedor, se estiver utilizando o Google Chrome, se ele não está dando problema de Cross Origin! Geralmente o chrome bloqueia requisições externas para a mesma página seguindo essa política de mesma origem. Se estiver com esse problema, tente rodar a página em um servidor local (como: xampp, wamp, lamp, etc) e veja se corrige o problema!


text:
Q: Is there a neater way to solve 2016 AIME ii #13 (and generalize it?) 2016 AIME II #13:

Beatrix is going to place six rooks on a $6 \times 6$ chessboard where both the rows and columns are labeled $1$ to $6$; the rooks are placed so that no two rooks are in the same row or the same column. The $value$ of a square is the sum of its row number and column number. The $score$ of an arrangement of rooks is the least value of any occupied square.The average score over all valid configurations is $\frac{p}{q}$, where $p$ and $q$ are relatively prime positive integers. Find $p+q$.

You can find solutions on the AoPS wiki. My solution was similar to solution $1$. Without the flavortext, I believe the problem is:

Let $(a_1,a_2,a_3,a_4,a_5,a_6)$ and $(b_1,b_2,b_3,b_4,b_5,b_6)$ be random not-necessarily-distinct permutations of $(1,2,3,4,5,6)$. Find the expected value of $\min(a_i+b_i)$ where $1\le i\le 6$.

The solutions all include "bashing" out all possible cases (finding the probability the min is $2$, etc.). Is there a way to do this without "bashing"? Can this be extended, changing $6$ to a general $n$?

A: You have actually slightly overcomplicated the problem. A simpler version is

Let $(a_1, ..., a_n)$ be a permutation of $(1, ..., n)$, randomly chosen where all permutations have equal probability. Find the expected value of $K = \min\limits_{1 \leq i \leq n} i + a_i$.

where the chessboard is $n \times n$ and there are $n$ rooks being placed. Here, $a_i$ is the column number for the rook placed on row $i$.
In this particular problem, $n = 6$. But we are trying to find a "nice" solution, so let's leave $n$ unspecified.
Suppose $0 \leq j \leq n$. How many permutations are there where $K > j$?
It turns out that the answer is $b_j := (n + 1 - j)^j (n - j)!$. To see this, consider the fact that for $1 \leq i \leq j$, we must pick $a_i$ such that $j - i < a_i \leq n$ (which gives us $n - (j - i) = n + i - j$ options), but we cannot pick any of the $i - 1$ values already picked (so we have a total of $n + 1 - j$ options). So when we pick the first $j$ values of the permutation, there are $(n + 1 - j)^j$ possibilities. To pick the remaining $n - j$ choices, we have no constraints except that we not pick any of the previous $j$ choices, so this gives us $(n - j)!$ choices for the last part regardless of how we picked the first part.
For convenience, extend $b_j = 0$ when $j = n + 1$, since there are $0$ ways to make $K > n + 1$ (this is because $K \leq 1 + a_1 \leq 1 + n$).
We wish to compute $\sum\limits_{j = 1}^{n + 1} j (b_{j - 1} - b_j)$. We see that this is equal to $(\sum\limits_{j = 0}^n b_n) - (n + 1)b_{n + 1} = \sum\limits_{j = 0}^n b_n$.
So we must compute $\sum\limits_{j = 0}^n (n + 1 - j)^j (n - j)!$. Writing $u = n - j$, we can write the sum as $\sum\limits_{u = 0}^n (u + 1)^{n - u} u!$.
I do not see any way to simplify this sum.
So the expected value in question will be $\frac{\sum\limits_{u = 0}^n (u + 1)^{n - u} u!}{n!}$. This is simple enough that we can explicitly calculate the value for $n = 6$.


text:
Q: Include user details in AWS Cognito Oauth2 token I'm using AWS cognito with a NodeJS backend API and want to include user details in the access token return from /oauth2/token end point with scopes defined in the user pool client app.
Also if I use adminInitiateAuth API, there is no way to include the scopes in the return access token. So is it possible to have both user details and scopes in a one access token?

A: Cognito does not support custom claims in access tokens, which I think is a really good design choice.
You can manage extra / custom data fairly easily in your APIs and UIs in a much more extensible manner via claims caching:
https://authguidance.com/2017/10/03/api-tokens-claims/
There is a node sample of mine that does this here:
https://github.com/gary-archer/oauth.websample2
It is a pattern often implemented by API gateways, such as AWS:
https://authguidance.com/2018/12/16/serverless-api-deployment/

A: Amazon Cognito returns multiple tokens uppon succesful autehntication : an ID token, an Access Token, and optionaly a Refresh Token.
Question 1 : user details in Token
The ID Token contains the some PII details, such as the use name and email address.
https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html
When using AWS amplify, you can use Auth.currentAuthenticatedUser() to retrieve user details from Cognito
https://aws-amplify.github.io/docs/js/authentication
Question 2 : adminInitiateAuth
This is currently not supported
https://github.com/aws-amplify/aws-sdk-android/issues/477


text:
Q: personality issues - only mental? As far as I can see from googling, the term "personality issues" mostly means a type of mental disorders.
Can it be, however, that in certain contexts (like jokes, for example, but not necesserally), it could stand for problems associated with relations between individuals (difference in character, incompatibility)?

A: The term "personality issues" is often used as a kind explanation for differences of opinion that cannot be readily understood by one party. This can be a PC synonym for mental disorders and is used to describe such troubles without calling someone crazy or stupid.
As far as jokes if one does not understand or resents my humour it can be ascribed to my "personality issues" rather than our incompatibility which may be partly up to them.

A: When you're trying to express problems between two people, you usually say they have a personality conflict.
You may even say "there are personality issues between X and Y", but you would not say that either one individually has a personality issue, unless you are suggesting that the individual has blameworthy character defects.


text:
Q: How can I cycle through states in an array in React? I need to implement a button that cycles through these states in this array so that when the button is clicked State_1 in each object becomes State_2, then State_2 becomes State_3 and then goes back to State_1. The tricky part for me so far has been figuring out how to cycle only through the states in each object. Any suggestions would be greatly appreciated!
  "people": [
    {
      "name": "Alice",
      "State_1": "Apple",
      "State_2": "Cherry",
      "State_3": "Dates"
    },
    {
      "name": "Bob",
      "State_1": "Banana",
      "State_2": "Plumb",
      "State_3": "Clementine"
    },
    {
      "name": "Eve",
      "State_1": "Grapes",
      "State_2": "Apricots",
      "State_3": "Grapefruit"
    }
  ]
}

A: So you want something like this? Let me know if I understood your question correctly.

const people = [
    {
      "name": "Alice",
      "State_1": "Apple",
      "State_2": "Cherry",
      "State_3": "Dates"
    },
    {
      "name": "Bob",
      "State_1": "Banana",
      "State_2": "Plumb",
      "State_3": "Clementine"
    },
    {
      "name": "Eve",
      "State_1": "Grapes",
      "State_2": "Apricots",
      "State_3": "Grapefruit"
    }
]

var saveState1
people.forEach(p => {
  saveState1 = p.State_1
  p.State_1 = p.State_2
  p.State_2 = p.State_3
  p.State_3 = saveState1
});

console.log(people)


text:
Q: How to upgrade from 21.04 Hirsute to 22.04 Jammy? I have a personal system, which I would like to upgrade, preferably without having to do a fresh install.
So far, I have tried to use the Software Updater GUI, which prompted me to update to 21.10. However after clicking update, it hasn't followed up with any prompts or anything that I could see.
I have also tried to use do-release-upgrade and do-release-upgrade -p both of which has failed stating that my release is not supported anymore.
I have tried to use do-release-upgrade -d as well, which has failed stating that:

Upgrades to the development release are only available from the latest supported release.

After which, I've looked for ways to update an end of life distribution and found this. However editing my /etc/apt/sources.list hasn't yielded any results either.
What can I do to update my system besides a fresh install?


text: Q: How to show products to customer which is customer specific I need to have an idea how we can do the product to be visible to specific customer. Something like there are two customers when a product is assign to customer1 he could see the product when he is login and also the product should not be visible to the customer2.


text:
Q: Border clipped off in Chrome but not IE or Edge This CSS & HTML shows three text boxes that are completely wrapped in their borders when viewed in IE and Edge.  When viewed in Chrome (or on my Android's browser) the right side of the border is clipped off.
I can make it work by adding a trailing " " to each span, but I'd rather learn whether I'm doing something wrong...

        First service offered

        Second service offered

        Third service offered

A: I'm not 100% sure why that specific behavior is happening and the discrepancies between browsers, but I would bet it has to do with white-space:nowrap and the parent elements width: 30% and some quirkyness with that.
Instead of trying to work around that quirk, a much easier way to do this is change the display of the .link-bubble's from inline to block.  You can do this with the display: block on the class, or just change the elements from span to div or other block elements.  Here's some good reading on the box model - I'd also recommend reading up on css flexbox and grid, much easier and more modern way of handling positioning of elements vs divs and floats.
Also, If you really need the white-space: nowrap, add that style to the inner element.  See my example below.

        First service offered

        Second service offered

        Third service offered


text:
Q: SCSS/Sass Compass: How to locate duplicate selectors I just inherited a nice little project where the CSS was split in multiple small CSS files because of IFrames.
So now that I'm linking everything together and putting it in SCSS, I find myself with tons duplicate selectors with exactly the same styling in them.
I'm guessing there is a nice little option in compass SCSS to have it "suggest" duplication of tags
Can anybody point me in the right direction?
Cheers,
Jason

A: I had this same problem a while back and the end result was a quick Sasslint tool I wrote to parse .sass files and output the line numbers of each duplicate selector: https://github.com/dfltr/Sasslint
I haven't updated it to explicitly support SCSS, nor do I know if any modifications are even needed to do so, but it might be a good starting point for you.


text:
Q: Handling different versions of project and pushing changes I have started to use Git (bitbucket) recently. I have a project and a corresponding workspace and a repository in bit bucket. Now I have the need to customize this project for different clients. How do I set this up? Create a new repository for every new client project under same workspace? Or create new workspace for each client project?
When a new common feature is to be added/ existing common feature is to be updated (for ex. only few files have code changes but to be applied to all client projects) how to handle this? Checking out each client project, making changes and pushing is lot of redundant work.
I went through lot of links but could not find a concrete answer. Any help is appreciated.

A: Usage of bitbucket workspaces look different depending on which organization you work for. For example our company uses workspaces for similar projects: www.bitbucket.org/ecommerce-apps/amazon-integration or www.bitbucket.org/ai-components/machine-learning-template
Although it makes logical sense to divide workspaces into different clients in order to keep the code base separate.

As to the common feature git structure, here is what I have done before.
Have a common-features.git repository to hold all the common files which stay the same between projects. This helps to keep track of versions of changes made to common files. If you were to make pull each repo, make changes manually, and push changes, there is no traceability and it is easy to make mistakes. Having a common repo allows one to keep track of who changed what and when.
When it comes time to update the project repo with the new files, one would clone the project repository, setup a second remote and pull changes from there.
git clone https://github.com/client1/project1
git remotes add upstream https://github.com/commons/common-features
git pull upstream branchname --allow-unrelated-histories

Unfortunately you would still have to do this for each project repository as there may be different things going on, such as different branches. Perhaps you want to update most projects with the latest features but only update other projects after some time.
If you insist on automating the updating of common feature changes, you could consider using webhooks in order to push changes to other repos in the event of a push to master of the common repo.


text:
Q: How to use $regex in mongodb aggregation query within $match I am trying to use the $regex within $match, its not returning the matching documents.
db.collection('MyCollection', function (err, collection) {
  collection.aggregate([
    { $match: { 'Code': 'Value_01', 'Field2': { $regex: '/Value_2/g' } } },
    { $project: {
        _id: 1,
        CodeNumber: '$Code',
        FieldName2: '$Field2'
      }
    }
  ], function (err, Result_doc) {
    console.log(Result_doc);
  }
});

Can anyone tell me where its going wrong or the correct syntax?

I even tried with replacing the

'Field2': { $regex: /Value_2/g }

A: I got it working with the following code:
var Value_match = new RegExp('Value_2');

db.collection('MyCollection', function (err, collection) {

  collection.aggregate([
    { $match: { Code: 'Value_01', Field2: { $regex: Value_match } } },
    { $project: {
        _id: 1,
        CodeNumber: '$Code',
        FieldName2: '$Field2'
      }
    }
  ], function (err, Result_doc) {
    console.log(Result_doc);
  }
});

On pushing the object content to console using console.dir(Value_match) it prints out '/Value_2/'

A: As it says in the $regex docs you linked to, the two ways to do this are:
Field2: /Value_2/g

OR
Field2: { $regex: 'Value_2', $options: 'g' }

But I also tried your second attempt of 'Field2': { $regex: /Value_2/g } and that worked as well.
BTW, the g regex option doesn't make sense in this context as you just need one match anyway.  Note that it isn't even listed in the $regex docs.


text:
Q: Select all unique pairs for given element - Criteria API I have a 'meeting' entity with params: meetingId, catId, dogId.
There can be a lot of meetings where pairs catId and dogId are the same.
I need to calculate how many dogs a given cat has met. In other words, I need to calculate the number of meetings of the given cat where each meeting was with a different dog.
How can I achieve this using springframework.data.mongodb.core.query.Criteria?
public long countUniqueByCatId(String catId) {
            Query query = new Query()
                    .addCriteria(Criteria.where(CAT_ID).is(catId))
                    ....
            return template.count(query, Meeting.class);

And the same question applies to stream.
meetingsList.entrySet()
                    .stream()
                    .map { it -> it.value }
                    .filter { m -> (m.getCatId() == catId) }
                    ...
                    .count();

A: You can try this code
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> query = cb.createQuery(Long.class);
Root<meeting> meetings = query.from(meeting.class);

//here you can change meetings to your new catdogIds class
cq.select(cb.countDistinct(meetings)).where(Criteria.where(CAT_ID).is(catId));
return entityManager.createQuery(cq).getSingleResult();

For the stream, you can use .distinct() but you should implement the equals method
like in this example
https://www.journaldev.com/31860/java-stream-distinct-function
also you can create a class contains catId and dogId and then convert the result list to a set after overriding the equals method to return true when the compared object has the same cat and dog id.


text:
Q: Move Magento 1.9 to new server, but all pages give 404 I am trying to move Magento 1.9 to new server, but all pages give 404, my steps was

*

*Copied and installed Database and files on the new server

*Fixed connections on the local.xml file

*Reset the usecured and secured base url from the core_config_data

*Cleared all files in var/cache var/session


text:
Q: Iterating through dictionary for tuples This is more for clarification:
If I said:
for key, value in dictionary.iteritems():

This would actually give me keys and values rather than just each key being assigned to both "key" and "value"
It is just something that has always confused me about Python?

A: For purposes of example the following two are equivalent:
Example 1
for item in dictionary:
  print(item, dictionary[item])

Example 2
for k, v in dictionary.items():
  print(k, v)

However, in Example 1 you do not have direct access to the value of the item itself, only the key, whereas in Example 2 you do have access to it in the form of v.
Terminal
>>> dictionary = {'a': 1, 'b': 2, 'c': 3}
>>> for item in dictionary:
...   print(item, dictionary[item])
...
b 2
c 3
a 1
>>> for k, v in dictionary.items():
...   print(k, v)
...
b 2
c 3
a 1

And of course k, v are arbitrary as k and v can be anything, e.g.:
>>> for abc, xyz in dictionary.items():
...   print(abc, xyz)
...
b 2
c 3
a 1


text:
Q: What is the purpose of the _loc variable when defining grammar rules in camlp4? The _loc variable appears in here in the grammar rule for the match ... with expression as an argument passed to the mk_sequence function.
    | "match"; e = sequence; "with"; a = match_case ->
        <:expr< match $mksequence' _loc e$ with [ $a$ ] >>

But it is not used in the mksequence's function body.
  value mksequence _loc =
    fun
    [ <:expr< $_$; $_$ >> | <:expr< $anti:_$ >> as e -> <:expr< do { $e$ } >>
    | e -> e ]
  ;

The _loc variable also appears in other places in the grammar rules.
In the camlp4 code generation tutorial, it says that _loc stands for location. But I don't quite understand the explanation there. Can someone explain to me the purpose for passing an unused _loc variable around?

A: Roughly speaking, _loc is "the current position". Normally it is bould to the location of the matched AST in parsing rules.
_loc is an ordinary OCaml variable, and actually omnipresent in CamlP4 code, but P4's syntax sugar nicely hide most of their existence. You can learn how '_loc' is introduced and used in P4 by preprocess your P4 module by P4. For example,
EXTEND Gram
  my_syntax:
    [ [ "match"; e = sequence; "with"; a = match_case ->
          <:expr< match $mksequence' _loc e$ with [ $a$ ] >>
    ] ];
END;

If you preprocess the above by camlp4rf, you got what it really means:
Gram.extend (my_syntax : 'my_syntax Gram.Entry.t)
  ((fun () ->
      (None,
       [ (None, None,
          [ ([ Gram.Skeyword "match";
               Gram.Snterm
                 (Gram.Entry.obj (sequence : 'sequence Gram.Entry.t));
               Gram.Skeyword "with";
               Gram.Snterm
                 (Gram.Entry.obj (match_case : 'match_case Gram.Entry.t)) ],
             (Gram.Action.mk
                (fun (a : 'match_case) _ (e : 'sequence) _
                   (_loc : Gram.Loc.t) ->
                   (Ast.ExMat (_loc, (mksequence' _loc e), a) : 'my_syntax)))) ]) ]))
     ())

It is bit hard but you can find Gram.Action.mk takes a function introducing an argument _loc. It is bound to the location of an AST which matches with the specification starts with [ Gram.Skeyword "match".... Then _loc is used at <:expr< match ... >> which is expanded into Ast.ExMat (_loc, ...), in addition to its second use at mksequence' _loc e, which is written by hand.
<:expr<...>> and the other <:XXX<...>> constructs in p4 uses this _loc variable so that you can create your AST without considering much about the location of it. It automatically uses _loc, "the current parsed location". If you do not want to use _loc for <:expr<...>> you can use <:expr@myloc<...>> to explicitly specify the location of your AST.
Sometimes you want to use <:expr<...>> outside of parsing rules, and in that case _loc is unbound. You must use <:expr@myloc<...>>, or use <:expr<...> after binding _loc by something else. Typically, let _loc = Loc.ghost which means "no where".
P4 is very complex, and there are not much documentations available in the net. Sometimes expanding your P4 code by P4 helps understanding how it works.


text:
Q: "Missing number, treated as zero" error with xcntperchap package I get some unexpected error messages ("! Missing number, treated as zero.") building both the examples provided in the xcntperchap package documentation and the following MWE:
\documentclass{book}

\usepackage{xcntperchap}
\RegisterTrackCounter{chapter}{nscene}

\begin{document}

\newcounter{nscene}
\newcommand{\act}[1]{\chapter{Act #1 with \ObtainTrackedValueExp{chapter}{nscene} scenes}\setcounter{nscene}{0}}
\newcommand{\scene}{\stepcounter{nscene}}

\act{A}
\scene

\act{B}
\scene
\scene

\act{C}
\scene

\end{document}

Am I doing something wrong?
Thanks


text:
Q: htaccess redirect remove category slug from url Using .htaccess file in apache server, how can I get
http://mysite/[category]/[post-title]

redirect to
http://mysite/[post-title]

where [category] and [post-title] could be any category name and post-titles respectively.
please help.
thanks

A: Try:
RedirectMatch 301 ^/[^/]+/([^/]+)/?$ /$1

A: if you are using wordpress i recommend that plugin
WP No Category Base
it works like a charm with my blog


text:
Q: Filter columns by the percentile of values in Pandas I would like to filter out columns with 'many' zero values in pandas.
It is not difficult to filter columns consist of 'all zero values', but what I want to do is filter columns with 'many zero values', for example, more than 75% of the column values.
Dataset (A has 3 zeros of 4 values, which is 75% of the column values.)
A B C
0 0 0
0 0 1
0 1 2
1 2 3

Result
B C
0 0
0 1
1 2
2 3

Are there any suggestion?

A: You can use mean of boolean mask, where True values are converted to 1, and then invert condition - >= to < for filter all columns with less mean as 0.75:
print ((df == 0).mean())
a    0.75
b    0.50
c    0.25
dtype: float64

print ((df == 0).mean() < 0.75)
a    False
b     True
c     True
dtype: bool

df = df.loc[:, (df == 0).mean() < 0.75]
print (df)
   b  c
0  0  1
1  0  1
2  1  0
3  1  1

A: You can use list comprehension , sum function and drop i.e
df = pd.DataFrame({'a':[0,0,0,1],'b':[0,0,1,1],'c':[1,1,0,1]})
mask = [i for i,j in enumerate((df == 0).astype(int).sum(axis=0).values)  if (j/df.shape[0])>=0.75]
df = df.drop(df.columns[mask], axis=1)

You can set the percentile as you like.
Output : if 75 percentile i.e (j/df.shape[0])>=0.75

   b  c
0  0  1
1  0  1
2  1  0
3  1  1

Output : if 50 percentile i.e (j/df.shape[0])>=0.50

   c
0  1
1  1
2  0
3  1


text:
Q: Apple's heart rate monitoring example and byte order of bluetooth heart rate measurement characteristics On the heart rate measurement characteristics:
http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
EDIT
Link is now at
https://www.bluetooth.com/specifications/gatt/characteristics/
and look for "heart rate measurement".
They no longer offer an XML viewer, but instead you need to view XML directly.
Also for services it's on this page.
END EDIT
I want to make sure I'm reading it correctly. Does that actually says 5 fields? The mandatory, C1, C2, C3, and C4? And the mandatory is at the first byte, and C4 is at the last two bytes, C1 and C2 are 8-bit fields, and C3 to C4 are 16-bit each. That's a total of 8 bytes. Am I reading this document correctly?
EDIT:
I'm informed that the mandatory flag fields indicate something is 0, it means it's just not there. For example, if the first bit is 0, C1 is the next field, if 1, C2 follows instead.
END EDIT
In Apple's OSX heart rate monitor example:
- (void) updateWithHRMData:(NSData *)data
{
    const uint8_t *reportData = [data bytes];
    uint16_t bpm = 0;

    if ((reportData[0] & 0x01) == 0)
    {
        /* uint8 bpm */
        bpm = reportData[1];
    }
    else
    {
        /* uint16 bpm */
        bpm = CFSwapInt16LittleToHost(*(uint16_t *)(&reportData[1]));
    }

    ... // I ignore rest of the code for simplicity
}

It checks the first bit as zero, and if it isn't, it's changing the little endianness to whatever the host byte order is, by applying CFSwapInt16LittleToHost to reportData[1].
How does that bit checking work? I'm not entirely certain of endianess. Is it saying that whether it's little or big, the first byte is always the mandatory field, the second byte is the C1, etc? And since reportData is an 8-bit pointer (typedef to unsigned char), it's checking either bit 0 or bit 8 of the mandatory field.
If that bit is bit 8, the bit is reserved for future use, why is it reading in there?
If that bit is 0, it's little-endian and no transformation is required? But if it's little-endian, the first bit could be 1 according to the spec, 1 means "Heart Rate Value Format is set to UINT16. Units: beats per minute (bpm)", couldn't that be mis-read?
I don't understand how it does the checking.
EDIT:
I kept on saying there was C5, that was a blunder. It's up to C4 only and I edited above.

A:
Am I reading this document correctly?

IMHO, you are reading it a little wrong.
C1 to C4 should be read as Conditional 1 to Conditional 4. And in the table for org.bluetooth.characteristic.heart_rate_measurement, if the lowest bit of the flag byte is 0, then C1 is met, otherwise, C2 is.
You can think it a run-time configurable union type in the C programming language(, which is determined by the flag. Beware this is not always true because the situation got complicated by C3 and C4).
// Note: this struct is only for you to better understand a simplified case.
// You should still stick to the profile documentations to implement.

typedef struct {
    uint8_t flag;
    union {
        uint8_t bpm1;
        uint16_t bpm2;
    }bpm;
} MEASUREMENT_CHAR;

How does that bit checking work?

if ((reportData[0] & 0x01) == 0) effectively checks the bit with bitwise AND operator. Go and find a C/C++ programming intro book if any doubt.
The first byte is always the flag, in this case. The value of flag dynamically determines how should the rest of the bytes should be dealt with. C3 and C4 are both optional, and can be omitted if the corresponding bits in the flag were set zeroes. C1 and C2 are mutual exclusive.
There is no endianness ambiguity in the Bluetooth standard, as it has been well addressed that little-endian should be used all the time. You should always assume that those uint16_t fields are transferred as little endian. Apple's precaution is just to reassure the most portability of the code, since they would not guarantee the endianness of architectures used in their future products.

A: I see how it goes. It's not testing for Endianness. Rather, it's testing for whether the field is 8 bit or 16 bit, and in the case of 16 bit, it'll convert from little endianness to host order. But I see that before conversion and after conversion it's the same number. So I guess the system is little endian to begin with so I don't know what's the point.


text:
Q: how I can get html source from webview without not page load on webview.? I want to get page source (html) from webview in android but I do not want to page load first.
Many source on stackoverflow says first load the page and use js ,onpagefinish event and then I will get the source but I do not want to this.I want to write url and back source to me. It is possible?
For example I write www.google.com and come me "..."


text:
Q: How to read a semi-colon separated file with double quotes in the columns? I have a semi-colon separated file which I want to read. The data in the file is given below. In the 4th row , I want to be able to read only 4 columns.
But I'm failing to do that in R.
ID;Comment;Date;Amt
1;Hello;5-06-2003;85.13
2;World;5-06-2013;127.39
3;Airlines;5-06-1999;148.34
4;"Air"l;ine"s";5-09-2013;87.94

data<-read.table(fileName,header=T,sep = ";",quote="\"",na.strings = c("" , ".", "-", "NA" ));

The above code does not work. Can anyone help ?

A: fread from the data.table package, which can handle such "exceptions" quite nicely, would be one way to solve this.
data.table::fread("file.txt")
   ID     Comment      Date    Amt
1:  1       Hello 5-06-2003  85.13
2:  2       World 5-06-2013 127.39
3:  3    Airlines 5-06-1999 148.34
4:  4 Air"l;ine"s 5-09-2013  87.94

A: Another way is to use some delicious regex
path <- tempfile()
writeLines('ID;Comment;Date;Amt
1;Hello;5-06-2003;85.13
2;World;5-06-2013;127.39
3;Airlines;5-06-1999;148.34
4;"Air"l;ine"s";5-09-2013;87.94', path)

(rl <- scan(path, what = ''))

read.table(text = gsub('^(\\w+);(.*?);(Date|[-0-9]+);(Amt|[0-9.]+)$',
                       '\\1 \\2 \\3 \\4', rl),
           quote = '', header = TRUE, stringsAsFactors = FALSE)

#   ID       Comment      Date    Amt
# 1  1         Hello 5-06-2003  85.13
# 2  2         World 5-06-2013 127.39
# 3  3      Airlines 5-06-1999 148.34
# 4  4 "Air"l;ine"s" 5-09-2013  87.94

And a simplified version gives the same thing
read.table(text = gsub('^(.*?);(.*);(.*?);(.*?)$',
                       '\\1 \\2 \\3 \\4', rl),
           quote = '', header = TRUE, stringsAsFactors = FALSE)


text:
Q: Homepage not responsive with Internet Explorer 11 I'm confused! I have made a simple webpage to just show an image and some text. It's responsive and it works fine in Firefox, Chrome, Safari and Internet Explorer 10, but not in Internet Explorer 11.
The problem is that it's not responsive, it take a long time to load and it doesn't show the Font Awesome icons in Internet Explorer 11. What could be the reason for this and how could this be fixed? Really preciate some help since I can't find any solution for this when I google around. Thanks!

@import url(http://fonts.googleapis.com/css?family=Shadows+Into+Light);

a {
text-decoration: none;
color: #2952a1;
}

html
{
overflow-y: scroll;
}

body {
margin:0;
padding:0;
height:100%;
color: #7F7F7F;
height: 100%;
}

#wrapper {
margin-top: 2%;
width: 100%;
height: 100%;
}

#card {
height: 100%;
margin: 0 auto;
width: 80%;
}

#mobileH1 {
display: none;
}

#desktopH1 {
display: block;
}

#leftSide {
height: auto;
float: left;
width: 50%;
}

#rightSide {
padding-top: 5%;
float: right;
width: 49%;
height: auto;
}

#leftSide img {
display: block;
height: auto;
width: 100%;
padding-top: 1%;
margin: 0 auto;
}

h1 {
text-align: left;
font-family: 'Shadows Into Light', cursive;
font-weight: 400;
font-size: 55px;
margin: 0;
}

p {
font-family: 'Dancing Script', cursive;
font-family: 'Shadows Into Light', cursive;
font-size: 28px;
margin: 0;
padding: 10px;
}

@media only screen and (min-width: 150px) and (max-width: 768px)
{

#mobileH1 {
display: block;
}

#desktopH1 {
display: none;
}

#card {
width: 90%;
}

#leftSide {
width: 100%;
}

#rightSide {
float: left;
padding-top: 0;
width: 100%;
}

#leftSide img {
width: 80%;
padding-top: 1%;
}

h1 {
font-size: 36px;
text-align: center;
}

p {
font-size: 24px;
}

}

@media only screen and (min-width: 150px) and (max-width: 320px)
{
h1 {
font-size: 28px;
text-align: center;
}
}
<!DOCTYPE html>

 <title>Konstkort & affischer</title>
 <meta name="description" content="Description text" />
 <meta name="viewport" content="width=width-device, initial-scale=1" />
 <meta charset="utf-8" />
 <link href="stylesheet.css" rel="stylesheet" type="text/css">
 <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

Headline!

Headline

    Text

     Phone number

     Mail

A: It Seems that you have coded proper div tags from your css file and we believe it is not the problem in the code and it might be the reason it get loaded in other browser as well as in Internet Explorer 10. Please try following suggestions to get rid of common issue in "Internet Explorer 11" while it unable to load the webpage.

You might want to turn off Tracking Protection and ActiveX Filtering
  in your "Internet Explorer 11" browser (TOOLS option). Tracking Protection and
  ActiveX Filtering help protect your privacy by blocking images or
  other content that might put your security or privacy at risk.

If the issue persists please try resetting Internet Explorer's security settings

Open the desktop, and then tap or click the Internet Explorer icon on
  the taskbar.Tap or click the Tools button Tools button, and then tap
  or click Internet options.
On the Security tab, tap or click Default level, and then tap or click
  OK.

If none of these suggestions work, you can try resetting Internet Explorer to its default settings.
Hope this helps!


text:
Q: Restaurar base de datos SQL en SQL 2008 Hola, hay forma de restaurar una base de datos que se genero en SQL Server 2012 en un SQL Server 2008? Al intentar hacerlo me marca error de conversión. Alguien sabrá si es posible? El error que me sale es el siguiente: la conversión especificada no es válida. (sqlmanagerui)

A: La primera respuesta que puedes buscar en la documentación oficial es No. Por razones de compatibilidad, se puede hacer hacia arriba, en al menos, tres versiones.

Pero existen algunas posibilidades que en función de la complejidad de la base de datos, puede ser superSencilla, o requerir algún pequeño retoque.
La primera es la utilización de la herramienta de generación de scripts.
Desde Sql Management Studio puedes generar los scripts, con datos

Siguiente

Siguiente
Hay que entrar en el botón de Avanzadas

Repasa todas las posibilidades, porque son muy interesantes. Ten especial cuidado con la versión para servidor y con los datos a incluir.
Por defecto, y depende de la versión, algunas opciones, como los desencadenadores, permisos, etc, te vienen marcados como false.

Cuando lo tengas preparado.
Aceptar
Ahora marca guardar como archivo de script y busca una ruta.

Siguiente ....
Esta opción funciona muy bien.
Exportar mediante scripts

A: Lamentablemente las herramientas naturales de SQL Server para restaurar a versiones anteriores no son tan directas, o al menos es lo que he visto.
La razón de por qué no lo hace, desde mi punto de vista, es debido a que internamente existen procedimientos almacenados que no son compatibles o incluso podría existir funciones o funcionalidades en la nueva versión que no existen en la anterior y que al momento de restaurar no sabe que hacer con ellas.
La recomendación sería, suponiendo que cuentas con la estructura de la base de datos en el 2008, realizar un link desde el 2008 a un servidor 2012 y pasas las tablas una a una.
Obviamente hay que tomar en cuenta las dependencias entre tablas por lo que la secuencia de carga es importante, es decir, cargar primeramente las que no dependen de otras tablas y asegurar que cuando cargues cada tabla cuente ya con las tablas a las que tiene relación (constrains).
Suerte!