text:
Q: How to animate centered square to the top I have a UIView in a portrait-only app.

*

*The view is centered vertically and horizontally with AutoLayout ("manually" using storyboards).

*The width equals the (main)view.width * 0.9

*The height is the same size of the width (it is a square).

I want to tap a button inside this UIView and animate it only vertically until it reaches the top border of the screen (eg. height*0.9, 10 pts, whatever is possible).
When I click again, I want to reposition back the view to its original position (centered as it was when I first tapped).
During the transition the square should not be tappable.
After reading many posts I could not understand what's the best way to do this (I red mainly developers saying old techniques using centerX should be avoided and lamentations about some versions of the SO behaving in strange ways).
I suppose I should find a way to get the current "position" of the constraints and to assign a constraint the "final" position, but I was not able to do it.
Any help is appreciated

A: You are all going the wrong way about this.
Add one constraint that pins the view to the top, and add one constraint that pins the view to centerY. It will complain, so pick one and disable it (I think the property in Interface Builder is called Installed).
If the initial state is the view in the center, disable the constraint that pins it to the top, and viceversa.
Now write IBOutlets for both constraints in your controller and connect them to those constraints. Make sure the declaration of that variable is not weak, otherwise the variable will become nil when the constraint is disabled.
Whenever you want to toggle your animation you can enable one constraint and disable the other.
@IBOutlet var topConstraint: NSLayoutConstraint!
@IBOutlet var centerConstraint: NSLayoutConstraint!

func toggleState(moveToTop: Bool) {
  UIView.animateWithDuration(0.25) {
    self.topConstraint.isActive = moveToTop
    self.centerConstraint.isActive = !moveToTop
    self.view.layoutIfNeeded()
  }
}

A: While you can use Autolayout to animate - to take the constraint constraining the centerY and set its constant to a value that would move to the top (e.g., constant = -(UIScreen.main.bounds.height / 2)), I would recommend using view's transform property.
So to move the view to the top you can use:
let topMargin = CGFloat(20)
let viewHalfHeight = self.view.bounds.height / 2
let boxHalfHeight = self.box.bounds.height / 2
UIView.animate(withDuration: 0.2) {
    box.transform = CGAffineTransform.identity
         .translatedBy(x: 0, y: -(viewHalfHeight - (boxHalfHeight + topMargin)))
}

You are moving box.center related to the view.center - so if you want to move the box to the top, you have to move its center by half a view's height (because the view's centerY is exactly height / 2 far from the view's top). That is not enough though, because then only a bottom half of the box is visible (now the box.centerY == view.top). Therefore you have to move it back by the box.bounds.height / 2 (in my code boxHalfHeight) - to make the top half visible. And to that boxHalfHeight you add topMargin so that there is some margin to the top.
Then, to move the box back to original position:
UIView.animate(withDuration: 0.2) {
    box.transform = CGAffineTransform.identity
}

EDIT
If you really want to go with autolayout, you have to have a reference to the centerY constraint, so for example if it is created this way:
let boxCenterYConstraint = self.box.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
boxCenterYConstraint.isActive = true

Then you can try this:
// calculating the translation is the same
let topMargin = CGFloat(20)
let viewHalfHeight = self.view.bounds.height / 2
let boxHalfHeight = self.box.bounds.height / 2
let diff = -(viewHalfHeight - (boxHalfHeight + topMargin))

boxCenterYConstraint.constant = diff
self.view.setNeedsLayout()
UIView.animate(withDuration: 0.2) {
    self.view.layoutIfNeeded()
}

And animation back:
boxCenterYConstraint.constant = 0
self.view.setNeedsLayout()
UIView.animate(withDuration: 0.2) {
    self.view.layoutIfNeeded()
}


text:
Q: expand column width of a grid view HI,
I need to expand column width of the grid view by dragging it to suitable length like we do in excel after selecting a column.Is it possible?

A: Have a look at Demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deploy Compodoc documentation on GitLab without using GitLab Pages Dear fellow developers,
I'd like to deploy our Compodoc documentation to GitLab in order to make it available to every developer within our team (like an API page).
According to the company I'm working for, I can't use GitLab Pages for this.
Any ideas?
Any help is appreciated

A: The company I am working for does not allow GitLab pages for some reason. So I had to come up with another solution.

Please keep in mind that I was looking for a way to make the
  documentation accessible to every developer.

In order to do so, I basically had to make two steps:

*

*Modify package.json
"docgen": "./node_modules/.bin/compodoc -p src/tsconfig.app.json",
"doc:buildandserve": "compodoc -p src/tsconfig.app.json -s",
"bundle-report": "webpack-bundle-analyzer dist/stats.json"
This will build and serve the documentation wherever it
is deployed.

*Modify build pipeline
I had to insert an extra step within my pipe to execute the above code so that developers can access the documentation like  http:\\www.your-applications-url.com\documentation
Hope this helps.


text:
Q: How to avoid error-message during the execution of a bash script? I need to write a bash-script which will find all files with name string.h on the computer and copy them to some folder. My code is here:
#!/bin/bash

sudo find / -type f -name "string.h" -exec cp {} $HOME/MyDocuments \;

But during the execution of the script, I get error-messages on my console terminal "permission denied". How I can avoid getting this message? Console terminal must be clear.

A: Suppress the error messages from stderr(2) to the NULL stream designated by /dev/null
sudo find / -type f -name "string.h" -exec cp "{}" $HOME/MyDocuments \; 2 > /dev/null

where the 2 in the above line stands for file descriptor.

I would personally recommend you to investigate the actual cause of the issue rather than suppressing it. Do the above only if you are absolutely sure that the errors are trivial.


text:
Q: Javascript - get array of dates between 2 dates var range = getDates(new Date(), new Date().addDays(7));

I'd like "range" to be an array of date objects, one for each day between the two dates.
The trick is that it should handle month and year boundaries as well.

A: Just came across this question, the easiest way to do this is using moment:
You need to install moment and moment-range first:
const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);

const start = moment()
const end = moment().add(2, 'months')
const range = moment.range(start, end)
const arrayOfDates = Array.from(range.by('days'))
console.log(arrayOfDates)

A: I was recently working with moment.js, following did the trick..
function getDateRange(startDate, endDate, dateFormat) {
        var dates = [],
            end = moment(endDate),
            diff = endDate.diff(startDate, 'days');

        if(!startDate.isValid() || !endDate.isValid() || diff <= 0) {
            return;
        }

        for(var i = 0; i < diff; i++) {
            dates.push(end.subtract(1,'d').format(dateFormat));
        }

        return dates;
    };
    console.log(getDateRange(startDate, endDate, dateFormat));

Result would be:
["09/03/2015", "10/03/2015", "11/03/2015", "12/03/2015", "13/03/2015", "14/03/2015", "15/03/2015", "16/03/2015", "17/03/2015", "18/03/2015"]

A: Try this, remember to include moment js,
function getDates(startDate, stopDate) {
    var dateArray = [];
    var currentDate = moment(startDate);
    var stopDate = moment(stopDate);
    while (currentDate <= stopDate) {
        dateArray.push( moment(currentDate).format('YYYY-MM-DD') )
        currentDate = moment(currentDate).add(1, 'days');
    }
    return dateArray;
}

A: I have been using @Mohammed Safeer solution for a while and I made a few improvements. Using formated dates is a bad practice while working in your controllers. moment().format() should be used only for display purposes in views. Also remember that moment().clone() ensures separation from input parameters, meaning that the input dates are not altered. I strongly encourage you to use moment.js when working with dates.
Usage:

*

*Provide moment.js dates as values for startDate, endDate parameters

*interval parameter is optional and defaults to 'days'. Use intervals suported by .add() method (moment.js). More details here

*total parameter is useful when specifying intervals in minutes. It defaults to 1.

Invoke:
var startDate = moment(),
    endDate = moment().add(1, 'days');

getDatesRangeArray(startDate, endDate, 'minutes', 30);

Function:
var getDatesRangeArray = function (startDate, endDate, interval, total) {
    var config = {
            interval: interval || 'days',
            total: total || 1
        },
        dateArray = [],
        currentDate = startDate.clone();

    while (currentDate < endDate) {
        dateArray.push(currentDate);
        currentDate = currentDate.clone().add(config.total, config.interval);
    }

    return dateArray;
};

A: I'm using simple while loop to calculate the between dates

var start = new Date("01/05/2017");
var end = new Date("06/30/2017");
var newend = end.setDate(end.getDate()+1);
end = new Date(newend);
while(start < end){
   console.log(new Date(start).getTime() / 1000); // unix timestamp format
   console.log(start); // ISO Date format
   var newDate = start.setDate(start.getDate() + 1);
   start = new Date(newDate);
}

A: var listDate = [];
var startDate ='2017-02-01';
var endDate = '2017-02-10';
var dateMove = new Date(startDate);
var strDate = startDate;

while (strDate < endDate){
  var strDate = dateMove.toISOString().slice(0,10);
  listDate.push(strDate);
  dateMove.setDate(dateMove.getDate()+1);
};
console.log(listDate);

//["2017-02-01", "2017-02-02", "2017-02-03", "2017-02-04", "2017-02-05", "2017-02-06", "2017-02-07", "2017-02-08", "2017-02-09", "2017-02-10"]

A: Array(7).fill().map((_,i) => dayjs().subtract(i, "day").format("YYYY-MM-DD"));

A: Here's a one liner that doesn't require any libraries in-case you don't want to create another function.  Just replace startDate (in two places) and endDate (which are js date objects) with your variables or date values.  Of course you could wrap it in a function if you prefer
Array(Math.floor((endDate - startDate) / 86400000) + 1).fill().map((_, idx) => (new Date(startDate.getTime() + idx * 86400000)))

A: I use this function
function getDatesRange(startDate, stopDate) {
    const ONE_DAY = 24*3600*1000;
    var days= [];
    var currentDate = new Date(startDate);
    while (currentDate <= stopDate) {
        days.push(new Date (currentDate));
        currentDate = currentDate - 1 + 1 + ONE_DAY;
    }
    return days;
}

A: You can do it easily using momentJS
Add moment to your dependencies
npm i moment

Then import that in your file
var moment = require("moment");

Then use the following code to get the list of all dates between two dates
let dates = [];
let currDate = moment.utc(new Date("06/30/2019")).startOf("day");
let lastDate = moment.utc(new Date("07/30/2019")).startOf("day");

do {
 dates.push(currDate.clone().toDate());
} while (currDate.add(1, "days").diff(lastDate) < 0);
dates.push(currDate.clone().toDate());

console.log(dates);

A: Not a shortest possible but easy, immutable and without dependencies
function datesArray(start, end) {
    let result = [], current = new Date(start);
    while (current <= end)
        result.push(current) && (current = new Date(current)) && current.setDate(current.getDate() + 1);
    return result;
}

Usage

function datesArray(start, end) {
    let result = [], current = new Date(start);
    while (current <= end)
        result.push(current) && (current = new Date(current)) && current.setDate(current.getDate() + 1);
    return result;
 }

//  Usage

const test = datesArray(
  new Date('2020-02-26'),
  new Date('2020-03-05')
 );

