text:
Q: How to send a localNotification at a specific time everyday, even if that time has passed? I have this code which runs a notification everyday at 7am, it gets the current date and then runs the notification when it gets to the set hour, my problem is if the time has already passed the set run time then everyday it will run at the user current time not my time on 7am, here is my code
var dateFire: NSDateComponents = NSDateComponents()
var getCurrentYear = dateFire.year
var getCurrentMonth = dateFire.month
var getCurrentDay = dateFire.day

dateFire.year = getCurrentYear
dateFire.month = getCurrentMonth
dateFire.day = getCurrentDay
dateFire.hour = 7
dateFire.minute = 0
dateFire.timeZone = NSTimeZone.defaultTimeZone()

var calender: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var date: NSDate = calender.dateFromComponents(dateFire)!

var localNotification = UILocalNotification()
localNotification.fireDate = date
localNotification.alertBody = "A new day has begun and a fresh layer on snow lies on the mountain! Can you beat your highscore?"
localNotification.repeatInterval = NSCalendarUnit.CalendarUnitDay

UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

As you can see NSCalendarUnit.CaldendarUnitDay makes it run everyday at 7am. I don't know so that even if the time is after 7am the notification will still run the next day would be greatly appreciated

A: Updated @Paulw11 's answer to Swift 3.0 and wrapped up in a function:
/// Set up the local notification for everyday
/// - parameter hour: The hour in 24 of the day to trigger the notification
class func setUpLocalNotification(hour: Int, minute: Int) {

    // have to use NSCalendar for the components
    let calendar = NSCalendar(identifier: .gregorian)!;

    var dateFire = Date()

    // if today's date is passed, use tomorrow
    var fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire)

    if (fireComponents.hour! > hour
        || (fireComponents.hour == hour && fireComponents.minute! >= minute) ) {

        dateFire = dateFire.addingTimeInterval(86400)  // Use tomorrow's date
        fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire);
    }

    // set up the time
    fireComponents.hour = hour
    fireComponents.minute = minute

    // schedule local notification
    dateFire = calendar.date(from: fireComponents)!

    let localNotification = UILocalNotification()
    localNotification.fireDate = dateFire
    localNotification.alertBody = "Record Today Numerily. Be completely honest: how is your day so far?"
    localNotification.repeatInterval = NSCalendar.Unit.day
    localNotification.soundName = UILocalNotificationDefaultSoundName;

    UIApplication.shared.scheduleLocalNotification(localNotification);

}

A: You need to check the current hour and if it is later than 6:59 you need to schedule your notification for tomorrow - this will prevent your notification from being scheduled in the past -
var calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var dateFire=NSDate()

var fireComponents=calendar.components(NSCalendarUnit.CalendarUnitDay|NSCalendarUnit.CalendarUnitMonth|NSCalendarUnit.CalendarUnitYear|NSCalendarUnit.CalendarUnitHour|NSCalendarUnit.CalendarUnitMinute, fromDate:dateFire)

if (fireComponents.hour >= 7) {
    dateFire=dateFire.dateByAddingTimeInterval(86400)  // Use tomorrow's date

    fireComponents=calendar.components(NSCalendarUnit.CalendarUnitDay|NSCalendarUnit.CalendarUnitMonth|NSCalendarUnit.CalendarUnitYear|NSCalendarUnit.CalendarUnitHour|NSCalendarUnit.CalendarUnitMinute, fromDate:dateFire)
}

fireComponents.hour = 7
fireComponents.minute = 0

dateFire = calendar.dateFromComponents(fireComponents)!

var localNotification = UILocalNotification()
localNotification.fireDate = dateFire
localNotification.alertBody = "A new day has begun and a fresh layer on snow lies on the mountain! Can you beat your highscore?"
localNotification.repeatInterval = NSCalendarUnit.CalendarUnitDay

UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

A: Updated version (Swift 2.0)
    let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    var dateFire=NSDate()

    var fireComponents=calendar.components([.Month, .Day, .Hour, .Minute], fromDate:NSDate())

    if (fireComponents.hour == 7) {
        dateFire=dateFire.dateByAddingTimeInterval(86400)  // Use tomorrow's date

        fireComponents=calendar.components([.Month, .Day, .Hour, .Minute], fromDate:NSDate())
    }

    fireComponents.hour = 7
    fireComponents.minute = 0

    dateFire = calendar.dateFromComponents(fireComponents)!

    let localNotification = UILocalNotification()
    localNotification.fireDate = dateFire
    localNotification.alertBody = "Don't forget to visit Quote Daily to receive daily motivation."
    localNotification.repeatInterval = NSCalendarUnit.Day

    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

A: Swift 5.1
This one for example fires every day at 8:00 A.M. :
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Title"
notificationContent.body = "This is a test"
notificationContent.badge = NSNumber(value: 1)
notificationContent.sound = .default

var datComp = DateComponents()
datComp.hour = 8
datComp.minute = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: datComp, repeats: true)
let request = UNNotificationRequest(identifier: "ID", content: notificationContent, trigger: trigger)
                UNUserNotificationCenter.current().add(request) { (error : Error?) in
                    if let theError = error {
                        print(theError.localizedDescription)
                    }
                }


text:
Q: Problem logging in even though password is accepted I am logged in as user_a. I created another account user_b with root privileges using the following steps:
sudo -s
useradd user_b
passwd user_b
>sum_passwd
sudo adduser user_b admin

After which I rebooted and tried to login as user_b but after typing the password, I see momentary darkness and then the login screen again. This does not happen if I try to type some incorrect password, as I am prompted immediately. I can login just fine to the guest_account and user_a but the newly created user_b is causing problems.
How do I fix this?

A: you used a password that is the same as the username? If so, I believe that Ubuntu doesn't like this. If not, have you checked the useradd GUI that ships with Ubuntu to ensure that user_b is listed?

redpajama_set_name: RedPajamaStackExchange


text:
Q: std::set_intersection of struct objects I'm trying to get an intersection of two sets that stores objects of type of a struct called dist, using std::set_intersection. I want the result to be stored in another set<dist>.
However, compiler gives the following error:
In file included from /usr/include/c++/5/algorithm:62:0,
             from /usr/include/x86_64-linux-gnu/c++/5/bits/stdc++.h:64,
             from /home/kirill/CLionProjects/contest/main.cpp:1:
/usr/include/c++/5/bits/stl_algo.h: In instantiation of '_OutputIterator std::__set_intersection(_InputIterator1, _InputIterator1, _InputIterator2, _InputIterator2, _OutputIterator, _Compare) [with _InputIterator1 = std::_Rb_tree_const_iterator<dist>; _InputIterator2 = std::_Rb_tree_const_iterator<dist>; _OutputIterator = std::_Rb_tree_const_iterator<dist>; _Compare = __gnu_cxx::__ops::_Iter_less_iter]':
/usr/include/c++/5/bits/stl_algo.h:5122:48:   required from '_OIter std::set_intersection(_IIter1, _IIter1, _IIter2, _IIter2, _OIter) [with _IIter1 = std::_Rb_tree_const_iterator<dist>; _IIter2 = std::_Rb_tree_const_iterator<dist>; _OIter = std::_Rb_tree_const_iterator<dist>]'
/home/kirill/CLionProjects/contest/main.cpp:65:73:   required from here
/usr/include/c++/5/bits/stl_algo.h:5076:16: error: passing 'const dist' as 'this' argument discards qualifiers [-fpermissive]
      *__result = *__first1;
            ^
