text:
Q: How do I pass an argument to the parent constructor in oop PHP? I am trying to instantiate two objects from a base class and and pass an argument to the parent class constructor from the child class constructor. This doesn't seem to be working. It acts as if the objects are not even sub objects of the parent class. I do not know what I am doing wrong.
I've tried rearranging the includes, passing no arguments (that results in an error, "expects an argument"), and other tinkering to no avail.
The parent class:
class SuperHero {
    private $health;
    private $name;
    private $isDead;

    public function __construct($name) {
        $this->name;
        $this->isDead = false;
    }

    // ...

    public function attack($opponent) {
        echo $this->name.' attacks '.$opponent->name.'!
';
        $dmg = mt_rand(1, 10);
        $opponentHealth = determineHealth($opponent, $dmg);
        echo $opponent->name.' has '.$opponentHealth.' health left!
';
    }

    // ...

The child class:
<?php
require_once('SuperHero.php');
class Batman extends SuperHero {

    public function __construct() {
        parent::__construct('Batman');
        $this->health = mt_rand(1, 1000);
    }

}

The executed script:
require_once('Batman.php');
require_once('Superman.php');

$h1 = new Batman;
$h2 = new Superman;

echo $h1->name.' is starting with '.$h1->health.' health!
';
echo $h2->name.' is starting with '.$h2->health.' health!
';

while($h1->getIsDead() == false && $h2->getIsDead() == false){
    $h1->attack($h2);
    $h2->attack($h1);
}

Actual results
is starting with 317 health!
Superman is starting with 300 health!
attacks !

Expected results
Batman is starting with 317 health!
Superman is starting with 300 health!
Batman attacks Superman!

A: Your parent class' constructor looks like this
public function __construct($name) {
    $this->name;
    $this->isDead = false;
}

$this->name; alone does nothing, it attempts to get that value. You need to assign it a value, by doing
$this->name = $name;

Then, all your attributes are private, meaning that you cannot access them by doing $batman->name. You will need to implement a getter for that, $batman->getName() (for each property that you want to get). If they were public, you could get them by doing $batman->name, but then you can overwrite it as well by $batman->name = 'Robin';. Better use a getter.
Further, determineHealth() should probably a method of the class and called on the $opponent object, instead of an actual function.
class SuperHero {
    private $health;
    private $name;
    private $isDead;

    public function __construct($name, $health) {
        $this->name = $name;
        $this->health = $health;
        $this->isDead = false;
    }

    public function attack($opponent) {
        $dmg = mt_rand(1, 10);
        echo $this->getName().' attacks '.$opponent->getName().' with '.$dmg." damage. ";
        $opponentHealth = $opponent->determineHealth($dmg);
        echo $opponent->getName().' has '.$opponentHealth." health left!
\n";
    }

    public function getName() {
        return $this->name;
    }

    public function getHealth() {
        return $this->health;
    }

    public function isDead() {
        return $this->isDead;
    }

    public function determineHealth($health) {
        $this->health -= $health;
        if ($this->health <= 0) {
            $this->health = 0;
            $this->isDead = true;
        }
        return $this->health;
    }
}

class Batman extends SuperHero {
    public function __construct() {
        $health = mt_rand(1, 1000);
        parent::__construct('Batman', $health);
    }
}

class Superman extends SuperHero {
    public function __construct() {
        $health = mt_rand(1, 1000);
        parent::__construct('Superman', $health);
    }
}

$h1 = new Batman;
$h2 = new Superman;

echo $h1->getName().' is starting with '.$h1->getHealth()." health!
\n";
echo $h2->getName().' is starting with '.$h2->getHealth()." health!
\n";

$h1->attack($h2);
$h2->attack($h1);

Output:
Batman is starting with 445 health!

Superman is starting with 229 health!

Batman attacks Superman with 5 damage. Superman has 224 health left!

Superman attacks Batman with 9 damage. Batman has 436 health left!

*

*Live demo at https://3v4l.org/aDegT

A: The name and health members of superclass are not available in subclass as they are private.
Either you should change them to public or you should create public getters and setters and use them instead.

A:
Private Variable can't be inherited.

    <?php
class SuperHero {
    private $health;
    private $name;
    private $isDead;

    public function __construct($name) {
        $this->name = $name;
        $this->isDead = false;
    }

    public function name()
    {
        return $this->name;
    }

    public function attack($opponent) {
        echo $this->name.' attacks '.$opponent->name.'!
';
        $dmg = mt_rand(1, 10);
        $opponentHealth = determineHealth($opponent, $dmg);
        echo $opponent->name.' has '.$opponentHealth.' health left!
';
    }
}

class Batman extends SuperHero {

    public function __construct() {
        parent::__construct('Batman');
        $this->health = mt_rand(1, 1000);
    }

}
class Superman extends SuperHero {