for (let i = 0; i < test.length; i ++ ) {
    console.log(
      test[i].toISOString().slice(0,10)
    );
}

A: Using JavaScript
const getDatesBetween = (startDate, endDate, includeEndDate) => {
    const dates = [];
    const currentDate = startDate;
    while (currentDate < endDate) {
        dates.push(new Date(currentDate));
        currentDate.setDate(currentDate.getDate() + 1);
    }
    if (includeEndDate) dates.push(endDate);
    return dates;
};

Using TypeScript
const getDatesBetween = (
  startDate: Date,
  endDate: Date,
  includeEndDate?: boolean
) => {
  const dates = [];
  const currentDate = startDate;
  while (currentDate < endDate) {
    dates.push(new Date(currentDate));
    currentDate.setDate(currentDate.getDate() + 1);
  }
  if (includeEndDate) dates.push(endDate);
  return dates;
};

Example
console.log(getDatesBetween(new Date(2020, 0, 1), new Date(2020, 0, 3)));
console.log(getDatesBetween(new Date(2020, 0, 1), new Date(2020, 0, 3), true));

A: I use moment.js and Twix.js they provide a very great support for date and time manpulation
var itr = moment.twix(new Date('2012-01-15'),new Date('2012-01-20')).iterate("days");
var range=[];
while(itr.hasNext()){
    range.push(itr.next().toDate())
}
console.log(range);

I have this running on http://jsfiddle.net/Lkzg1bxb/

A: I had trouble using the answers above. The date ranges were missing single days due to timezone shift caused by the local day light saving time (DST). I implemented a version using UTC dates that fixes that problem:

function dateRange(startDate, endDate, steps = 1) {
  const dateArray = [];
  let currentDate = new Date(startDate);

  while (currentDate <= new Date(endDate)) {
    dateArray.push(new Date(currentDate));
    // Use UTC date to prevent problems with time zones and DST
    currentDate.setUTCDate(currentDate.getUTCDate() + steps);
  }

  return dateArray;
}

const dates = dateRange('2020-09-27', '2020-10-28');
console.log(dates);

Note: Whether a certain timezone or DST is applied, depends entirely on your locale. Overriding this is generally not a good idea. Using UTC dates mitigates most of the time related problems.
Bonus: You can set the time interval for which you want to create timestamps with the optional steps parameter. If you want weekly timetamps set steps to 7.

A: var boxingDay = new Date("12/26/2010");
var nextWeek  = boxingDay*1 + 7*24*3600*1000;

function getDates( d1, d2 ){
  var oneDay = 24*3600*1000;
  for (var d=[],ms=d1*1,last=d2*1;ms<last;ms+=oneDay){
    d.push( new Date(ms) );
  }
  return d;
}

getDates( boxingDay, nextWeek ).join("\n");
// Sun Dec 26 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Mon Dec 27 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Tue Dec 28 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Wed Dec 29 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Thu Dec 30 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Fri Dec 31 2010 00:00:00 GMT-0700 (Mountain Standard Time)
// Sat Jan 01 2011 00:00:00 GMT-0700 (Mountain Standard Time)

A: Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

function getDates(startDate, stopDate) {
    var dateArray = new Array();
    var currentDate = startDate;
    while (currentDate <= stopDate) {
        dateArray.push(new Date (currentDate));
        currentDate = currentDate.addDays(1);
    }
    return dateArray;
}

Here is a functional demo http://jsfiddle.net/jfhartsock/cM3ZU/

A: If you are using moment then you can use their "official plugin" for ranges moment-range and then this becomes trivial.
moment-range node example:
const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);

const start = new Date("11/30/2018"), end = new Date("09/30/2019")
const range = moment.range(moment(start), moment(end));

console.log(Array.from(range.by('day')))

moment-range browser example:

window['moment-range'].extendMoment(moment);

const start = new Date("11/30/2018"), end = new Date("09/30/2019")
const range = moment.range(moment(start), moment(end));

console.log(Array.from(range.by('day')))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.1/moment-range.js"></script>

date fns example:
If you are using date-fns then eachDay is your friend and you get by far the shortest and most concise answer:

console.log(dateFns.eachDay(
  new Date(2018, 11, 30),
  new Date(2019, 30, 09)
))
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>

A: d3js provides a lot of handy functions and includes d3.time for easy date manipulations
https://github.com/d3/d3-time
For your specific request:
Utc
var range = d3.utcDay.range(new Date(), d3.utcDay.offset(new Date(), 7));

or local time
var range = d3.timeDay.range(new Date(), d3.timeDay.offset(new Date(), 7));

range will be an array of date objects that fall on the first possible value for each day
you can change timeDay to timeHour, timeMonth etc for the same results on different intervals

A: @softvar's solution, but then including working dates option
/**
 * Returns array of working days between two dates.
 *
 * @param {string} startDate
 *   The start date in yyyy-mm-dd format.
 * @param {string} endDate
 *   The end date in yyyy-mm-dd format.
 * @param {boolean} onlyWorkingDays
 *   If true only working days are returned. Default: false
 *
 * @return {array}
 *   Array of dates in yyyy-mm-dd string format.
 */
function getDates(startDate, stopDate, onlyWorkingDays) {
  let doWd = typeof onlyWorkingDays ==='undefined' ? false : onlyWorkingDays;

  let dateArray = [];
  let dayNr;
  let runDateObj = moment(startDate);
  let stopDateObj = moment(stopDate);

  while (runDateObj <= stopDateObj) {
    dayNr = runDateObj.day();
    if (!doWd || (dayNr>0 && dayNr<6)) {
     dateArray.push(moment(runDateObj).format('YYYY-MM-DD'));
    }

    runDateObj = moment(runDateObj).add(1, 'days');
  }
  return dateArray;
}

A: This is how i like to do it
// hours * minutes * seconds * milliseconds
const DAY_IN_MS = 24 * 60 * 60 * 1000

/**
 * Get range of dates
 * @param {Date} startDate
 * @param {Number} numOfDays
 * @returns {array}
 */
const dateRange = (startDate, numOfDays) => {
    const startDateMs = startDate.getTime()

    // get array of days and map it to Date object
    return [...Array(numOfDays).keys()].map(i => new Date(startDateMs + i * DAY_IN_MS))
}

A: That's another few lines solution using date-fns library:

const { format, differenceInDays, addDays } = dateFns;

const getRangeDates = (startDate, endDate) => {
  const days = differenceInDays(endDate, startDate);
  console.log([...Array(days + 1).keys()].map((i) => format(addDays(startDate, i), 'YYYY-MM-DD')));
};

getRangeDates('2021-06-01', '2021-06-05');
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>

A: function (startDate, endDate, addFn, interval) {

 addFn = addFn || Date.prototype.addDays;
 interval = interval || 1;

 var retVal = [];
 var current = new Date(startDate);

 while (current <= endDate) {
  retVal.push(new Date(current));
  current = addFn.call(current, interval);
 }

 return retVal;

}

A: I looked all the ones above. Ended up writing myself. You do not need momentjs for this. A native for loop is enough and makes most sense because a for loop exists to count values in a range.
One Liner:
var getDaysArray = function(s,e) {for(var a=[],d=new Date(s);d<=new Date(e);d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};

Long Version
var getDaysArray = function(start, end) {
    for(var arr=[],dt=new Date(start); dt<=new Date(end); dt.setDate(dt.getDate()+1)){
        arr.push(new Date(dt));
    }
    return arr;
};

List dates in between:
var daylist = getDaysArray(new Date("2018-05-01"),new Date("2018-07-01"));
daylist.map((v)=>v.toISOString().slice(0,10)).join("")
/*
Output:
    "2018-05-01
    2018-05-02
    2018-05-03
    ...
    2018-06-30
    2018-07-01"
*/

Days from a past date until now:
var daylist = getDaysArray(new Date("2018-05-01"),new Date());
daylist.map((v)=>v.toISOString().slice(0,10)).join("")

A: Using ES6 you have Array.from meaning you can write a really elegant function, that allows for dynamic Intervals (hours, days, months).

function getDates(startDate, endDate, interval) {
const duration = endDate - startDate;
const steps = duration / interval;
return Array.from({length: steps+1}, (v,i) => new Date(startDate.valueOf() + (interval * i)));
}
const startDate = new Date(2017,12,30);
const endDate = new Date(2018,1,3);
const dayInterval = 1000 * 60 * 60 * 24; // 1 day
const halfDayInterval = 1000 * 60 * 60 * 12; // 1/2 day

console.log("Days", getDates(startDate, endDate, dayInterval));
console.log("Half Days", getDates(startDate, endDate, halfDayInterval));

A: Note: I'm aware this is slightly different than the requested solution, but I think many will find it useful.
If you want to find each "x" intervals (days, months, years, etc...) between two dates, moment.js and the moment-range extension packages enable this functionality.
For example, to find each 30th day between two dates:
window['moment-range'].extendMoment(moment);

var dateString = "2018-05-12 17:32:34.874-08";
var start  = new Date(dateString);
var end    = new Date();
var range1 = moment.range(start, end);
var arrayOfIntervalDates = Array.from(range1.by('day', { step: 30 }));

arrayOfIntervalDates.map(function(intervalDate){
  console.log(intervalDate.format('YY-M-DD'))
});

A: *

*Generate an array of years:
const DAYS = () => {
 const days = []
 const dateStart = moment()
 const dateEnd = moment().add(30, 'days')
 while (dateEnd.diff(dateStart, 'days') >= 0) {
  days.push(dateStart.format('D'))
  dateStart.add(1, 'days')
 }
 return days
}
console.log(DAYS())

*Generate an arrays for month:
        const MONTHS = () => {
         const months = []
         const dateStart = moment()
         const dateEnd = moment().add(12, 'month')
         while (dateEnd.diff(dateStart, 'months') >= 0) {
          months.push(dateStart.format('M'))
          dateStart.add(1, 'month')
         }
         return months
        }
        console.log(MONTHS())

*Generate an arrays for days:
        const DAYS = () => {
         const days = []
         const dateStart = moment()
         const dateEnd = moment().add(30, 'days')
         while (dateEnd.diff(dateStart, 'days') >= 0) {
          days.push(dateStart.format('D'))
          dateStart.add(1, 'days')
         }
         return days
        }
        console.log(DAYS())

A: Using lodash & moment:
const startDate = moment();
_.range(0, 7).map((d) => startDate.clone().add(d, 'day').toDate())

A: This may help someone,

You can get the row output from this and format the row_date object as you want.

var from_date = '2016-01-01';
var to_date = '2016-02-20';

var dates = getDates(from_date, to_date);

console.log(dates);

function getDates(from_date, to_date) {
  var current_date = new Date(from_date);
  var end_date     = new Date(to_date);

  var getTimeDiff = Math.abs(current_date.getTime() - end_date.getTime());
  var date_range = Math.ceil(getTimeDiff / (1000 * 3600 * 24)) + 1 ;

  var weekday = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
  var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
  var dates = new Array();

  for (var i = 0; i <= date_range; i++) {
     var getDate, getMonth = '';

     if(current_date.getDate() < 10) { getDate = ('0'+ current_date.getDate());}
     else{getDate = current_date.getDate();}

    if(current_date.getMonth() < 9) { getMonth = ('0'+ (current_date.getMonth()+1));}
    else{getMonth = current_date.getMonth();}

    var row_date = {day: getDate, month: getMonth, year: current_date.getFullYear()};
    var fmt_date = {weekDay: weekday[current_date.getDay()], date: getDate, month: months[current_date.getMonth()]};
    var is_weekend = false;
    if (current_date.getDay() == 0 || current_date.getDay() == 6) {
        is_weekend = true;
    }
    dates.push({row_date: row_date, fmt_date: fmt_date, is_weekend: is_weekend});
    current_date.setDate(current_date.getDate() + 1);
 }
 return dates;
}

https://gist.github.com/pranid/3c78f36253cbbc6a41a859c5d718f362.js

A: Here's a canned method that will accept Moment dates or strings or a mixture as inputs and generate an array of dates as Moment dates. If you don't want Moment dates as output then change what the map() method returns.
const moment = require('moment');

// ...

/**
 * @param {string|import('moment').Moment} start
 * @param {string|import('moment').Moment} end
 * @returns {import('moment').Moment[]}
 */
const getDateRange = (start, end) => {
  const s = moment.isMoment(start) ? start : moment(start);
  const e = moment.isMoment(end) ? end : moment(end);
  return [...Array(1 + e.diff(s, 'days')).keys()].map(n => moment(s).add(n, 'days'));
};

A: Function:
  var dates = [],
      currentDate = startDate,
      addDays = function(days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
      };
  while (currentDate <= endDate) {
    dates.push(currentDate);
    currentDate = addDays.call(currentDate, 1);
  }
  return dates;
};