/home/kirill/CLionProjects/contest/main.cpp:26:8: note:   in call to 'dist& dist::operator=(const dist&)'
 struct dist {
    ^
CMakeFiles/contest.dir/build.make:62: recipe for target 'CMakeFiles/contest.dir/main.cpp.o' failed
make[3]: *** [CMakeFiles/contest.dir/main.cpp.o] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/contest.dir/all' failed
make[2]: *** [CMakeFiles/contest.dir/all] Error 2
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/contest.dir/rule' failed
make[1]: *** [CMakeFiles/contest.dir/rule] Error 2
Makefile:118: recipe for target 'contest' failed
make: *** [contest] Error 2

Here is a struct definition:
struct dist {
    int x_dist;
    int y_dist;

    bool operator<(dist const & b) const {
        return tie(x_dist, y_dist) < tie(b.x_dist, b.y_dist);
    }
};

Here I'm invoking a set_intersection method:
#define all(c) (c).begin(), (c).end()
void intersection_taxi_fan() {
    intersection.clear();
    set_intersection(all(taxi_dist), all(fan_dist), intersection.begin());
}

A: You cannot pass intersection.begin() as parameter of set_intersection because it is iterator to const value

*Note: All iterators in a set point to const elements.
  [from http://www.cplusplus.com/reference/set/set/]

and set_intersection modifies value (in line [1] in below snippet code of set_intersection algorithm) which is pointed by this iterator.
    else if (*first2<*first1) ++first2;
else {
  *result = *first1;   // [1] try modifying const value
  ++result; ++first1; ++first2;
}

Const-object cannot be modified.
You can use std::inserter to insert elements into your intersection set
    set_intersection(all(taxi_dist), all(fan_dist), inserter(intersection, intersection.end()));


text:
Q: jQuery resize to aspect ratio How would I resize a image in jQuery to a consistent aspect ratio. For example setting maximum height and have the width resize correctly. Thanks.

A: Use JQueryUI Resizeable
$("#some_image").resizable({ aspectRatio:true, maxHeight:300 });

aspectRatio: true -> maintain original aspect ratio

A: Here's a useful function that might do what you want:
jQuery.fn.fitToParent = function()
{
    this.each(function()
    {
        var width  = $(this).width();
        var height = $(this).height();
        var parentWidth  = $(this).parent().width();
        var parentHeight = $(this).parent().height();

        if(width/parentWidth < height/parentHeight) {
            newWidth  = parentWidth;
            newHeight = newWidth/width*height;
        }
        else {
            newHeight = parentHeight;
            newWidth  = newHeight/height*width;
        }
        var margin_top  = (parentHeight - newHeight) / 2;
        var margin_left = (parentWidth  - newWidth ) / 2;

        $(this).css({'margin-top' :margin_top  + 'px',
                     'margin-left':margin_left + 'px',
                     'height'     :newHeight   + 'px',
                     'width'      :newWidth    + 'px'});
    });
};

Basically, it grabs an element, centers it within the parent, then stretches it to fit such that none of the parent's background is visible, while maintaining the aspect ratio.
Then again, this might not be what you want to do.

A: You could calculate this manually,
i.e.:
function GetWidth(newHeight,orginalWidth,originalHeight)
{
if(currentHeight == 0)return newHeight;
var aspectRatio = currentWidth / currentHeight;
return newHeight * aspectRatio;
}

Make sure you use the ORIGINAL values for the image otherwise it will degrade over time.
EDIT: example jQuery version (not tested)
jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
    var aspectRatio = $(this).data('aspectRatio');
    if (aspectRatio == undefined) {
        aspectRatio = $(this).width() / $(this).height();
        $(this).data('aspectRatio', aspectRatio);
    }
    $(this).height(newHeight);
    $(this).width(parseInt(newHeight * aspectRatio));
}

A: There's no accounting for the amount of copy and pasters out there eh! I also wanted to know this and all I saw were endless examples of scaling width OR height.. who would want the other overflowing?!

*

*Resize width AND height without the need for a loop

*Doesn't exceed the images original dimensions

*Uses maths that works properly i.e width/aspect for height, and height*aspect for width so images are actually scaled properly up and down :/

Should be straight forward enough to convert to javascript or other languages
//////////////
private void ResizeImage(Image img, double maxWidth, double maxHeight)
{
    double srcWidth = img.Width;
    double srcHeight = img.Height;

    double resizeWidth = srcWidth;
    double resizeHeight = srcHeight;

    double aspect = resizeWidth / resizeHeight;

    if (resizeWidth > maxWidth)
    {
        resizeWidth = maxWidth;
        resizeHeight = resizeWidth / aspect;
    }
    if (resizeHeight > maxHeight)
    {
        aspect = resizeWidth / resizeHeight;
        resizeHeight = maxHeight;
        resizeWidth = resizeHeight * aspect;
    }

    img.Width = resizeWidth;
    img.Height = resizeHeight;
}

A: This is a good solution if you need perfect height and width aspect ratio after crop it will give perfect crop ratio

getPerfectRatio(img,widthRatio,heightRatio){

  if(widthRatio < heightRatio){
    var height = img.scalingHeight - (img.scalingHeight % heightRatio);
    var finalHeight = height
    var finalWidth = widthRatio * (height/heightRatio);

    img.cropHeight = finalHeight;
    img.cropWidth = finalWidth
  }
  if(heightRatio < widthRatio){;
    var width = img.scalingWidth - (img.scalingWidth % widthRatio);
    var finalWidth = width;
    var finalHeight  = heightRatio * (width/widthRatio);
    img.cropHeight = finalHeight;
    img.cropWidth = finalWidth
  }

  return img

}


text:
Q: Regex matching positive or negative dollar amount or percentage How might I efficiently use regex to match input that could be a positive or negative dollar amount or percentage.

*

*Input could start with optional + or -

*Followed by optional $

*Then digits with optional comma as a digit group separator following a digit in the thousands/hundred thousands/millions...

*Followed by an optional decimal point and one or two digits

*And finally a possible %, but only if the input doesn't contain a $, and the number is from -100.00 to +100.00

So it would match input like:
12, -60, $25.50, -$1.5, +$25,000, 5.5%, -100%, +100%, 0.01%
And return false with input like:
Text, +$10%, -5.001
I've been evaluating them separately with:
function percentValue(input) {
    regex = /^[+-]?\$?(?=.)(\d*|\d{1,3}(,\d{3})*)?(\.\d{1,2})?$/;
    return regex.test(input);
}

function dollarValue(input) {
    regex = /^[+-]? *100(\.0{0,2})? *%?$|^[+-]? *\d{1,2}(\.\d{1,2})? *%?$/;
    return regex.test(input);
}

Results
percentValue('5.5%');  // True
percentValue('-100%'); // True
percentValue('+.01%'); // True
percentValue('0.001'); // False
percentValue('101%');  // False
percentValue('$100%'); // False

dollarValue('+$12');    // True
dollarValue('-$60.5');  // True
dollarValue('$25,000'); // True
dollarValue('-$5.001'); // False
dollarValue('1,00.25'); // False
dollarValue('$text');   // False

I've been unsuccessful trying to combine them into one. Should I be using another lookahead for the percentage?

A:

var test = [
    '12',
    '-60',
    '$25.50',
    '-$1.5',
    '+$25,000',
    '5.5%',
    '-100%',
    '+100%',
    '0.01%',
    'Text',
    '+$10%',
    '-5.001',
];
console.log(test.map(function (a) {
  return a+' :'+/^[+-]?(?:\$?\d{1,3}(?:,\d{3})*(?:\.\d\d?)?|(?:100|\d\d?)(?:\.\d\d?)?%)$/.test(a);
}));

Demo & explanation


text:
Q: Code Signing Certificate Reputation with SmartScreen Filter I am using a standard (i.e. not EV) Authenticode code signing certificate to sign a Windows desktop application in the hope that Smartscreen Filter will eventually stop blocking it.
I was hoping to certify the application but since my code signing certificate was issued by GoDaddy it appears that I can't do that since you need a certificate from Symantec, Entrust, GlobalSign, WoSign or Digicert in order to create a Windows Certification Dashboard account (the first step in the certification process).
So here's my question: Will my non-certified Windows application signed with a standard GoDaddy SHA-2 code signing certificate still accumulate reputation?

A: According to these article, most likely yes, but you need to check details in your certificate
https://social.technet.microsoft.com/wiki/contents/articles/51151.microsoft-trusted-root-certificate-program-participants-as-of-january-30-2018.aspx


text:
Q: Why aren't smoothing capacitors used in smoothing the output of fully controlled bridge rectifiers? I was wondering why smoothing capacitors are not used in smoothing the output of fully controlled bridge rectifiers, like it is used in the uncontrolled bridge rectifiers.

A: Capacitive load to SCR rectifier is begging troubles. Thyristors and triacs cannot stand too quickly growing current. See, they have max di/dt spec. Too fast growing current kills them. So, only those applications work which have  an inductor between the SCR and the possible smoothing capacitor.
I have seen such 3-phase rectifiers. The triggering angle of the thyristors was controlled by the output DC voltage stabilization circuit.
To be more exact, the fatality of the fast growing inrush peak to the capacitor through a triggered SCR is not the only reason to leave the capacitor off or to use an LC filter instead of plain capacitor.  If one calculates how much energy is wasted in losses during the current peak, he finds that the amount is substantial and it can cause intolerable amount of heat in high power systems - in those which pay off to be designed with SCRs. Charging the cap through an inductor like in buck switching regulators is much more efficient.
Finally, as already said by others in a comment, motors can work well with less smoothed voltage. And some high power industrial processes (welding, arc furnance, electroplating) need sustaining DC current. A series inductor can stabilize it well enough.


text:
Q: Adding nothing to a list :)
I want to write DRY erlang code but I have a problem. I've got a record like this
-record(person, {firstname, lastname, phones=[], emails=[]}).

And I use it to create an adress book which is simple lists of persons. Then I want to call a function:
updatePersonsInfo(FName,LName,Phone, Email,[Old = #person{firstname = FName, lastname = LName} | T]) ->
  UpdatedPhonesList = #person.phones ++ [Phone],
  UpdatedEmailsList = #person.emails ++ [Email],
  [Old#person{phones= UpdatedPhonesList, emails = UpdatedEmailsList}] ++ T;

And I want to call this function but I want to add only an email. Something like this:
updatePersonsInfo(FName,LName, "",Email,Book);

But then I receive an error:
** exception error: bad argument
 in operator  ++/2
    called as 4 ++ []

So I guess this is just a matter of adding nothing to list. Of course I can split this function to: updatePersonsEmail and updatePersonsPhone, but the logic of these two functions will be the same which will make my code ugly.
Any ideas? I tried to use null atom, or _ , or even [] but nothing worked.

A: #person.phones  doesnot return old phone list. It returns just number of 'phones' field in the 'person' record..
That is why erlang complains about 4++[]
To get old phone list, you have to use  Old#person.phones


text:
Q: Create startup-script for Google GCE to create a proxy server I want a to create proxy server while creating a new instance of Google Compute Engine that will allow information to be passed from a bot that checks out automatically on shopping websites.
I know it can be done by creating a startup-script, but I don't know how can I write a startup-script to create a proxy server on Google cloud?
Help me, please!
Thanks in Advance!

A: You may follow the instructions in the GCP public documentation. It shows how to configure an instance as a network proxy, and use that instance as a proxy server. The tutorial in the article is well explained.

A: I have created free tool which is doing exactly this, basically will setup Google Cloud Proxy server for you.
https://createproxy.com
So you can create as many Google Cloud Proxy Servers as is your Google limit for creating instancies. If you reach this limit you can always contact Google support team to increase your instance limit, or you can create another proxy servers with different account or by different provider such as Amazon AWS, DigitalOcean, Vultr, Linode...
Also you can create/delete proxy servers by calling API https://createproxy.com/api/


text:
Q: Clear post data I am creating a login function but once I refresh the page it tries to re-login.
This is my current code:
    if(isset($_POST['login-submit']))
    {
        authenticator::login($_POST['login-username'], $_POST['login-password']);
        $_POST = array();
    }

And this is the login function:
        public static function login($username, $password)
        {
            session_start();

            if($_SESSION['loggedIn'])
                echo '<script>alert("You are already logged in.");</script>';
            else
            {
                $row = mysql_fetch_row(mysql_query("SELECT `password` FROM users WHERE username='$username';"));

                if(md5(md5($password."!#5fDa!2")) === $row[0])
                    $_SESSION['loggedIn'] = true;
                else
                    echo'<script>alert("Invalid username or password.")</script>';
            }
        }

So once I reload the page the message "You are already logged in" shows up (If logged in ofcourse) which means that the post data is not being cleared probably (I think). Is there another way to do it?


text:
Q: How to remove the separator between the header and the first row in a grouped tableView I am creating a static tableView. My goal is to have a single view that displays a tableView with 3 rows (get support, send feedback, participation terms), and a header + footer.
Right now, it all works fine EXCEPT the fact that there are two extra separators (one between the header and the first cell and the other between the last cell and the footer) that I cannot seem to get rid of.
Here is my code:
final class viewController: UITableViewController {

    private let headerContainer = UIView()
    private let footerContainer = UIView()

    private let tableData = ["Get Support", "Send Feedback", "Participation Terms"]

    override func viewDidLoad() {
        super.viewDidLoad()

        setupHeaderAndFooter()
        setupTableView()
    }

    func setupHeaderAndFooter() {
        /* setup code here (not relevant to this question) */

    func setupTableView() {
        // reinitializing tableView so that we can change its style to grouped
       tableView = UITableView(frame: CGRect.zero, style: .grouped)
       tableView.delegate = self
       tableView.separatorStyle = .singleLine
    }

    //MARK: UITableView Methods

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return headerContainer
    }

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
         return 150
    }

    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return footerContainer
    }

    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 200
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableData.count
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
        cell.textLabel!.text = tableData[indexPath.row]
        return cell
    }
}

A: One way to achieve this is don't use default separator provided by UITableView. and place one UILabel or UIView and set its background color to light gray and set its height=1 (As per your requirement), width (full tableview width or as per your requirement) and position at bottom of all you content inside cell, header or footer.

A: Ok here you go.
The easy trick is actually a one-liner and a self-explanatory:
self.tableView.separatorColor = self.tableView.backgroundColor

AFTER:

I hope this helps!

A: You have to set clipsToBounds to true on your header view.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = //Get your header here
    header.clipsToBounds = true
    return header
}

Before:

After:


text:
Q: When requesting metadata of Amazon S3 file using iOS Swift 3 & AWS SDK 2.5, OSStatus error, Security Error has occurred I'm using AWS SDK 2.5 and Swift 3.  Having gotten S3 to work in Android, I'm transitioning to iOS and Swift.
After following the solution in another StackOverflow question Checking metadata of Amazon S3, I receive an OSStatus error [-34018] Security error has occurred.
Here's the code snippet based on that solution.
let request = AWSS3HeadObjectRequest()
request!.bucket = bucketName
request!.key = key