    public function __construct() {
        parent::__construct('Superman');
        $this->health = mt_rand(1, 1000);
    }

}

$h1 = new Batman;
$h2 = new Superman;

echo $h1->name().' is starting with '.$h1->health.' health!
';
echo $h2->name().' is starting with '.$h2->health.' health!
';

while($h1->getIsDead == false && $h2->getIsDead == false){
    $h1->attack($h2);
    $h2->attack($h1);
}

?>

Here in Parent class function name() will return the name that is passed from parent::__construct('Name').

Output
Batman is starting with 327 health!
Superman is starting with 842 health!
Batman attacks Superman!


text:
Q: Very custom UIButton animation in iOS I have a custom button which is my own subclass of UIButton. It looks like a circled arrow, starting at some angle startAngle end finishing at some endAngle=startAngle+1.5*M_PI.
startAngle is a button's property which is then used in its drawRect: method.
I want to make this arrow to continuously rotate by 2Pi around its center when this button is pressed. So I thought that I can easily use [UIView beginAnimations: context:] but apparently it can't be used as it doesn't allow to animate custom properties. CoreAnimation also doesn't suite as it only animates the CALayer properties.
So what is the easiest way to implement an animation of a custom property of UIView subclass in iOS?
Or maybe I missed something and it is possible with already mentioned techniques?
Thank you.

A: Thanks to Jenox I have updated animation code using CADisplayLink which seems to be really more correct solution than NSTimer. So I show the correct implementation with CADisplayLink now. It is very close to the previous one, but even a bit simpler.
We add the QuartzCore framework to our project.
Then we put the following lines in the header file of our class:
CADisplayLink* timer;
Float32 animationDuration;  // Duration of one animation loop
Float32 initAngle;  // Represents the initial angle
Float32 angle;  // Angle used for drawing
CFTimeInterval startFrame;  // Timestamp of the animation start

-(void)startAnimation;  // Method to start the animation
-(void)animate;  // Method for updating the property or stopping the animation

Now in implementation file we set the values for duration of the animation and the other initial values:
initAngle=0.75*M_PI;
angle=initAngle;
animationDuration=1.5f;  // Arrow makes full 360° in 1.5 seconds
startFrame=0;  // The animation hasn't been played yet

To start the animation we need to create the CADisplayLink instance which will call method animate and add it to main RunLoop of our application:
-(void)startAnimation
{
   timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(animate)];
   [timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

This timer will call animate method every runLoop of the application.
So now comes the implementation of our method for updating the property after each loop:
-(void)animate
{
   if(startFrame==0) {
      startFrame=timer.timestamp;  // Setting timestamp of start of animation to current moment
      return;  // Exiting till the next run loop
   }
   CFTimeInterval elapsedTime = timer.timestamp-startFrame;  // Time that has elapsed from start of animation
   Float32 timeProgress = elapsedTime/animationDuration;  // Determine the fraction of full animation which should be shown
   Float32 animProgress = timingFunction(timeProgress); // The current progress of animation
   angle=initAngle+animProgress*2.f*M_PI;  // Setting angle to new value with added rotation corresponding to current animation progress
   if (timeProgress>=1.f)
   {  // Stopping animation
      angle=initAngle; // Setting angle to initial value to exclude rounding effects
      [timer invalidate];  // Stopping the timer
      startFrame=0;  // Resetting time of start of animation
   }
   [self setNeedsDisplay];  // Redrawing with updated angle value
}

So unlike case with NSTimer we now don't need to calculate the time interval at which to update the angle property and redraw the button. We now only need to count how much time has passed from the start of animation and set the property to value which corresponds to this progress.
And I must admit that animation works a bit more smoothly than in case of NSTimer.
By default, CADisplayLink calls the animate method each run loop. When I calculated the frame rate, it was 120 fps. I think that it is not very efficient so I have decreased the frame rate to just 22 fps by changing the frameInterval property of CADisplayLink before adding it to mainRunLoop:
timer.frameInterval=3;

It means that it will call the animate method at first run loop, then do nothing next 3 loops, and call on the 4-th, and so on. That's why frameInterval can be only integer.

A: Thanks again to k06a for suggestion to use timer. I've made some study about working with NSTimer and now I want to show my implementation, since I think, it can be useful for others.
So in my case I had a UIButton subclass which was drawing a curved arrow which started from some angle Float32 angle; which is the main property from which the drawing of whole arrow starts. That means that just changing the value of angle will rotate whole arrow. So to make animation of this rotation I put the following lines in the header file of my class:
NSTimer* timer;
Float32 animationDuration;  // Duration of one animation loop
Float32 animationFrameRate;  // Frames per second
Float32 initAngle;  // Represents the initial angle
Float32 angle;  // Angle used for drawing
UInt8 nFrames;  // Number of played frames

-(void)startAnimation;  // Method to start the animation
-(void)animate:(NSTimer*) timer;  // Method for drawing one animation step and stopping the animation

Now in implementation file I set the values for duration and frame rate of my animation and the initial angles for drawing:
initAngle=0.75*M_PI;
angle=initAngle;
animationDuration=1.5f;  // Arrow makes full 360° in 1.5 seconds
animationFrameRate=15.f;  // Frame rate will be 15 frames per second
nFrames=0;  // The animation hasn't been played yet

To start the animation we need to create the NSTimer instance which will call method animate:(NSTimer*) timer every 1/15 seconds:
-(void)startAnimation
{
   timer = [NSTimer scheduledTimerWithTimeInterval:1.f/animationFrameRate target:self selector:@selector(animate:) userInfo:nil repeats:YES];
}

This timer will call animate: method immediately and then repeat it every 1/15 second until it will be manually stopped.
So now comes the implementation of our method for animating a single step:
-(void)animate:(NSTimer *)timer
{
   nFrames++;  // Incrementing number of played frames
   Float32 animProgress = nFrames/(animationDuration*animationFrameRate); // The current progress of animation
   angle=initAngle+animProgress*2.f*M_PI;  // Setting angle to new value with added rotation corresponding to current animation progress
   if (animProgress>=1.f)
   {  // Stopping animation when progress is >= 1
      angle=initAngle; // Setting angle to initial value to exclude rounding effects
      [timer invalidate];  // Stopping the timer
      nFrames=0;  // Resetting counter of played frames for being able to play animation again
   }
   [self setNeedsDisplay];  // Redrawing with updated angle value
}

The first thing I want to mention is that for me just comparison line angle==initAngle didn't work due to rounding effects. They don't are exactly the same after full rotation. That's why I check if they are just close enough and then set angle value to initial value to block small drift of angle value after many repeated animation loops.
And to be totally correct, this code must also manage conversion of angles to always be between 0 and 2*M_PI with something like this:
angle=normalizedAngle(initAngle+animProgress*2.f*M_PI);

where
Float32 normalizedAngle(Float32 angle)
{
   while(angle>2.f*M_PI) angle-=2.f*M_PI;
   while(angle<0.f) angle+=2.f*M_PI;
   return angle
}

And another important thing is that, unfortunately, I don't know any easy way to apply easeIn, easeOut or other default animationCurves to this kind of manual animation. I think it doesn't exist. But it is, of course, possible to do it by hands. The line standing for that timing function is
Float32 animProgress = nFrames/(animationDuration*animationFrameRate);

It can be treated as Float32 y = x;, that means linear behavior, a constant speed, which is the same as speed of time. But you can modify it to be like y = cos(x) or y = sqrt(x) or y = pow(x,3.f) which will give some nonlinear behavior. You can think it yourself taking into account that x will go from 0 (start of animation) to 1 (end of animation).
For better looking code it is better to make some independent timing function:
Float32 animationCurve(Float32 x)
{
  return sin(x*0.5*M_PI);
}

But now, since the dependence between animation progress and time is not linear, it's safer to use the time as indicator for stopping the animation. (You might want for example to make your arrow to make 1.5 full turns and than rotate back to the initial angle, that means your animProgress will go from 0 to 1.5 and than back to 1 while timeProgress will go from 0 to 1.)
So to be safe we separate time progress and animation progress now:
Float32 timeProgress = nFrames/(animationDuration*animationFrameRate);
Float32 animProgress = animationCurve(timeProgress);

and then check time progress to decide if should the animation stop:
if(timeProgress>=1.f)
{
   // Stop the animation
}

By the way, if somebody knows some sources with list of useful timing functions for animation, I would appreciate if you share them.
Built in MacOS X utility Grapher helps a lot in visualizing the functions, so that you can see how your animation progress will depend on time progress.
Hope it helps somebody...

A: - (void)onImageAction:(id)sender
{
    UIButton *iconButton = (UIButton *)sender;
    if(isExpand)
{
    isExpand = FALSE;

    // With Concurrent Block Programming:
    [UIView animateWithDuration:0.4 animations:^{
        [iconButton setFrame:[[btnFrameList objectAtIndex:iconButton.tag] CGRectValue]];
    } completion: ^(BOOL finished) {
        [self animationDidStop:@"Expand" finished:YES context:nil];
    }];
}
else
{
    isExpand = TRUE;

    [UIView animateWithDuration:0.4 animations:^{
        [iconButton setFrame:CGRectMake(30,02, 225, 205)];
    }];

    for(UIButton *button in [viewThumb subviews])
    {
        [button setUserInteractionEnabled:FALSE];
        //[button setHidden:TRUE];
    }
    [viewThumb bringSubviewToFront:iconButton];

    [iconButton setUserInteractionEnabled:TRUE];
   // [iconButton setHidden:FALSE];
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change progressDialog text i have an asynctask but if i implement a Thread.Sleep , then my app crashes , i dont know  why, in onPreExecute i can see my first message and then after two secs it appears the other one i put in doInBackground  , but its not working
private class sendMail extends AsyncTask<Void, Void, Void> {

        protected void onPreExecute() {
            dialog.setMessage("Please wait...");
            dialog.show();

        }

        // automatically done on worker thread (separate from UI thread)
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            dialog.setMessage("Downloading files...");

            new BackgroundTask().execute();

//MY DOWNLOADING METHODS STUFF

And then i dismiss this dialog somewhere else
Log

An error occurred while executing doInBackground()

A: You cannot access the UI elements from a background thread you can update the progressbar in onProgressUpdate, most importantly you need to publishProgress(value) in doInBackground and update using onProgressUpdate. Read more about the AsyncTask here.
Example code:
class MyTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected String doInBackground(Integer... params) {
            for (; count <= params[0]; count++) {
                try {
                    Thread.sleep(1000);
                    publishProgress(count);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "Task Completed.";
        }
        @Override
        protected void onPostExecute(String result) {
            progressBar.setVisibility(View.GONE);
                txt.setText(result);
                btn.setText("Restart");
        }
        @Override
        protected void onPreExecute() {
            txt.setText("Task Starting...");
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            txt.setText("Running..."+ values[0]);
            progressBar.setMessage("Downloading files...");
            progressBar.setProgress(values[0]);
        }
    }

A: Use UI thread to show dialog message in doInBackground refer this https://stackoverflow.com/a/15757788/6626966


text:
Q: Drawing on previewLayer: AVCaptureVideoPreviewLayer I have a small app, a SimpleCamera that shows a live (video) preview, with a button on the screen to take a photo. The photo is then displayed and you can save it or discard it. It all works, and I have used this code to draw a grey border around the screen preview. That too works fine. But that's all I can draw on that preview screen? I can't work out how to add the next bit of code shown below this first code block?
    // Provide a camera preview
    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    view.layer.addSublayer(cameraPreviewLayer!)
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    cameraPreviewLayer?.frame = view.layer.frame
    //Add preview layer for drawing
    let previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
    previewLayer.frame = self.view.layer.frame
    previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    self.view.layer.addSublayer(previewLayer)
    //Add Rectangle
    let cgRect = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
    let myView = UIImageView()
    myView.frame = cgRect
    myView.backgroundColor = UIColor.clear
    myView.isOpaque = false
    myView.layer.cornerRadius = 10
    myView.layer.borderColor =  UIColor.lightGray.cgColor
    myView.layer.borderWidth = 3
    myView.layer.masksToBounds = true
    previewLayer.addSublayer(myView.layer)
    // Bring the camera button to front
    view.bringSubview(toFront: cameraButton)
    captureSession.startRunning()

No matter where I put this code, it simply doesn't show up.
    //Add circles
    let midX = screenWidth / 2
    let midY = screenHeight / 2
    let w = screenWidth
    var circlePath = UIBezierPath(arcCenter: CGPoint(x: midX,y: midY), radius: CGFloat(w * 0.010), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
    let circleRads = [ 0.07, 0.13, 0.17, 0.22, 0.29, 0.36, 0.40, 0.48, 0.60, 0.75 ]
    for pct in circleRads {
        let rad = w * CGFloat(pct)
        circlePath = UIBezierPath(arcCenter: CGPoint(x: midX, y: midY), radius: CGFloat(rad), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
        circlePath.lineWidth = 2.5
        circlePath.stroke()
    }

     // draw text time stamp on image
     let now = Date()
     let formatter = DateFormatter()
     formatter.timeZone = TimeZone.current
     formatter.dateFormat = "yyyy-MM-dd HH:mm"
     let dateString = formatter.string(from: now)
     let paragraphStyle = NSMutableParagraphStyle()
     paragraphStyle.alignment = .center
     let attrs = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Thin", size: 26)!, NSAttributedStringKey.paragraphStyle: paragraphStyle]
     let string = dateString
     string.draw(with: CGRect(x: 12, y: 38, width: 448, height: 448), options: .usesLineFragmentOrigin, attributes: attrs, context: nil)

A: Part answered. I can draw a Border around the entire screen. This is the SimpleCamera app from the AppCoda Swift 4 Intermediate iOS 11 Book. This is the code for the CameraController.swift file, and the Border drawing section is Line 176 to Line 192 when opened in XCode.
But I still can't figure out how to make the commented section draw a set of circles, and put a date stamp on the image, and save it.
//
//  CameraController.swift
//  Camera
//
//  Created by Simon Ng on 16/10/2016.
//  Copyright © 2016 AppCoda. All rights reserved.
//

import UIKit
import AVFoundation
import Foundation

class CameraController: UIViewController {

@IBOutlet var cameraButton:UIButton!

//===================================
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var imgOverlay: UIImageView!
@IBOutlet weak var btnCapture: UIButton!
@IBOutlet weak var btnInfo: UIButton!
@IBOutlet weak var btnSocial: UIButton!
@IBOutlet weak var shapeLayer: UIView!
@IBOutlet weak var btnRed: UIButton!
@IBOutlet weak var btnGreen: UIButton!
@IBOutlet weak var btnBlue: UIButton!
@IBOutlet weak var btnYellow: UIButton!
@IBOutlet weak var btnWhite: UIButton!

//===================================

var backFacingCamera: AVCaptureDevice?
var frontFacingCamera: AVCaptureDevice?
var currentDevice: AVCaptureDevice!

var stillImageOutput: AVCapturePhotoOutput!
var stillImage: UIImage?

var cameraPreviewLayer: AVCaptureVideoPreviewLayer?

let captureSession = AVCaptureSession()

var toggleCameraGestureRecognizer = UISwipeGestureRecognizer()
var zoomInGestureRecognizer = UISwipeGestureRecognizer()
var zoomOutGestureRecognizer = UISwipeGestureRecognizer()
//===============================

//let stillImageOutput = AVCaptureStillImageOutput()
var previewLayer : AVCaptureVideoPreviewLayer?

let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
var aspectRatio: CGFloat = 1.0

var viewFinderHeight: CGFloat = 0.0
var viewFinderWidth: CGFloat = 0.0
var viewFinderMarginLeft: CGFloat = 0.0
var viewFinderMarginTop: CGFloat = 0.0

var lineColor : UIColor?
var color: Int = 0
//==============================

override func viewDidLoad() {
    super.viewDidLoad()

     configure()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Action methods

@IBAction func capture(sender: UIButton) {

    // Set photo settings
    let photoSettings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])
    photoSettings.isAutoStillImageStabilizationEnabled = true
    photoSettings.isHighResolutionPhotoEnabled = true
    photoSettings.flashMode = .off

    stillImageOutput.isHighResolutionCaptureEnabled = true
    stillImageOutput.capturePhoto(with: photoSettings, delegate: self)
}

// MARK: - Segues

@IBAction func unwindToCameraView(segue: UIStoryboardSegue) {

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    if segue.identifier == "showPhoto" {
        let photoViewController = segue.destination as! PhotoViewController
        photoViewController.image = stillImage
    }
}

// MARK: - Helper methods

private func configure() {
    // Preset the session for taking photo in full resolution
    captureSession.sessionPreset = AVCaptureSession.Preset.photo

    // Get the front and back-facing camera for taking photos
    let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified)

    for device in deviceDiscoverySession.devices {
        if device.position == .back {
            backFacingCamera = device
        } else if device.position == .front {
            frontFacingCamera = device
        }
    }

    currentDevice = backFacingCamera

    guard let captureDeviceInput = try? AVCaptureDeviceInput(device: currentDevice) else {
        return
    }

    // Configure the session with the output for capturing still images
    stillImageOutput = AVCapturePhotoOutput()

    // Configure the session with the input and the output devices
    captureSession.addInput(captureDeviceInput)
    captureSession.addOutput(stillImageOutput)

    // Provide a camera preview
    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    view.layer.addSublayer(cameraPreviewLayer!)
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    cameraPreviewLayer?.frame = view.layer.frame
    //////////////

    //Add circles
    // red circles - radius in %
/*
    let midX = screenWidth / 2
    let midY = screenHeight / 2
    let w = screenWidth
    //let h = screenHeight
    var circlePath = UIBezierPath(arcCenter: CGPoint(x: midX,y: midY), radius: CGFloat(w * 0.010), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
    let circleRads = [ 0.07, 0.13, 0.17, 0.22, 0.29, 0.36, 0.40, 0.48, 0.60, 0.75 ]
    for pct in circleRads {
        let rad = w * CGFloat(pct)
        circlePath = UIBezierPath(arcCenter: CGPoint(x: midX, y: midY), radius: CGFloat(rad), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
        circlePath.lineWidth = 2.5
        circlePath.stroke()
    }
     // draw text time stamp on image
     let now = Date()
     let formatter = DateFormatter()
     formatter.timeZone = TimeZone.current
     formatter.dateFormat = "yyyy-MM-dd HH:mm"
     let dateString = formatter.string(from: now)
     // print(dateString)
     let paragraphStyle = NSMutableParagraphStyle()
     paragraphStyle.alignment = .center
     let attrs = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Thin", size: 26)!, NSAttributedStringKey.paragraphStyle: paragraphStyle]
     let string = dateString
     string.draw(with: CGRect(x: 22, y: 18, width: 448, height: 448), options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
     print("Did the date")
*/
    //Add Rectangular border
     let previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
     previewLayer.frame = self.view.layer.frame
     previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
     self.view.layer.addSublayer(previewLayer)

    let cgRect = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
    let myView = UIImageView()
    myView.frame = cgRect
    myView.backgroundColor = UIColor.clear
    myView.isOpaque = false
    myView.layer.cornerRadius = 10
    myView.layer.borderColor =  UIColor.lightGray.cgColor
    myView.layer.borderWidth = 3
    myView.layer.masksToBounds = true

    previewLayer.addSublayer(myView.layer)
    ///////////////

    // Bring the camera button to front
    view.bringSubview(toFront: cameraButton)
    captureSession.startRunning()

    print("so far 2")
    // Toggle Camera recognizer
    toggleCameraGestureRecognizer.direction = .up
    toggleCameraGestureRecognizer.addTarget(self, action: #selector(toggleCamera))
    view.addGestureRecognizer(toggleCameraGestureRecognizer)

    // Zoom In recognizer
    zoomInGestureRecognizer.direction = .right
    zoomInGestureRecognizer.addTarget(self, action: #selector(zoomIn))
    view.addGestureRecognizer(zoomInGestureRecognizer)

    // Zoom Out recognizer
    zoomOutGestureRecognizer.direction = .left
    zoomOutGestureRecognizer.addTarget(self, action: #selector(zoomOut))
    view.addGestureRecognizer(zoomOutGestureRecognizer)
}

@objc func toggleCamera() {
    captureSession.beginConfiguration()

    // Change the device based on the current camera
    guard let newDevice = (currentDevice?.position == AVCaptureDevice.Position.back) ? frontFacingCamera : backFacingCamera else {
        return
    }

    // Remove all inputs from the session
    for input in captureSession.inputs {
        captureSession.removeInput(input as! AVCaptureDeviceInput)
    }

    // Change to the new input
    let cameraInput:AVCaptureDeviceInput
    do {
        cameraInput = try AVCaptureDeviceInput(device: newDevice)
    } catch {
        print(error)
        return
    }

    if captureSession.canAddInput(cameraInput) {
        captureSession.addInput(cameraInput)
    }

    currentDevice = newDevice
    captureSession.commitConfiguration()
}

@objc func zoomIn() {
    if let zoomFactor = currentDevice?.videoZoomFactor {
        if zoomFactor < 5.0 {
            let newZoomFactor = min(zoomFactor + 1.0, 5.0)
            do {
                try currentDevice?.lockForConfiguration()
                currentDevice?.ramp(toVideoZoomFactor: newZoomFactor, withRate: 1.0)
                currentDevice?.unlockForConfiguration()
            } catch {
                print(error)
            }
        }
    }
}

@objc func zoomOut() {
    if let zoomFactor = currentDevice?.videoZoomFactor {
        if zoomFactor > 1.0 {
            let newZoomFactor = max(zoomFactor - 1.0, 1.0)
            do {
                try currentDevice?.lockForConfiguration()
                currentDevice?.ramp(toVideoZoomFactor: newZoomFactor, withRate: 1.0)
                currentDevice?.unlockForConfiguration()
            } catch {
                print(error)
            }
        }
    }
}
}

extension CameraController: AVCapturePhotoCaptureDelegate {

func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
    guard error == nil else {
        return
    }

    // Get the image from the photo buffer
    guard let imageData = photo.fileDataRepresentation() else {
        return
    }

    stillImage = UIImage(data: imageData)
    performSegue(withIdentifier: "showPhoto", sender: self)
}

}

A: You need a CAShapeLayer to add the bezierpath to.
let circleLayer = CAShapeLayer()
circleLayer.path = circlePath.cgPath
self.view.layer.addSublayer(circleLayer)


text:
Q: Mongoose/Mongo structure for a data map
Hi there, I have some data, and I'd like some help with finding the correct data structure for displaying it. My goal is to have a map like the image above. Different physical sites will have the latitude and longitude information, but the circular radius will be determined by different statistics at each site. The user will be able to select which set of data they'd like to see. There are approximately 26 sets of data. Only one set of locations.
My data looks like this:
Locations (approximately 5000 pieces)
var locSchema = mongoose.Schema({
 name : 'string',
 siteID : 'number',
 address1 : 'string',
 address2 : 'string',
 loc: {type: [Number], index: '2dsphere'}
});

Specific Data (approximately 12000 pieces)
var dataSchema = mongoose.Schema({
  providerNumber : "number",  //The "siteID" of the site.
  date : "date",
  volume : "number",
  cost : "number",
  label : "string",  //There are 26 different stats each with a different label
  siteID : "oid"  //The oid of the site
});

My first guess was that they should be a single collection with each piece of data stored as an array:
name : 'string',
siteID : 'number',
address1 : 'string',
address2 : 'string',
loc: {type: [Number], index: '2dsphere'},
data : [
   {
     providerNumber : "number",  //The "siteID" of the site.
     date : "date",
     volume : "number",
     cost : "number",
     label : "string",  //There are 26 different stats each with a different label
     siteID : "oid"  //The oid of the site
   },
   ...
]

But I'm not sure how to create that kind of data structure in Mongoose, especially the array of objects. Also, there is a chance that there will be multiple sets of updated data that will need to be visualized.
So my questions are:
1. What is the best structure for this data?
2. What is the syntax for creating it in Mongoose?
3. Any advice on making it exapandable?

A: I have a bias towards keeping the data in mongo as flat and denormalized as possible. I have run into problems updating and maintaining subdocuments, especially arrays. I also like to model my data based off of how it's going to be used most often. My preference would be something like:
var schema = mongoose.Schema({
  name: String,
  siteID: Number,
  address1: String,
  address2: String
  loc: { type: [Number], index: '2dsphere' }
  date: Date,
  volume: Number,
  cost:  Number,
  label: String
});

This means you're going to have some duplication of data (name, address1, etc), but I think it's worth it if you're manipulating the dataSchema portion more than you are the locSchema. It's now much simpler to add/remove/update data. You can use mongo aggregation to group and structure the data however you would like.


text:
Q: Python inserting to list vs dict I've written code that simply reads from a database and save the results to a collection in python
I've first written in so that it was the items were stored in a dictionary, but later I realized the indexes were just incremental, so I changed it to a list.
However after that the speed of the program dramatically dropped. I first thought something was wrong with the MySQL database but turns out after I changed the collection to a dict, it came back to normal.
Code was something like:
cursor = db.cursor(pymysql.cursors.SSDictCursor)
cursor.execute('SELECT * FROM db')
coll = []  # or coll = {}
for i in cursor:
    coll.append(i)  # or coll[len(coll)] = i

I compared coll.append() and coll[len(coll)] = i separately and those line themselves seem to not differ that much (append was slower but not enough to cause the dramatic slowing down, which in a different orders of magnitude)
I thought the ordering might cause some issues, when I used an OrderedDict, the speed didn't seem to be affected.
I was wondering if it could be based on how lists and dictionaries are implemented (maybe lists has to be saved in continuous memory, thus requiring frequent reallocation of memory while dictionaries doesn't have to be continuous), but I wanted to know why this was really happening
Edit:
Here is the actual code I am running, in the case that the simplified code is missing something relevant:
with closing(cdr_db.cursor(pymysql.cursors.SSDictCursor)) as cdr_cursor:
    cdr_cursor.execute(query.format(TABLE_NAME))

    nID_to_num = {}  # []
    num_to_nID = {}
    g = snap.TNGraph.New()

    for call in cdr_cursor:
        from_num = call['from_num']
        to_num = call['to_num']

        if from_num == 0 or to_num == 0:
            continue

        if from_num not in num_to_nID:
            curr_index = len(nID_to_num)
            g.AddNode(curr_index)
            num_to_nID[from_num] = curr_index
            nID_to_num[curr_index] = from_num  # nID_to_num.append(from_num)
        if to_num not in num_to_nID:
            curr_index = len(nID_to_num)
            g.AddNode(curr_index)
            num_to_nID[to_num] = curr_index
            nID_to_num[curr_index] = to_num  # nID_to_num.append(to_num)

        g.AddEdge(num_to_nID[from_num], num_to_nID[to_num])

This is ran in Python 2.7 64bit in Windows 7.

A: Update after new code posted and more back and forth between Mark and Antti:
I believe the reason why your original test case didn't show the problem is that, in your original test case, you only showed using len() for the dict case, where in your full example, you always use len().
After playing around with timing some more, I found that if I modify the list example below to match your full example more closely, e.g. coll.append(len(coll)) -- because you are calculating len() in both cases, then the dict case is faster.  Your original small example was incorrectly attributing the cost of len() to the dict version, even though len() is called for both versions.
However, (assuming that you are executing this code in a function, and not at script level where all lookups are costly), I found that I could recover that time and make lists faster than dicts again by predefining a = coll.append outside the loop and using that instead.
If this is the issue that you are seeing and it is that time-critical, then you will probably want to move some other lookups outside of your loop, such as the ones for len and g.AddNode.
** Original answer below **
I cannot verify your claim that dicts are faster than lists in this use-case, so perhaps you changed something else.  You didn't specify a version, so I mostly used Python 2, but used 3 to determine it was comparable in some instances.  Here is the code:
def usedict(times, size):
    cursor = list(range(size))
    for iteration in range(times):
        coll = {}
        for i in cursor:
            coll[len(coll)] = i

def uselist(times, size):
    cursor = list(range(size))
    for iteration in range(times):
        coll = []
        for i in cursor:
            coll.append(i)

And here are some results:
$ python -m timeit "import listdict;listdict.uselist(10, 100000)"
10 loops, best of 3: 49.7 msec per loop
$ python -m timeit "import listdict;listdict.usedict(10, 100000)"
10 loops, best of 3: 103 msec per loop
$ python3 -m timeit "import listdict;listdict.uselist(10, 100000)"
10 loops, best of 3: 65.9 msec per loop
$ python3 -m timeit "import listdict;listdict.usedict(10, 100000)"
10 loops, best of 3: 131 msec per loop
$ python -m timeit "import listdict;listdict.uselist(1, 10000000)"
10 loops, best of 3: 666 msec per loop
$ python -m timeit "import listdict;listdict.usedict(1, 10000000)"
10 loops, best of 3: 3.66 sec per loop
$ python -m timeit "import listdict;listdict.uselist(100000, 10)"
10 loops, best of 3: 69.6 msec per loop
$ python -m timeit "import listdict;listdict.usedict(100000, 10)"
10 loops, best of 3: 82.1 msec per loop
$ python -m timeit "import listdict;listdict.uselist(100000, 4)"
10 loops, best of 3: 29.4 msec per loop
$ python -m timeit "import listdict;listdict.usedict(100000, 4)"
10 loops, best of 3: 34.4 msec per loop
$ python -m timeit "import listdict;listdict.uselist(1000000, 1)"
10 loops, best of 3: 151 msec per loop
$ python -m timeit "import listdict;listdict.usedict(1000000, 1)"
10 loops, best of 3: 148 msec per loop
$ python3 -m timeit "import listdict;listdict.uselist(1000000, 1)"
10 loops, best of 3: 177 msec per loop
$ python3 -m timeit "import listdict;listdict.usedict(1000000, 1)"
10 loops, best of 3: 213 msec per loop
$ python -m timeit "import listdict;listdict.uselist(1000000, 3)"
10 loops, best of 3: 245 msec per loop
$ python -m timeit "import listdict;listdict.usedict(1000000, 3)"
10 loops, best of 3: 272 msec per loop

For larger containers, lists were a clear winner -- 5 times faster with 10e6 items.  The only place where dicts came out ahead was Python 2.7 with a single entry per container, and that was by a trivial amount.
This was on a 32 bit Ubuntu 14.04 system.


text:
Q: Python: List with [< >, <>...] I'm using PySVN to get diff between 2 links, and the function I'm using returns a list with '<>':
[<PysvnDiffSummary u'sdk_include/EthernetScannerSDK.h'>, <PysvnDiffSummary u'sdk_include/EthernetScannerSDKDefine.h'>, <PysvnDiffSummary u'sdk_include/CMakeLists.txt'>]

What exactly is this type of data? And how can I acces only the part after " ' "? (E.G. from < PysvnDiffSummary u'sdk_include/EthernetScannerSDK.h' > I only want sdk_include/EthernetScannerSDK.h, without using .split(' \' ') if possible.

A: It's a representation of PySvnDiffSummary object. Try using dir(Object) to get it's attributes and from there. It's probably going to be something like object.url
so when you find out what the attribute is (from comments elsewhere, it's __name), you'll want something like:
urls = [sumary.__name for summary in list]

Working list with just what you want :)


text:
Q: Is there is any relationship between determinant and spectral radius of the matrix? We all know that determinant is the product of the eigen values of a matrix. I have found some general term for the determinant of the adjacency matrices from some series of graphs. Can i establish some relation between the determinant and spectral radius of those graphs?

A: Gutman defined the energy of a graph $G$ as the sum of the absolute values of its eigenvalues
$$
E(G) = \sum_{\lambda \in \sigma(A)} |\lambda|.
$$
If we order the eigenvalues of the adjacency matrix in non-decreasing order $\lambda_1 \leq \lambda_2 \leq \cdots \leq \lambda_n$, the square of the energy satisfies
$$
   E(G)^2 = \sum_{i=1}^n |\lambda_i|^2
          + \sum_{i \neq j} |\lambda_i||\lambda_j|.
$$
It's well-known that $\sum_{i=1}^n |\lambda_i|^2$ is twice the number of graph edges, hereafter denoted $2m$. We can use the arithmetic-geometric mean inequality to change the second summation to a product of $n(n-1)$ terms,
$$
   E(G)^2 \geq 2m + n(n-1)\left(\prod_{i \neq j} |\lambda_i| |\lambda_j|\right)^{1/(n(n-1))}.
$$
This product is bounded below by $|\det(A)|^{2/n}$ and the energy satisfies
$$
   E(G) \geq \sqrt{2m + n(n-1) |\det(A)|^{2/n}}.
$$
The largest eigenvalue of the adjacency matrix is always positive, so we can rewrite the above as
$$
   \lambda_n \geq \sqrt{2m + n(n-1) |\det(A)|^{2/n}}
             - \sum_{i=1}^{n-1} |\lambda_i|.
$$
This is the strongest relationship that I know of between the determinant and spectral radius of an adjacency matrix.


text:
Q: jQuery infinite scroll ignore browser bounce up I have this function that is loading 5 items at time based on the page number.  But what's happening is that when the user scrolls to the bottom of the page, the $.post function fires once, and then again when the browser bounce finishes, because position_bot == $(document).height() is actually true twice.  Then 10 items are loaded each time.
I'm trying to find a way to ignore the browser bounce situation so the call only fires once.
Any suggestions or help would be great.
$(function(){
    $('#loading').show();
    var page = 1,
        total_brands = '<?php echo $brandsCount?>',
        post_link = '<?php echo $brandsUrl?>',
        post_data = {page_num: page};

    $.post(post_link, post_data, function(data){
        $('.brandsResult').append(data);
        $('#loading').hide();
    });

    $(window).scroll(function (e) {

        var position_bot = $(window).scrollTop() + $(window).height(),
            displayed_brands = $('ul.category-list > li').length;

        // Show loading image if near bottom
        if(position_bot > $(document).height() - 120 && displayed_brands < total_brands) {
            $('#loading').show();
        }

        // If page is at the bottom
        if(position_bot == $(document).height()) {

            // Increase page number
            page++;
            post_data = { page_num: page };
            console.log('page', page);

            // Check if all items are displayed
            if((page-1) * 5 > total_brands){
                $('#loading').hide();
            } else {
            // Firing twice ???
                $.post(post_link, post_data, function(data){
                    $('#loading').hide();
                    $('.brandsResult').append(data);
                });

            }

        }
    });
});

A: I would set a boolean to control loading state and tell the code not to do anything if true...
    var processing = false;

if(position_bot == $(document).height() && !processing) {

    if((page-1) * 5 > total_brands){
       $('#loading').hide();
       processing = false;
    } else {
       processing = true;
       $.post(post_link, post_data, function(data){
           $('#loading').hide();
           $('.brandsResult').append(data);
           processing = false;
       });

    }
}

I believe this is happening cause $('#loading').show() is pushing the screen, acting as a change in height, which is not enough to push beyond the boundaries of your conditional. A simple boolean would (or could) prevent this. It may require some adjustments and this is just a basic and totally untested example.


text:
Q: MouseEnterUp' is not valid. 'MouseEnter' is not an event on 'System.Windows.Trigger' I've got WPF window(WPF browser app) with 3 rectangles. I want to set trigger on one of the rectangles. But When I write in XAML
 <Rectangle Height="17" HorizontalAlignment="Left" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="278" >
        <Rectangle.Triggers>
            <Trigger Mouse.MouseEnter="MouseEnterUp"/>
        </Rectangle.Triggers>
    </Rectangle>

and define MouseEnterUp as
    public void MouseEnterUp(object sender, MouseEventArgs e)
    {
        Window2 x = new Window2();
        x.Show();
    }

I've got such error
'MouseEnterUp' is not valid. 'MouseEnter' is not an event on 'System.Windows.Trigger'.
What's wrong?

A: That's not how Triggers work... but anyway, you don't need a trigger for this:
<Rectangle Height="17" HorizontalAlignment="Left" Name="rectangle1" Stroke="Black"
        VerticalAlignment="Top" Width="278"
        Mouse.MouseEnter="MouseEnterUp">
</Rectangle>


text:
Q: A simple osmosis problem The following is adapted from a problematic question* asked on the Bio site. I would like to ask it free of those distractions here. If there is anything unduly artificial about the problem please advise and I'll try to revise the question. I think it belongs to physics at least as much as to chemistry.
Question: A bag whose walls form a semi-permeable membrane contains a mixture of 5% of solute A and 10% of solute B (both in water). The membrane allows passage of B particles but not A particles.
The bag is lowered into a solution containing a 10% solution of solute B. Instead of asking a multiple choice question let me keep it open-ended. What would we expect in terms of the movement of water/solutes in this situation? Can we predict, in rough terms, a final equilibrium state?
Thanks for any clarification!
*The problem is that one of the solutes was poorly chosen.

A:
What would we expect in terms of the movement of water/solutes in this situation? Can we predict, in rough terms, a final equilibrium state?

Some amount of particles B will exit the bag, so as to equalized the osmotic pressure on both sides of the membrane.
The final state will be $<10$% B inside the bag and $>10$% B outside the bag.
The question does not specify whether the percentages are weight percent or something else.  Without knowing more information such as molecular weight or molarity one can not make a quantitative determination of the final state.
Also, the question doesn't explicitly state that water can pass through the membrane, although such is usually the case.  Water would initially enter the bag stretching the bag and raising the hydraulic pressure inside the bag.  If the bag is elastic and not permanently deformed, extra water will eventually leave the bag, as osmotic pressure balances by B exiting the bag.


text:
Q: Can't rewrite php url using htaccess This will be a niche question but I am having trouble rewriting my url.
I am trying to rewrite from /view.php?user=Alex0111 to view/Alex0111. I also have a second get variable of /view.php?user=Alex0111&id=5 which I want to be view/Alex0111/5
Here are the contents of my .htaccess file
DirectoryIndex Home.php

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^view/([0-9A-Za-z]+) view.php?user=$1 [NC,L] #doesn't work causes internal error

I've checked this line of code multiple times to the tutorial I am following but I am missing the mark on something.

A: Replace both of your rewrite rules with:
RewriteRule ^view/(.+)/(.+)  view.php?user=$1&id=$2  [NC,END,QSA]

Your first rewrite rule will interfere because it will rewrite the path as Markus mentioned in comments.
The [END] flag will throw an error if you have an old Apache version. In that case, use the [L]
The [QSA] flag tells the server to add any additional query parameters that the user sent. eg: view/Alex01/5?param=value


text:
Q: UnwantedTokenException(found=., expected 80) JPA on Spring Web Project I m seeing this error when I used my readAll method on myService .What can be problem is onyone see this error before I couldn't find any usefull information about it after a wide googling here is my codes
NewsDAO
public interface NewsDAO extends GenericDAO<News, Serializable> {
  }

NewsDAOImpl
public class NewsDAOImpl extends GenericJPADAOImpl<News, Serializable> implements NewsDAO {

}
News
@Entity
@Table(name = "News")
public class News implements Serializable {...blah blah}

The problem appear when I use this method (its a method from my service level)
  @Override
public List<Article> articleList() {
    return articleDAO.readAll();
}

There is no connection error I m using mysql on a spring project  .Any advice will be great
Thanks
UnwantedTokenException(found=., expected 80) at  org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:587)
at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.rangeVariableDeclaration(JPQLParser.java:2249)
at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.identificationVariableDeclaration(JPQLParser.java:2162)
at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.fromClause(JPQLParser.java:2043)
at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.selectStatement(JPQLParser.java:364)
at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.document(JPQLParser.java:281)
at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.parse(JPQLParser.java:134)
at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.buildParseTree(JPQLParser.java:95)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:215)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:190)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:142)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:126)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1475)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at $Proxy42.createQuery(Unknown Source)
at com.dcat.dao.impl.GenericJPADAOImpl.readAll(GenericJPADAOImpl.java:38)
at com.dcat.ipp.service.impl.AdminServiceImpl.getNewsList(AdminServiceImpl.java:348)
at com.dcat.ipp.service.impl.AdminServiceImpl.getNewsListAsSpot(AdminServiceImpl.java:354)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy48.getNewsListAsSpot(Unknown Source)
at com.dcat.ipp.controller.HomeController.getNewsSpotList(HomeController.java:144)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

A: In my case, I was using em.createQuery and a native query with it.
EntityManager em = getEntityManager();
Query query = em.createQuery("SELECT a From Product")

It got solved -  when I used Native query,
EntityManager em = getEntityManager();
Query query = em.createNativeQuery("SELECT * from tbl_product")


text:
Q: How can I get `\texttt` in `\href` to work with Springer Nature's sn-jnl class? Using version 2019/11/18 of Springer's sn-jnl.cls template (archived as a gist here), I get the following:
\documentclass{sn-jnl}
\usepackage{xparse}
\NewDocumentCommand{\githublink}{m m o}{\href{}{\texttt{}}}
\begin{document}
. \githublink{}{}[]                                                                                \end{document}

! Argument of \XKV@d@fine@k@y has an extra }.
<inserted text>
                \par
l.5 . \githublink{}{}[]

What's going on here, and how do I fix this?
EDIT
This can be further minimized to
\documentclass{article}
\RequirePackage{hyperref}%
%%\RequirePackage{hypcap}%
\gdef\breakurldefns{%
%\if@pdflatex\else%
  \RequirePackage[hyphenbreaks]{breakurl}%
  \let\href\burlalt%
  %\fi
}%
\breakurldefns%
%    \bgroup
\usepackage{hyperref}
\begin{document}
. \href{}{\texttt{}}
\end{document}

A: If you try
\documentclass{article}
\usepackage{hyperref}
\usepackage[hyphenbreaks]{breakurl}
\begin{document}

. \burlalt{aaaa}{bbb}
\end{document}

You get

so the first argument is typeset, you can use font changes there. The second argument is the URL

A: The breakurl package shouldn't be used with pdflatex, but to avoid that it is loaded you must load the class with the option pdflatex as the class is a bit dump and doesn't make use of existing methods to detect the output mode automatically.
\documentclass[pdflatex]{sn-jnl}
\begin{document}

\href{abc}{\texttt{abc}}
\end{document}


text:
Q: Not able to find Snackbar of Android app in Appium automation I have a ToDo Android app which shows a Snackbar whenever a new ToDo is saved. In my automation test I am not able to capture the Snackbar so I tried with following xpath driver.findElementByXPath("//*[@text='TO-DO saved']").isDisplayed() and also tried driver.findElementByAndroidUIAutomator("new UiSelector().text(\"TO-DO saved\")").isDisplayed() but didn't get success.
Can anybody help me to get the Android Snackbar element in appium?

A: I've noticed that it happens only when the Snackbar contains action button, when it doesn't, Appium finds it very fast.
I still didn't find any solution.

A: Snackbar is element that appears only in certain condition and often for a short period of time.
You can try catching it with FluentWait:
FluentWait<WebDriver> wait = new WebDriverWait(driver, 10).ignoring(NoSuchElementException.class);
wait.until(visibilityOfElementLocated(By.xpath("//*[@text='TO-DO saved']")));

Default polling period is 500 milliseconds, should be enough in most cases.
Still think its better to replace xpath locator with id, probably you have to add resource-id for snackbar if its not in place.


text:
Q: outlook 2010 autocomplete disabled Autocomplete for e-mail addresses is not working in my Outlook 2010. The Microsoft help for turning on autocomplete does not include the scenario where it's disabled.

I've tried toggling the other checkboxes that I can still use and Emptying the Auto-Complete list. But it doesn't help and there's no tooltip on why the checkbox is disabled.
Edit: I tried these forum suggestions, including making the registry entry with value 1.


text: Q: WPF Microsoft Blend missing project user control I don't know what am doing wrong but in any way that I have tried: Cleaning Solution then Rebuilding and restarting program none of those seems to do anything. Am looking for News.xaml to appear in assets window. Screenshots below:


text:
Q: Loop repeated do statement with mouse left button variable click & hold Hey, currently testing a autoclicker for a few games, I am quite new to C++
How can I use left mouse button to run a do statement for the mouse click function without it stopping the do statement
I've tried different flags including :
input.mi.dwFlags = (MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP);

with mouse_event(MOUSEEVENTF)
do {
    if (GetAsyncKeyState(VK_LBUTTON) & 0x80000000) {
        enabled = true;

        while (GetAsyncKeyState(VK_LBUTTON) & 0x80000000) {
            Sleep(1000 / cps);
            INPUT input;
            input.type = INPUT_MOUSE;
            input.mi.dx = 0;
            input.mi.dy = 0;
            input.mi.dwFlags = (MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP);
            input.mi.mouseData = 0;
            input.mi.dwExtraInfo = NULL;
            input.mi.time = 0;
            SendInput(1, &input, sizeof(INPUT));

        }
    }

} while (true);

I am trying to make it so when you hold down left click, it runs the while statement containing the autoclicking function, without stopping the while statement due to repetitive clicking.

A: There is something you should notice in your code:
First, How to judge the return value of GetAsyncKeyState()

If the function succeeds, the return value specifies whether the key
  was pressed since the last call to GetAsyncKeyState, and whether the
  key is currently up or down. If the most significant bit is set, the
  key is down, and if the least significant bit is set, the key was
  pressed after the previous call to GetAsyncKeyState. However, you
  should not rely on this last behavior; for more information, see the
  Remarks.

the type of return value is SHORT which is 2 bytes. So try GetAsyncKeyState(VK_LBUTTON) & 0x8000 instead.
Second, How to use SendInput() to send different mouse state.
You should create a new INPUT data to save different action, but not just combine all of them.
Code Sample:
do {
        if (GetAsyncKeyState(VK_LBUTTON) & 0x8000)
        {
            enabled = true;
            while (GetAsyncKeyState(VK_LBUTTON) & 0x8000)
            {
                INPUT input[2];
                input[0].type = input[1].type = INPUT_MOUSE;
                input[0].mi.dx = 0;
                input[0].mi.dy = 0;
                input[0].mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN;
                input[1].mi.dx = 0;
                input[1].mi.dy = 0;
                input[1].mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTUP;
                SendInput(2, input, sizeof(INPUT) * 2);
            }
        }

    } while (true);


text:
Q: Which AmqpEvent or AmqpException to handle when an exclusive consumer fails I have two instances of the same application, running in different virtual machines. I want to grant exclusive access to a queue for the consumer of one of them, while invalidating the local cache that is used by the consumer on the other.
Now, I have figured out that I need to handle ListenerContainerConsumerFailedEvent but I am guessing that implementing an ApplicationListener for this event is not going to ensure that I am receiving this event because of an exclusive consumer exception. I might want to check the Throwable of the event, or event further checks.
Which subclass of AmqpException or what further checks should I perform to ensure that the exception is received due to exclusive consumer access?

A: The logic in the listener container implementations is like this:
if (e.getCause() instanceof ShutdownSignalException
            && e.getCause().getMessage().contains("in exclusive use")) {
        getExclusiveConsumerExceptionLogger().log(logger,
                "Exclusive consumer failure", e.getCause());
        publishConsumerFailedEvent("Consumer raised exception, attempting restart", false, e);
    }

So, we indeed raise a ListenerContainerConsumerFailedEvent event and you can trace the cause message like we do in the framework, but on the other hand you can just inject your own ConditionalExceptionLogger:
/**
 * Set a {@link ConditionalExceptionLogger} for logging exclusive consumer failures. The
 * default is to log such failures at WARN level.
 * @param exclusiveConsumerExceptionLogger the conditional exception logger.
 * @since 1.5
 */
public void setExclusiveConsumerExceptionLogger(ConditionalExceptionLogger exclusiveConsumerExceptionLogger) {

and catch such an exclusive situation over there.
Also you can consider to use RabbitUtils.isExclusiveUseChannelClose(cause) in your code:
/**
 * Return true if the {@link ShutdownSignalException} reason is AMQP.Channel.Close
 * and the operation that failed was basicConsumer and the failure text contains
 * "exclusive".
 * @param sig the exception.
 * @return true if the declaration failed because of an exclusive queue.
 */
public static boolean isExclusiveUseChannelClose(ShutdownSignalException sig) {


text:
Q: Springboot query MongoDb Atlas search index I have a MongoDb that has a collection of cars which includes fields like:
price: "49,500"
brand: "Mercedes-benz",
model: "E 400d"
power: "340 PS"
engine: "2995 cmc"
etc.

On my Springboot backend I want to create and endpoint which will return search suggestions based on the user input.
For example if the user searches for:
"mer", "Mer", "Mercedes", "Mercedes benz","Nercedes"(fuzzy search N instead of M), "benz", "E400"(without spaces and missing d), "E 400"(missing d), "400d"(missing E), "E400 d" (missplaced whitespace), "E400d"( no whitespaces) and other similar use cases I want to return to the user the correct results.
My current index:
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "brand": {
        "maxGrams": 20,
        "tokenization": "edgeGram",
        "type": "autocomplete"
      },
      "model": {
        "maxGrams": 20,
        "tokenization": "edgeGram",
        "type": "autocomplete"
      },
      "power": {
        "maxGrams": 20,
        "tokenization": "edgeGram",
        "type": "autocomplete"
      }
    }
  }
}

Example java query:
val collection = mongoTemplate.getCollection("cars")
    val agg = Document(
            "\$search", Document(
            "autocomplete", Document("query", searchInput)
            .append("path", "brand")
            .append("fuzzy", Document("maxEdits", 1))
    )
 )

    collection.aggregate(
            listOf(
                    agg,
                    limit(20),
                    project(fields(include("brand", "model", "power")))
            )
    )


text:
Q: Use @Timed for inheritanced functions We use a abstract classes for services like this pseudocode
abstract class AbstractApiService {
    @Timed(value="get", useClassPrefix=true)
    def get(Long id) {
       ... returns sth ....
    }

    @Timed(value="create", useClassPrefix=true)
    def create(Map params) {
        ... returns sth ....
    }
}

There are beans which inherit AbstractApiService and serve features like creating, deleting, updating entities like
class UserAccountService extends AbstractApiService {
    ... code ....
}

I would like to get metrics for each call a function from child classes like UserAccountService, but Prometheus sends events with full parent class prefix.
App is based on Grails 3.3.8
build.gradle:
compile 'com.moelholm:prometheus-spring-boot-starter:1.0.2'
compile 'io.dropwizard.metrics:metrics-core:4.0.0-alpha2'
compile 'io.dropwizard.metrics:metrics-jvm:4.0.0-alpha2'
compile 'org.grails.plugins:dropwizard-metrics:1.0.0.M2'

A: Unfortunately, I believe you will have to define the @Timed annotation for each method you want tracked.  I don't think that the annotation code will spin up a separate metric for each concrete class.

A: I created a custom manual solution
https://gist.github.com/michmzr/1e03534bc5fb6df89065f6964acf9c71


text:
Q: Bootstrap working via link, but not when downloaded I am trying to do some website by using Bootstrap and Spring Boot.
When I put web location of bootstrap.min.css in href, it is working perfectly.
Code:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

But when I download the same library and put it in a folder, Bootstrap is not recognized at my website.
Code:
<link rel="stylesheet" href="/static/bootstrap-4.5.2-dist/css/bootstrap.min.css">

Can someone explain me how to fix this problem?

A: I manage to figure this out. Despite the fact that location of file is in static, Spring boot recognizes automatically that it is in static, so it is enough to write href="/bootstrap-4.5.2-dist/css/bootstrap.min.css".


text:
Q: is there any easy way to drag and drop cells from table to table? I need to pick random cells from one table to another by drag and drop , is there any library to do this?? using javascript and php.
And i need to save the cell id in database for future use.

A: Ya you can do it with jqueryesay ui
see this example
http://www.jeasyui.com/tutorial/dd/dnd3.php.
To save the cell id , you can use array push and store it to database.


text:
Q: pcmanfm doesn't send files to trash on external drive I have a HDD which I mount on /mnt/sda1 at startup (in /etc/fstab)
Whenever I want to send a file to the trash in pcmanfm, I get the following message :

Some files cannot be moved to trash can because the underlying file
  systems don't support this operation. Do you want to delete them
  instead?

The owner of /mnt/sda1 and /mnt/sda1/.Trash-1000 is user 1000 (me), and I have read write permissions.
When deleting a file in the CLI using gvfs-trash or gio trash it correctly sends the file to /mnt/sda1/.Trash-1000, and pcmanfm sees the file in the Trash and can even restore it. Still it cannot delete it.
Any clues ?

A: This is a bit late, but I ran into the same issue. As it turns out, you have to disable the 'Erase files on removable media instead of "trash can" creation' preference. Apparently PCManFM sees any drives with an unmount button as removable media. Once that's done, sending files to trash works as expected.


text:
Q: android eclipse graphical layout bugs...do i have to restart Sometimes eclipse has problems with the graphical android layout such as not displaying the design or not displaying background images and other problems that don't disappear except when u restart eclipse.
The question is : do i have to restart eclipse every time when when i face these problems or is there an alternative way, because restarting eclipse has become very annoying for me and wastes a lot of my time.
Isn't there a way to some how refresh the layout or something?

A: Its hard to know what the exact problems you are having but it sounds like you may be able to clean your project to fix this when you have these problems

Project --> Clean... --> Choose your project

Sometime Eclipse doesn't recognize your changes right away and is still working with the last build so you need to clean and rebuild to get rid of weird errors or layout issues


text:
Q: Integral of Exponential raised by exponential: $\int_{-\infty}^{\infty}\mathrm{d}x(1-\exp[\frac{-b}{\sqrt{2\pi}a}\exp(-\frac{x^2}{2a^2})]).$ I am interested in the following integral

$$\int_{-\infty}^{\infty}\mathrm{d}x\left(1-\exp\left[\frac{-b}{\sqrt{2\pi}a}\exp\left(-\frac{x^2}{2a^2}\right)\right]\right).$$

Does anyone know how to solve this integral?

A: Using the identity $1-e^{-z}=\sum_{n\geq 1}\left(-1\right)^{n-1}\frac{z^n}{n!}$, the desired integral is $\sum_{n\geq 1}\frac{I_n}{n!}$ with $$I_n:=\int_{-\infty}^{\infty}\text{d}x\exp\left[\frac{b^n}{a^n\sqrt{2\pi}^n}\exp\left(-\frac{nx^2}{2a^2}\right)\right]=\frac{b^n}{a^n\sqrt{2\pi}^n}\sqrt{\frac{2\pi a^2}{n}}.$$Define $C:=\sqrt{2\pi a^2},\,q:=\frac{b}{a\sqrt{2\pi}}$, so the desired integral is $$C\sum_{n\geq 1}\left(-1\right)^{n-1}\frac{q^n}{n!\sqrt{n}}.$$I'm not aware of any closed-form expression for this, but it clearly converges.


text:
Q: Maximum of the Vandermonde determinant / minimum of the logarithmic energy The problem is to find the asymptotics (as $n\to\infty$) of the maximum (say $M_n$) of the Vandermonde determinant
$$V_n:=\prod_{0\le i<j\le n-1}(a_j-a_i)
$$
over all $a_0,\dots,a_{n-1}$ such that $0=a_0<\dots<a_{n-1}=1$ (or, better, an upper bound on $M_n$ which is asymptotic to $M_n$; or, at least, the asymptotics of $\ln M_n$). It is clear that the maximum is attained.
These questions can be obviously restated in terms of the minimization of the logarithmic energy
$$\sum_{0\le i<j\le n-1}\ln\frac1{a_j-a_i}.
$$
I have encountered this problem working on a matter involving higher-order divided differences. It is known that the $n$-tuple $(a_0,\dots,a_{n-1})$ maximizing $V_n$ is given by the formula $a_i=(1+x_i)/2$, where the $x_i$'s are the roots of the polynomial $(1-x^2)P'_{n-1}(x)$ (taken in the ascending order) and $P_{n-1}$ is the Legendre polynomial of degree $n-1$; these points $x_0,\dots,x_{n-1}$ are also known as the Fekete points; see e.g. SE Mathematics. The picture below suggests that $\ln M_n\sim-(a+bn)^2$ as $n\to\infty$, for some real constants $a<0$ and $b>0$.

A: Since you know already that the optimal $a_i$ have
$2a_i + 1 = x_i = \pm 1$ and the roots of $P'_{n-1}$,
the calculation of $V_n$ comes down to the discriminant of $P'_{n-1}$,
its leading coefficient, and its values at $\pm 1$, all of which are
available in closed form via formulas for
Jacobia
polynomials (since $P'_{n-1}$ is a multiple of $P^{(1,1)}_{n-2}$).
For the asymptotic growth of $\log M_n$, as ofer zeitouni suggests
it is enough to find the maximum of the logarithmic energy
$\int\!\!\int \log|x-y| \, d\mu(dx) \, d\mu(dy)$ over probability measures
supported on $[0,1]$, and it is known that the optimal $\mu$ is
the measure $\pi^{-1} dx/\sqrt{x-x^2}$ obtained from the uniform measure
$d\theta$ on ${\bf R} / \pi{\bf Z}$ via $x = \cos^2 \theta$.
The leading term is $\log M_n \sim -b n^2$ with $b=\log 2$, because the
optimal measure on an interval of length $4$ has logarithmic energy zero
so the average of the $n \choose 2$ terms for $(0,1)$ approaches $-\log 4$.

A: I am amazed that nobody noticed that Iosif asks for the calculation of the transfinite diameter of the interval $[0,1]$. This notion applies to arbitrary compact domains $K$ in ${\mathbb R}^n$ :
$$d(K)=\lim_{k\rightarrow+\infty}\sup_{x_1,\ldots,x_k\in K}\left(\prod_{\alpha<\beta}|x_\alpha-x_\beta|\right)^{2/k(k-1)}.$$
In the particular case where $K\subset{\mathbb C}$ is simply connected, then the inverse of $d(K)$ is the conformal radius of ${\mathbb C}\setminus K$.

A: I would like to provide some details on the answers by ofer zeitouni and Noam D. Elkies.
By Selberg's formula, as presented in the answer by ofer zeitouni, one easily finds
$$(1)\qquad M_n=\lim_{\beta\to\infty} A(n,\beta)^{1/(2\beta)}=
\prod _{j=0}^{n-1} \frac{j^j (j+1)^{(j+1)/2}}{(j+n-1)^{(j+n-1)/2}}
$$
(with $0^0:=1$), which follows immediately from the observation that for any real $a$ and any real $c>0$
$$\Gamma(a+c\beta)^{1/(2\beta)}\sim(c\beta/e)^{c/2}
$$
as $\beta\to\infty$.
I asked for an upper bound on $M_n$, which would be asymptotic to $M_n$, thinking that an explicit expression for $M_n$ would not be possible. However, as is now clear from the answers by ofer zeitouni and Noam D. Elkies, such an expression is not so hard to obtain, and formula (1) presents this expression.
On the other hand, the relation between the logarithmic energy
$E_{n,a}:=2\sum_{0\le i<j\le n-1}\ln(a_j-a_i)$ and its ostensibly more general version $n^2E_\mu$ with $E_\mu:=\int\ln|x-y|\mu(dx) \mu(dy)$
for probability measures $\mu$ supported on $[0,1]$ seems unclear, I guess because of the singularities on the diagonal. Namely, one would expect that
$$(2)\qquad 2\ln M_n=\max_{0=a_0<\dots<a_{n-1}=1}E_{n,a}
\le n^2 \max_\mu E_\mu.
$$
However, it is not clear if $2E_{n,a}=2\sum_{0\le i<j\le n-1}\ln(a_j-a_i)$ could be written as
$n^2E_\mu=n^2\int\ln|x-y|\mu(dx) \mu(dy)$
for some probability measure $\mu$ on $[0,1]$.
In fact, quite surprisingly to me, the inequality in (2) is false, at least for large enough $n$. Indeed, it is not hard to show based on formula (1) that for some real $c\in(0,\infty)$
$$(3)\qquad M_n=(c+o(1))m_n,\quad\text{where}\quad m_n:=2^{-n^2} \sqrt{(n-1)!}\,(8e)^{n/2} n^{3/8}
$$
$$(4)\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad >>2^{-n^2}=\text{(?)}=\exp\Big\{\frac{n^2}2\,\max_\mu E_\mu\Big\}.
$$
The asymptotics $M_n=(c+o(1))m_n$ follows because
$$\ln\frac{M_{n+1}}{M_n}
=-n \ln2+\frac{n-1}{2}\,\ln (n-1)+\frac{n+1}{2}\,\ln (n+1)-\frac{2n-1}{2}\,\ln(2 n-1)$$
   $$=d_n+O(1/n^2)$$
for large $n$, where
$d_n:=\frac{3}{8 n}-2n\ln2+\frac{1}{2}\ln n+\frac12(1+\ln2)$.
A curious corollary to (3)--(4) is that for each large enough natural $n$ there is some $a=(a_0,\dots,a_{n-1})$ with $0=a_0<\dots<a_{n-1}=1$ such that $2E_{n,a}$ cannot be approximated by (let alone written as) $n^2E_{\mu_k}$ for any sequence $(\mu_k)$ of probability measures on $[0,1]$.
Yet, it also follows from (3)--(4) that the logarithmic asymptotics $\ln M_n\sim\frac{n^2}2 \max_\mu E_\mu$ holds.
One can also see that $\ln(M_{n+1}/M_n)<d_n$ for $n\ge4$, and hence for each $k\ge4$ and all $n>k$ one has the upper bound $M_k\exp\sum_{j=k}^{n-1}d_j$ on $M_n$, which is asymptotic to $M_n$ as $n>k\to\infty$. In particular, for $n\ge4$ one has
$M_n<\tilde c_4 m_n$, where $m_n$ is as before and
$\tilde c_4:=\frac{512}{25} \sqrt{\frac{2}{15}} e^{(6 \gamma -43)/16}=0.631\dots$ and $\gamma$ is the Euler constant.

A: Write $V(a)$ for the determinant $\prod_{0\leq i<j\leq n-1} |a_i-a_j|$. Selberg's formula tells you that
$$\int_0^1 \cdots \int_0^1 V(a)^{2\beta} \prod_{i=0}^{n-1} da_i=
n! \prod_{j=0}^{n-1} \frac{(\Gamma(1+j\beta))^2 \cdot \Gamma((j+1)\beta)}
{\Gamma(2+(n+j-1)\beta)\cdot \Gamma(\beta)}=:A(n,\beta)$$
Thus the asymptotics you seek are given by $\lim_{\beta\to\infty} A(n,\beta)^{1/2\beta}$,
which can be read from known asymptotics for the Gamma function. I did not try to perform the actual computation.
Remark: The constant $-2b^2$ is the maximum  of the logarithmic energy
$$\int \log |x-y| \mu(dx) \mu(dy) $$
over all probability measures supported on $[0,1]$. I am sure that this
maximizer has been computed somewhere; Maybe it appears in Saff and Totik's book, which I do not have access to at the moment.


text:
Q: Proving $\lim x^n = a^n$ as $x$ goes to $a$ from definition
Using the $\varepsilon-\delta$ definition show that
  $\displaystyle \lim_{x \to a} x^n = a^n$

What I've done? Pretty much stuck on the step where one usually constructs delta:
$\displaystyle |x^n-a^n| < \varepsilon \implies \bigg|x-a\bigg|\bigg|\sum_{k=0}^{n-1}x^k a^{n-k-1}\bigg| <\varepsilon \implies |x-a| < \frac{\epsilon}{ \bigg| \displaystyle \sum_{k=0}^{n-1}x^k a^{n-k-1}\bigg|}$.
At this stage I cannot bound the denominator. Any suggestions are appreciated.

A: You want to have:
$$\delta < \frac{\epsilon}{\text{something}} < \frac{\epsilon}{|\sum_{k=0}^{n-1} x^k a^{n-k-1}|}$$
Then, $\text{something}$ must be greater than $|\sum x^k a^{n-k-1}|$. If we choose $\delta < 1$, then we would have for $|x - a| < \delta < 1$, $|x| < 1 + |a|$.
$$|\sum_{k=0}^{n-1} x^k a^{n-k-1}| \le \sum_{k=0}^{n-1}|x|^k |a|^{n-k-1} < \sum_{k=0}^{n-1} (1 + |a|)^k |a|^{n-k-1} < \sum_{k=0}^{n-1} (1+|a|)^k (1+|a|)^{n-k-1} \le \sum_{k=0}^{n-1} (1+|a|)^{n-1} = n(1 +|a|)^{n-1}$$
Thus, choosing:
$$\delta = \min\{1, \frac{\epsilon}{n(1+|a|)^{n-1}}\}$$
does the job.


text:
Q: Android : moving bmp leaving a trail ( Surface View and Canvas ) I was trying to animate a sprite for an android app and i've encounter a small problem. I'm drawing on a surfaceView that i add on top of already existing layouts. On this surfaceView, i wanted to animate few sprites so they would walk along a path.
So this is the result i'm facing right now :
The walking sprite is leaving a trail. So i decided to google this problem and apparently i had to clear the canvas first before drawing on it.
This was my onDraw method before :
public void onDraw(Canvas canvas) {
    update();
    int srcX = currentFrame * width;
    int srcY = directionX * height;
    Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
    Rect dst = new Rect(x, y, x + width, y + height);
    canvas.drawBitmap(bmp, src, dst, null);

}

And this was my onDraw method after
public void onDraw(Canvas canvas) {
    canvas.drawRGB(0, 0, 0);
    update();
    int srcX = currentFrame * width;
    int srcY = directionX * height;
    Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
    Rect dst = new Rect(x, y, x + width, y + height);
    canvas.drawBitmap(bmp, src, dst, null);

}

So i now have this as a result

which is great because it leaves no more trail BUT i cant see the layouts underneath. Is there anyway i can get the best of both world ? I thought clearing the canvas would work but it obviously doesnt not work as expected.
I'll post my code below
SurfaceView :
public class MonsterView extends SurfaceView {

private Bitmap monsterImg;
private SurfaceHolder holder;
private MonsterThread mainThread;
private Sprite monsterSprite;
private int x;
private int xSpeed = 1;

public MonsterView(Context context) {
    super(context);
    this.mainThread = new MonsterThread(this);
    this.x = 0;

    holder = getHolder();
    holder.setFormat(PixelFormat.TRANSPARENT);

    holder.addCallback(new SurfaceHolder.Callback() {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            mainThread.setRunning(true);
            mainThread.start();
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            boolean retry = true;
            mainThread.setRunning(false);
            while (retry) {
                try {
                    mainThread.join();
                    retry = false;
                } catch (InterruptedException e) {
                }
            }

        }
    });
    setZOrderOnTop(true);
    monsterImg = BitmapFactory.decodeResource(getResources(), R.drawable.fire);
    monsterSprite = new Sprite(this,monsterImg);
}

@Override
public void onDraw(Canvas canvas) {
    if (x == getWidth() - monsterImg.getWidth()) {
        xSpeed = -1;
    }
    if (x == 0) {
        xSpeed = 1;
    }
    x = x + xSpeed;
    monsterSprite.onDraw(canvas);
}

Thread :
public class MonsterThread extends Thread {
private MonsterView monsterSurface;
private boolean running;
static final long FPS = 35;

public MonsterThread(MonsterView monsterSurface){
    this.monsterSurface = monsterSurface;
    this.running = false;
}

@Override
public void run() {
    long ticksPS = 1000 / FPS;
    long startTime;
    long sleepTime;

    while(running){
        Canvas c = null;
        startTime = System.currentTimeMillis();
        try{
            c = monsterSurface.getHolder().lockCanvas();
            synchronized (monsterSurface.getHolder()){

                monsterSurface.onDraw(c);
            }
        } finally {
            if( c!= null){
                monsterSurface.getHolder().unlockCanvasAndPost(c);

            }
        }
        sleepTime = ticksPS-(System.currentTimeMillis() - startTime);
        try {
            if(sleepTime > 0)
                sleep(sleepTime);
            else
                sleep(10);
        } catch (Exception e){}
    }
}

public MonsterView getMonsterSurface() {
    return monsterSurface;
}

public void setMonsterSurface(MonsterView monsterSurface) {
    this.monsterSurface = monsterSurface;
}

public boolean isRunning() {
    return running;
}

public void setRunning(boolean running) {
    this.running = running;
}

Sprite :
public class Sprite {
private static final int BMP_ROWS = 4;
private static final int BMP_COLUMNS = 3;
private int x = 0;
private int y = 0;
private int xSpeed = 5;
private MonsterView monsterView;
private Bitmap bmp;
private int currentFrame = 0;
private int width;
private int height;

private int directionX;

public Sprite(MonsterView monsterView, Bitmap bmp) {
    this.monsterView = monsterView;
    this.bmp=bmp;
    this.width = bmp.getWidth() / BMP_COLUMNS;
    this.height = bmp.getHeight() / BMP_ROWS;
    this.directionX = 2;
}

private void update() {
    if (x > monsterView.getWidth() - width - xSpeed) {
        xSpeed = -5;
        directionX = 1;
    }
    if (x + xSpeed < 0) {
        xSpeed = 5;
        directionX = 2;
    }
    x = x + xSpeed;
    currentFrame = ++currentFrame % BMP_COLUMNS;
    Log.d("test", ""+currentFrame);
}

public void onDraw(Canvas canvas) {
    update();
    int srcX = currentFrame * width;
    int srcY = directionX * height;
    Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
    Rect dst = new Rect(x, y, x + width, y + height);
    canvas.drawBitmap(bmp, src, dst, null);

}

A: You're using setZOrderOnTop(), which is putting the Surface part of the SurfaceView on a layer above everything else.  (By default, it's a separate layer below everything else.)  When you clear it with canvas.drawRGB(0, 0, 0) you're setting the entire layer to opaque black, which is going to obscure the View layer beneath it.
If instead you clear it to transparent black, with canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR), you should get the results you want.
FWIW, you shouldn't override onDraw() if you're only drawing on the Surface.  The onDraw() method is called by the View hierarchy to draw on the View part of the SurfaceView.  If something manages to invalidate the SurfaceView's View, your onDraw() will be called, and you'll end up with a character sprite on the View layer.  (Depending on your layout this may not be visible.)  Just give the method a different name.

A: There are a number of ways to handle this, but generally, the way to do this is by maintaining a background layer (which is just another image), and sprite layers. Instead of clearing, at each frame you blit (copy) your background onto the surface (which erases everything), then you blit your sprites.

A: So you're going to have to draw the background bitmap onto the surface first before drawing your sprite. Right now you're drawing black which is covering your background layouts.
Alternatively you might be able to do canvas.drawRect with a Paint with paint.setColor to Color.Transparent.


text:
Q: Get and show json data from website's APIs in Delphi XE I am trying to re-write a piece of code I wrote in Python to Delphi.
The Python code is:
url = "https://www.bitstamp.net/api/ticker/"
response = urllib.urlopen(url)
data = json.loads(response.read())
lastvalue = data['last']

And this is enough to assign to the variable called "lastvalue" the value that I get from bitstamp's API.
I would like to do the same thing with delphi (I am using delphi XE6). I tried to find some answer here, and I am able to connect to the bitstamp's website and to get the full string, by doing this:
function GetURLAsString(const aurl:  string): string;
var
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);
    Result := lHTTP.Get(aURL);
  finally
    lHTTP.Free;
  end;
end;

And then I call this function with this:
procedure TForm2.Button1Click(Sender: TObject);
var
mydata : string;

begin
mydata := GetURLAsString('https://www.bitstamp.net/api/ticker/');
Label1.Text := mydata;
end;

I'm stuck here. I searched a lot but I am not able to figure out how can I assign to Label1.Text just the value assigned to "last".
When I run this I get {"high": "629.40", "last": "622.00", "timestamp": "1401544416", "bid": "621.99", "vwap": "617.47", "volume": "15147.30475739", "low": "602.26", "ask": "622.00"} assigned to Label1.Text.
I hope I was able to explain the question. I am really stuck in this point for some days, I hope someone can help me.

A: You can use the DBXJSON unit to parse the JSON response.
Try this sample
var
  LJsonObj   : TJSONObject;
  LJsonValue : TJSONValue;
begin
    mydata := GetURLAsString('https://www.bitstamp.net/api/ticker/');
    LJsonObj    := TJSONObject.ParseJSONValue(TEncoding.Default.GetBytes(mydata),0) as TJSONObject;
  try
     LJsonValue := LJsonObj.Get('last').JsonValue;
     Label1.Text:= LJsonValue.Value;
  finally
     LJsonObj.Free;
  end;
end;

A: With the SuperObject free open source JSON parser, the code would be:
var
  Mydata: string;
  MyObject: ISuperObject;
  Last: string;
begin
  ... // perform GET request and store response in Mydata

  MyObject := SO(Mydata);
  Last := MyObject.S['last'];

  ...

or shorter:
  // get the JSON web resource content
  Mydata := GetURLAsString('...');

  // get the value of the 'last' property of the object
  Last := SO(Mydata).S['last'];


text:
Q: How to dynamically load correct version of 3rd party unmanaged control in c# My app is a c# plug in to a 3rd party unmanaged app. I have a windows form with one of their controls (an AxInterop) that depends on one of their unmanaged dlls. Their 2015 version of the same control depends on a different type library file (eg. abc.tlb is now 123.tlb), but they both support the same interface.
I don't want to create separate builds.
How can I get my code to use the ABC.tlb for the earlier versions and use 123.tlb for the 2015 version?
Can you load tlb files like assemblies at start up?
thanks

A: ok, solved it using dynamics after all. The AxInterop control was a red herring. The control has a property that is of the type that changed for 2015. I used dynamics to get the property from the third party's workspace object and then set the property to that value. My project has no references to ABC or 123.


text:
Q: Prove every permutation of the alphabet contains a subset of six letters in order Prove that no matter the arrangement of the alphabet you can find a subset of six letters in alphabetical order, read from left to right or right to left.
For example the permutation {g,w,z,c,d,p,i,b,y,t,a,n,u,e,r,j,l,x,s,v,m,f,q,k,h,o} contains the subset {a,e,j,l,m,q}.
I know I have to construct a partially ordered set and possibly use Dilworth's Theorem, however I don't know how to begin tackling this problem.


text:
Q: Git: How to reset devel to master? I have branches master and devel.
I want to save devel somewhere for the (unlikely) case if I will need to restore the information in it and afterward to reset the head of devel to the head of master (without modifying master).
Is the following the right way to do this?
git checkout devel
git checkout -b devel-save
git push
git checkout devel
git reset --hard master
git push --force

A:
Can I be sure of no data loss if I do this as I described in the question?

No data will be lost.
You can also directly push develop: git push develop:old-develop, then reset master and force push.
The reflog mentioned in the comment.
On GitHub side, you have a poor man reflog which allows you to get back past deleted history. But in your case, that history will be visible and reference (under a new branch name).


text:
Q: How can I replace my cursor with a circle instead of drawing it to canvas in p5.js? The problem: I'm trying to create a simple drawing app using p5.js. Instead of the standard cursor image, I'd like to show a circle at my cursor location that represents the size of the drawing brush.
Potential solution 1: Replace the cursor using the cursor() function native to p5.
Why it doesn't work: The p5 cursor function only takes the following parameters:

ARROW, CROSS, HAND, MOVE, TEXT, or WAIT, or path for image

As such, there's no native way to replace the cursor using the ellipse class.
Potential solution 2: Use the noCursor() function and then draw the circle at the cursor location, while also drawing the background, as such:
var brushSize = 50;

function setup() {
  createCanvas(1080,720);
  noCursor();
}

function draw() {
  background(100);
  ellipse(mouseX,mouseY,brushSize);

}

Why it doesn't work: While this solution gets the desired effect i.e. replacing the cursor with a circle the size of the brush, the constantly updating background prevents me from actually drawing to the canvas with the brush when I want to.
Is there some way I can replace the cursor without actually drawing the ellipse to the canvas? Is there any way to save and then instantly reload a canvas in p5? I couldn't find such a method searching through the API docs. Any hints are appreciated.

A: According to the reference, you can pass a URL into the cursor() function to set an image.
If you want to use an image that you draw, you're going to have to draw them ahead of time and save them to files, and then use those files. Something like this:
cursor('images/ellipse-15.png');

Where ellipse-15.png is an image that you generated ahead of time, to match when brushSize is 15, for example.
Btw P5.js is just setting the cursor CSS property. You can read more about it here.
If you want to go with the noCursor() approach and draw the ellipse yourself, you could draw your drawing to a buffer (the createGraphics() function is your friend) and then draw the ellipse on top of that every frame. I'd still probably use a cross cursor just because there's going to be some annoying lag if you draw it yourself.

A: Create a circular DIV inside the canvas container and show it on top of the actual canvas.


text:
Q: Qt with codeblocks - undefined reference to vtable I've created project in qt (GUI and skeleton for logic), and then I've created QT project in codeblocks in order to do coding part in this IDE.
Unfortunately I'm getting errors in style:  undefined reference to vtable for Calc_Button, etc.
This code compiles fine with Qt but it doesn't want to compile with codeblocks. The same compiler is used.
I can provide code, but it is really quite a lot of it - even just the stubs.
That's how Calc_Button class looks like:
#ifndef CALC_BUTTON_H
#define CALC_BUTTON_H

#include <QPushButton>

class Calc_Button : public QPushButton
{
    Q_OBJECT
private:
protected:

public:
    explicit Calc_Button(QWidget *parent = 0);

signals:
    void clicked(QString);

public slots:
    void click()
    {
        emit clicked(QString(this->text()));
    }

};

#endif // CALC_BUTTON_H

and this is cpp:
#include "calc_button.h"

Calc_Button::Calc_Button(QWidget *parent) :    QPushButton(parent)
{

}

A: This error message is usually misleading but it the actual reason is (usually) that You did not define one of your virtual functions.
Here is a sample demo:
class MyClass
{
    public:
    virtual void doSomething() { }
    virtual void doSomethingMore();
};

int main()
{
    MyClass obj;
    obj.doSomething();
    obj.doSomethingMore();
    return 0;
}

compilation info:

/home/4VqWl0/ccMjLi2V.o: In function main':
  prog.cpp:(.text+0x19): undefined reference tovtable for MyClass.
  prog.cpp:(.text+0x1e): undefined reference toMyClass::doSomethingMore()'
  collect2: ld returned 1 exit status

Good Read:
What does it mean that the "virtual table" is an unresolved external?


text:
Q: Customize error message when compiling PDF Given the following R knitr document:
\documentclass{article}
\begin{document}

<<data>>=
opts_chunk$set(comment = NA)  # omits "##" at beginning of error message
x <- data.frame(x1 = 1:10)
y <- data.frame()
@

<<output_x>>=
if (nrow(x) == 0) stop("x is an empty data frame.") else summary(x)
@

<<output_y>>=
if (nrow(y) == 0) stop("y is an empty data frame.") else summary(y)
@

\end{document}

As expected, the last chunk returns an error with the custom message. The compiled PDF looks a little different:
Error: y is an empty data frame.

I want this text to just be
y is an empty data frame.

Without the Error: part or the red color. Can I achieve this? How?
Edit: I was able to make it in the mock data through the following workaround:
<<output_y>>=
if (nrow(y) == 0) cat("y is an empty data frame.") else summary(y)
@

However, that doesn't work with my real data, because I need the function to be stopped at that point.

A: Although I do not understand why an error should not be called Error, you are free to customize the output hook error to remove Error: from the message:
library(knitr)
knit_hooks$set(error = function(x, options) {
  knitr:::escape_latex(sub('^Error: ', '', x))
})

A: You could do something like this. options("show.error.messages" = FALSE) turns off error messages, so you could temporarily employ that once the if statement is entered and use on.exit to reset it.
This way, stop stops the function, Error: is avoided, and the desired message is printed in red.
> f <- function(x) {
      if(x > 5) {
          g <- getOption("show.error.messages")
          options(show.error.messages = FALSE)
          on.exit(options(show.error.messages = g))
          message("x is greater than 5.")
          stop()
      }
      x
  }
> f(2)
# [1] 2
> f(7)
# x is greater than 5.

Note:  I'm not exactly sure how safe this is and I'm not a big supporter of changing options settings inside functions.


text:
Q: Function object is not subscriptable     # TensorFlow and tf.keras
    import tensorflow as tf
    from tensorflow import keras

    # Helper libraries
    import numpy as np
    import matplotlib.pyplot as plt
    import os
    import cv2

    print(tf.__version__)

    DATADIR ="D:\Datasetes\legen"
    CATEGORIES = ['light']

    for category in CATEGORIES:
        path = os.path.join(DATADIR,category) #to create a path to the image in our drive
        for img in os.listdir(path):
            img_array = cv2.imread(os.path.join(path,img),cv2.IMREAD_GRAYSCALE)
            plt.imshow(img_array , cmap="gray")
            plt.show
            plt.figure()
            plt.imshow(img_array)
            plt.colorbar()
            plt.grid(False)
            plt.show()
            break
        break

    class_names = ['light', 'power', 'capture']
    train_images.shape
    len(train_labels)
    train_labels
    train_images = train_images / 255.0
    train_labels = train_labels / 255.0

    test_images = test_images / 255.0
    test_labels = test_labels / 255.0

    def class_names():
        for category in CATEGORIES:

            path = os.path.join(DATADIR,category)
            class_names = CATEGORIES.index(category)

            for img in (os.listdir(path)):
                try:
                    img_array = cv2.imread(os.path.join(path,img) ,cv2.IMREAD_GRAYSCALE)  # convert to array
                    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))  # resize to normalize data size
                    training_data.append([new_array, class_num])
                except Exception as e:
                    pass

    import random
    random.shuffle(training_data)
    img_array = cv2.imread(os.path.join(path,img),cv2.IMREAD_GRAYSCALE)
    plt.figure(figsize=(10,10))
    for i in range(10):
        plt.subplot(5,5,i+1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(img_array, cmap='gray')
        plt.xlabel(class_names(train_labels))
        plt.show()
        break
TypeError                                 Traceback (most recent call last)
<ipython-input-147-400073625620> in <module>
     29     plt.grid(False)
     30     plt.imshow(img_array, cmap='gray')
---> 31     plt.xlabel(class_names(train_labels))
     32     plt.show()
     33     break

TypeError: class_names() takes 0 positional arguments but 1 was given
this is the code that I am using and it keeps on giving an error as ''function' object is not subscriptable.I have added the whole code into this. please help as this is a school project and it is included in my goddamn GPA the error happens in the line with :the last part of the code

A: The name class_names is used both as a variable and also as a function name.Hence there is an ambiguity when you do
class_names[]

First Used here
class_names = ['light', 'power', 'capture']

Then here
def class_names():

After this class_names is no longer a list but a function.
Then, when you do
class_names[something] - it is an error


text:
Q: Time reversal and Antilinear operators I'm struggeling to solve this question. Can anyone help me please?

Let us consider a generic quantum mechanical system governed by
  the Hamiltonian $\ H(t) $.
In what follows we denote the evolution operator by
  $\ u(t, t_0) $. Hence,
  $\ |Ψ(t)>  = u(t, t_0)|Ψ_0> $
  satisfies the time-dependent Schrodinger equation, where $\ |Ψ_0> $  represents the
  wave function at $\ t = t_0$.
(a) Prove the unitarity condition
  $\ u^† (t, t_0)u(t, t_0) = u(t, t_0)u^†(t, t0) = I $ .
(b) Now let us assume that the system under study exhibits a symmetry
  represented by an antilinear (and antiunitary) operator $U$ which has nothing
  to do with the time reversal. Show that in this case  $\ [u(t, t0), U] = 0 $, and
  thus the system is unstable since its spectrum is unbounded from below.
(c) Show that instability disappears if antilinear $U$ includes time reversal.

The conclusion from (b) and (c) is that symmetries represented by antilinear
operators are possible, but they necessarily involve time reversal.

A: Let's make $u(t)=e^{it}$ ($H$ is hermitian)
Then $u^\dagger u=e^{-it}e^{it}=e^{it}e^{-it}=u u^{\dagger}=1$
Let $e^{it}$ and $U$ act on $\phi$:
$$(e^{it} U-U e^{it})\phi=(-e^{it}U+ e^{-it}U)\phi,\quad \text{or}\quad (-e^{it}+e^{-it})U\phi.$$
Now $U\phi=-U\phi$, so $(-e^{it}+ e^{-it})=-(-e^{it}+e^{-it})$ and therefore $0$, so (b) holds
When we include time reversal in $U$, let $U e^{it}$ act on $\phi(0)$, which becomes $-\phi(t)$.
Try it from there yourself.