Usage:
var dates = getDatesRange(new Date(2019,01,01), new Date(2019,01,25));
dates.forEach(function(date) {
  console.log(date);
});

Hope it helps you

A: getDates = (from, to) => {
    const cFrom = new Date(from);
    const cTo = new Date(to);

    let daysArr = [new Date(cFrom)];
    let tempDate = cFrom;

    while (tempDate < cTo) {
        tempDate.setUTCDate(tempDate.getUTCDate() + 1);
        daysArr.push(new Date(tempDate));
    }

    return daysArr;
}


text:
Q: Set cursor position in Edit Text android How can i set the cursor position in android edit text? Im making a button which would make the cursor one character forward ie. an arrow key like

A: You can length of the string entered in edit text.
editText.setSelection(editText.getText().length());

A: You have to use setSelection(int position) method of edittext.
Like edt.setSelection(0)


text:
Q: Sorting an array objects by property having null value I need some help in sorting an array of objects.
The object has property value it can have either 100 or 0 or null.
I want to sort this array in descending order but null should always come in the end.
Example 1
Input
array = [{key: a, value: 100},{key: a, value: null},{key: a, value: 0}]

Expected output
array = [{key: a, value: 100},{key: a, value: 0},{key: a, value: null}]

A: try this
array.sort(function(a,b){
  var valA = a.value == null ? Number.MAX_SAFE_INTEGER : a.value;
  var valB = b.value == null ? Number.MAX_SAFE_INTEGER : b.value;
  return valA - valB;
})

A: You could check the value and use a very large value as sort value.

var array = [{key: 'a', value: 100},{key: 'a', value: null},{key: 'a', value: 0}];

array.sort(function (a, b) {
    return (b.value === null ? Infinity : b.value) - (a.value === null ? Infinity : a.value);
});

console.log(array);