let s3 = AWSS3.default()
s3.headObject(request!) {
    (output1 : AWSS3HeadObjectOutput?, error : Error?) -> Void in
    if error == nil {
        print("Error: could not find file \(error)")
    } else {
        print (output1?.lastModified! ?? "")
    }
}

I have a valid Cognito pool ID, bucket and key.  I'm not sure what the issue is.  Any suggestions would be greatly appreciated.

A: You need to enable keychain capability in your XCode project. Apple changed the way how keychain is accessed on iOS10. for more information please see https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/AddingCapabilities/AddingCapabilities.html


text:
Q: Можно ли при помощи @DateTimeFormat сделать такое? Можно ли при помощи параметра pattern к аннотации @DateTimeFormat сделать такого вида валидацию YYYY-MM-DDThh:mm:ss[.sss]±hh:mm
([.sss] - опционально от 1 до 3 цифр)? И может ли @DateTimeFormat валидировать String например?

A: *

*Нашел ответ в английской ветке

этот метод должен вам помочь. Мы просто парсим и если вылетает ошибка то значит не соответствует.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss.SSS");

boolean isValidDate(String input) {
  try {
      format.parse(input);
      return true;
   }
   catch(ParseException e){
      return false;
   }
}

источник
почитайте внимательно что каждая буква означаетю разница между DD и dd
форматирование даты

*в случае с ±hh:mm можно написать метод
Date min, max;
Date date;
return date.after(min) && date.before(max);
источник

*реализацию опуиональноти миллисекунд вижу только в написании трех методов тз пункта 1 которые по очереди будут проверять.


text:
Q: how to extend the plugin? please help to fix the error
in django cms added plugin polls. then try to extend it for this tutorial. as a result of my directory structure looks like.
The problem is that when you try to run the site console displays the following error message:
Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__
    return self.application(environ, start_response)
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 187, in __call__
    self.load_middleware()
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 47, in load_middleware
    mw_instance = mw_class()
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/django/middleware/locale.py", line 24, in __init__
    for url_pattern in get_resolver(None).url_patterns:
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 365, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 360, in urlconf_module
    self._urlconf_module = import_module(self.urlconf_name)
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
    __import__(name)
  File "/home/kalinins/.virtualenvs/blogik4/blogik4/blogik4/urls.py", line 8, in <module>
    admin.autodiscover()
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 29, in autodiscover
    import_module('%s.admin' % app)
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
    __import__(name)
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/cms/admin/__init__.py", line 11, in <module>
    plugin_pool.plugin_pool.discover_plugins()
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/cms/plugin_pool.py", line 36, in discover_plugins
    load('cms_plugins')
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/cms/utils/django_load.py", line 56, in load
    get_module(app, modname, verbose, failfast)
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/cms/utils/django_load.py", line 40, in get_module
    module = import_module(module_name)
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
    __import__(name)
  File "/home/kalinins/.virtualenvs/blogik4/blogik4/djangocms_polls/cms_plugins.py", line 17, in <module>
    plugin_pool.register_plugin(CMSPollPlugin)  # register the plugin
  File "/home/kalinins/.virtualenvs/blogik4/local/lib/python2.7/site-packages/cms/plugin_pool.py", line 87, in register_plugin
    % (plugin, template)
ImproperlyConfigured: CMS Plugins must define a render template (<class 'djangocms_polls.cms_plugins.CMSPollPlugin'>) that exists: djangocms_polls/poll_plugin.html

A: You need to define list of templates in your settings, in CMS_TEMPLATES variable.
And... put your existing template to djangocms_polls subdir, so it will be in djangocms_polls/templates/djangocms_polls/poll_plugin.html.

A: you need to create an html template in your template folder
in this case the template poll_plugin.html inside your registered template folder djangocms_polls
...
render_template = "djangocms_polls/poll_plugin.html"
..

this template MUST exist so that the CMS PLugin can work, this is the template which the plugin renders the context data to.


text:
Q: Manual Authentication with Amazon Cognito I know of two ways to authenticate as a user and obtain the access token, one is through the Hosted UI and another with various provided SDKs.
What I'm looking for is an endpoint obtain the access token directly with user credentials.
POST https://that-special-endpoint.com/login
{
 username: "example@email.com",
 password: "Abc123456",
 ...client ID, etc.
}

I've searched for some time but could not find how to do this. Is this not possible due to some security concerns that I'm not aware of?
I did consider creating a Lambda API and make use of the Cognito SDK to cater for my use case but I'm not sure if it's advisable...

A: Similar question is answered here. You can access https://cognito-idp.[region].amazonaws.com/ to call InitiateAuth and RespondToAuthChallenge APIs.

InitiateAuth

*

*Create a json file, aws-auth-data.json
{
    "AuthParameters": {
        "USERNAME": "your-email@example.com",
        "PASSWORD": "your-first-password",
        "SECRET_HASH": "......(required if the app client is configured with a client secret)"
    },
    "AuthFlow": "USER_PASSWORD_AUTH",
    "ClientId": "5m........................"
}

*Send a request on https://cognito-idp.us-east-2.amazonaws.com/ (if the user pool is on us-east-2 region) to call InitiateAuth API and initiate an authentication flow.

curl -X POST --data @aws-auth-data.json \
-H 'X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth' \
-H 'Content-Type: application/x-amz-json-1.1' \
https://cognito-idp.us-east-2.amazonaws.com/

*Then you'll get the user's tokens.

{
    "AuthenticationResult": {
        "AccessToken": "eyJra........",
        "ExpiresIn": 3600,
        "IdToken": "eyJra........",
        "RefreshToken": "eyJjd........",
        "TokenType": "Bearer"
    },
    "ChallengeParameters": {}
}

RespondToAuthChallenge

You may get a challenge as InitiateAuth response. For example, you will be asked to change password when you make a first 'InitiateAuth' attempt:
{
    "ChallengeName": "NEW_PASSWORD_REQUIRED",
    "ChallengeParameters": {
        "USER_ID_FOR_SRP": "abababab-......",
        "requiredAttributes": "[]",
        "userAttributes": "{\"email_verified\":\"true\",\"email\":\"your-email@example.com\"}"
    },
    "Session": "DNdY......"
}

In this case, change the password with RespondToAuthChallenge and you will get tokens.
{
    "ChallengeName": "NEW_PASSWORD_REQUIRED",
    "ChallengeResponses": {
        "USERNAME": "your-email@example.com",
        "NEW_PASSWORD": "your-second-password"
    },
    "ClientId": "5m........................",
    "Session": "DNdYN...(what you got in the preceding response)"
}

curl -X POST --data @aws-change-password.json \
-H 'X-Amz-Target: AWSCognitoIdentityProviderService.RespondToAuthChallenge' \
-H 'Content-Type: application/x-amz-json-1.1' \
https://cognito-idp.us-east-2.amazonaws.com/

See also:
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html
https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#amazon-cognito-user-pools-client-side-authentication-flow


text:
Q: How do you disable Restlet Client logging Info level? In my log I have this being displayed multiple times:
Nov 16, 2012 8:51:32 AM org.restlet.ext.net.HttpClientHelper stop
INFO: Stopping the HTTP client
I thought I fixed it when I added this code to my client:
HttpClientHelper httpClientHelper = new HttpClientHelper(null);
Engine.getInstance().getRegisteredClients().clear();
Engine.getInstance().getRegisteredClients().add(httpClientHelper);
httpClientHelper.getLogger().setLevel(Level.WARNING);

Apparently it worked for the start of the log but then it came up later in the log. Can someone explain to me why it started to work as expected but then it brought up that info log entry again?

A: For me, setting the logService to this worked:
public class SilentLogService extends LogService {

  @Override
  public boolean isLoggable(Request request) {
      return false;
  }

}


text:
Q: Detect row selection change from inside a cell component I'm using Tabulator for some data needs in my application and have created a few custom cell.s
I currently have a custom cell with an "Edit" button that toggles the row selection and its editibility. There is also a button external from the grid to allow for selecting all rows (as shown in the screenshot)

What I would like to do is have the button change from "Edit" to "Cancel" when the row is highlighted (either by clicking the "Edit" button or when all rows are selected programmatically).
From with in the cell I can get the current row selection by doing cell.getRow().isSelected() but I don't see a way to detecting when a particular row selection has changed.
One solution I have in mind is to use CSS to hide/show the "Edit" or "Cancel" button since Tabulator will add the class tabulator-selected to anything that is highlighted. But this seems more like a hack.
Thanks in advance for the thoughts, opinions and comments!

In case it's relevant, I'm using Tabulator wrapped in a Vue component. The custom cell is just vanilla JS at the moment.

A: The correct approach would be to use a formatter on the cell that sets the selected state of the toggle based on the selected state of the row, which can be retrieved using cell.getRow().isSelected()
you could then use the rowSelectionChanged callback and the reformat function on the row component to trigger a reformat of that row when its selection state is changed:
var table = new Tabulator("#example-table", {
    rowSelectionChanged:function(data, rows){
        rows.forEach(function(row){
            row.reformat();
        });
    },
});

A: there are callbacks built into Tabulator that tell you when row selection has changed, rowSelected, rowDeselected and rowSelectionChanged. Full documentation of these can be found in the Callbacks Documentation
It is only safe to change the formatting of cells in the formatter, so you want to watch for the change of selection on a row and then trigger a reformat of that row:
var table = new Tabulator("#example-table", {
    rowSelectionChanged:function(data, rows){
        rows.forEach(function(row){
            row.reformat();
        });
    },
});

A: I figured out what appears to be a suitable way of detecting row-selection change from with in a cell. It uses the MutationObserver API and checks the row-element for the tabulator-selected CSS class.
(I also opened a feature request on GitHub, so maybe in the future there will be a different way to handle this)
/**
 * A custom formatter/cell to enable the selection of an individual row
 *
 * @param {Object} cell Tabulator Cell object
 * @returns {HTMLElement}
 */
export default function(cell) {
  const checkbox = document.createElement('input')
  checkbox.type = 'checkbox'
  checkbox.onchange = function() {
    cell.getRow().toggleSelect()
  }

  // Callback function to execute when mutations are observed
  function mutationCallback(mutationsList) {
    for (let mutation of mutationsList) {
      // if you are using something other than a checkbox, you would perform the element changes in there
      checkbox.checked = mutation.target.classList.contains('tabulator-selected')
    }
  }

  // Create an observer to only watch for attribute changes (like CSS classes) and activate it
  const rowEl = cell.getRow().getElement()
  // list of all available config options: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
  const config = { attributes: true, attributeFilter: ['class'] }
  const observer = new MutationObserver(mutationCallback)
  observer.observe(rowEl, config)

  return checkbox
}


text:
Q: convert passport usage from mongoose to sequelize I am building an app that requires authentication during login and for that I have used passport(passport-local). The app does not run for the login part and the last option available after removing all syntax errors is that the way in which I am using passport(as given in their docs) is for mongoose while I am using sequelize. Can someone please tell how to rectify my passport.js file so that it works fine for sequelize as well?
(using mysql through sequelize; database is already populated)
here is my passport.js file
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const Users = require('./db').Users