text:
Q: Reason for decoherence time's dependence on variables? Zurek 2001 is a review article on decoherence in quantum mechanics. Equation 5.36 on p. 24 gives an estimate of the decoherence time, which I'll paraphrase as follows:
$ \frac{t_D}{t_R} = \left(\frac{\lambda_T}{x-x'}\right)^2 $ .
My attempt to interpret the meaning of the variables is:
$t_D$ is the decoherence time
$t_R$ is the thermal relaxation time for the object, which isn't perfectly isolated from its environment
$\lambda_T$ is the de Broglie wavelength for the mass of the whole object at an energy corresponding to the temperature of the environment
$x-x'$ is the difference in position between two states of interest, i.e., $t_D$ is going to be the time-scale for the exponential decay of the off-diagonal element of the density matrix corresponding to $x$ and $x'$
The result is that for a macroscopic object such as Schrodinger's cat at room temperature, we have $t_D/t_R\sim10^{-40}$.
Question 1: Am I correctly interpreting the meaning of the variables?
Question 2: Can anyone give a hand-waving argument for why we have this particular dependence on the variables?
Zurek arrives at this estimate after a very long derivation that to me is not very understandable. All I've been able to accomplish is some plausibility arguments:

*

*In the classical limit we expect the ratio inside the parens to go to zero, and it does, since the de Broglie wavelength goes to zero.

*Coherence is more difficult to maintain at macroscopic scales, where $|x-x'|$ is large.

*The result is positive, since the exponent is even.
Zurek, "Decoherence, einselection, and the quantum origins of the classical," http://arxiv.org/abs/quant-ph/0105127

A: The equation (5.36) in the (newest version) of the paper is:
$$ρ_S (x, x′ , t) = ρ_S (x, x′ , 0) e^{
−γt\left(\frac{x−x'}{\lambda_T}\right)^2} \tag{1}$$
where $\rho_S$ should be the off-diagonal term in the density operator, $\gamma$ the relaxation coefficient and $\lambda_T=\frac{\hbar}{\sqrt{2Mk_BT}}$ is the thermal de Broglie wavelength of the system. The equation follows from their master equation(which they derived earlier in the paper), in the high-temperature limit.
Master equation: $\dot \rho_S=-\frac{i}{\hbar}\left[ H_{ren},\rho_S\right]-\gamma(x-x')(\partial_x-\partial_{x'})\rho_S-\frac{\gamma}{\lambda_T^2}(x-x')^2\rho_S $
where $H_{ren}$ is the renormalized Hamiltonian.
In the macroscopic limit (i.e. when $\hbar$ is small compared to other quantities with dimensions of action, such as $2M k_B T (x − x′ )^2$ in the last term) the high-temperature master equation is dominated by:
$$\dot \rho_S(x,x',t)= -\gamma \left( \frac{x-x'}{\lambda_T}\right)^2\rho_S(x,x',t)$$
Solve this, and equation $(1)$ follows smoothly. Now, the exponential decay of the off-diagonal terms makes it plausible to define a decoherence timescale $\tau_D$:
$$\tau_D=\gamma^{-1}\left(\frac{ \lambda_T}{x-x'}\right)^2$$
Now let's get back to O.P.'s questions; I think the answer to the first question is yes, the interpretation looks correct($\tau_R=\gamma^{-1}$ is the thermal relaxation time).
About the second question, I would be more than happy if the O.P. finds the above derivation enough hand-wavy! Else, there is a typical representation of what's going on in this other well known paper(around page 13) by the same author. The reasoning is around the lines of having Gaussian distribution wave packets and doing numerical simulations and seeing what happens.


text:
Q: Only apply a CSS rule in Firefox How can I make the margin-top : -5%; apply only in Firefox?
In this code:
#snap {
    width: 100%;
    overflow: hidden;
    margin-top: -5%; // only apply in Firefox
}

A: You could use @supports to hack it.

Allows native feature detection, similar to Modernizr, using @supports

In the code below, margin-top: -50px will be applied to the div if -moz-transform: translate(0, 0) is supported on a browser.

div {
  width: 100px;
  height: 100px;
  background: red;
}

@supports (-moz-transform: translate(0, 0)) {
  div {
    margin-top: -50px;
  }
}

A: May be this works. It's a hack for Firefox that worked years ago. Have not tested it with latest Firefox.
  @-moz-document url-prefix() {
      #snap {
         margin-top: -5%;
            }
  }

Source: http://css-tricks.com/snippets/css/css-hacks-targeting-firefox/


text:
Q: SSHTunnel with key value (not path) I have an SSH key stored in a variable as I'm using a cloud function and don't have access to a filesystem. For example:
with SSHTunnelForwarder(
   ssh_address_or_host='my-host',
   ssh_username='my-user',
   ssh_pkey='/home/david/.ssh/id_rsa' # this
) as tunnel:

Instead of passing the path to the ssh_pkey file, how can I hardcode that as a string? Yes, I will move it to an environmental variable or something else, but for testing, is there a way to pass it a string?

A: As @TimRoberts commented, the ssh_pkey accepts paramiko.pkey.PKey instance, not only a path to a key file.
For an example how to construct PKey from a string, see:
SSH/SCP through Paramiko with key in string

A: This is how I solved it for GCP Cloud Functions. First I used Python to print out a base64 encoded key of my key file 'temp_key.pem'.  The reason I did this was because copying and pasting the key didn't work in the GCP environment variables even though it did locally:
import base64
with open('temp_key.pem', 'rb') as f:
    blob = base64.b64encode(f.read())

print(blob)
for_google_cloud_function = blob.decode('utf-8')
print(for_google_cloud_function)

The output of this I used an my environment variable SSH_KEY_BLOB. In my GCP Cloud Function I then added this (I've missed out the line getting it from the GCP environment variables):
# decode key back into a useable form from base64
SSH_KEY_BLOB_DECODED = base64.b64decode(SSH_KEY_BLOB)
SSH_KEY = SSH_KEY_BLOB_DECODED.decode('utf-8')

# pass key to parmiko to get your pkey
pkey = paramiko.RSAKey.from_private_key(io.StringIO(SSH_KEY))

# setup your SSHTunnel like normal
server = SSHTunnelForwarder(
    remote_server_ip,
    ssh_username=SSH_USERNAME,
    ssh_pkey=pkey,
    remote_bind_address=('127.0.0.1', 27017)
)

That way the key is not hard coded and the function is self sufficient from the file. They may be better ways but this worked for me.


text:
Q: Generate table schema inspecting Excel(CSV) and import data How would I go around creating a MYSQL table schema inspecting an Excel(or CSV) file.
Are there any ready Python libraries for the task?
Column headers would be sanitized to column names. Datatype would be estimated based on the contents of the spreadsheet column. When done, data would be loaded to the table.
I have an Excel file of ~200 columns that I want to start normalizing.

A: Use the xlrd module; start here. [Disclaimer: I'm the author]. xlrd classifies cells into text, number, date, boolean, error, blank, and empty. It distinguishes dates from numbers by inspecting the format associated with the cell (e.g. "dd/mm/yyyy" versus "0.00").
The job of programming some code to wade through user-entered data to decide on what DB datatype to use for each column is not something that can be easily automated. You should be able to eyeball the data and assign types like integer, money, text, date, datetime, time, etc and write code to check your guesses. Note that you need to able to cope with things like numeric or date data entered in text fields (can look OK in the GUI). You need a strategy to handle cells that don't fit the "estimated" datatype. You need to validate and clean your data. Make sure you normalize text strings (strip leading/trailing whitespace, replace multiple whitespaces by a single space. Excel text is (BMP-only) Unicode; don't bash it into ASCII or "ANSI" -- work in Unicode and encode in UTF-8 to put it in your database.

A: Quick and dirty workaround with phpmyadmin:

*

*Create a table with the right amount of columns. Make sure the data fits the columns.

*Import the CSV into the table.

*Use the propose table structure.

A: As far as I know, there is no tool that can automate this process (I would love for someone to prove me wrong as I've had this exact problem before).
When I did this, I came up with two options:
(1) Manually create the columns in the db with the appropriate types and then import, or
(2) Write some kind of filter that could "figure out" what data types the columns should be.
I went with the first option mainly because I didn't think I could actually write a program to do the type inference.
If you do decide to write a type inference tool/conversion, here are a couple of issues you may have to deal with:
(1)  Excel dates are actually stored as the number of days since December 31st, 1899; how does one infer then that a column is dates as opposed to some piece of numerical data (population for example)?
(2) For text fields, do you just make the columns of type varchar(n) where n is the longest entry in that column, or do you make it an unbounded char field if one of the entries is longer than some upper limit? If so, what's a good upper limit?
(3) How do you automatically convert a float to a decimal with the correct precision and without loosing any places?
Obviously, this doesn't mean that you won't be able to (I'm a pretty bad programmer).  I hope you do, because it'd be a really useful tool to have.

A: Just for (my) reference, I documented below what I did:

*

*XLRD is practical, however I've just saved the Excel data as CSV, so I can use LOAD DATA INFILE

*I've copied the header row and started writing the import and normalization script

*Script does: CREATE TABLE with all columns as TEXT, except for Primary key

*query mysql: LOAD DATA LOCAL INFILE loading all CSV data into TEXT fields.

*based on the output of PROCEDURE ANALYSE, I was able to ALTER TABLE to give columns the right types and lengths. PROCEDURE ANALYSE returns ENUM for any column with few distinct values, which is not what I needed, but I found that useful later for normalization. Eye-balling 200 columns was a breeze with PROCEDURE ANALYSE. Output from PhpMyAdmin propose table structure was junk.

*I wrote some normalization mostly using SELECT DISTINCT on columns and INSERTing results to separate tables. I have added to the old table a column for FK first. Just after the INSERT, I've got its ID and UPDATEed the FK column. When loop finished I've dropped old column leaving only FK column. Similarly with multiple dependent columns. It was much faster than I expected.

*I ran (django) python manage.py inspctdb, copied output to models.py and added all those ForeignkeyFields as FKs do not exist on MyISAM. Wrote a little python views.py, urls.py, few templates...TADA

A: Pandas can return a schema:
pandas.read_csv('data.csv').dtypes

References:

*

*pandas.read_csv

*pandas.DataFrame


text:
Q: Condition for a certain subset being a subgroup For any finite group $G$ and $n$ a divisor of $|G|$, consider the following subset of elements of "co-order" dividing $n$:
$$G(n) = \{ g \in G \mid g^{|G|/n} = 1 \}$$

*

*By a classical theorem of Frobenius, $\frac{|G|}{n} \mid |G(n)|$.

*A conjecture of Frobenius (which was proved via the classification of finite simple groups) states that if there's equality in the above divisibility, $G(n)$ is a normal subgroup.

*$G(n)$ contains the identity and is closed to taking inverse and conjugation.

I'm interested in the following question:

For a prime $p$, when is $G(p)$ a subgroup of $G$?

*

*By Lagrange's Theorem, if $G(p)$ is a subgroup of $G$, then $|G(p)| \in \{ |G|, \frac{|G|}{p} \}$.

*When $G$ is abelian, $G(p)$ is a evidently a subgroup.

*When $G$ is a non-cyclic $p$-group, $G(p)=G$.

*In fact, as long as the $p$-Sylow subgroup of $G$ is not cyclic, $G(p)=G$.

The case $p=2$ is very elegant: composing the natural maps $G \to S_G \to \{\pm 1\}$, we obtain $G(2)$ as the kernel of this composition, hence it's a normal subgroup.
The case $p=3$ is false in general (as seen from the example $G=S_3$), and so I guess an additional condition should be imposed - perhaps $p$ should be the smallest prime dividing $|G|$.
An additional question is:

When $G(p)$ is a subgroup, does is have an alternative characterization?

For example, for $p=2$, if the 2-Sylow subgroup of $G$ is cyclic, $G(2)=\langle g^2 \mid g\in G\rangle$.

A: You have noted (accurately) that $G(p) =G$ unless $G$ has a cyclic Sylow $p$-subgroup. However, it is also clear that when $G$ has a cyclic Sylow $p$-subgroup and $G(p) \neq G,$
the group $G$ has a normal $p$-complement. For, otherwise, we have by Burnside's transfer theorem, there is a $p$-regular element $x \in N_{G}(P) \backslash C_{G}(P)$. Now we have $P = [P,x] \times C_{P}(x).$ Since $P$ is cyclic and $P \neq C_{P}(x),$ we must have $P = [P,x]$ and $C_{P}(x) = 1.$ But then $P \leq G^{\prime},$ a contradiction, since $[G:G(p)] =p$ and $G(p)$ is clearly a normal subgroup when it is a subgroup.
On the other hand, if $G$ has a normal $p$-complement and cyclic non-trivial Sylow $p$-subgroup, then clearly $G$ has a normal subgroup of index $p$, and that that subgroup is indeed $G(p)$.
The conclusion (when $|G|$ has order divisible by $p,$ is that $G(p)$ is a subgroup of $G$ if and only if one of the following cases occur:
$G(p) = G$, or, $G$ has a normal $p$-complement and a cyclic Sylow $p$-subgroup.
Notice that when $p =2$, every finite group with a cyclic Sylow $2$-subgroup is known to have a normal $2$-complement, so the condition given for $p$ odd to guarantee that $[G:G(p)] = p$ is somewhat analogous to what you observed when $p =2$. It is indeed sufficient that $G$ should have a cyclic Sylow $p$-subgroup when $p$ is the smallest prime divisor of $|G|$ to ensure that $[G:G(p)] = p$. It is not, however, necessary.


text:
Q: Advice on which test to run to show a valid sample of participants I have collected data on medical diagnosis and am wanting to know which test I should use to show my participants are similar to a pre and post intervention.  The first set of data yielded 53% male and the post data yielded a 55% male.  I used and independent variable T-Test.  I am not sure this is the best test to use, is there any other test I should run to show validity?
Yes, I collected data on 2 separate groups of patients admitted with a specific diagnosis in a 3 month time frame from Jan-Mar, then a new intervention was put into place to improve the outcome of patients with this diagnosis which went into place in April. So after a 1 month adaptation period I collected data from a different group based on that same diagnosis from May-July. Basically I just want to show the 2 groups were similar in age and gender.

A: A test of equality of proportions would be a two sample proportions test, or a chi-square test. For ages (as long as they're not really coarsely grouped), a test of equality of means would be a t-test; an example of a test of equality of distribution would be the Kolmogorov-Smirnov test.
However, an ordinary hypothesis test is not an appropriate way to "show the groups are similar".
In large samples very similar groups would be rejected as being the same, while in small samples very different groups would not be rejected.
Better to specify what you mean by "similar" and make some assessment of that.
One possibility would be equivalence testing, but a reasonable measure of how different the two samples are is probably adequate - diagnostic plots or basic statistical comparisons.


text:
Q: Unable to disable back button once a form is submitted to firebase once i fill the form and submit it to Firebase,the code navigates me to my homepage but as soon as i press back button of my android phone, it send's user to previous form page with all previous filled data is available. i have tired using WillPopScope function to disable back button of my android phone but no response..
i have also created a function using willpopscope and called it in main but no result.
            @override
              Widget build(BuildContext context) {
                  return new WillPopScope(
                      onWillPop: () async =>false,
                   child: new Scaffold(
                   appBar: new AppBar(
                  title: new Text('Welcome'),
                    actions: <Widget>[
                       _onbackpressed(), //tried disabling the back button by calling this fucntion
                       new FlatButton(
                      child: new Text('Logout',
                          style: new TextStyle(fontSize: 17.0, color: Colors.white)),
                      onPressed: _signOut)
                   ],
                  ),
              body: _showTodoList(),
                floatingActionButton: FloatingActionButton(
                                    onPressed: () {
                               signupPage(context);

                          },
                           tooltip: 'Increment',
                           child: Icon(Icons.add),
                 )

              ),
            );
          }

     //extra funtion to disable the back button-
   _onbackpressed(){
    return new WillPopScope(
      onWillPop: () async =>false,
       child: new Container(width: 0.0,height: 0.0,),
       );

     }

         //function used to send the user form to server

                  RaisedButton(
                       elevation: 7.0,
                        child: Text('Upload'),
                        textColor: Colors.white,
                        color: Colors.blue,
                        onPressed: () {
                              final StorageReference firebaseStorageRef =
                              FirebaseStorage.instance.ref().child(Username);
                              final StorageUploadTask task =
                              firebaseStorageRef.putFile(_image);
                              success(context);

                             },
                   ),

        //where success is a fuction
              success(BuildContext context){
      Navigator.of(context)
     .push(MaterialPageRoute(builder:(context)=>Redirect() ));
 }

A: Instead of pushing a new screen when the user submits the form, you should pop it, like this:
success(BuildContext context){
    Navigator.of(context).pop();
}

The reason for this is because you have a stack of screens. When the user is done with one, you should send him back to where you want, instead of putting another one on the top and leaving the already used one on the stack.


text:
Q: libGDX HTML5 Project Builds Differently on Different Machine This is a strange one! On my old desktop, I was able to build and run my libGDX project for HTML5 using the gradlew html:dist gradle command.
I uploaded the files to my site and everything worked well.
But on my laptop I synced the project via GitHub to Android Studio, ran the same command and it appears that the default ApplicationListener runs instead of my own custom one.
The only thing that appears is a red rectangle: http://johnathongoss.com/jaggybattles/
The desktop and android versions run and build fine on my laptop.
I'm using Android Studio and the latest version of libGDX.
Here is some code:
public class HtmlLauncher extends GwtApplication {

    @Override
    public ApplicationListener createApplicationListener() {
            return  new MyGame();
    }

    @Override
    public GwtApplicationConfiguration getConfig () {

            GwtApplicationConfiguration cfg = new GwtApplicationConfiguration(1280, 720);

            return cfg;
    }

}

//MyGame Class (Doesn't seem to get this far?)

@Override
public void create() {
    camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
    setScreen(new LoadingScreen(this)); //Loads the assets and sets Main Menu Screen

}

I've had this problem before but it was because I didn't change the createApplicationListener() method to return my own custom ApplicationListener. Now it seems to return the right one, I really don't know what could be causing this.
I should point out I can't access my desktop computer anymore due to relocating.
Any advice would be gratefully received!
Edit: Loading Class
https://gist.github.com/jaggygames/79b1bd821f4203aadecfe5e8ba925150
Assets Class:
https://gist.github.com/jaggygames/5b863f1692b0974b769d5694b5a3334f
MyDistance Font Class
https://gist.github.com/ea7b5965488cd5672e9e7c20917df9a1


text:
Q: Unresolved external symbol during dll linking ALL,
I have a static link library which exports a class. This class contains a member of std::mutex.
When I link this library to my main project there is no problem, but when I try to link the library to dynamic link library in the same project I'm getting the undefined external symbol.
I double check and all the libraries I link are the same.
Whats weird is that the linker complain about the member and not the class itself.
What could be the issue?
TIA!
P.S. if it matter - I'm working with msvc 2017 on Windows 8.1.
P.P.S.:
Command to build the application:
/GS /analyze- /W4 /Zc:wchar_t /I"C:\Program Files (x86)\Visual Leak Detector\include" /I"..\dbinterface" /I"..\libdbwindow\res\gui" /I"c:\wxWidgets\lib\vc_dll\mswud" /I"c:\wxWidgets\include" /I"." /I"C:\Program Files (x86)\Visual Leak Detector\include" /Zi /Gm- /Od /Fd"vc_mswuddll\docview.pdb" /Zc:inline /fp:precise /D "WIN32" /D "_DEBUG" /D "_CRT_SECURE_NO_DEPRECATE=1" /D "_CRT_NON_CONFORMING_SWPRINTFS=1" /D "_SCL_SECURE_NO_WARNINGS=1" /D "WXMSW" /D "_UNICODE" /D "WXUSINGDLL" /D "_WINDOWS" /D "NOPCH" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /RTC1 /Gd /Oy- /MDd /FC /Fa"vc_mswuddll" /EHsc /nologo /Fo"vc_mswuddll\docview" /Fp"vc_mswuddll\docview.pch" /diagnostics:classic
Command to build the library:
/GS /analyze- /W4 /Zc:wchar_t /I"C:\Program Files (x86)\Visual Leak Detector\include" /I"..\dbinterface" /I"..\libfieldswindow" /I"..\libshapeframework" /I"..\libpropertypages" /I"..\libpropertieshandlers" /I"c:\wxWidgets\lib\vc_dll\mswud" /I"c:\wxWidgets\include" /I"." /Zi /Gm- /Od /Fd"vc_mswuddll\tabledataedit.pdb" /Zc:inline /fp:precise /D "MEMORYLEAKS" /D "WIN32" /D "_USRDLL" /D "DLL_EXPORTS" /D "_DEBUG" /D "_CRT_SECURE_NO_DEPRECATE=1" /D "_CRT_NON_CONFORMING_SWPRINTFS=1" /D "_SCL_SECURE_NO_WARNINGS=1" /D "WXMSW" /D "_UNICODE" /D "WXUSINGDLL" /D "MY_DLL_BUILDING" /D "_WINDLL" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /RTC1 /GR /Gd /Oy- /MDd /FC /Fa"vc_mswuddll" /EHsc /nologo /Fo"vc_mswuddll" /Fp"vc_mswuddll\tabledataedit.pch" /diagnostics:classic
The symbol is declared as
class __declspec(dllexport) Database
{
protected:
    struct Impl;
    Impl *pimpl;
    // more members here
};

struct Database::Impl
{
    static std::mutex my_mutex;
    // more members here
};

EDIT:
c:\Users\Igor\OneDrive\Documents\dbhandler_app\dbhandler\Debug>dumpbin /symbols
dbinterface.lib
Microsoft (R) COFF/PE Dumper Version 14.16.27045.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Dump of file dbinterface.lib

File Type: LIBRARY

COFF SYMBOL TABLE
000 010569A5 ABS    notype       Static       | @comp.id
001 80000191 ABS    notype       Static       | @feat.00
002 00000000 SECT1  notype       Static       | .drectve
    Section length   41, #relocs    0, #linenums    0, checksum        0
    Relocation CRC 00000000
005 00000000 SECT2  notype       Static       | .debug$S
    Section length 23FC, #relocs    2, #linenums    0, checksum        0
    Relocation CRC 3EE39AC2
008 00000000 SECT3  notype       Static       | .debug$T
    Section length   70, #relocs    0, #linenums    0, checksum        0
    Relocation CRC 00000000
00B 00000000 SECT4  notype       Static       | .bss
    Section length    4, #relocs    0, #linenums    0, checksum        0, select
ion    2 (pick any)
    Relocation CRC 00000000
00E 00000000 SECT4  notype       External     | ___@@_PchSym_@00@UfhvihUrtliUlmv
wirevUwlxfnvmghUwyszmwoviPzkkUwyrmgviuzxvUwvyftUhgwzucOlyq@4B2008FD98C1DD4
00F 00000000 SECT5  notype       Static       | .msvcjmc
    Section length    1, #relocs    0, #linenums    0, checksum 77073096
    Relocation CRC 00000000
012 00000000 SECT5  notype       Static       | __BDBDE527_dbinterface@pch
013 00000000 SECT6  notype       Static       | .debug$S
    Section length   84, #relocs    2, #linenums    0, checksum        0, select
ion    5 (pick associative Section 0x4)
    Relocation CRC 4D9779EE
016 00000000 SECT7  notype       Static       | .chks64
    Section length   38, #relocs    0, #linenums    0, checksum        0
    Relocation CRC 00000000

String Table Size = 0x8A bytes

  Summary

           4 .bss
          38 .chks64
        2480 .debug$S
          70 .debug$T
          41 .drectve
           1 .msvcjmc

EDIT 1:
Link command for application:
/OUT:"vc_mswuddll\docview.exe" /MANIFEST /NXCOMPAT /PDB:"vc_mswuddll\docview.pdb" /DYNAMICBASE "vld.lib" "dbinterface.lib" "wxmsw31ud_core.lib" "wxbase31ud.lib" "wxtiffd.lib" "wxjpegd.lib" "wxpngd.lib" "wxzlibd.lib" "wxregexud.lib" "wxexpatd.lib" "kernel32.lib" "user32.lib" "gdi32.lib" "comdlg32.lib" "winspool.lib" "winmm.lib" "shell32.lib" "shlwapi.lib" "comctl32.lib" "ole32.lib" "oleaut32.lib" "uuid.lib" "rpcrt4.lib" "advapi32.lib" "version.lib" "wsock32.lib" "wininet.lib" "odbc32.lib" "odbccp32.lib" /DEBUG /MACHINE:X86 /SAFESEH /INCREMENTAL /PGD:"vc_mswuddll\docview.pgd" /SUBSYSTEM:WINDOWS /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /ManifestFile:"vc_mswuddll\docview.exe.intermediate.manifest" /ERRORREPORT:PROMPT /NOLOGO /LIBPATH:"C:\Program Files (x86)\Visual Leak Detector\lib\Win32" /LIBPATH:".\Debug" /LIBPATH:"c:\wxWidgets\lib\vc_dll" /TLBID:1
Link command for the dynamic library:
/OUT:"..\dbhandler\vc_mswuddll\tabledataedit.dll" /MANIFEST /NXCOMPAT /PDB:"vc_mswuddll\tabledataedit.pdb" /DYNAMICBASE "vld.lib" "dbinterface.lib" "fieldswindow.lib" "shapeframework.lib" "propertieshandlers.lib" "propertypages.lib" "wxmsw31ud_adv.lib" "wxmsw31ud_core.lib" "wxbase31ud.lib" "wxtiffd.lib" "wxjpegd.lib" "wxpngd.lib" "wxzlibd.lib" "wxregexud.lib" "wxexpatd.lib" "kernel32.lib" "user32.lib" "gdi32.lib" "comdlg32.lib" "winspool.lib" "winmm.lib" "shell32.lib" "shlwapi.lib" "comctl32.lib" "ole32.lib" "oleaut32.lib" "uuid.lib" "rpcrt4.lib" "advapi32.lib" "version.lib" "wsock32.lib" "wininet.lib" "odbc32.lib" "odbccp32.lib" /IMPLIB:"vc_mswuddll\tabledataedit.lib" /DEBUG /DLL /MACHINE:X86 /SAFESEH /INCREMENTAL /PGD:"vc_mswuddll\tabledataedit.pgd" /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /ManifestFile:"vc_mswuddll\tabledataedit.dll.intermediate.manifest" /ERRORREPORT:PROMPT /NOLOGO /LIBPATH:"C:\Program Files (x86)\Visual Leak Detector\lib\Win32" /LIBPATH:"..\dbhandler\Debug" /LIBPATH:"..\libfieldswindow\vc_mswuddll" /LIBPATH:"..\libshapeframework\vc_mswuddll" /LIBPATH:"..\libpropertieshandlers\vc_mswuddll" /LIBPATH:"..\libpropertypages\vc_mswuddll" /LIBPATH:"c:\wxWidgets\lib\vc_dll" /TLBID:1
EDIT:
And here is the result of dumpbin with the change:
c:\Users\Igor\OneDrive\Documents\dbhandler_app\dbhandler\Debug>dumpbin /symbols
dbinterface.lib
Microsoft (R) COFF/PE Dumper Version 14.16.27045.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Dump of file dbinterface.lib

File Type: LIBRARY

COFF SYMBOL TABLE
000 010569A5 ABS    notype       Static       | @comp.id
001 80000191 ABS    notype       Static       | @feat.00
002 00000000 SECT1  notype       Static       | .drectve
    Section length   41, #relocs    0, #linenums    0, checksum        0
    Relocation CRC 00000000
005 00000000 SECT2  notype       Static       | .debug$S
    Section length 23FC, #relocs    2, #linenums    0, checksum        0
    Relocation CRC 3EE39AC2
008 00000000 SECT3  notype       Static       | .debug$T
    Section length   70, #relocs    0, #linenums    0, checksum        0
    Relocation CRC 00000000
00B 00000000 SECT4  notype       Static       | .bss
    Section length    4, #relocs    0, #linenums    0, checksum        0, select
ion    2 (pick any)
    Relocation CRC 00000000
00E 00000000 SECT4  notype       External     | ___@@_PchSym_@00@UfhvihUrtliUlmv
wirevUwlxfnvmghUwyszmwoviPzkkUwyrmgviuzxvUwvyftUhgwzucOlyq@4B2008FD98C1DD4
00F 00000000 SECT5  notype       Static       | .msvcjmc
    Section length    1, #relocs    0, #linenums    0, checksum 77073096
    Relocation CRC 00000000
012 00000000 SECT5  notype       Static       | __BDBDE527_dbinterface@pch
013 00000000 SECT6  notype       Static       | .debug$S
    Section length   84, #relocs    2, #linenums    0, checksum        0, select
ion    5 (pick associative Section 0x4)
    Relocation CRC 4D9779EE
016 00000000 SECT7  notype       Static       | .chks64
    Section length   38, #relocs    0, #linenums    0, checksum        0
    Relocation CRC 00000000

String Table Size = 0x8A bytes

  Summary

           4 .bss
          38 .chks64
        2480 .debug$S
          70 .debug$T
          41 .drectve
           1 .msvcjmc

A: __declspec(dllexport) means the question is about an import library of a DLL (not a "static link library"), and in that case the error is due to my_mutex not being exported. This could be resolved by exporting:

*

*either the entire nested class;
struct __declspec(dllexport) Database::Impl
{
  static std::mutex my_mutex;
  // more members here
};

*or just the static variable in question.
struct Database::Impl
{
  static __declspec(dllexport) std::mutex my_mutex;
  // more members here
};

This should work for the std::mutex used in the example here, but will run into C4251 with other STL templatized classes. That, in turn, can be worked around (see One way of eliminating C4251 warning when using stl-classes in the dll-interface for example), but a better solution might be to rearrange the APIs so that my_mutex does not need to be exported to begin with.


text:
Q: CSS3 Icon: inserted content isn't placed consistently I'm creating icons using only CSS3. So far so good, but I've run into a problem with the simplest one.
I just want to have an "!" centered in a circle, but its position isn't consistent. Sometimes it's a pixel higher, a pixel to the left, or both.
I have no idea what's causing this.
Here's a fiddle.
.nos {
    position: relative;
    height: 12px; width: 12px;
    border: 2px solid #e04006;
    border-radius: 50%; -webkit-border-radius: 50%; -moz-border-radius: 50%;
    display: block;
    color: #e04006;
    overflow: hidden;
    cursor: default;
}

.nos:hover {
    overflow: visible;
}

.nos span {
    position: absolute;
    padding-left: 18px;
    display: block;
    font-size: 14px; line-height: 16px; text-decoration: underline;
    white-space: nowrap;
}

.nos:before {
    content: '\21';
    position: absolute; top: 0; bottom: 0; left: 0; right: 0;
    margin: 0;
    height: 16px; width: 16px;
    display: block;
    font-family: "Lucida Console", Monaco, monospace; text-align: center; font-size: 12px; line-height: 12px; font-weight: bold;
}

A: Remove the height: 16px; width: 16px; from .nos:before
Update Fiddle

A: Looks like I managed to fix it after some tinkering. Not sure what did the trick.
.nos {
    position: relative;
    width: 12px; height: 12px;
    border: 2px solid #e04006;
    -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%;
    display: inline-block;
    color: #e04006;
    overflow: hidden;
    cursor: default;
}

.nos:hover {
    overflow: visible;
}

.nos span {
    position: absolute; top: -2px; left: -2px;
    height: 16px;
    padding-left: 18px;
    display: block;
    text-decoration: underline; font-size: 14px; line-height: 16px;
    white-space: nowrap;
}

.nos:before {
    content: '\21';
    position: absolute; top: -2px; left: -2px;
    width: 16px;
    display: block;
    font-family: Verdana, Geneva, sans-serif; text-align: center; font-weight: bold;  font-size: 13px; line-height: 13px;
}

Fiddle


text:
Q: equivalent to Content Provider in Windows Store App Android Content Provider system allows other apps to access the data of an app.
Is there any equivalent, or similar approach in WinRT?
I read App contract and extensions and Share contract in MSDN, but it has to execute provider app (an app holds data source) firstly, and then select target app afterward.
In Android Content Provider however, it can query data provider's repository while using target app (data receiver) with no selection of choosing steps. small but big difference in usage.

A: I'm not sure what kind of data you want your app to share, but it seems to me that what you are looking for might be the file picker contracts. They, I quote:

Make files accessible from a file picker if your app has a unique and/or valuable view of those files or if users cannot easily access the files another way.


text:
Q: Rails 3 migration error: SQLite3::SQLException: table "myTable" already exists: I've never worked with a db before, so this is all new to me.  I'm working in RubyMine, Rails 3.

*

*First, what is a migration, and why do it?  Can't I just edit a db through a database browser?  Does migration retain my data, or something?

*Secondly, I inherited a project, and there are 3 files in the migration folder with names like 20120128022506_users.rb.  If I just run the migrate task, I get:

SQLite3::SQLException: table "projects" already exists: CREATE TABLE "projects" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "partner_id" integer, "name" varchar(255))

And in fact, if you look in the file called "20120531031320_projects.rb", as expected, it is trying to make a projects table:
 def up
    create_table :projects do |table|
      table.integer :partner_id
      table.string :name
    end
    add_index :projects, :name
  end

This project was ported over from Sinatra, and maybe the db and migration files are out of sync (if that is the correct terminology).  Anyway, is there way to sync things up between these migration files and the db, so that I can add a new table to the db with a new migration file?

A: I solved this by putting a conditional in the migration to see if "projects" exists in the db:
  def up
    if (!ActiveRecord::Base.connection.tables.include?("projects"))
      create_table :projects do |table|
        table.integer :partner_id
        table.string :name
      end
    end
  end


text:
Q: How can i set google admob size? I'm on integrating google admob to android.
Guard said that SMART_BANNER is the size that have full width of screen.
But when i used SMART_BANNER,it is not matches to screen width.
If you know about this method,please help me.

A: Try the following code
<com.google.ads.AdView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        ads:adSize="SMART_BANNER" />


text:
Q: EF entity with local file reference, transactional integrity I have EF entity that has a reference to local file. I'd like:

*

*file to be created/updated/removed along with entity

*file changes rollback to take place along with database operation rollback (by using of temporary backups, for example)

Is there any working solution for this? Wouldn't like to do my own :(

A: using migrations there is an "up" and a "down" method that get called whenever a version is applied or rolled back. fairly sure you can write whatever code you want in that method.


text:
Q: How to make the data return 0 when using UNION ALL? When using UNION ALL,the data will not return 0. For example, if the frequency for high in table score is zero, it will return nothing. That is why I want to apply outer join in my code
Table1
  id    |   myid     |    score       |
---------------------------------------
1       |    20      |    high        |
2       |    20      |    low         |
3       |    21      |    average        |
4       |    21      |    high        |
5       |    21      |    low         |

Table2
 id2    |   myid     |   score      |
-------------------------------------
1       |    21      |   high       |
2       |    21      |   low        |
3       |    20      |   low        |
4       |    20      |   low        |
5       |    20      |   low        |

The output that I got for myid=20
myid     |  score       | f  |
-------------------------------
 20      |   low        | 4   |
 20      |   high       | 1   |

Desired output
 myid    |  score       | f  |
-------------------------------
 20      |   low        | 4   |
 20      |   high       | 1   |
 20      |   average    | 0   |

My code:
select myid, score, count(*) as f
from
(
  select myid, score from table1 where myid=12
  union all
  select myid, score from table2 where myid=12
) unioned
group by myid, score

A: The UNION ALL query is not enough because it may not contain all the possible values of score: 'high', 'low' and 'average'.
Use a query that returns all these possible values and left join the UNION ALL query:
select s.score, count(t.score) f
from (select 'high' score union all select 'low' union all select 'average') s
left join (
  select * from Table1 where myid = 20
  union all
  select * from Table2 where myid = 20
) t on t.score = s.score
group by s.score

See the demo.
Results:
> score   |  f
> :------ | -:
> average |  0
> high    |  1
> low     |  4

A: You should take a union of the two tables, and then aggregate on that:
SELECT
    myid,
    score,
    COUNT(*) AS f
FROM
(
    SELECT myid, score FROM table1
    UNION ALL
    SELECT myid, score FROM table2
) t
GROUP BY
    myid,
    score;

A: You can use UNION both tables, and then GROUP BY myid. For example:
select
  myid, score, count(*) as f
from (
  select myid, score from table1
  union all
  select myid, score from table2
) x
group by myid, score

EDIT:
If you want to always show high and low values as zero in the absence of rows for them, you can use a LEFT JOIN to do it:
select myid, score, sum(c) as f
from (
  select 'low' as score union select 'high'
) s
left join (
  select myid, score, 1 as c from table1
  union all
  select myid, score, 1 from table2
) x on x.score = s.score
group by myid, score

Mind I didn't test this last query.


text:
Q: Visual Studio wcf client c# SOAP evenlope method name with different case I have a C# WCF client that should call a third part WCF web service: the misfortune of the web service is that the parameter type is equal to the method name and change only the case sensitive: when i make the following call where the type of the variable lclassname has the same name of the method ClassName (change only the case sensitive):
var lclassName = new className()
...
...
var lreturnValue = new ClassName(lclassName);

I have noticed in the raw XML request that Visual Studio make a thing like this when i try to call the web service using the client class Reference.cs build by Visual Studio throught the Add Service reference function:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <ClassName xmlns="">
            <ClassName...>

            </ClassName...>
        </ClassName...>
    </s:Body>
</s:Envelope>

I have traced the SOAP raw http request made by Visual Studio throught the System.Diagnostics.TextWriterTraceListener in web.config.
if you note Visual Studio change the first case letter of the type of the parameter. Why?
I call a web service of third party and i can't change the type of the parameter.
Is there a way to say to Visual Studio when call WCF client throught SOAP not to change the names of the methods? (For example with some attributes or some options in endpoint web.config)
Thanks.


text:
Q: How would I make a simple recursive function outputting the number of divisors a number has? In an online class, I received this problem.
Write a function numDivisors( N ) that returns the number of integers from 1 to N (inclusive) that divide N evenly. For example, numDivisors(42) would return 8, since 1, 2, 3, 6, 7, 14, 21, and 42 are divisors of 42. (Python 2.7)
Although I have solved it with a loop, I'm wondering how I would go about this with recursion.
The basic functionality of this function with a loop would be:
def numDivisors( N ):
    """ returns # of integers that divide evenly into N """
    divisors = 1 # the factor 1
    if N != 1:
      divisors += 1 # the factor N

    for i in range(2,int(N)): # loops through possible divisors
      if N % i == 0: # factor found
        divisors += 1
    return divisors

How could I implement it recursively using the bare basics (declaration, conditionals, looping, etc. up to list comprehensions)?
Thanks!

A: If we have to be recursive:
>>> def ndiv(N, i=1):
...    return 1 if N==i else ((N % i == 0) + ndiv(N, i+1))
...

Let's test it.  As per the question:

For example, numDivisors(42) would return 8

>>> ndiv(42)
8

Thus, this produces the desired output.
If we can do away with recursion, here is how to do it just using list comprehension:
>>> def div(N):
...     return sum(1 for i in range(1, N+1) if N % i == 0)
...
>>> div(42)
8

A: how about
def find_divisors(N,i=1):
    if i >= N**0.5+1: return set([])
    if N%i == 0: return set([i,N//i]).union(find_divisors(N,i+1))
    return find_divisors(N,i+1)

recursion is a pretty lousy solution to this problem ... do you really need to find all the divisors? or are you looking for a special one?


text:
Q: why does the code not work and return correct in the if statement

var question_list = ["What is 1 + 1", "What is 2 + 2"]
var answer_list = [2, 4]
let currentNumber = 0;
let scoreboard = 0;

function submit() {
    let user_answer = $('#question-number').val()
    console.log(user_answer)
    console.log(answer_list[currentNumber])
    if (user_answer === answer_list[currentNumber]) {
        console.log("correct");
    } else {
        console.log("eror");
    }
}
submit();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="question-number" />

I am not sure why the if else statement gives me the else answer because
the terminal will print out
2
2
eror


text:
Q: Does molten solder flow towards a heat source? When soldering both plumbing and wiring I have heard the advice that you shoulf apply solid solder opposite to your heat source, since the solder "will flow towards the heat" once it melts.
Is this a true statement, in general?
I could imagine that perhaps an increasing temperature gradient would decrease the solder's viscosity, and maybe that could promote more flow?
(And obviously a really uneven temperature could leave areas below the melting point, so in that case the advice sort of makes sense but only in a trivial way.)
I can think of other reasons why you might want to apply solder away from the heat source - in particular so the heating device doesn't get in your way. Also because by applying the solder far from the heat source your have a high likelihood of the melting temperature being exceeded throughout the joint once it melts at the solder. I wonder if there are the only genuine explanations.
Related:

*

*Explanation that soldering relies on capillary action

*Example of surface tension effects during soldering

A: If you are sitting close to the melt temperature, the hotter the solder gets, the lower its viscosity becomes. Since viscosity is the retarding force in capillary flow, this means that hot solder flows far more easily into small crevices, which yields the impression that solder flows or is drawn towards the source of heat.
Most soldering irons have fairly limited heat delivery rates (20 to 40 watts) which means it's often a challenge to get enough heat into a joint in advance, which magnifies this effect.

A: According to this, viscosity is not the important factor; surface tension is.  This relates to the contact angle between the molten solder and the metal surface it is on.  When that contact angle is between 0 and 90 degrees, the solder flows. Between 90 and 180 degrees, the solder does not wet the surface.  The contact angle of a solder droplet on a given metal is dependent on temperature, and approaches zero at high temperature.  This drawing is from :


text:
Q: Alternative to CLUSTER without table lock I'm facing performance degradation and increasing storage usage as a result of frequent new and updated records causing index and storage fragmentation.
VACUUM doesn't help much.
Unfortunetely CLUSTER isn't an option as it causes downtime and pg_repack isn't available for AWS RDS.
I'm looking for hacky alternatives to CLUSTER. One that seems to work fine in my local tests is:
begin;

create temp table tmp_target as select * from target;

delete from target;
insert into target select * from tmp_target order by field1 asc, field2 desc;

drop table tmp_target;

commit;

The ordering of ctid looks correct with:
select ctid, field1, field2 from target order by ctid;

The question is: does this look fine? Is it going to lock the target table for SELECT queries causing downtime in apps?
Is there a way to list the locks involved in the transaction?
Related to Cluster command locking read only queries on replica

A: If it's just about table bloat, VACUUM FULL is the tool to do it. (VACUUM only shrinks the physical file if it can opportunistically truncate it at the end.) However, VACUUM FULL also takes an exclusive lock on the table, just like CLUSTER.
To do the same without exclusive lock pg_repack is the tool you are looking for. It's unfortunate that Amazon does not seem to allow it.

*

*VACUUM returning disk space to operating system
Manual solutions introduce all sorts of corner cases and race conditions. You would need to specify your table and possible access patterns exactly before we can discuss the best solution.
Your current solution is no good either way. You do the sort operation after deleting all rows (locking them), which will not shorten the downtime (the duration of the lock) for SELECT queries.
If you have no concurrent write access and no depending objects, this might be better:
BEGIN;

CREATE TEMP TABLE tmp_target AS TABLE target ORDER BY field1, field2 DESC;

TRUNCATE target;
INSERT INTO target TABLE tmp_target;

-- DROP TABLE tmp_target;  -- optional; dropped at end of session automatically

COMMIT;

*

*Sort in the background before taking the lock.
Strictly speaking, INSERT without ORDER BY is free to write rows in any physical order. Practically, though, it will copy the current physical order of the temp table with a plain SELECT * FROM (or TABLE for short).

*Use TRUNCATE instead of DELETE, which is faster for big tables. Be aware of some implications like TRUNCATE does not work with FK constraints. Read the manual for full coverage.
You may want to drop existing indexes right before TRUNCATE and recreate after INSERT to make this faster.
Related:

*

*Best way to populate a new column in a large table?

*Why wouldn't VACUUM ANALYZE clear all dead tuples?

*Configuring PostgreSQL for read performance

A: pg_repack is available on RDS now.


text:
Q: Running c++ in Windows as .exe I wrote a c++ program and converted it to a .exe file with the hopes to let it run on windows without needing to install a compiler. I ran well on my main computer (which has a compiler so it ran as expected) but did not run on another device. The error message shown was "libgcc_s_dw2-1.dll was not found"
How can I run a c++ program (or .exe file) from a flashdrive or other medium on any windows machine without extra installation.

A: C++ programs require additional c++ standard and runtime libraries to run. Most linker links to these libraries dynamically. That is some dll are required for running the program. You can run the program from a portable flash drive by copying those dll to the same folder as the application.
Alternatively, some linkers also have option to statically link, that is incorporate the code in dll ( kind of ) to your binary exe.
So you can either find out what all dll is required and copy them to your local folder ( maybe use something like dependancy walker or this newer one, i haven't actually used the newer alternative). Or use static linking like shown in this answer.


text:
Q: Eclipse and GWT desing mode I am Working with GWT and eclipse. I am facing a problem . The design mode of eclipse is not working. I am using the eclipse 3.7 . Where is the problem?

A: One way to see design view is extending the view part. you can try this one.
public class test extends ViewPart {

    public test() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public void createPartControl(Composite parent) {
        // TODO Auto-generated method stub
    }
    @Override
    public void setFocus() {

    }

}

A: You need to right click the file you want to open, then click open with --> GWT Designer.

A: Make sure your resource exclusion filters are not too strict.
If you are using Maven, the issue is explained here.


text:
Q: Request a certificate from the certificate authority Phishing question.
I have a tcp server application that uses certificates for tls/ssl and stored in the pkcs#12 file.  Assuming a CA is installed somewhere on the network and is accessible,  would it be normal practice to request a ssl certificate from the CA (once), programmatically (C#) and write it out to the pkcs#12 file for use by the server.
Would that be normal practice, or would the more likely scenario be a case of buying the certificate from a CA like Thawte or Versign etc, specically for that customer, and creating the pkcs#12 file beforehand, and installing as part of installation process.

A: I think this is a case where the argument can go either way.
Programmatic certificate requests and signing have their merits if you need to manage a large number of sites, at the loss of human-mediated validation if something goes horribly wrong (for example, if someone hijacks or listens in on your initial request). At some point, a trust decision needs to be made, either programmatically, or as a human operator.
This paper by Bruce Schneier goes into more detail, discussing potential risks to the CA architecture underpinning the trust decisions for PKI cryptography. I believe this covers many cases that are pertinent to your issue and your design that you may not have, and should, consider.


text:
Q: What has been your successful pitch to Management for using SCRUM? What approach did you take to describe the benefits of SCRUM to clients / business units who do not have a technical background? Please list any analogies you thought were useful.  Finally, how did you address the concerns that the Waterfall camp had?

A: I basically go around about risk reduction and ROI, since these are the main things people at the higher management level care about.
Using a incremental process significantly reduces the risk of wasting money on something that's not gonna be useful, because the customer helps steer the product development in the right direction through series of planned feedback cycles. The #1 reason for project failure according to the CHAOS research is lack of customer involvement. So why not use a process that eliminates that risk?
Also, with a incremental process you start delivering something in a much shorter time than when using a waterfall approach, which effectively increases the ROI (return on investment), since the customer starts benefiting from the product after one or two months, instead of waiting 6 to 12 months in a typical waterfall project.
You can also mention improved customer satisfaction, team self-improvement and self-management, which reduces the administrative overhead, improved employee satisfaction.

A: An additional point is protection of investment - with traditional approaches, a system typically "ages" with time, its value decreases, and maintenance costs rise until it's no longer feasable to maintain it. With an Agile approach applied well, the code should be maintainable and extensible indefinitely.
Here is a good, short video on all three points: http://www.youtube.com/watch?v=OWvSnYjqOTQ

A: I would mention the benefits of focus. Because the guiding principle of sprints is functional focus and shipability, all details (e.g. ergonomics) need to be taken care of, whose fixing would otherwise be postponed under pressure in more global approaches. You don't have it all but what you have is solid. Non technical people appreciate that because it reduces risk from their point of view: it injects honesty and trust, together with interactivity, in the dialog with clients.


text:
Q: How do I update bash on a Quantal system? I'm running Ubuntu Quantal (version 12.10), which no longer receives security updates from Canonical. What's the quickest way to update my copy of bash against the big vulnerability reported today?

A: The cleanest way is to compile from source.
The correct way is to upgrade.
The wrong way is to get the package from a release which has patched that (according to this question, fixes have been released for supported versions - 10.04, 12.04, 14.04) and install it.

A: It is possible to download the Precise (12.04) Bash package from http://packages.ubuntu.com/precise/bash and install it on Quantal (12.10).
I have been running this on a server all day and haven't noticed any problems. I plan to upgrade the server, but for a number of reasons I can't do it for a couple of weeks. This is only a stopgap solution.
To do this you need to follow the link above, choose which architecture your system is running (amd64 or i386) and download the relevant package. It can then be installed using dpkg, with something like:
sudo dpkg -i  /path/to/download/bash_4.2-2ubuntu2.3_amd64.deb


text:
Q: Regarding not able to get all the registered routes in node I have used express router for us routing in my app
now i want to get list of all the registered routes but not able to get it
I have used route as follows
global.router = express.Router();
app.use('/api', require('./routes'));

I have declared all routes in routes.js file and that is working perfectly fine
but when I try to access the all the routes then it is return undefined in route
let allRoutes = app._router.stack.map(r => r.route.path)

A: app._router.stack.forEach(function(r){
  if (r.route && r.route.path){
    console.log(r.route, r.route.path)
  }
})

Can you make sure by consoling if you're getting list of all routes in app._router.stack?
If yes, then you can map through it by using forEach.
Make sure you have express version 4.x


text:
Q: person is eligible to play on the team problem=A soccer team is looking for girls from ages 10 to 12 to play on their team. Write a program to ask the user's age and whether the user is male or female (using "m" or "f"). Display a message indicating whether the person is eligible to play on the team. but Make the program so that it doesn't ask for the age unless the user is a girl.
here is my code
name=raw_input("Enter ur name ")
gender=raw_input("Enter ur gender ")
if gender=="f":
    age=float(raw_input("enter ur age "))
if 10<= age <=12:
    print "ur eligible"
elif gender=="m":
     print "male not allowed"
else :
    print "ur not eligible"

A: Here are few quick points I noticed:
1.Indentation issue for the if statement in the age condition.
This if statement should ideally be within the if statement of gender==f.

*The way python requires you to write/use "and" condition. You can look at the syntax here https://www.learnpython.org/en/Conditions

*If someone enters an age out of the range required, there should be display on the screen such as female but not eligible.

*Its always good to introduce certain print statements as part of debugging to see how/where your code is reaching upto while executing.
The below piece of code should help
name=input("Enter ur name ")
gender=input("Enter ur gender ")
if gender=="f":
    age=float(input("enter ur age "))
    if age <=12 and age >=10:
        print ("ur eligible")
    else:
        print("female but not eligible"              )
elif gender=="m":
     print ("male not allowed")

A: It is just an indentation problem.
You should add also an else inside the first if in case you want show that a girl without the correct age is not elegible. Finally, you could want change the last message to show that a sex different to f or m is not valid.
name=raw_input("Enter ur name ")
gender=raw_input("Enter ur gender ")
if gender=="f":
    age=float(raw_input("enter ur age "))
    if 10<= age <=12:
        print "ur eligible"
    else:
        print "ur not eligible"
elif gender=="m":
     print "male not allowed"
else:
    print 'gender should be "m" (male) or "f" (female)'


text:
Q: Not able to call service in angularjs I am getting the following error:
Error: [$injector:unpr] Unknown provider: myServiceProvider <- myService

while calling a service in angularjs please help me to solve this issue
var app = angular.module('app', [])

app.controller('myController', ['$scope', 'stringService', function ($scope, stringService) {
    $scope.output = stringService.processString(input);
}]);

var app = angular.module('app', []);
app.factory('stringService', function(){
    return{
        processString: function(input){
            if(!input){
                return input;
            }

            var output = "";
            for(var i = 0; i < input.length; i++){
                if(i > 0 && input[i] == input[i].toUpperCase()){
                    output = output + " ";
                }
                output = output + input[i];
            }
            return output;
        }
    }
});

A: In:
['$scope', 'myService', function ($scope,   stringService)

you are injecting myService which doesn't exist. So, change to:
['$scope', 'stringService', function ($scope,   stringService)

A: You define your factory as stringService, but you're trying to inject it as myService, if you do it as following it should work:
app.controller('myController', ['$scope', 'stringService', function ($scope, stringService) {
    $scope.output = stringService.processString(input);
}]);

A: Change your second module line to this:
var app = angular.module('app');

If you pass 2 parameters, it defines a new module. If you pass one parameter, then it does a module lookup.
You should be defining the module once.

A: your code defined two app named app, myService doesn't exist, it should change to stringService,
i think your code should be like this:
var app = angular.module('app', []);
app.factory('stringService', function(){
return{
processString: function(input){
if(!input){
return input;
}
var output = "";
for(var i = 0; i < input.length; i++){
if(i > 0 && input[i] == input[i].toUpperCase()){
output = output + " ";
}
output = output + input[i];
}
return output;
}
}
});

app.controller('myController',
['$scope', 'stringService', function ($scope, stringService) {
$scope.output = stringService.processString(input);
}]);


text:
Q: Why would you assign a function to a variable instead of declaring a named function? Why would I do this:
var myfunc = function() { /* code */ };

...

myfunc();

instead of this:
function myfunc() { /* code */ }

...

myfunc();

Are there any benefits of using one over the other? I have seen both examples used in different places.

A: The only difference as far as I can tell is that the anonymous function cannot call itself recursively while the named function can. There is a third type of construct that combines both of these, i.e. you can have a named function expression:
var myfunc = function myfunc() { /* code */ };

A: If a function is declarated normally, the function name (its identifier) will not be deleteable even if the identifier is redeclared. The identifier will only be deleted when its scope ends.
function myfunc() { /* code */ };

if (delete myfunc) { //will fail
  alert('myfunc deleted');
} else {
  alert('can not delete myfunc');
}

myfunc = null;

if (delete myfunc) { //will still fail
  alert('myfunc deleted');
} else {
  alert('can not delete myfunc');
}

var myfunc = null;

if (delete myfunc) { //will still fail
  alert('myfunc deleted');
} else {
  alert('can not delete myfunc');
}

But if a function declaration is assigned to a variable, its identifier can be deleted. This is especially useful when you need to create a global function but only use it temporarily, so that it can be deleted when it's no longer needed or to avoid possible identifier conflit with third party scripts.
var myfunc = function() { /* code */ };

if (delete myfunc) { //will succeed
  alert('myfunc deleted');
} else {
  alert('can not delete myfunc');
}

//or...
var myfunc = function myrealfunc() { /* code */ };

if (delete myfunc) { //will succeed
  alert('myfunc deleted');
} else {
  alert('can not delete myfunc');
}

A: There are a few differences, mostly pragmatic. When you 'var' a function, the normal assumption is some kind of 'locally' scoped function ( think a nested function ). When you do,    function myFunction() {}, the function is mostly assumed to be globally scoped (though you could wrap this inside an anonymous function as well).
In the case of a javascript 'class', if you want to create a locally scoped function, you would have to use 'var' to declare it.
var myClass = function() {
 var test = function() {
  //This function has local scope
  }
};

Adding to the above comments, this is a simple example.
  var myVariable = resultFunction();

  function resultFunction() {
  return 1;
  }

The above code will work. But you can't do the following
 var myVariable = resultFunction();

 var resultFunction = function() {
    return 1;
 };

But you can do
 var resultFunction = function() {
    return 1;
 };

 var myVariable = resultFunction();


text:
Q: How can i use SOCKS4 and SOCKS5 proxies with aiohttp ClientSession? How can i use SOCKS4 and SOCKS5 proxies with aiohttp ClientSession? Need some small example. Thanks!

A: Have you tried aiosocks ?
import asyncio
import aiosocks
from aiosocks.connector import SocksConnector

conn = SocksConnector(proxy=aiosocks.Socks5Addr(PROXY_ADDRESS, PROXY_PORT), proxy_auth=None, remote_resolve=True)
session = aiohttp.ClientSession(connector=conn)
async with session.get('http://python.org') as resp:
    assert resp.status == 200


text:
Q: java.lang.ClassCastException: java.util.ArrayList cannot be cast to org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO I am getting below error while calling the url with API manager.
Detailed error
TID: [-1234] [] [2020-06-13 06:26:45,558] ERROR {org.apache.synapse.transport.passthru.ServerWorker} - Error processing GET request for : /test/test. java.lang.ClassCastException: java.util.ArrayList cannot be cast to org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO
        at org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler.doRoleBasedAccessThrottling_aroundBody14(APIThrottleHandler.java:628)
        at org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler.doRoleBasedAccessThrottling(APIThrottleHandler.java:505)
        at org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler.doThrottle_aroundBody4(APIThrottleHandler.java:238)
        at org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler.doThrottle(APIThrottleHandler.java:195)
        at org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler.handleRequest_aroundBody0(APIThrottleHandler.java:174)
        at org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler.handleRequest(APIThrottleHandler.java:162)
        at org.apache.synapse.rest.API.process(API.java:367)
        at org.apache.synapse.rest.RESTRequestHandler.apiProcessNonDefaultStrategy(RESTRequestHandler.java:149)
        at org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:95)
        at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:71)
        at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:327)
        at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:98)
        at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
        at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:368)
        at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:189)
        at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)

A: This might be due to the used throttle handler(in synapse-configs API definition) APIThrottleHandler is the old one and it is used as below.
<handler class="org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler">
         <property name="policyKey" value="gov:/apimgt/applicationdata/tiers.xml"/>
         <property name="policyKeyApplication"
                   value="gov:/apimgt/applicationdata/app-tiers.xml"/>
         <property name="id" value="A"/>
         <property name="policyKeyResource"
                   value="gov:/apimgt/applicationdata/res-tiers.xml"/>
</handler>

And it is not accepting an array as per the implementation.
This could be overcome by switching to the new throttle handler(ThrottleHandler) by modifying synapse configs of each API as below.
<handler class="org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler">
         <property name="policyKey" value="gov:/apimgt/applicationdata/tiers.xml"/>
         <property name="policyKeyApplication"
                   value="gov:/apimgt/applicationdata/app-tiers.xml"/>
         <property name="id" value="A"/>
         <property name="policyKeyResource"
                   value="gov:/apimgt/applicationdata/res-tiers.xml"/>
</handler>

Hope this will help.


text:
Q: How can I read the contents of a file into a list in Lisp? I want to read in the contents of a file into a list. Some of my attempts so far have been -
(defun get-file (filename)
  (let ((x (open filename)))
    (when x
      (loop for line = (read-line x nil)
     while line do (list line)))
    (close x)))

(defun get-file (filename)
  (let ((x (open filename :if-does-not-exist nil)) (contents (list nil)))
    (when x
      (loop for line = (read-line x nil)
     while line do (cons contents line)))
    (close x) contents))

(defun get-file (filename)
  (let ((x (open filename :if-does-not-exist nil)) (contents nil))
    (when x
      (loop for line = (read-line x nil)
     while line do (append contents line)))
    (close x) contents))

None of these worked. Can anyone tell me a way? Or even better - how to put all of the contents into an array?

A: How about
(defun get-file (filename)
  (with-open-file (stream filename)
    (loop for line = (read-line stream nil)
          while line
          collect line)))

A: I'll add libraries in.
edit even easier, with uiop, which is included in ASDF:
(uiop:read-file-lines "file.txt")

https://common-lisp.net/project/asdf/uiop.html#UIOP_002fSTREAM
also has
(uiop:read-file-string "file")

With Alexandria's read-file-into-string and split-sequence:
(alexandria:read-file-into-string "file.txt")
(split-sequence:split-sequence #\Newline *)

With str:
(str:lines (str:from-file "file.txt"))

More recipes on files: https://lispcookbook.github.io/cl-cookbook/files.html

A: Where are the problems?
(defun get-file (filename)
  (let ((x (open filename)))
    (when x
      (loop for line = (read-line x nil)
            while line
            do (list line)))    ; <-- you are not collecting, just doing
    (close x)))                 ; <- the function returns the value of CLOSE

(defun get-file (filename)
  (let ((x (open filename :if-does-not-exist nil))
        (contents (list nil)))
    (when x
      (loop for line = (read-line x nil)
            while line
            do (cons contents line)))  ; <-- again, the cons goes nowhere
    (close x) contents))               ; <-- CONTENTS has never been changed

(defun get-file (filename)
  (let ((x (open filename :if-does-not-exist nil))
        (contents nil))
    (when x
      (loop for line = (read-line x nil)
            while line
            do (append contents line)))  ; <- again the result goes nowhere
    (close x) contents))                 ; <-- CONTENTS has never been changed

LOOP
The DO clause of LOOP will just execute something for side effects.
COLLECT will collect the result and the LOOP then will return a list of collected values upon exit.
Opening and closing of files
As already mentioned, use WITH-OPEN-FILE instead of OPEN/CLOSE. WITH-OPEN-FILE will close the file upon leaving the dynamic scope. Not just from a normal exit, but also upon error conditions, by using UNWIND-PROTECT to ensure the execution.
Reading file contents
If you want to read the contents of a file, you can use the function READ-SEQUENCE. With the usual problems. For example when you read an ASCII file as text into a string, the string may be shorter than the file. For example Common Lisp will represent internally CRLF with a single character, on platforms where CRLF is newline. Another example: in Unicode supporting implementations the UTF-8 code in the file may be replaced with a single character.

A: 2023 Update
With the Transducer pattern it's very easy to process the contents of a file (or any other stream of data). For a file specifically:
(t:transduce #'t:pass #'t:cons #p"path/to/file.txt")

This will read each line from the given file into a list. Note that there's not much reason to do this, as any processing you'd likely want to do on the list after that can be accomplished during the transduction itself, thus avoiding the need to pull the entire file into memory at once.
For instance, to count the number of words in a file:
(t:transduce (t:comp (t:map #'str:words) ;; (2) Split each line into a list of words.
                     #'t:concatenate)    ;; (3) Flatten that list back into a single stream.
             #'t:count       ;; (4) Count the total number of split words.
             #p"foobar.txt") ;; (1) Read from a file, one line at a time.

Note that the t: namespace prefix in either example is the nickname assumed to have been given to the library upon import, as in:
(:local-nicknames (#:t #:transducers))