module.exports = function (passport) {
  console.log("passport is working");

  passport.serializeUser(function (users, done) {
    console.log("Serialize");
    done(null, users.id)
  })

  function findById(id, fn) {
    User.findOne(id).exec(function (err, user) {

      if (err) {
        return fn(null, null);
      } else {
        return fn(null, user);
      }
    });
  }

  passport.deserializeUser(function (id, done) {
    console.log("DeSerialize");
    findById(id, function (err, user) {
      console.log(user);
      done(err, user);
    });
  })

  passport.use(new LocalStrategy(
    function (username, password, done) {
      Users.findOne({ where: { username: username } },
        function (err, users) {
          if (err) { return done(err); }
          if (!users) {
            return done(null, false, { message: 'Incorrect username.' });
          }
          if (!users.validPassword(password)) {
            return done(null, false, { message: 'Incorrect password.' });
          }
          return done(null, users);
        });
    }
  ));
}

and here is my db.js file
const Sequelize = require('sequelize');

const db = new Sequelize(
  'mydb',
  'myuser',
  'mypass',
  {
    dialect: 'mysql',
    host: 'localhost',
    pool: {
      max: 8,
      min: 0,
      aquire: 30000,
      idle: 10000
    },
  }
);

const Users = db.define('users', {
  email: {
    type: Sequelize.STRING,
    allowNull: false,
    unique: true
  },
  username: {
    type: Sequelize.STRING,
    allowNull: false,
    unique: true,
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false,
  }

})

db.sync().then(() => console.log("Database is ready"))

exports = module.exports = {
  db,
  Users
}

also,as a side note,can I do a res.send after post request using passport.authenticate?
app.post('/login', passport.authenticate('local'),
function(req, res) {
    res.send({
        url:'/profile',
        username:req.body.username
    });
  });

thanks in advance!!

A: findById has been replaced by findByPk method in Sequelize 4.
http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-findByPk

A: Yes, you need to change the functions where you fetch your user. This:
function findById(id, fn)
Should be something like:
function findById(id, fn) {
    User.findById(id).then((user) {
      return fn(null, user);
    });
  }

And you also need to change this a bit:
passport.use(new LocalStrategy(
    function (username, password, done) {
      Users.findOne({ where: { username: username } })
        .then((user) => {
          if (!user) {
            return done(null, false, { message: '' });
          }

          // validate your password**
          return done(null, user);
        });
    }
  ));

If you want to use a function like user.validatePassword() you will need to define an instance method (check sequelize docs) or here
.


text:
Q: What does more specialized mean when specializing a primary template? C++ template specialization rules mentioned specialization has to be more specialized than the primary template. Following #1 code snippet causes compilation error which says the second line is not more specialized, but the last snippet (#2) works which looks very close to #1. Both code snippets specialized int N as 0, so why the first snippet is complained as "not more specialized"?
// #1
template<int N, typename T1, typename... Ts> struct B;
template<typename... Ts> struct B<0, Ts...> { }; // Error: not more specialized

// #2
template<int N, typename T1, typename... Ts> struct B;
template<typename T, typename... Ts> struct B<0, T, Ts...> { }; // this works

A: For more specialized:

Informally "A is more specialized than B" means "A accepts a subset of the types that B accepts".

Whatever types the specialization could accept are supposed to be subset of types the primary template could accept. But for B<0>, it could be accepted by the specialization only, while the primary template can't, because the template parameter T1 is essential.


text:
Q: How to split a this string 'gi|216ATGCTGATGCTGTG' in this format 'gi|216 ATGCTGTGCTGATGCTG' in Perl? I am parsing the fasta alignment file which contains
gi|216CCAACGAAATGATCGCCACACAA
gi|21-GCTGGTTCAGCGACCAAAAGTAGC

I want to split this string into this:
gi|216 CCAACGAAATGATCGCCACACAA
gi|21- GCTGGTTCAGCGACCAAAAGTAGC

For first string, I use
$aar=split("\d",$string);

But that didn't work. What should I do?

A: So you're parsing some genetic data and each line has a gi| prefix followed by a sequence of numbers and hyphens followed by the nucleotide sequence? If so, you could do something like this:
my ($number, $nucleotides);
if($string =~ /^gi\|([\d-]+)([ACGT]+)$/) {
    $number      = $1;
    $nucleotides = $2;
}
else {
    # Broken data?
}

That assumes that you've already stripped off leading and trailing whitespace. If you do that, you should get $number = '216' and $nucleotides = 'CCAACGAAATGATCGCCACACAA' for the first one and $number = '216-' and $nucleotides = 'GCTGGTTCAGCGACCAAAAGTAGC' for the second one.
Looks like BioPerl has some stuff for dealing with fasta data so you might want to use BioPerl's tools rather than rolling your own.

A: Here's how I'd go about doing that.
#!/usr/bin/perl -Tw

use strict;
use warnings;
use Data::Dumper;

while ( my $line = <DATA> ) {

    my @strings =
        grep {m{\A \S+ \z}xms}                        # no whitespace tokens
        split /\A ( \w+ \| [\d-]+ )( [ACTG]+ ) /xms,  # capture left & right
        $line;

    print Dumper( \@strings );
}

__DATA__
gi|216CCAACGAAATGATCGCCACACAA
gi|21-GCTGGTTCAGCGACCAAAAGTAGC

A: If you just want to add a space (can't really tell from your question), use substitution. To put a space in front of any grouping of ACTG:
$string =~ s/([ACTG]+)/ \1/;

or to add a tab after any grouping of digits and dashes:
$string =~ s/([\d-]+)/\1\t/;

note that this will substitute on $string in place.


text:
Q: What is the name of the file that has the greatest average I/O time for an individual transaction (SQL) I assume the answer is going to be some sort of calculation on a v$ file, but I don't know what constitutes an I/O time?
My question is:
What constitutes an I/O time?


text:
Q: What KML features are suitable to display 3D atmospheric density data using Google Earth? I wish to use Google Earth to visualise and explore 3D atmospheric density data. In my case it is ionospheric electron density, which is a niche area, but I can imagine this might have been done by someone to display say atmospheric moisture content or pollution levels (or volcanic ash plumes??).
I am new to KML files, but reading over the developer guide it isn't obvious how best to go about this. Would you slice your 3D density data into many 2D layers and use < altitude > elements? Or would it be better to use grid the data into many small cubes and use < polygon >s? Or some other option?
I'm sure this has been done before, but I couldn't find any suitable examples.

A: Something like this:
http://docs.geoserver.org/2.2.4/user/googleearth/features/kmlheighttime.html
But you will have to put this in a geo-database, like postgres.
I've managed something simular, with building geometrie. In the database the geometrie was a multipolygon. In one column I set the height parametervield.
You could do the same with pointfeatures and also timeparameter....


text:
Q: WiX bundle installation force reboot details I have Windows program installation bootstrapper project. There is .NET Framework, Visual Studio C++ redistributable, device driver installer and my application installer in chain:
<Chain>
    <PackageGroupRef Id="Netfx45Xxx"/>

    <ExePackage Id="CppRedist"
        SourceFile="..\redist\vcredist_x86.exe" DetectCondition="VC2012CPPX86REDIST">
    </ExePackage>

    <MsiPackage Id="BlmInstall"
        SourceFile="..\bin\Release\BlmInstall.msi"></MsiPackage>
    <MsiPackage Id="UAUDriver" SourceFile="..\redist\setup.msi"></MsiPackage>
</Chain>

I want system to restart after .NET installation and then continue installation after reboot automatically. DotNET package group defined as:
<Fragment>
    <PackageGroup Id="Netfx45Xxx">
        <ExePackage
            Id="Netfx45Xxx"
            Cache="no" Compressed="no"
            PerMachine="yes"
            Permanent="yes"
            Vital="yes" InstallCommand="/q"
            SourceFile="..\redist\dotnetfx45_full_x86_x64.exe"
            DownloadUrl="http://go.microsoft.com/fwlink/?LinkId=225702"
            DetectCondition="NETFRAMEWORK40"
            InstallCondition="(VersionNT >= v6.0 OR VersionNT64 >= v6.0) AND (NOT (Netfx4FullVersion="4.5.50709" OR Netfx4x64FullVersion="4.5.50709"))">

            <ExitCode Value="1641" Behavior="forceReboot"/>
            <ExitCode Value="3010" Behavior="forceReboot"/>
            <ExitCode Value="0"    Behavior="success"/>
        </ExePackage>
    </PackageGroup>
  </Fragment>

*

*When the .NET Framework installation is finished, Windows shows its usual window containing the list of opened applications and asking user for force reboot. The issue is that those lists contains my setup application too. It looks very lousy when my installation program asking the user to abort my herself and force reboot. How could it be solved?

*After reboot installation continues, but the user is forced to read the license agreement and accept it again. Is it possible to avoid it?

A: Finally we managed to solve this issue:

*

*The exit codes were fine. The reason was that the .NET installer command line argument /norestart was missed. InstallCommand for the Netfx45Xxx package group should look like:
InstallCommand="/norestart /q"
With this value for InstalCommand, during our installation, Windows doesn't ask to force a reboot and allows installation to perform the reboot itself.

*So, as I explained above, it seems that Windows force reboot hampered installation from reboot performing. Since it was finished abnormally I suggest that adding a special Windows registry entry for installation application to continue after system restart was not added.


text:
Q: Magento 2 Product stock alert wrong price sent over email One customer who is set up in the GENERAL group was on a product detail page of a product with no inventory and clicked "Notify me when back in stock". Once the product was back in stock they received an email but it showed the WHOLESALE pricing rather than the GENERAL pricing. Why did the email send the wrong pricing to this user? How can we fix this?
Magento version: 2.2.4

A: Please check the /vendor/magento/module-product-alert/Model/Observer.php and made configuration according to your requirement in _processStock function.
Thanks


text:
Q: "Failed to parse json" error while doing "yo angular" I am learning Angular from this tutorial and here is what I have done so far:
I installed Node v0.10.29 successfully on my 64bit Windows 7 machine. After that, while installing yeoman, I got this issue: https://github.com/yeoman/yeoman.io/issues/283
I ignored that issue assuming that its minor and installed generator-angular which was successful. I used cmd as an administrator for all this.
After that, did yo angular and here is what I got:
c:\x-news>yo angular

     _-----_
    |       |    .--------------------------.
    |--(o)--|    |    Welcome to Yeoman,    |
   `---------'   |   ladies and gentlemen!  |
    ( _'U`_ )    '--------------------------'
    /___A___\
     |  ~  |
   __'.___.'__
 '   `  |° ' Y `

Out of the box I include Bootstrap and some AngularJS recommended modules.

[?] Would you like to use Sass (with Compass)? No
[?] Would you like to include Bootstrap? Yes
[?] Which modules would you like to include?
   create app\styles\main.css
   create app\index.html
   create bower.json
   create .bowerrc
   create package.json
   create Gruntfile.js
   invoke   angular:common:C:\Users\Rahul\AppData\Roaming\npm\node_modules\gener
ator-angular\app\index.js
   create     .editorconfig
   create     .gitattributes
   create     .jshintrc
   create     .gitignore
   create     test\.jshintrc
   create     app\.buildignore
   create     app\.htaccess
   create     app\404.html
   create     app\favicon.ico
   create     app\robots.txt
   create     app\views\main.html
   create     app\images\yeoman.png
   invoke   angular:main:C:\Users\Rahul\AppData\Roaming\npm\node_modules\generat
or-angular\app\index.js
   create     app\scripts\app.js
   invoke   angular:controller:C:\Users\Rahul\AppData\Roaming\npm\node_modules\g
enerator-angular\app\index.js
   create     app\scripts\controllers\main.js
   create     test\spec\controllers\main.js
   invoke   karma:app

I'm all done. Running bower install & npm install for you to install the require
d dependencies. If this fails, try running the command yourself.

   create     test\karma.conf.js
   create     .travis.yml
npm WARN package.json xnews@0.0.0 No description
npm WARN package.json xnews@0.0.0 No repository field.
npm WARN package.json xnews@0.0.0 No README data
npm WARN package.json xnews@0.0.0 No description
npm WARN package.json xnews@0.0.0 No repository field.
npm WARN package.json xnews@0.0.0 No README data
npm WARN deprecated grunt-ngmin@0.0.3: use grunt-ng-annotate instead
npm WARN deprecated ngmin@0.4.1: use ng-annotate instead
bower cached        git://github.com/angular/bower-angular-scenario.git#1.2.16
bower validate      1.2.16 against git://github.com/angular/bower-angular-scenar
io.git#1.2.16
bower cached        git://github.com/angular/bower-angular.git#1.2.16
bower validate      1.2.16 against git://github.com/angular/bower-angular.git#1.
2.16
bower cached        git://github.com/angular/bower-angular-mocks.git#1.2.16
bower validate      1.2.16 against git://github.com/angular/bower-angular-mocks.
git#1.2.16
bower cached        git://github.com/es-shims/es5-shim.git#3.1.1
bower validate      3.1.1 against git://github.com/es-shims/es5-shim.git#~3.1.0
bower cached        git://github.com/twbs/bootstrap.git#3.2.0
bower validate      3.2.0 against git://github.com/twbs/bootstrap.git#~3.2.0
bower cached        git://github.com/bestiejs/json3.git#3.3.2
bower validate      3.3.2 against git://github.com/bestiejs/json3.git#~3.3.1
npm WARN optional dep failed, continuing fsevents@0.2.0
npm ERR! Failed to parse json
ERR! Unexpected string
npm ERR! File: C:\Users\Rahul\AppData\Roaming\npm-cache\send\0.1.4\package\packa
ge.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! cwd c:\x-news
npm ERR! node -v v0.10.29
npm ERR! npm -v 1.4.14
npm ERR! file C:\Users\Rahul\AppData\Roaming\npm-cache\send\0.1.4\package\packag
e.json
npm ERR! code EJSONPARSE
npm ERR! Failed to parse json
npm ERR! Unexpected string
npm ERR! File: C:\Users\Rahul\AppData\Roaming\npm-cache\send\0.1.4\package\packa
ge.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "karma-phantomjs-launcher" "k
arma-jasmine" "grunt-karma" "--save-dev"
npm ERR! cwd c:\x-news
npm ERR! node -v v0.10.29
npm ERR! npm -v 1.4.14
npm ERR! file C:\Users\Rahul\AppData\Roaming\npm-cache\send\0.1.4\package\packag
e.json
npm ERR! code EJSONPARSE
--

> phantomjs@1.9.7-15 install c:\x-news\node_modules\karma-phantomjs-launcher\nod
e_modules\phantomjs
> node install.js

Download already available at C:\Users\Rahul\AppData\Local\Temp\phantomjs\phanto
mjs-1.9.7-windows.zip
Extracting zip contents
Copying extracted folder C:\Users\Rahul\AppData\Local\Temp\phantomjs\phantomjs-1
.9.7-windows.zip-extract-1406128242405\phantomjs-1.9.7-windows -> c:\x-news\node
_modules\karma-phantomjs-launcher\node_modules\phantomjs\lib\phantom
Writing location.js file
Done. Phantomjs binary available at c:\x-news\node_modules\karma-phantomjs-launc
her\node_modules\phantomjs\lib\phantom\phantomjs.exe
bower cached        git://github.com/jquery/jquery.git#2.1.1
bower validate      2.1.1 against git://github.com/jquery/jquery.git#>= 1.9.0
||

> ws@0.4.31 install c:\x-news\node_modules\karma\node_modules\socket.io\node_mod
ules\socket.io-client\node_modules\ws
> (node-gyp rebuild 2> builderror.log) || (exit 0)

/
c:\x-news\node_modules\karma\node_modules\socket.io\node_modules\socket.io-clien
t\node_modules\ws>node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bi
n\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild
npm WARN optional dep failed, continuing fsevents@0.2.0
bower install       json3#3.3.2
bower install       es5-shim#3.1.1
bower install       angular-scenario#1.2.16
bower install       angular-mocks#1.2.16
bower install       angular#1.2.16
bower install       bootstrap#3.2.0
bower install       jquery#2.1.1
\-
json3#3.3.2 bower_components\json3

es5-shim#3.1.1 bower_components\es5-shim

angular-scenario#1.2.16 bower_components\angular-scenario
└── angular#1.2.16

angular-mocks#1.2.16 bower_components\angular-mocks
└── angular#1.2.16

angular#1.2.16 bower_components\angular

bootstrap#3.2.0 bower_components\bootstrap
└── jquery#2.1.1

jquery#2.1.1 bower_components\jquery
-\

> jpegtran-bin@0.2.7 postinstall c:\x-news\node_modules\grunt-contrib-imagemin\n
ode_modules\imagemin\node_modules\imagemin-jpegtran\node_modules\jpegtran-bin
> node index.js

√ pre-build test passed successfully-

> gifsicle@0.1.6 postinstall c:\x-news\node_modules\grunt-contrib-imagemin\node_
modules\imagemin\node_modules\imagemin-gifsicle\node_modules\gifsicle
> node index.js

√ pre-build test passed successfully

> optipng-bin@0.3.9 postinstall c:\x-news\node_modules\grunt-contrib-imagemin\no
de_modules\imagemin\node_modules\imagemin-optipng\node_modules\optipng-bin
> node index.js

√ pre-build test passed successfully

> pngquant-bin@0.3.1 postinstall c:\x-news\node_modules\grunt-contrib-imagemin\n
ode_modules\imagemin\node_modules\imagemin-pngquant\node_modules\pngquant-bin
> node index.js

√ pre-build test passed successfully
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     c:\x-news\npm-debug.log
npm ERR! not ok code 0
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     c:\x-news\npm-debug.log
npm ERR! not ok code 0
app/index.html modified.

c:\x-news>

As you can notice, the first error here is Failed to parse json. Not sure why it is failing.
As per this answer, I did bower install. Nothing was displayed. I assumed it went successful (I checked the version later).
Versions:
c:\x-news>node --version
v0.10.29

c:\x-news>bower --version
1.3.8

c:\x-news>grunt --version
grunt-cli v0.1.13
grunt v0.4.5

c:\x-news>yo --version
1.2.0

c:\x-news>npm --version
1.4.14

I tried this multiple times, starting over, still failed. What am I doing wrong here? Can anyone please point me into the right direction?

A: Just a tip for anyone running into this issue, the error can be the result of incorrect formatting in your package.json. The terminal error in the question says:
npm ERR! Unexpected string
npm ERR! File: C:\Users\Rahul\AppData\Roaming\npm-cache\send\0.1.4\package\packa
ge.json

So look for something similar in your terminal. It might even point to a specific line number(Note: if it does and you see nothing wrong check a line or two up because the error is often on a line before the one logged in the console error). In my case it pointed to a trailing ',' that caused the JSON parse error.
Carefully go through the package.json line by line. If you don't find anything that could be causing the problem then run npm cache clean and npm install again as suggested above. Hope that helps someone!


text:
Q: Winrar self extracting SFX fail to launch I created an SFX file (to unzip and launch a program directly) with Winrar which is supposed to be installed in a TEMP folder. I specified to launch "bin/myprogram.exe" after extraction.
When I launch the SFX, I can see that my program is launched but is closed after 0,5 sec. If I go manually to the TEMP folder and launch myself the .exe, verything works very well.
Someone already had the same problem?
My procedure :
I select all the files needed (bin, programData and .ico)
New Archive, set to SFX mode. Under SFX Options button, in Advanced tab :

*

*Setup : I write bin/myprogram.exe after extraction

*Mode : Decompress in a tempory file

I tried to unzip in a specified folder or in programFile but nothing changed. Same situation

A: Since this is Windows, simply use bin\myprogram.exe instead.


text:
Q: Lose keyNavigation in ExtJs4 after editing element I want to implement interactive TreePanel with keyboard arrows navigation. After first click on any item it works properly.
I added keybinding < A >-add, < E >-edit, < D >-deleting. After  Add dialog shown, user enter name of new item and press Ctrl-S or press Save button. Here is code of saving:
saveItem: function(wnd) {
    rec = wnd.getRecord();
    var store = this.getProductCategoryStore();

    if (wnd.parent) {
        parent = wnd.parent
        parent.data.leaf = false;
        parent.set('loaded', false);
    } else
        parent = this.getCategoryTree().getRootNode();

    if (rec.phantom)
        parent.appendChild( rec );
    store.sync();
    wnd.close();

    if (wnd.parent)
        parent.expand();

    this.getCategoryTree().focus();
    this.getCategoryTree().selectPath( rec.getPath() );
},

So, last two rows is my trying to focus on Tree, but it doesn't working. < A >, < E >, < D > - working, but arrows doesn't work. If I clicking on tree manually it works again.

A: SOLVED. It's cool to use Ext.FocusManager to understand how focus works in application. To proper focusing in tree:
tree.getView().focus()


text:
Q: Staggering animation on just the new items of a list using Angular animations? In angular you can stagger animations, as I'm doing here for instance:
 <div
  masonryLayout
  [masonryOptions]="masonryOptions"
  [input]="photos"
  class="grid"
  [@photosAnimation]="photos.length"
  >
    <img
      *ngFor="let photo of photos; let i = index"
      (click)="onPhotoClick(photo)"
      src="{{photo.photo.medium}}"
      class="grid-item clickable hover-outline"
      [ngClass]="[photo.addedToCart ? 'in-cart-icon':'']"
      alt="{{photo.motive}}"
    />
</div>

I'm constantly adding new items to the list on demand, as the user clicks the "show more photos" button for instance. But this retriggers the animation on all the photos, how do I only stagger-animate a subset of the list?
EDIT: I've got two different semi-solutions,
1) The first photos instantly load, subsequent photos load with the stagger:
animations: [
    trigger('photosAnimation', [
      transition('* => *', [
        query(
          ':enter',
          style({ opacity: 0, transform: 'translateY(-20%)' }),
          { optional: true }
        ),
        query(
          ':enter',
          stagger('100ms', [
            animate('100ms', style({ opacity: 1, transform: 'translateY(0)' }))
          ]),
          { optional: true }
        )
      ])
    ])
  ]

2) The other option re-animates all the photos when new ones are added to the list:
animations: [
    trigger('photosAnimation', [
      transition('* => *', [
        query(
          '*',
          style({ opacity: 0, transform: 'translateY(-20%)' }),
          { optional: true }
        ),
        query(
          '*',
          stagger('100ms', [
            animate('100ms', style({ opacity: 1, transform: 'translateY(0)' }))
          ]),
          { optional: true }
        )
      ])
    ])
  ]

Neither of these semi-solutions completely satisfy my wish to both stagger in the first list and animate in additions to the list.

A: I ran into this. Since you cant bind to a variable in animations.
I ended up loading my new results in chunks of arrays and pushing that chunk to an array. Then wrapping the ngFor in another ngFor that iterates over the chunks of arrays.
Here is the HTML
<div *ngFor="let chunk of S.pictureChunks [@listAnimation]="S.pictureChunks.length">
   <div *ngFor="let picture of chunk">
    <img [@childAnimation]="S.pictureChunks.length" [src]='picture'>
  </div>

Here is my animate code for list
    trigger('listAnimation', [
  transition('* => *', [
    query('@childAnimation', stagger(50, [
      animateChild()
    ]), { optional: true })
  ])
]),
trigger('childAnimation', [
  transition(':enter', [
    style({ opacity: 0 }),
    animate(300, style({ opacity: 1 }))
  ])
]


text:
Q: Selecting possible sum fillers So I've got to write a program in which the user should input some kind of package weight and distance for sending it with 3 type of post marks with user inputted values and it has to print out every possible combination of post marks on the package. Usually, I've got no problems with combinatoric algorithms, but I don't think this has something to do with combinatorics since the values of the numbers matter. I've been thinking for hours cant figure anything out. This is my source just for the function I'm in.
float weight,price,total_price,m1,m2,m3;
int zone;

system("cls");

cout<<"Input package weight: ";
cin>>weight;

    if (weight<0 && weight>10) error();

   else if (weight<1) price=20;
   else if (weight<2) price=35;
   else if (weight<5) price=70;
   else price=120;

system("cls");

cout<<"Input zone(1/2/3): ";
cin>>zone;

    switch(zone)
    {
        case 1: total_price=price*1;    break;
        case 2: total_price=price*1.2;  break;
        case 3: total_price=price*1.5;  break;
        default: error();

system("cls");

cout<<"Input your mark price(1/3): ";
cin>>m1;
system("cls");
cout<<"Input your mark price(2/3): ";
cin>>m2;
system("cls");
cout<<"Input your mark price(3/3): ";
cin>>m3;

output();

A: I don't have an efficient way to get the desired result ( I am still learning the basics of algorithms :) ), but I believe the following approach will do the trick.
Let's start simple.
If the requirement was with just two stamps,

*

*Find the max among the two stamp prices, and divide the total cost by
this ( taking value as a size_t to remove fractional part ). This
returns the total number of time the costlier stamp can be used for
to send the package.

*Now iterate from 0 to this count. The iteration
index represents the number of costlier stamp used. Find the
remaining amount for which we have to use the cheaper stamp. If we
could perfectly divide the remains amount with the cheaper stamp (
fmod( diff, price_of_cheaper_stamp ) ), we have one of the set that
we need. That is ( iteration_index, diff/price_of_cheaper_stamp ).

*Continue the iteration to find the remaining sets.

Code would look as follows:
std::vector< std::pair< std::size_t, std::size_t > >
GetCombinations( double inTotal, double inM1, double inM2 )
{
    std::vector< std::pair< std::size_t, std::size_t > > result;
    auto maxVal = std::max( inM1, inM2 );
    auto minVal = std::min( inM1, inM2 );
    std::size_t maxCount = inTotal / maxVal;
    for( std::size_t i = 0; i <= maxCount; ++i )
    {
        auto diff = inTotal - ( maxVal * i );
        if( fmod(diff, minVal) == 0 )
        {
            result.emplace_back( i, diff / minVal );
        }
    }
    return result;
}

We can now extend this to have the three stamp scenario.

*

*We will take the price of the costliest stamp. Find maximum number of
time we can use that stamp.

*Then iterate from 0 till the count, And for the difference in amount
that needs to be compensated with the cheaper stamps, compute the
combinations using the previous approach.

Code would look as follows:
struct Set
{
    std::size_t x;  // count of costliest stamp
    std::size_t y;
    std::size_t z;  // count of cheapest stamp
};

std::vector< Set >
GetCombinations( double inTotal, double inM1, double inM2, double inM3 )
{
    std::vector< Set > result;
    auto maxVal = std::max( inM1, std::max( inM2, inM3 ) );
    std::size_t maxCount = inTotal/maxVal;

    // Find the prices of cheaper stamps.
    auto m1 = std::min( inM1, inM2 );
    auto m2 = std::min( inM2, inM3 );
    for( std::size_t i=0; i <= maxCount; ++i )
    {
        auto diff = inTotal - ( maxVal * i );
        auto subCombinations = GetCombinations( diff, m1, m2 );
        for( auto const & subComb : subCombinations )
        {
            result.push_back( Set{ i, 0, 0 } );
            result.back().y = subComb.first;
            result.back().z = subComb.second;
        }
    }
    return result;
}

You can find the complete code in : https://ideone.com/OkIDKK


text:
Q: sum, min, max & mean of R-values above a regression line in Python I have a time-series dataframe which i have plotted as below (2 dataframes are plotted together in the picture below)
the line plot lines are thin orange & blue lines. the regression line or the trend line of each dataset would be something like the thick orange & blue lines respectively.
How do I calculate the sum, min, max & mean of R-values (the distance from the regression line) above & below a regression line separately? That is sum, min, max & mean of the positive R-values & negative R-values separately in python.
There may be a term for what i am trying to do but i am new to statistics & do not know that. Can any one guide me?

Update The data i have is something like below (actual data is much longer). Overall trend is down but there are small upswings in between.

Time Values
101 20.402
102 20.302
103 20.202
104 20.102
105 20.002
106 19.902
107 19.802
108 19.702
109 19.602
110 19.502
111 19.402
112 19.302
113 19.202
114 20.337
115 20.437
116 20.537
117 18.802
118 18.702
119 18.602
120 18.502
121 18.402
122 18.302
123 18.202
124 18.102
125 18.002
126 17.902
127 17.802
128 17.702
129 17.602
130 17.502
131 18.502
132 18.402
133 18.302
134 17.702
135 17.602
136 17.502
137 17.402
138 17.302
139 17.202
140 17.102
141 17.002

A: This example uses your posted data and calculates positive and negative errors separately, excluding errors of exactly zero.
import numpy

xData = numpy.array([101.0, 102.0, 103.0, 104.0, 105.0, 106.0, 107.0, 108.0, 109.0, 110.0, 111.0, 112.0, 113.0, 114.0, 115.0, 116.0, 117.0, 118.0, 119.0, 120.0, 121.0, 122.0, 123.0, 124.0, 125.0, 126.0, 127.0, 128.0, 129.0, 130.0, 131.0, 132.0, 133.0, 134.0, 135.0, 136.0, 137.0, 138.0, 139.0, 140.0, 141.0])
yData = numpy.array([20.402, 20.302, 20.202, 20.102, 20.002, 19.902, 19.802, 19.702, 19.602, 19.502, 19.402, 19.302, 19.202, 20.337, 20.437, 20.537, 18.802, 18.702, 18.602, 18.502, 18.402, 18.302, 18.202, 18.102, 18.002, 17.902, 17.802, 17.702, 17.602, 17.502, 18.502, 18.402, 18.302, 17.702, 17.602, 17.502, 17.402, 17.302, 17.202, 17.102, 17.002])

polynomialOrder = 1 # example straight line

# curve fit the test data
fittedParameters = numpy.polyfit(xData, yData, polynomialOrder)
print('Fitted Parameters:', fittedParameters)

modelPredictions = numpy.polyval(fittedParameters, xData)
fitErrors = modelPredictions - yData

positiveErrors = []
negativeErrors = []

# this logic excludes errors of exactly zero
for error in fitErrors:
    if error < 0.0:
       negativeErrors.append(error)
    if error > 0.0:
       positiveErrors.append(error)

print('Positive error statistics:')
print('    sum =',  numpy.sum(positiveErrors))
print('    min =',  numpy.min(positiveErrors))
print('    max =',  numpy.max(positiveErrors))
print('    mean =', numpy.mean(positiveErrors))

print()

print('Negative error statistics:')
print('    sum =',  numpy.sum(negativeErrors))
print('    min =',  numpy.min(negativeErrors))
print('    max =',  numpy.max(negativeErrors))
print('    mean =', numpy.mean(negativeErrors))


text:
Q: Rails ActiveAdmin nearly duplicate code for columns I'd like to figure out a way to not duplicate so much code with ActiveAdmin when creating and index and a CSV. For example:
index do
    column('Order Id', sortable: 'orders.number') {|oi| oi.order.number }
    column('Price', sortable: :price_cents) { |oi| oi.price.format }
    ...
end

csv do
  column('Order Id') {|oi| oi.order.number }
  column('Price') { |oi| oi.price.format }
  ...
end

Where the columns are essentially identical (with the exception of sortable). I tried pulling the column calls out into a method, but it appears since ActiveAdmin is a DSL that this doesn't work.
Any suggestions? Thanks.


text:
Q: Proving the trace of a transformation is independent of the basis chosen How would you prove the trace of a transformation from V to V (where V is finite dimensional) is independent of the basis chosen?

A: The simplest way it to note that a basis transformation of a transformation $T$ is done via $ATA^{-1}$ where $A$ is an invertible matrix, and that the trace has the property $\operatorname{tr}(AB)=\operatorname{tr}(BA)$. Putting this together, you get $$\operatorname{tr}(ATA^{-1}) = \operatorname{tr}(A^{-1}AT) = \operatorname{tr}T$$

A: Let $A,B$ be $n \times n$ matrices, it applies $tr(AB) = tr(BA)$.
proof $\: tr(AB) = \sum_{i} (AB)_{ii} = \sum_{i}(\sum_{k}A_{ik}B_{ki})= \sum_{k}\sum_{i} (B_{ki} A_{ik}) = \sum_{k} (BA)_{kk} = tr(BA)$ q.e.d.
Let $A$ be a $n \times n$ matrix. The change of basis is given by $U^{-1}AU$, where $U$ is an invertible $n \times n$ matrix.
We finally can see that: $\:$ $tr(U^{-1}AU) = tr(AUU^{-1}) = tr(A)$.

A: An elementary proof could be the following. First, let $A$ be the matrix of your linear transformation in any basis of $V$. The characteristic polynomial of $A$ is
$$
Q_A(t) = \mathrm{det}\ (A - tI) =
\begin{vmatrix}
a^1_1 - t & a^1_2      & \dots & a^1_n \\
a^2_1     & a^2_2 - t  & \dots & a^2_n \\
\vdots    & \vdots     & \ddots & \vdots \\
a^n_1     & a^2_2      & \dots & a^n_n - t
\end{vmatrix}
$$
You can compute easily at least the first terms of this polynomial taking into account that, by the definition of the determinant:
$$
Q_A(t) = (a^1_1 -t)\cdot \dots \cdot (a^n_n - t) + \quad \text{sums of products with at most $n-2$ terms in the diagonal} \quad \ .
$$

Hence

$$
Q_A(t) = (-1)^n t^n +(-1)^{n-1} (a^1_1 + \dots + a^n_n) t^{n-1} + \quad ( \text{terms of degree}\ \leq n-2 ) \ .
$$
That is, up to a sign, the trace of $A$ is the coefficient of $t^{n-1}$ in the characteristic polynomial of $A$, $Q_A(t)$.
Now you can prove that $Q_A(t)$ does not depend on the basis you have chosen. Indeed, if $B$ is the matrix of the same linear transformation in another basis, then $A$ and $B$ are related through an equality like $B= S^{-1}A S$, where $S$ is the change of basis matrix. So
$$
Q_B(t) = \mathrm{det}\ (S^{-1}A S - tI ) = \mathrm{det}\ (S^{-1}A S - S^{-1}tIS ) = \mathrm{det}\ (S^{-1}(A  - tI)S )
$$
Thus
$$
Q_B(t) = \mathrm{det}\ (S^{-1}) \ \mathrm{det}\ (A  - tI )\ \mathrm{det}\ (S) = \mathrm{det}\ (A  - tI ) = Q_A(t) \ .
$$
Hence, the characteristic polynomial is invariant through basis change. In particular, so are its coefficients. More particularly, the trace.

A: There are a few ways to view this. The simplest is that if you have two $n \times n$ matrices $A, B$ then
$$
\operatorname{tr}(AB) = \operatorname{tr}(BA).
$$
This is an easy calculation.
Alternatively (some of the words may be unfamiliar to you, in which case ignore this bit), note that we have a canonical isomorphism $\operatorname{End}(V) \approx V \otimes V^\vee$, and that the trace on $\operatorname{End}(V)$ corresponds to the functional on $V \otimes V^\vee$ induced by the natural bilinear pairing of evaluation between $V$ and $V^\vee$. Verifying this is probably just as much work, but I think it's comforting to know that matrices are unnecessary for the definition.


text:
Q: Why doesn't Dart's DateTime object make use of the less than and greater than operator override methods? So I've noticed that one of Dart's unique abilities that it has over other languages is that you can override "primitive" comparisons (<, >, <=, >=, ==) in order to implement your own methods.
Now I was also looking through the DateTime class documentation to understand what it is and how to use it, and I noticed that they've opted to have the named methods DateTime.isBefore(DateTime other) and DateTime.isAfter(DateTime other). In human/pseudo code, these would translate to dateTime < other and dateTime > other, and naturally I thought why not just implement this directly into Dart?
I know this can be done using extensions as in this DartPad, and sure enough it works exactly as expected and to my knowledge, there's no way to know that an extension is being used...
But why wasn't overriding operators considered when developing the DateTime object? Or if it was considered, why wasn't it included?

A: For several reasons, but mainly because the ordering is not compatible with ==.
Two DateTime objects are equal if they have the same time and timezone, but they are considered before/after each other based entirely on the time, as modified for timezone.
It was considered a bad design to have a <= b which was not the same as (a < b || a == b), and for that reason, < and <= was dropped entirely.


text:
Q: setDuration only affects one CALayer when animating multiple CALayers I'm trying to animate a change in position for numerous CALayers simultaneously. Implicit animations seems to work fine, but if I try to explicitly specify a value for the duration properties of each CALayer, only one is animated while the other is changed successfully but without any animation. Here is the code I am working with:
CGPoint initialPt = CGPointMake(160.0, 10);
CGPoint pt2 = CGPointMake(160.0, 185.0);
CGPoint pt3 = CGPointMake(160.0, 270.0);

CABasicAnimation *firstAnim = [CABasicAnimation animationWithKeyPath:@"postion"];
[firstAnim setFromValue:[NSValue valueWithCGPoint:initialPt]];
[firstAnim setToValue:[NSValue valueWithCGPoint:pt2]];
[firstAnim setDuration:1.0];
[layer1 setPosition:p2];
[layer1 addAnimation:firstAnim forKey:@"Slide"];

CABasicAnimation *secondAnim = [CABasicAnimation animationWithKeyPath:@"position"];
[secondAnim setFromValue:[NSValue valueWithCGPoint:initialPt]];
[secondAnim setToValue:[NSValue valueWithCGPoint:pt3]];
[secondAnim setDuration:1.0];
[layer2 setPosition:p3];
[layer2 addAnimation:secondAnim forKey:@"Slide2"];

I've already tried using CATransaction as well but nothing changed. If I comment out the setDuration method, both layers animate the position change without issue, except that they are at a fixed duration. It seems that for some reason setting the animation explicitly muddles things up but I'm lost as to why. Any help would be much appreciated! Thanks.

A: The problem is you type the wrong word!
CABasicAnimation *firstAnim = [CABasicAnimation animationWithKeyPath:@"postion"]; change the 'postion' to 'position'

should be
CABasicAnimation *firstAnim = [CABasicAnimation animationWithKeyPath:@"position"]; change the 'postion' to 'position'

'postion' to position


text:
Q: Jenkins retrieve details of last successful build I have jenkins pipeline (Jenkinsfile) for build process, which setup build version number for each build once its successful. Now want to retrieve details like currentBuild.displayName of previous successful build in jenkinsfile and increment current builds build number.
I don't want to use Jenkins build number, because failed build numbers are wasted if I use Jenkins Build number.
Can get this with groovy def buildName = Jenkins.instance.getItem('Gateway').lastSuccessfulBuild.displayName
But how can I run it in Jenkinsfile ?

A: You can use it in script block:
steps {
    script{
        def lastSuccessBuildName = Jenkins.instance.getItem(env.JOB_NAME).lastSuccessfulBuild.displayName
        echo "Last Success Build Name: ${lastSuccessBuildName}"
    }
}


text:
Q: HapiJS + create-react-app + webpack-dev-middleware configuration I am currently using a create-react-app with HapiJS as a proxy for serving the static files.
This is how my current setup looks like:
//server.js
const server = new Hapi.Server({
        port: process.env.PORT || 80,
        routes: {
            files: {
                relativeTo: Path.join(__dirname, '../build')
            }
        }
    });
await server.register(Inert);
server.route(routes); // comes from an array of routes defined in react-routes.js
await server.start();
console.log('Server running at:', server.info.uri);

//react-routes.js
//All the routes mapped here should return an index.html file.
//React will take care of routing.
const routes = [
    { method: 'GET', path: '/home', config: fileHandler }
    { method: 'GET', path: '/account', config: fileHandler }
    ]

const fileHandler = {
    handler: (req, res) => {
        return res.file('index.html');
    }
}

I am using nodemon in development to run the server and react-scripts start to run the react-app.
Now the problem is, the HapiJS server only serves the static files from the build folder generated using react-scripts build. I understand that in order to connect to the webpack build, I need to use a middleware for HapiJS.
Looking at the webpack documentation, I see that it needs a reference to the webpack.config.js file. But I am not at liberty to use eject in order to access the webpack.config.js as required.
So the questions are:

*

*How do I setup webpack-dev-middleware with HapiJS in conjunction with create-react-app?

*How do I access the webpack.config.js without ejecting (and preferably without using any 3rd party modules)?

NOTE: This is not Server Side Rendering, I am using HapiJS as a proxy since there are cross-domain API calls involved and the proxy helps me avoid the infamous CORS error and serve the application as well.


text:
Q: ServiceStack 4 C# client async call hangs I am using ServiceStack 4 client to access a RESTful api endpoint. I have written two methods to return a list of objects. The synchronize method returns data as expected. The async methods hangs on the line :
var response = await client.GetAsync<List<Debtor>>("api/Debtor");

This is how my methods are defined:
    public async Task<List<Debtor>> GetDebtorsAsync()
    {
        var debtors = new List<Debtor>();

        try
        {
            var client = new JsonServiceClient(GlobalSingleton.ServerURI);
            var response = await client.GetAsync<List<Debtor>>("api/Debtor");
            debtors = response;
        }
        catch (Exception ex)
        {
            throw;
        }
        return debtors;
    }

    List<Debtor> IDebtorDal.GetDebtors()
    {
        var debtors = new List<Debtor>();

        try
        {
            var client = new JsonServiceClient(GlobalSingleton.ServerURI);
            var response = client.Get<List<Debtor>>("api/Debtor");
            var r = response.GetResponseStatus();
            debtors = response;
        }
        catch (Exception ex)
        {
            var x = ex.Message;
            throw;
        }
        return debtors;
    }

A: The ServiceStack Service Clients should only be used for calling ServiceStack Services. You can use HTTP Utils for calling 3rd party (i.e. non-ServiceStack) services.
The JsonServiceClient uses .NET's HttpWebRequest which has a default limit on the number of concurrent HTTP Requests to a single domain which you can increase with:
ServicePointManager.DefaultConnectionLimit = n;

Alternatively for async requests you can use JsonHttpClient instead which is built on Microsoft's newer HttpClient which doesn't have these limits.


text:
Q: Turn off composer install command when deploy on Digital Ocean App Platform I would like to ask if there is a way to disable the composer install command for my application on the Digital Ocean App Platform?
Btw I used Digital Ocean App Platform
Here I want to ask about time to deploy the code is very long for code changes that are even only one line. This is because the server always runs composer install for every code deployment from github to the Digital Ocean server.
How do I turn off the composer install command in this case? I can run artisan commands through the console without having to repeat myself as I explained above
Please help


text:
Q: how to give input border left and right small length I need to display the input field and i need give border bottom , left and right. But here i want only small portion border left side and right side.

.solid {
  border-style: solid;
  border-left-style: dashed;
  border-top: none;
  border-right-style: dashed;
}
<input class="solid">

A: You can use box-shadow to create this type of border.

input {
  width: 300px;
  border: none;
  margin: 50px;
  height: 35px;
  box-shadow: 13px 13px 0px -10px #000000, -13px 13px 0px -10px #000000;
  outline: none;
  font-size: 22px;
  background: none;
}
<input type="text">

A: Here you go. I had to add a div element outside the input field to use the before and after selectors.

.field {
  position: relative;
  display: inline-block;
}
.solid {
  border: none;
  border-bottom: 2px solid #000;
  padding: 5px;
}
.solid:focus {
  outline: none;
}
.field::after {
  content: '';
  width: 2px;
  height: 10px;
  position: absolute;
  background: #000;
  bottom: 0;
  right: 0;
}
.field::before {
  content: '';
  width: 2px;
  height: 10px;
  position: absolute;
  background: #000;
  bottom: 0;
  left: 0;
  z-index: 1;
}

  <input class="solid" type="text">

A: Here is how you can give input border left and right of small length
Html
<input type="text">

CSS
input[type="text"] {
padding: 20px;
background: linear-gradient(#000, #000), linear-gradient(#000, #000),linear-gradient(#000, #000);
background-size: 1px 20%, 100% 1px, 1px 20%;
background-position: bottom left, bottom center, bottom right;
background-repeat: no-repeat;
border: none;
color: #999;
}

Find the working fiddle
Reference

A:

html,body,input {
  padding: 0;
  margin: 0;
  border: 0;
  background-color: transparent;
}
.input-block {
  position: relative;
  width: 216px;/* important to define input width;width of input + 2x padding*/
  margin: 0 auto;
}
input {
  width: 208px;
  padding: 0 4px;
  outline: none;
  border-bottom: 1px solid black;
}
.input-lr-border {
  position: absolute;
  width: 1px;
  background-color: black;
  bottom: 0;
  height: 4px;
}
.left-border-input {
  left: 0;
}
.right-border-input {
  right: 0;
}

  <input/>

A:

li{
list-style: none;
width: 200px;
border-bottom: 2px solid #000;
position: relative;
padding: 2px 5px;
margin: 0 0 10px;
}
li:before, li:after{
  background: #000;
  content: '';
  position: absolute;
  bottom: 0;
  width: 2px;
  height: 5px;
}
li:before{
  left: 0;
}
li:after{
  right: 0;
}
input{
  border:0;
outline: none;
}

<input type="text" placeholder="First Name" />

<input type="text" placeholder="Last Name" />

<input type="text" placeholder="Email" />


text:
Q: Autocorrelation test - Rolling-window regressions I am performing 5-year rolling regressions over a 90-year period with monthly data and wanted to test for autocorrelation in the residuals. A Durbin-Watson test on the full sample leads to the conlusion that there is a positive 1st-order autocorrelation, while a DW test on the first window leads to the acceptance of the null hypothesis.
So please forgive me this neophyte question, but should I perform the DW test on the full sample, or on each window?
In this later case if there is AC for just a few windows, do I perform a GLS regression for each to be consistent? If there is no AC it should provides the same estimates than OLS anyway, even if OLS is more effective when this condition is not violated, isn't it?


text:
Q: Azure File Share refuses file deletion I've tried removing a file in an Azure File Share using

*

*the az CLI

*Azure Storage Explorer

Both yield the error:
The specified resource may be in use by an SMB client. and ErrorCode:SharingViolation
I've tried listing file handles with the Azure Powershell and az CLI commands, but no file handles are shown. Supposedly, this should reveal any file locks.
I've also tried rebooting everything (that I know of!) that is connected to this file share. Other files in the same directory can be deleted. Everything else with this file share seems normal.
Any idea how I can find the source of the lock, and how to delete it?

A: Can you check any other client accessing the share?
Create another test file in the same storage account(fileshare) for testing purpose and see are facing the similar  issue?
Sharingviolation: The operation failed because the object is already opened and does not allow the sharing mode that the caller requested.
Based on the error message you may refer to this article: https://learn.microsoft.com/en-us/rest/api/storageservices/managing-file-locks
which provides detailed information on file locks
Try to Unlock all Azure file share locks
This article lists common problems that are related to Microsoft Azure Files when you connect from Windows clients. It also provides possible causes and resolutions for these problems. In addition to the troubleshooting steps in this article: Unable to delete files


text:
Q: Magento 2: I need to call same class method in static function I need to call same class method in same Class static function. Is it possible.
Any idea please share.
public function getMake()
{
  // sample
}
static public function getMaker()
{
   // call getMake() function here

}

A: To call an non-static function you need an instantiated object of the class or access to $this in the function which is not the case in a static function.
I don't know what your classes returns or do but it is possible to call the non-static function by passing an object of the class into the static function like so:
class Foo {

    private function bar () {
        echo "Hello World!";
    }

    static public function staticBar (Foo $foo) {
        return $foo -> bar ();
    }
}


text:
Q: How can I combine these two JavaScript objects? I have two JavaScript objects as follows;
cages = [
  {
    "id":1,
    "name":"Cage 1"
  },
  {
    "id":2,
    "name":"Cage 2"
  }
]

animals = [
  {
    "id":1,
    "name":"doge",
    "cages": [
      {
        "id":1,
        "name":"Cage 1"
      },
      {
        "id":2,
        "name":"Cage 2"
      }
    ]
  }
  {
    "id":2,
    "name":"kat",
    "cages": [
      {
        "id":2,
        "name":"Cage 2"
      }
    ]
  }
]

I want to add the animals to the cages object, so that I end up with;
cages = [
  {
    "id":1,
    "name":"Cage 1",
    "animals": [
      {
        "id":1,
        "name":"doge"
      }
    ]
  },
  {
    "id":2,
    "name":"Cage 2",
    "animals": [
      {
        "id":1,
        "name":"doge"
      },
      {
        "id":2,
        "name":"kat"
      }
    ]
  }
]

What are some ways of combining two objects like this? Which ones are most efficient? My first attempt had some nested for loops that got pretty deep and messy and never quite worked. Here's some incomplete logic I've got so far;
for(var i=0; i<animals.length; i++) {
    for(var n=0; n<animals.cages.length) {
      cages[].push(animals[i]);
    }
  }

I need to know how to specify which cage to push the animal into. I wish it was as simple as cages[cage].push(animals[i]); but in this case the keys are the same for each cage object.

A: Using a nested loop
var i, j, k;
for (i = 0; i < animals.length; ++i) {
    for (j = 0; j < animals[i].cages.length; ++j) {
        // assuming cages[k].id === k
        // you may want to create a new cages object instead
        k = animals[i].cages[j].id; // neat shorthand
        if (!cages[k].animals) { // if no animals yet
            cages[k].animals = []; // initialise
        }
        cages[k].animals.push(
            { // add new animal to cage
                id: animals[i].id,
                name: animals[i].name
            }
        );
    }
}


text:
Q: capture traffic from emulator to a server on the same machine I am trying to capture http traffic using pcap4j from an android emulator / ios simulator to a server which is hosted on the same machine. The machine can run either linux / windows or osx.
I tried capturing packets from wireshark first for testing, but it didn't catch any. I guess this is because the emulator uses the loopback interface to talk to the server since they are running on the same machine. Is there any way I can capture the traffic other than making the emulators use a sort of "man in the middle http proxy"?
Thanks.

A:
I tried capturing packets from wireshark first for testing, but it didn't catch any. I guess this is because the emulator uses the loopback interface to talk to the server since they are running on the same machine

Yes, so, unless you capture on the loopback interface, you won't see the traffic.  On Linux, that interface is called "lo"; on OS X (and most other UN*Xes), it's called "lo0".  On Windows, you're out of luck, unfortunately.

A: The iOS Simulator uses the same network interfaces as the host.  There is not separate interface and Wireshark will see traffic from within the iOS Simulator the same way it will see traffic from any other Mac OS application.


text:
Q: How to conduct power analysis for unbalanced one-way ANOVA in R? I am looking for a way to conduct power analysis for unbalanced one-way ANOVA in R. I found the pwd package; however, it only allows me to calculate power for balanced one-way ANOVA.
I would appreciate if you could provide any R codes, or introduce a R package me to perform power analysis for unbalanced one-way ANOVA.

A: I would probably use simulation to calculate the power. It is fairly easy to set up for a one-way ANOVA. Here is a quick and dirty R simulation with an example that compares 3 groups. To add more groups, just add the corresponding sample sizes sampsi, group means mus and standard deviation sds (note that the standard deviations are assumed to be equal in a traditional ANOVA). I assumed an $\alpha = 0.05$ in the example below.
# Number of simulations
n_sim <- 10000

# Sample size of each group
sampsi <- c(20, 50, 70)

# Mean of each group
mus <- c(10, 11, 12)

# Standard deviation of each group (assumed to be equal!)
sds <- c(5, 5, 5)

p_vals <- NULL

# Set seed for reproducibility
set.seed(142857)

for(i in 1:n_sim) {

  dat_tmp <- data.frame(
    y = rnorm(sum(sampsi), mean = rep(mus, times = sampsi), sd = rep(sds, times = sampsi))
    , group = factor(rep(seq_along(mus), times = sampsi))
  )

  mod <- anova(lm(y~group, data = dat_tmp))

  p_vals[i] <-  mod$`Pr(>F)`[1]

  rm(dat_tmp)

}

# Simulated power

cat("Simulated power is:", mean(p_vals <= 0.05)*100, "%")

Simulated power is: 30.22 %


text:
Q: panel with scrollbar in c# i am trying to create a POS system, and there will be buttons creating dynamically,  wondering what is the best way to create or layout the buttons.
I am currently using Metro Framework for C# window form, is there a way to create a pannel to have fixed amount of rows, and x columns of buttons so that if it has more than x columns, it will generate a scroll bar for you to slide to the rest of the buttons.
thank you


text:
Q: keep footer last in list when dragging new item into the list from another I have Vue Draggable working like a Kanban board with multiple columns, and I have made each column at least the height of the viewport so that each item can easily be dragged into the column next to it (for cases where one column is much longer than the next, for example).
I also have a button in the footer slot to add new cards to the column. This works well in that it is generally always at the bottom of the list, is not draggable, etc.
The issue arises when I drag an item from another list in below the footer (but still within the height of the draggable element). When I do this, the footer does not stay below the new item, which looks odd.
Once I drop the element, it snaps into place and the footer is one again at the bottom - it is only when the new card is being moved that it appears below the footer.
Is there any way to make sure that even during the move event and a new card being added to a list that the footer stays as the last element?
This issue seems to be captured in this comment on Github issues - https://github.com/SortableJS/Vue.Draggable/issues/673#issuecomment-554149705 - but no solution is provided in that thread.
Any help greatly appreciated.

A: So for anyone having the same issue I solved this by doing the following:

*

*Hooking into the onMove event using the :move prop to run a function each time an item is moved... e.g. :move="fixFooter"

*Creating a function that checks if the moved item would be the last in the new list (thus by default it would sit below the footer without this fix), and if so on the $nextTick append the footer to the Draggable container so it gets moved below the item coming in to the list... (just learnt that .appendChild will move an existing element to the end)

*It then checks if the from/to list is the same to account for the item being dragged back into the list it's coming from during the same drag event (otherwise you get the same undesirable footer behaviour as before if you drag an item out of a list and back below the footer without dropping it).

fixFooter(e) {
  if(e.relatedContext.list.length === e.draggedContext.futureIndex) {
    var newListDom = e.relatedContext.component.$el;
    var newListFooter = e.relatedContext.component.$slots.footer[0].elm;
    this.$nextTick(() => {
      newListDom.appendChild(newListFooter);
    });
  } else if(e.from === e.to && (e.from.children.length - 1) === e.draggedContext.futureIndex) {
    var currentListDom = e.from;
    var currentListFooter = e.from.lastChild;
    this.$nextTick(() => {
      currentListDom.appendChild(currentListFooter);
    });
  }
}

A: Seems like for vue draggable next this is enough:
fixFooter(e) {
  if (e.relatedContext.list.length === e.draggedContext.futureIndex) {
    var newListDom = e.to

    var newListFooter = e.to.lastChild
    this.$nextTick(() => {
      newListDom.appendChild(newListFooter);
    });
  }
}


text:
Q: (Prolog) Get sum of variables without list very new to Prolog and I'm absolutely awful at it.
I am trying to get a sum for all the marks received on assignments, and return it. The sum predicate must be of the form sumAssignments(S).
Here's the knowledge base I've made:
assignment(1, A).
assignment(2, B).
assignment(3, C).
assignment(4, D).
assignment(5, E).

...Where assignment(1, A) means that assignment 1 has a variable grade A (could be 70, could be 50, etc.).
Here is my attempt at getting the sum, just for the first two assignments for testing purposes:
sumAssignments(S) :- assignment(1, A), assignment(2, B), S=A+B.

That always returns yes. The key here is I can't use lists.

A: I found out that only constants belong in predicates, so instead of assignment(1, A). we would find an arbitrary number to represent 'A', in this case maybe 67 or 100: assignment(1, 67). The summation works fine after doing that.