text:
Q: Ruby: mixins, inheritance and constants name resolution My program has following structure:
module M1
    class A
        def action
            C.new.foo
        end
    end

    class C
        def foo
            puts "M1::C foo"
        end
    end
end

module M2
    class A
        def action
            C.new.foo
        end
    end

    class C
        def foo
            puts "M2::C foo"
        end
    end
end

As both M1::A and M2::A share same code, I've been thinking of putting common code inside separate class (or module) and inherit from it (include it). Something like this:
class ABase
    def action
        C.new.foo
    end
end

module M1
    class A < ABase
    end

    class C
        def foo
            puts "M1::C foo"
        end
    end
end

module M2
    class A < ABase
    end

    class C
        def foo
            puts "M2::C foo"
        end
    end
end

However, when I tried, I've got into trouble with name resolution uninitialized constant ABase::C. What is the proper way to achieve code sharing in this case?

A: Due to the way constants are resolved based on definition scope and not in inherited scopes you'll need to bridge that with a method call:
class ABase
  def action
    # Within this scope only constants defined in `ABase` are resolved.
    # As ABase::C and ::C (root-level) don't exist, C can't be resolved.
    # However, a method `c` defined in a subclass will be.
    c.new.foo
  end
end

module M1
  class A < ABase
    def c
      C
    end
  end

  class C
    def foo
      puts "M1::C foo"
    end
  end
end

module M2
  class A < ABase
    # This resolves C as either M2::A::C, M2::ABase::C, M2::C or ::C,
    # whichever it finds first.
    def c
      C
    end
  end

  class C
    def foo
      puts "M2::C foo"
    end
  end
end

Then you get the expected results:
M1::A.new.action
# => M1::C foo
M2::A.new.action
# => M2::C foo


text:
Q: Mixing Programming Languages in the "Code Blocks" IDE? Is there a way I can mix, for example, C# code and C++ code in the Code Blocks IDE?
If I'm not clear enough, this is basically about adding code files from another language to C++.

A: Not in Code::Blocks, no. If you were looking for a free ide you should try monodevelop or sharpdevelop.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java driver class, Runnable, and main method I am to create a program in Java using multiple methods inside the driver class. Previously, we have only used the main method in such applications.
I know I am to use something like this:
public static void main(String[] args)
{
    U4A4 u = new U4A4();
    u.run();
}

to run the method public U4A4().
Yes, I know this is terribly basic, but I've been searching around all evening and I thought someone here might be able to put it in simple terms how exactly I should do this.
My compiler is getting mad when I try to put in public class U4A4 implements Runnable at the top of my code (it's right after my imports) and starts wanting me to make it abstract. I have no idea what that is.
So, where do I put implements Runnable and where do I use run()?
Thank you so much for bearing with me here.
Edit: This is what I've got so far. http://pastebin.com/J8jzzBvQ

A: You have implemented Runnable interface, but not overriden the run method of that interface. I have commented code where you will have to place your thread logic so the thread will work for you.
import java.util.Scanner;

public class U4A4 implements Runnable
{
    private int count = 0;
    private double accum = 0;
    private int apr, min, months;
    private double balance, profit;

    public static void main(String[] args)
    {
        U4A4 u = new U4A4();
        u.run();
    }

    public U4A4()
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter credit card balance: ");
        balance = in.nextDouble();
        System.out.print("\n\nEnter minimum payment (as % of balance): ");
        min = in.nextInt();
        System.out.print("\n\nEnter annual percentage rate: ");
        apr = in.nextInt();

        profit = this.getMonths(balance);

        System.out.println("\n\n\n# of months to pay off debt =  " + count);
        System.out.println("\nProfit for credit card company = " + profit + "\n");
    }

    public double getMonths(double bal)
    {
        double newBal, payment;
        count++;

        payment = bal * min;

        if (payment < 20 && bal > 20)
        {
            newBal = bal * (1 + apr / 12 - 20);
            accum += 20;

        } else if (payment < 20 && bal < 20)
        {
            newBal = 0;
            accum += bal;
        } else
        {
            newBal = bal * (1 + apr / 12) - payment;
            accum += payment;
        }
        if (newBal != 0) {
            getMonths(newBal);
        }

        return accum;
    }

    public void run() {
        // TODO Auto-generated method stub
        // You have to override the run method and implement main login of your thread here.
    }
}


text:
Q: How can I graph results from common data? I'm not entirely sure how to word this question for the title, but I can give a simplified example to (hopefully) explain my issue better. Say I have the following tables:
Maths Class:

Student
Score

Alex
90

Alex
75

Bob
85

Jake
80

Jake
95

Steve
60

Science Class:

Student
Score

Alex
95

Ash
80

Bob
90

Bob
75

Steve
85

and

Student
Grade

Alex
Senior

Ash
Sophomore

Bob
Freshman

Jake
Senior

Steve
Junior

This image below shows the desired format of the graph, but was created by having scores & grade levels in the same table. Ideally I wouldn't have to do that. This is a simplified example, but to do that for my real data would mean adding to half a dozen graphs.
Additionally, not every student took every test, and some students took a test multiple times and have several scores.
I understand how to handle this, and I'm fine with the graph including several scores from the same student. Just mentioning it because I'd prefer to keep separate tables for each subject. I feel that combining all of the subjects onto one table would result in a muddle of students and scores that would be hard to understand at first glance.
Is it possible for excel to do this?


text:
Q: Convert ES6 Iterable to Array Say you have an array-like Javascript ES6 Iterable that you know in advance will be finite in length, what's the best way to convert that to a Javascript Array?
The reason for doing so is that many js libraries such as underscore and lodash only support Arrays, so if you wish to use any of their functions on an Iterable, it must first be converted to an Array.
In python you can just use the list() function. Is there an equivalent in ES6?

A: The following approach is tested for Maps:
const MyMap = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3]
]);

const MyArray = [...MyMap].map(item => {
  return {[item[0]]: item[1]}
});

console.info( MyArray ); //[{"a", 1}, {"b", 2}, {"c": 3}]

A: Summary:

*

*Array.from() function, it takes an iterable as in input and returns an array of the iterable.

*Spread syntax: ... in combination with an array literal.

const map = new Map([[ 1, 'one' ],[ 2, 'two' ]]);

const newArr1  = [ ...map  ];  // create an Array literal and use the spread syntax on it
const newArr2 = Array.from( map );  //

console.log(newArr1, newArr2);

Caveat when copying arrays:
Be cognizant of the fact that via these methods above only a shallow copy is created when we want to copy an array. An example will clarify the potential issue:

let arr = [1, 2, ['a', 'b']];

let newArr = [ ...arr ];

console.log(newArr);

arr[2][0] = 'change';

console.log(newArr);

Here because of the nested array the reference is copied and no new array is created. Therefore if we mutate the inner array of the old array, this change will be reflected in the new array (because they refer to the same array, the reference was copied).
Solution for caveat:
We can resolve the issue of having shallow copies by creating a deep clone of the array using JSON.parse(JSON.stringify(array)). For example:

let arr = [1, 2, ['a', 'b']]

let newArr = Array.from(arr);

let deepCloneArr = JSON.parse(JSON.stringify(arr));

arr[2][0] = 'change';

console.log(newArr, deepCloneArr)

A: You can use Array.from or  spread syntax (...).
Example:

const x = new Set([ 1, 2, 3, 4 ]);

const y = Array.from(x);
console.log(y); // = [ 1, 2, 3, 4 ]

const z = [ ...x ];
console.log(z); // = [ 1, 2, 3, 4 ]

A: You can use the Array.from method, which is being added in ES6, but only supports arrays and iterable objects like Maps and Sets (also coming in ES6). For regular objects, you can use Underscore's toArray method or lodash's toArray method, since both libraries actually have great support for objects, not just arrays. If you are already using underscore or lodash, then luckily they can handle the problem for you, alongside adding various functional concepts like map and reduce for your objects.

A:  <Your_Array> = [].concat.apply([], Array.from( <Your_IterableIterator> ));

A: You could also do the following, but both approaches are certainly not recommendable (merely a proof-of-concept for completeness):
let arr = [];
for (let elem of gen(...)){
    arr.push(elem);
}

Or "the hard way" using ES5 + generator function (Fiddle works in current Firefox):
var squares = function* (n) {
  for (var i = 0; i < n; i++) {
    yield i * i;
  }
};

var arr = [];
var gen = squares(10);
var g;
while (true) {
  g = gen.next();
  if (g.done) {
    break;
  }
  arr.push(g.value);
}


text:
Q: How to render template directly without having a handler My GAE project has a setup like:
/static/.* --> images, css, js
/rest/.* --> a script handling all rest resources using webapp2 handlers

I want to use jinja2 templates to basically create some html pages but e.g. using the template inheritance jinja2 provides. More or less to do server side includes.
So all other incoming requests should directly render a template, e.g:
/ --> index template
/index.html --> index template
/some/path/to/a/page.html --> /some/path/to/a/page template
/some/path/to/a/page --> /some/path/to/a/page template

I would like to match both .html and paths without extension.
I don't want to create routes for all my paths, just some smart script that can handle this. Would this be possible?

A: Yes, you can. But still need the single handler for that:
# app.yaml
- url: /rest/.*
  script: main.app

# main.py
class PageHandler(webapp2.RequestHandler):
    def get(self, page):
        if not page.endswith('.html'):
            page += '.html'
        self.response.write(self.jinja2.render_template(page))

app = webapp2.WSGIApplication([
    webapp2.RedirectRoute('/rest/<page>', PageHandler, name='page'),
], debug=True)

Then you just link your pages with /rest/index.html or /rest/path/to/page
But if you are purely using this for static files, this will still use an instance to generate these pages, if you like you could use my app-engine-static github project. It's basically a project that would help you build dynamic sites using jinja2 then generate the static files and this will serve with app engine's built-in cdn and not consume instance hours:
http://blog.altlimit.com/2013/08/host-static-website-on-google-app.html


text:
Q: Javascript on page load without appending to body I'm trying to show an image using a Jumi module in Joomla.  Currently, the script is calling to append to the body tag but this places the image at the bottom of my template.  I need to be able to run my script without appending to the body but can't just call the function since my script uses an if else statement to determine what to do.  I'm very new to JS but is there a way to append to a paragraph tag or a div?
Link Here to Website

A: Yes there is:

...
document.getElementById("my-element").appendChild(img);

This will append your img to the element whose id you provide.
https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild


text:
Q: MySQL - Rows to Columns and keeps NULL We have the following table (TEST2) in the MySQL database (MySQL 5.6):
 TEAM_ID,MEMBER_ID,TYPE,SCORE
 1,2,A,150
 1,3,B,200
 1,1,B,50
 1,1,A,100
 1,2,B,NULL

We try to transform/pivot the above table based on the TYPE column:
If the TYPE column has value == A, move the value in the SCORE column into a new column called A_SCORE.  If the value in the SCORE column is NULL, it should show NULL in the new A_SCORE column.
If the TYPE column has value == B, move the value in the SCORE column into a new column called B_SCORE. If the value in the SCORE column is NULL, it should show NULL in the new B_SCORE column.
The following table is the one we are looking for (the wanted table):
 TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE,A_SCORE_MINUS_B_SCORE
 1,1,100,50,50
 1,2,150,NULL,NULL
 1,3,0,200,-200

We tried the following query
 SELECT TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE,SUM(A_SCORE-B_SCORE) AS ACTUAL_MINUS_B_SCORE FROM
  (SELECT TEAM_ID,MEMBER_ID,

 CASE
 WHEN SCORE IS NULL
 THEN NULL
 ELSE SUM(if(TYPE = 'A', SCORE,0) )
 END A_SCORE,

 CASE
 WHEN SCORE IS NULL
 THEN NULL
 ELSE SUM(if(TYPE = 'B', SCORE,0) )
 END B_SCORE
 FROM TEST2
 GROUP BY TEAM_ID,MEMBER_ID,SCORE) AS A
 GROUP BY TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE);

It returns something we don't want:
 TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE,A_SCORE_MINUS_B_SCORE
 1,1,0,50,-50
 1,1,100,0,100
 1,2,0,0,0
 1,2,150,0,150
 1,3,0,200,-200

If we tried the following, it generates a table close to what we want, but it doesn't return any NULL value.
 SELECT TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE,SUM(A_SCORE-B_SCORE) AS A_SCORE _MINUS_B_SCORE FROM
  (SELECT TEAM_ID,MEMBER_ID,

 SUM(if(TYPE = 'A', SCORE,0) ) AS A_SCORE,

 SUM(if(TYPE = 'B', SCORE,0) )AS B_SCORE
 FROM TEST2
 GROUP BY TEAM_ID,MEMBER_ID) AS A
 GROUP BY TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE;

The result of the above query:
 TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE,A_SCORE_MINUS_B_SCORE
 1,1,100,50,50
 1,2,150,0,0
 1,3,0,200,-200

Could any guru enlighten how to generate the wanted table in this case using MySQL?  The SQL fiddle is here for your convenience.
http://sqlfiddle.com/#!9/cfe7a1/1
Thanks!

A: Try this;)
SELECT TEAM_ID, MEMBER_ID, A_SCORE, B_SCORE, A_SCORE - B_SCORE AS A_SCORE_MINUS_B_SCORE
FROM (
    SELECT
        TEAM_ID, MEMBER_ID,
        CASE
            WHEN A_SCORE IS NULL AND NOT EXISTS (
                SELECT 1 FROM TEST2
                WHERE TEAM_ID = T1.TEAM_ID
                AND MEMBER_ID = T1.MEMBER_ID
                AND TYPE = 'A'
            ) THEN 0 ELSE A_SCORE END AS A_SCORE,
        CASE
            WHEN B_SCORE IS NULL AND NOT EXISTS (
                SELECT 1 FROM TEST2
                WHERE TEAM_ID = T1.TEAM_ID
                AND MEMBER_ID = T1.MEMBER_ID
                AND TYPE = 'A'
            ) THEN 0 ELSE B_SCORE END AS B_SCORE
    FROM (
        SELECT
           TEAM_ID, MEMBER_ID,
           MAX(CASE WHEN TYPE = 'A' THEN SCORE END) AS A_SCORE,
           MAX(CASE WHEN TYPE = 'B' THEN SCORE END) AS B_SCORE
        FROM TEST2
        GROUP BY TEAM_ID, MEMBER_ID
    ) T1
)T

SQLFiddle demo here

A: I don't quite understand the calculation criteria, but something like this should work...
SELECT team_id
     , member_id
     , COALESCE(MAX(CASE WHEN type = 'A' THEN score END),0) a_score
     , COALESCE(MAX(CASE WHEN type = 'B' THEN score END),0) b_score
     , COALESCE(MAX(CASE WHEN type = 'A' THEN score END),0)
     - COALESCE(MAX(CASE WHEN type = 'B' THEN score END),0) diff
  FROM test2
 GROUP
    BY team_id
     , member_id;


text:
Q: Use of javascript function inside if statement Can someone explain how the following if statement works. Inside the if statement there is a test for function addFieldToText, and its arguments. After this line the script jumps into the addFieldToText function
 if(!addFieldToText(refworksFieldMappingEntry.enterpriseCode, refworksFieldMappingEntry))

Is it basically saying if this function has not been called yet, then call it?
Hope this makes sense.

A: As soon as that if statement is encountered, it:

*

*Calls the addFieldToText function passing refworksFieldMappingEntry.enterpriseCode, refworksFieldMappingEntry as arguments.

*If addFieldToText returns false based on those arguments value, then the if statement is executed.

If the addFieldToText was not prefixed with ! (NOT operator) then addFieldToText would have to return a truthy value for the if statement to execute.
Here's a simplified example:

const isNumberDivisibleBy2 = (num) => {
  return num % 2 === 0
}

if (!isNumberDivisibleBy2(9)) {
  console.log('number is NOT divisible by 2')
} else {
  console.log('number is divisible by 2')
}


text:
Q: Rotate imageView random I am trying to get the image view to rotate random degree between 360 and 720. So I want the image view to rotate once(360 degrees), and then again rotate a random degree(0 to 360)
func rotateRandom2(){
    let lower : UInt32 = 360
    let upper : UInt32 = 720
    let diceRoll = CGFloat(arc4random_uniform(upper - lower) + lower)
    let degree =  0.0174532925 as CGFloat
    let rotate = diceRoll
    UIView.animateWithDuration(1, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut,      animations: { () -> Void in
        self.bottleImageView.transform = CGAffineTransformRotate(self.bottleImageView.transform, rotate)
        }, completion: nil)
}

A: You can use CABasicAnimation to animate z rotation. You can do as follow:
let rotateView = CABasicAnimation()
let randonAngle = arc4random_uniform(361) + 360
rotateView.fromValue = 0
rotateView.toValue = Float(randonAngle) * Float(M_PI) / 180.0
rotateView.duration = 1
rotateView.repeatCount = 0
rotateView.removedOnCompletion = false
rotateView.fillMode = kCAFillModeForwards
rotateView.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
view.layer.addAnimation(rotateView, forKey: "transform.rotation.z")


text:
Q: I need some help Write random test data to csv file using faker I am new to Python 2.7
I am trying to write some random test data to a csv file using the Python faker package.
I have stored a random first name value into a List variable called 'firstNameList'
I then write the value to the csv using write_to_csv.writerow(firstNameList)
The value that is written out in the csv file is
|('first_name', u'Monica')|
I just want the first name value in the csv e.g. Monica
I do not want the whole string |('first_name', u'Monica')| in the csv.
I have noticed my other first name variable firstName1 has the value Loraine
This one would be great to use.  But when i try to write firstName1 to the csv the output is
f i r s t _ n a m e
My code is below.
I am storing the value in a List variable because i want to populate a few rows in the csv.  Say 100 rows of random data.
If i store 100 first names into the names list variable I can then use a for loop to loop through the List and output the values to the csv file.
I will then do the same for address, email, phone etc.
from faker.factory import Factory
import csv

def writeTo_csv(fake):
    with open('test.csv', 'wb') as csvfile:
    write_to_csv = csv.writer(csvfile, delimiter=' ', quotechar='|',     quoting=csv.QUOTE_MINIMAL)
    write_to_csv.writerow(['id,', 'TITLE,', 'FNAME,', 'SNAME,', 'GENDER,',     'ADD1,', 'ADD2,', 'ADD3,', 'ADD4,', 'PCODE,', 'PHONE,', 'MOBILE,', 'DOB'])
    firstName1 = "first_name"
    firstNameList = [(firstName1, getattr(fake, firstName1)())]
    print "%s = %s" % (firstName1, getattr(fake, firstName1)())
    print firstNameList
    write_to_csv.writerow(firstName1)

if __name__ == "__main__":
fake = Factory.create('en_GB')
writeTo_csv(fake)

A: You have a tuple inside a list, in the firstNameList variable. You have to extract the random name like:
firstNameList[0][1]

When printing, writerow() accepts an iterable data structure and separates each element with the delimiter specified in the constructor, so if you pass a string it assumes each letter as a field, you must create a list or a tuple with all your names to separate them right. In following example I used a tuple, like:
write_to_csv.writerow((firstNameList[0][1],))

So the script gets like:
from faker.factory import Factory
import csv

def writeTo_csv(fake):
    with open('test.csv', 'wb') as csvfile:
        write_to_csv = csv.writer(csvfile, delimiter=' ', quotechar='|',     quoting=csv.QUOTE_MINIMAL)
        write_to_csv.writerow(['id,', 'TITLE,', 'FNAME,', 'SNAME,', 'GENDER,',     'ADD1,', 'ADD2,', 'ADD3,', 'ADD4,', 'PCODE,', 'PHONE,', 'MOBILE,', 'DOB'])
        firstName1 = "first_name"
        firstNameList = [(firstName1, getattr(fake, firstName1)())]
        print "%s = %s" % (firstName1, getattr(fake, firstName1)())
        print firstNameList
        write_to_csv.writerow((firstNameList[0][1],))

if __name__ == "__main__":
    fake = Factory.create('en_GB')
    writeTo_csv(fake)

That yields a test.csv file like:
id, TITLE, FNAME, SNAME, GENDER, ADD1, ADD2, ADD3, ADD4, PCODE, PHONE, MOBILE, DOB
Dana


text:
Q: Gamma Matrices in Dimensional Regularization Prove that $tr\left(\gamma_\mu\gamma_\nu\gamma_\rho\gamma_\sigma\gamma_5\right)=0$ when the spacetime dimension is not 4.
What I have tried:
We know that $\gamma_\alpha\gamma^\alpha=d\mathbb{1}$, so we can write:
$tr\left(\gamma_\mu\gamma_\nu\gamma_\rho\gamma_\sigma\gamma_5\right)=\frac{1}{d}tr\left(\gamma_\alpha\gamma^\alpha\gamma_\mu\gamma_\nu\gamma_\rho\gamma_\sigma\gamma_5\right)$
Then I thought I could commute $\gamma^\alpha$ past two gammas because if $\alpha\notin\left\{\mu,\,\nu,\,\rho,\,\sigma\right\}$, then $\left\{\gamma_\alpha,\,\gamma_\mu\right\}=0$ and somehow show that I get minus of what I started with, using the cyclicality of the trace and that $\left\{\gamma_5,\,\gamma_\mu\right\}=0$.
However, what I am not sure about is why can we always find such $\alpha$ so that $\alpha\notin\left\{\mu,\,\nu,\,\rho,\,\sigma\right\}$. I understand this is generally possible when $d\in\mathbb{R}\wedge d>4$, however, when $d\in\mathbb{C}$, this claim doesn't make any sense for me.
Can anyone provide a rigorous proof of this claim which avoids the hurdle I mentioned above?

A: As shown in chapter 47 of the book by Srednicki, using the definition of $\gamma_5$ and the relations $(\gamma^i)^2=-1$ and $(\gamma^0)^2=1$, we can show that
$\text{Tr}(\gamma_5\gamma^\mu\gamma^\nu\gamma^\rho\gamma^\sigma)=-4i\epsilon^{\mu\nu\rho\sigma}.$
We can now use a fundamental property of the Levi-Civita symbol, namely the fact that the number of its indices has to agree with the number of spacetime dimensions. If this is not the case, it vanishes. Hence, this proves the initial assertion.


text:
Q: Error: Unrecognised Selector when using class reference I have a class in a swift file called cloud I use a reference to that class in my project to call two of its methods.  But I get the following error and the app crashes;

NSForwarding: warning: object 0x7fc938717160 of class 'App.Cloud' does
  not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector -[App.Cloud persistentStoreWillChange]
(lldb)

Does anybody know who i could resolve this and why this is occurring ?
PS: The error only appears when installing the app and launching for the first time. If I quit and relaunch it does not appear, however it does not execute the methods.
Heres my class,
class Cloud {

let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

func persistentStoreWillChange (notification:NSNotification) {

    self.moc!.performBlock { () -> Void in
        if self.moc!.hasChanges {
            var error:NSError? = nil
            self.moc!.save(&error)
            if error != nil {
                println("Save error: \(error)")
            } else{
                // drop any manged object refrences
                self.moc!.reset()
            }

        }
    }
}

func persistentStoreDidChange () {
    println("Store Did Change")
}

//Refresh Data
func recieveChanges (notification:NSNotification){
    self.moc!.performBlock { () -> Void in
        self.moc!.mergeChangesFromContextDidSaveNotification(notification)
    }
}

//View Will Appear
func addObsevers() {

NSNotificationCenter.defaultCenter().addObserver(self, selector: "persistentStoreDidChange:", name: NSPersistentStoreCoordinatorStoresDidChangeNotification, object: nil)

 NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("persistentStoreWillChange:"), name:NSPersistentStoreCoordinatorStoresWillChangeNotification, object: moc!.persistentStoreCoordinator)

 NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("recieveICloudChanges:"), name:NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: moc!.persistentStoreCoordinator)

}

//View Will Dissapear
func removeObservers() {

 NSNotificationCenter.defaultCenter().removeObserver(self, name: NSPersistentStoreCoordinatorStoresDidChangeNotification, object: nil)
 NSNotificationCenter.defaultCenter().removeObserver(self, name: NSPersistentStoreCoordinatorStoresWillChangeNotification, object: moc!.persistentStoreCoordinator)
 NSNotificationCenter.defaultCenter().removeObserver(self, name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: moc!.persistentStoreCoordinator)
}

}

Class reference in View Controller:
let iCloudSync = Cloud()

override func viewWillAppear(animated: Bool) {

    iCloudSync.addObsevers()

    loadData()

}

override func viewWillDisappear(animated: Bool) {
    iCloudSync.removeObservers()
}

A: You need to derive class Cloud from NSObject when you declare it, like this:
class Cloud : NSObject {

Otherwise your selectors are invisible to Objective-C.

A: Well you do this, which says to call persistentStoreDidChange on self when the notification triggers:
NSNotificationCenter.defaultCenter().addObserver(self,
  selector: "persistentStoreDidChange",
  name: NSPersistentStoreCoordinatorStoresDidChangeNotification,
  object: nil)

But then it looks like you don't implement persistentStoreDidChange within class Cloud.
So either remove that observer, or implement the method.

A: Your methods have parameters so you must express this with ':' in their names. Changed code should look like this:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("persistentStoreWillChange:"), name: NSPersistentStoreCoordinatorStoresWillChangeNotification, object: moc!.persistentStoreCoordinator)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("recieveICloudChanges:"), name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: moc!.persistentStoreCoordinator)

A: You changed code but you forgot to change method declaration from
func persistentStoreDidChange () {
    println("Store Did Change")
}

to
func persistentStoreDidChange (notification: NSNotification) {
    println("Store Did Change")
}


text:
Q: Outliers in Works Schedule I am trying to find outliers for work schedules for individuals (mostly high variations). trying to find, if someone comes or leaves way outside the individual (8:30am to 5pm) or group normals (7am to 6pm). I tried using standard deviation but the problem with that is,

*

*It gives me outliers on both sides of the mean. That is if some comes in late during work hours (say 10am)or leaves early (say 4pm).

*Another problem is the mean itself. It takes lot of observations to bring down the mean to most frequent times if there are few extremes at the beginning of the data set. For example, one set had few in-times around 3pm, 11am, 10am, 9am but most of them were around 6am, but the mean took a lot of observations to get 6am mean. I thought of weighted averages but that would mean I will have to round up times to nearest 30 mins or so. But would like to avoid changing data points.

Is there any known way to find outliers in work schedule? I tried to search but all I get is outliers in time-series. But I am looking for outliers in time itself. Any suggestions?
Note: My data set has PersonID and multiple (swipe) times/day/PersonID. And I am using python 2.7.

A: If I understand correctly, you are looking to identify people who depart extremely early or arrive extremely late compared to their own and overall norms.

*

*The first issue you encountered seems related to tagging outliers that deviate by (N x standard deviation) late or early. You should be able to control whether to tag outliers on one or both sides.

*The second issue has to do with mean being biased or unstable with a small sample.
Unless you know the outlier thresholds ahead of time, you will need a healthy sample to identify outliers in any case. If mean does not zero in quick enough to the common, and
you seek the common value, use Mode instead of mean.

Also, I would suggest looking at the daily hours - difference between arrival and departure each day as a separate metric.
Below I have a directional approach / suggestion to tackle your problem, python3 (sorry).
It should address the issues you mentioned but does not add the daily hours I think you should include.
This is the output you can expect:
Outlier PersonIDs based on overall data
array([ 1.,  4.,  7.,  8.])
Outlier PersonIDs based on each user's data and overall deviation
array([ 1.,  3.,  4.,  5.,  7.,  8.,  9.])

This is the daily arrival and departure time distributions:

Here's the code:
#! /usr/bin/python3

import random
import pandas as pd
import numpy as np
import scipy.stats
import pprint
pp = pprint.PrettyPrinter(indent=4)

# Visualize:
import matplotlib.pyplot as plt

#### Create Sample Data START
# Parameters:
TimeInExpected=8.5 # 8:30am
TimeOutExpected=17 # 5pm
sig=1 # 1 hour variance
Persons=11
# Increasing the ratio between sample size and persons will make more people outliers.
SampleSize=20
Accuracy=1 # Each hour is segmented by hour tenth (6 minutes)

# Generate sample
SampleDF=pd.DataFrame([
    np.random.randint(1,Persons,size=(SampleSize)),
    np.around(np.random.normal(TimeInExpected, sig,size=(SampleSize)),Accuracy),
    np.around(np.random.normal(TimeOutExpected, sig,size=(SampleSize)),Accuracy)
    ]).T
SampleDF.columns = ['PersonID', 'TimeIn','TimeOut']

# Visualize
plt.hist(SampleDF['TimeIn'],rwidth=0.5,range=(0,24))
plt.hist(SampleDF['TimeOut'],rwidth=0.5,range=(0,24))
plt.xticks(np.arange(0,24, 1.0))
plt.xlabel('Hour of day')
plt.ylabel('Arrival / Departure Time Frequency')
plt.show()
#### Create Sample Data END

#### Analyze data
# Threshold distribution percentile
OutlierSensitivity=0.05 # Will catch extreme events that happen 5% of the time. - one sided! i.e. only late arrivals and early departures.
presetPercentile=scipy.stats.norm.ppf(1-OutlierSensitivity)

# Distribution feature and threshold percentile
argdictOverall={
    "ExpIn":SampleDF['TimeIn'].mode().mean().round(1)
    ,"ExpOut":SampleDF['TimeOut'].mode().mean().round(1)
    ,"sigIn":SampleDF['TimeIn'].var()
    ,"sigOut":SampleDF['TimeOut'].var()
    ,"percentile":presetPercentile
}
OutlierIn=argdictOverall['ExpIn']+argdictOverall['percentile']*argdictOverall['sigIn']
OutlierOut=argdictOverall['ExpOut']-argdictOverall['percentile']*argdictOverall['sigOut']

# Overall
# See all users with outliers - overall
Outliers=SampleDF["PersonID"].loc[(SampleDF['TimeIn']>OutlierIn) | (SampleDF['TimeOut']<OutlierOut)]

# See all observations with outliers - Overall
# pp.pprint(SampleDF.loc[(SampleDF['TimeIn']>OutlierIn) | (SampleDF['TimeOut']<OutlierOut)].sort_values(["PersonID"]))

# Sort and remove NAs
Outliers=np.sort(np.unique(Outliers))
# Show users with overall outliers:
print("Outlier PersonIDs based on overall data")
pp.pprint(Outliers)

# For each
OutliersForEach=[]
for Person in SampleDF['PersonID'].unique():
    # Person specific dataset
    SampleDFCurrent=SampleDF.loc[SampleDF['PersonID']==Person]
    # Distribution feature and threshold percentile
    argdictCurrent={
        "ExpIn":SampleDFCurrent['TimeIn'].mode().mean().round(1)
        ,"ExpOut":SampleDFCurrent['TimeOut'].mode().mean().round(1)
        ,"sigIn":SampleDFCurrent['TimeIn'].var()
        ,"sigOut":SampleDFCurrent['TimeOut'].var()
        ,"percentile":presetPercentile
    }
    OutlierIn=argdictCurrent['ExpIn']+argdictCurrent['percentile']*argdictCurrent['sigIn']
    OutlierOut=argdictCurrent['ExpOut']-argdictCurrent['percentile']*argdictCurrent['sigOut']
    if SampleDFCurrent['TimeIn'].max()>OutlierIn or SampleDFCurrent['TimeOut'].min()<OutlierOut:
        Outliers=np.append(Outliers,Person)

# Sort and get unique values
Outliers=np.sort(np.unique(Outliers))
# Show users with overall outliers:
print("Outlier PersonIDs based on each user's data and overall deviation")
pp.pprint(Outliers)


text:
Q: Storing similar objects in a database I am developing an a house renting/selling application, it will allow users to post rental and houses on sale. My concern is the two objects have some similar and different attributes,for example here is a house on rent can have the following attributes `
public class RentalHouse extends Property{

private int numOfBedrooms;
private int payMonthsInAdvance;
private double securityDeposit;
private double rentals;
private String dayOfVacancy;

}

Whilst a house on sale can have the following attributes
public class SaleHouse extends Property{

private int numOfBedrooms;
private double price;

}

public class Property {

private long id;
private String title;
private String description;
private ArrayList<String> images;
private String province;
private String area;

}

Now here is my question; is it good design to have 2 tables for one for rental houses the other for houses on sale? and what would you advice?


text:
Q: Layerd Web App - Problem with Add Migration I have layered web app, where Infrastructure project contain only Identities and Persistence contain all other entities. For Persistence I had manage to generate migrations but for Infrastructure not able. Difference between this two is that Persistence Inherits DbContext and Infrastrutcure ApiAuthorizationDbContext
Code is bellow:
public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
{
    public ApplicationDbContext(
        DbContextOptions<ApplicationDbContext> options,
        IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
    {

    }
}  public class IMSDbContext : DbContext, IIMSDbContext
    {
        private readonly ICurrentUserService _currentUserService;
        private readonly IDateTime _dateTime;

        public IMSDbContext(DbContextOptions<IMSDbContext> options) : base(options)
        {

        }

        public IMSDbContext(DbContextOptions<IMSDbContext> options, ICurrentUserService currentUserService, IDateTime dateTime) : base(options)
        {
            _currentUserService = currentUserService;
            _dateTime = dateTime;
        }

        public DbSet<ItemType> ItemTypes { get; set; }
        public DbSet<Item> Items { get; set; }
        public DbSet<Employee> Employees { get; set; }
        public DbSet<ItemDetail> ItemDetails { get; set; }
        public DbSet<Location> Locations { get; set; }
        public DbSet<ItemImage> ItemImages { get; set; }

        public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
        {

            foreach (var entry in ChangeTracker.Entries<AuditableEntity>())
            {
                switch (entry.State)
                {
                    case EntityState.Added:
                        entry.Entity.CreatedBy = _currentUserService.UserId;
                        entry.Entity.Created = _dateTime.Now;
                        break;
                    case EntityState.Modified:
                        entry.Entity.ModifiedBy = _currentUserService.UserId;
                        entry.Entity.Modified = _dateTime.Now;
                        break;

                }
            }
            return base.SaveChangesAsync(cancellationToken);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(typeof(IMSDbContext).Assembly);
        }
    }

When I run add-migration Identity -p Infrastructure -c ApplicationDbContext from Persistence project where is installed EFCore.Design
Got next error:

Unable to create an object of type 'ApplicationDbContext'. For the
  different patterns supported at design time, see
  https://go.microsoft.com/fwlink/?linkid=851728

Here is DI for Infrastructure:
 public static class DependencyInjection
    {
        public static IServiceCollection AddInfrastructure(this IServiceCollection services,
            IConfiguration configuration, IWebHostEnvironment environment)
        {

            services.AddScoped<IUserManager, UserManagerService>();
            services.AddTransient<INotificationService, NotificationService>();
            services.AddTransient<IDateTime, MachineDateTime>();

            services.AddDbContext<ApplicationDbContext>(
                options => options.UseSqlServer(configuration.GetConnectionString("IMSDatabase")));

            services.AddDefaultIdentity<ApplicationUser>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            return services;
        }
    }

And here is Startup from WebAPI project.
  public class Startup
    {
        private IServiceCollection _services;
        public Startup(IConfiguration configuration, IWebHostEnvironment environment)
        {
            Configuration = configuration;
            Environment = environment;

        }

        public IConfiguration Configuration { get; }
        public IWebHostEnvironment Environment { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddInfrastructure(Configuration, Environment);
            services.AddPersistence(Configuration);
            services.AddApplication();
            services.AddControllers();

            _services = services;
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        private void RegisteredServicesPage(IApplicationBuilder app)
        {
            app.Map("/services", builder => builder.Run(async context =>
            {
                var sb = new StringBuilder();
                sb.Append("
Registered Services
");
                sb.Append("

");
                sb.Append("
Type	Lifetime	Instance
");
                sb.Append("

");
                foreach (var svc in _services)
                {
                    sb.Append("
");
                    sb.Append($"{svc.ServiceType.FullName}	");
                    sb.Append($"{svc.Lifetime}	");
                    sb.Append($"{svc.ImplementationType?.FullName}	");
                    sb.Append("
");
                }
                sb.Append("

");
                await context.Response.WriteAsync(sb.ToString());
            }));
        }
    }

Can anyone help me to understand what I had did wrong ?
Kind Regards,
Danijel
UPDATE
When run pmc command:
add-migration Identity -c ApplicationDbContext -p Infrastructure -s Persistence -v
Using project 'src\Infrastructure'.
Using startup project 'src\Persistence'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile C:\Users\BoksanD\source\repos\IMS\Persistence\bin\Debug\netcoreapp3.0\IMS.Persistence.deps.json --additionalprobingpath C:\Users\BoksanD\.nuget\packages --additionalprobingpath C:\Microsoft\Xamarin\NuGet --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig C:\Users\BoksanD\source\repos\IMS\Persistence\bin\Debug\netcoreapp3.0\IMS.Persistence.runtimeconfig.json C:\Users\BoksanD\.nuget\packages\microsoft.entityframeworkcore.tools\3.0.0\tools\netcoreapp2.0\any\ef.dll migrations add Identity --json --context ApplicationDbContext --verbose --no-color --prefix-output --assembly C:\Users\BoksanD\source\repos\IMS\Persistence\bin\Debug\netcoreapp3.0\IMS.Infrastructure.dll --startup-assembly C:\Users\BoksanD\source\repos\IMS\Persistence\bin\Debug\netcoreapp3.0\IMS.Persistence.dll --project-dir C:\Users\BoksanD\source\repos\IMS\Infrastructure\ --language C# --working-dir C:\Users\BoksanD\source\repos\IMS --root-namespace IMS.Infrastructure
Using assembly 'IMS.Infrastructure'.
Using startup assembly 'IMS.Persistence'.
Using application base 'C:\Users\BoksanD\source\repos\IMS\Persistence\bin\Debug\netcoreapp3.0'.
Using working directory 'C:\Users\BoksanD\source\repos\IMS\Persistence'.
Using root namespace 'IMS.Infrastructure'.
Using project directory 'C:\Users\BoksanD\source\repos\IMS\Infrastructure\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Found IDesignTimeDbContextFactory implementation 'IMSDbContextFactory'.
Found DbContext 'IMSDbContext'.
Finding application service provider...
Finding Microsoft.Extensions.Hosting service provider...
No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'ApplicationDbContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.MissingMethodException: No parameterless constructor defined for type 'IMS.Infrastructure.Identity.ApplicationDbContext'.
   at System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)
   at System.Activator.CreateInstance(Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

And here is Program.cs
namespace IMS.WebAPI
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var northwindContext = services.GetRequiredService<IMSDbContext>();
                    northwindContext.Database.Migrate();

                    var identityContext = services.GetRequiredService<ApplicationDbContext>();
                    identityContext.Database.Migrate();

                }
                catch (Exception ex)
                {
                    var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred while migrating or initializing the database.");
                }
            }

            host.Run();
        }

        public static IWebHostBuilder CreateHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var env = hostingContext.HostingEnvironment;

                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                    if (env.IsDevelopment())
                    {
                        var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                        if (appAssembly != null)
                        {
                            config.AddUserSecrets(appAssembly, optional: true);
                        }
                    }

                    config.AddEnvironmentVariables();

                    if (args != null)
                    {
                        config.AddCommandLine(args);
                    }
                })
                .ConfigureLogging((hostingContext, logging) =>
                {
                    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                    logging.AddConsole();
                    logging.AddDebug();
                })
                .UseStartup<Startup>();
    }
}


text:
Q: How to resolve generic type with dynamic parameter? I have a generic class like
class EntityDao<T> where T: class
{
    void Update(T entity)
    {
       //Update entity to somewhere.
    }
}

while T might be any classes, like User, Company and etc.
I use Autofac to register EntityDao as Generic Type.
var builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(EntityDao<>));
var container = builder.Build();

In other places, I want to resove it dynamically.
string typeName = "User"; // might be "Company" or any other type name.

switch (typeName)
{
    case "User":
        container.Resolve<EntityDao<User>>().Update(entity);
        break;
    case "Company":
        container.Resolve<EntityDao<Company>>().Update(entity);
        break;
    default:
        break;
}

Here, typeName might have more than 50 values, and I thing there should be a generic way to avoid writing 50 cases.

A: *

*You cannot  have partially opened classes. You can see this question.

*But you can pass a parameter to a register.


text:
Q: How to return JSON data from php MongoCursor I am using PHP to connect with MongoDB. My code is as follows.
// connect
$m = new MongoClient($con_string); // connect to a remote host at a given port
$db = $m->main;

$customers = $db->customer->find();

i want to return $customers collection as json document to my HTML. How can i do this?

A: This also will work. And you can customize your json as well.
    $arr = array();

    foreach($customers as $c)
    {
        $temp = array("name" => $c["name"], "phone" => $c["phone"],
                                            "address" => $c["address"]);
        array_push($arr, $temp);
    }

    echo json_encode($arr);

A: Other answers work, but it is good to know that the generated JSON will have the following form (in this example I use an hypothetical "name" field for your customers):
{
    "5587d2c3cd8348455b26feab": {
        "_id": {
            "$id": "5587d2c3cd8348455b26feab"
        },
        "name": "Robert"
    },
    "5587d2c3cd8348455b26feac": {
        "_id": {
            "$id": "5587d2c3cd8348455b26feac"
        },
        "name": "John"
    }
}

So in case you don't want the Object _id to be the key of each of your result objects you can add a false parameter to iterator_to_array.
Your code would be:
echo json_encode(iterator_to_array($customers, false), true);

This creates the same result as
$result = Array();
foreach ($customers as $entry) {
    array_push($result, $entry);
}
echo json_encode($result, true);

which is an array of JSON objects
[
    {
        "_id": {
            "$id": "5587d2c3cd8348455b26feab"
        },
        "name": "Robert"
    },
    {
        "_id": {
            "$id": "5587d2c3cd8348455b26feac"
        },
        "name": "John"
    }
]

A: You can do this two ways:
echo json_encode(iterator_to_array($customers));

or you can manually scroll through it:
foreach($customers as $k => $row){
    echo json_encode($row);
}

Each of MongoDBs objects should have their __toString() methods correctly implemented to bring back the representation of the value.


text:
Q: Undefined module in angular-meteor tutorial I am trying to follow along with the angular-meteor.com tutorial for Angular 1. I keep getting the following error when trying to convert it to component syntax in step 3
I thought it was a typo somewhere so I tried downloading step 3 from git and still having same error!
modules.js?hash=451e0fb…:755Uncaught Error: [$injector:modulerr] Failed to instantiate module socially due to:
Error: [$injector:modulerr] Failed to instantiate module undefined due to:
Error: [ng:areq] Argument 'module' is not a function, got undefined

A: Had the same issue here, I think it's due to not properly removing the ecmascript package as instructed in Step 0
As soon as I followed the step-by-step instructions on removing and adding the correct packages it worked.


text:
Q: how can i access a value on a cell in tableview from different class? I can hold the value of touched cell but I cannot pass that value to another class or call from that class.
SearchTableViewController.m
**deneme= [[NSMutableArray alloc]init];
deneme=[tableData objectAtIndex:indexPath.row];

NSLog(@"my row = %@", deneme); //I can hold one of the selected or touched rows in table

HistoryTableViewController.m
**SearchTableViewController *obj = (SearchTableViewController *)[self.tabBarController.viewControllers objectAtIndex:11];
NSLog(@"my 2nd row= %@", [obj deneme]); //It doesn't retrieve here

A: I solved that problem estimately few weeks ago. I identified AppDelegate *appdelegate vs vs thing and I call it with writing appdelegate.anything from different ViewController classes.
It was just a piece of cake that I could not recognize for a while .. :(


text:
Q: Return string without vowels in python I want to take a string and print it back without the vowels for Ex: for 'the quick brown fox jumps over the lazy dog', I want to get 'th qck brwn fx jmps vr th lzy dg'.
I have tried using list comprehension, but I am only able to split the sentence into a list of words, I can't further split the words into individual letters in order to remove the vowels. Here's what I've tried:
a = 'the quick brown fox jumps over the lazy dog'
b = a.split()
c = b.split()
d = [x for x in c if (x!="a" or x!="e" or x!= "e" or x!="i" or x!="u")]
e = ' '.join(d)
f = ' '.join(f)
print(f)

A: You won't need to split the original string, since looping through a string in Python iterates through the characters of the string.
Using a list comprehension, you just check if the current character char is a vowel and exclude it in such a case.
Then, at the end, you can join up the string again.
a = 'the quick brown fox jumps over the lazy dog'
s = [char for char in a if char not in ('a', 'e', 'i', 'o', 'u')]
print(''.join(s))
# th qck brwn fx jmps vr th lzy dg

If your sentence may contain uppercase vowels, and wish to filter those out as well, you can do so using str.lower():
s = [char for char in a if char.lower() not in ('a', 'e', 'i', 'o', 'u')]

A: You can follow costaparas answer or also use regexes to remove vowels
import re
se = 'the quick brown fox jumps over the lazy dog'
se = re.sub(r"[aeiouAEIOU]", '', se)

re.sub replaces all occurence of the regex with second string

A: Please do this you will get your answer:-
    vowels = ('a', 'e', 'i', 'o', 'u')
    for x in string.lower():
        if x in vowels:
            string = string.replace(x, "")

    # Print string without vowels
    print(string)

your_string = "the quick brown fox jumps over the lazy dog"
vowel_remove(your_string) ```

I tried and get a result which you can see in given image:-

`developer@developer-x550la:~/MY_PROJECT/Extract-Table-Pdf/extractPdf$ python3 stak.py

th qck brwn fx jmps vr th lzy dg
`

A: Simple one-liner with filter:
>>> s = 'the quick brown fox jumps over the lazy dog'
>>> ''.join(filter(lambda x: x not in 'AEIOUaeiou', s))
'th qck brwn fx jmps vr th lzy dg'

A: vowels = ['a','e','i','o','u', 'A', 'E', 'I', 'O', 'U']

se = 'the quick brown fox jumps over the lazy dog'

for vowel in vowels:
    se = se.replace(vowel,'')

With the replace() method


text:
Q: How does light 'choose' between wave and particle behaviour? Light exhibits wave behaviour in phenomenon such as interference but particle behaviour in the photoelectric effect. How does light 'choose' where to be a wave and where to be a particle?

A:
How does light 'choose' where to be a wave and where to be a particle?

It doesn't. It always behaves as a wave (obeying the principle of superposition), and it always behaves as a particle (particle number being quantized).
It sounds like you may have been influenced by someone who told you that light behaves like a particle in some experiments, and like a wave in others. That's false.

A: Light always behaves as a particle and waves .So there is no particular time when it can behaves like a particle but not wave and vice versa .Thus light carries both of these two nature(particle and wave) along with it (light)for all time.
Actually why is my thinking is like light has two of these nature for all time?
Reasons for considering it as *wave *

*

*James Clerk Maxwell proved that speed of the electromagnetic waves in free space is the same as the speed of light c=2.998 ×10^8m/s. Thereby he concluded that light consists of electromagnetic waves .So it has wave nature for all time.

*Light also shows *interference *,*diffraction *,*polarization *.
And all of these property show that light has wave nature and it is for all time.

Reasons for considering light as particle

*

*Max plank in 1900 introduced concept of quantum of energy .The energy exchange  between radiation and surroundings is in *discrete or *quantised * form i.e energy exchange between electromagnetic waves is integer multiple of (plank constant *frequency of wave ).As light consists of electromagnetic waves then light is made of discrete bits of energy i.e photons with energy (plank constant *frequency of light).
Thereby photoelectric effect ,Compton effect all show the particle nature of light.

So radiation (electromagnetic waves) exhibit particle nature conversely material particles display wave like nature introduced by de Broglie(a moving particle has wave properties associated with it).This is confirmed experimentally by Davisson and Germer they proved that interference which is a property of waves can be obtained by with material particles such as electron.
So as radiation exhibit particle like nature but particles also exhibit
wave- like behavior .Thereby light always shows two type of natures both as waves and particles .

A: The fundamental experiment showing the apparent contradiction is Young's double slit: How can particle characteristics be transmitted when there is only an interfering wave between the point A of emission and point B of absorption?
However, for photons in vacuum (moving at c) there is a simple answer: The spacetime interval between A and B is empty, it is zero! That means that both points A and B are adjacent. A and B may be represented by mass particles (electrons etc.) which are exchanging a momentum. The transmission is direct, without need of any intermediate particle.
In contrast, a spacetime interval cannot be observed by observers. If a light ray is transmitted from Sun to Earth, nobody will see that A (Sun) and B (Earth) are adjacent. Instead, they will observe a space distance of eight light minutes and a time interval of eight minutes, even if the spacetime interval is zero. In this situation, the light wave takes the role of a sort of "placeholder": Light waves are observed to propagate at c (according to the second postulate of special relativity), but this is mere observation.
In short, the particle characteristics may be transmitted without any photon because the spacetime interval is zero. The wave characteristics (including the propagation at c) are observation only.
By the way, for light propagating at a lower speed than c (e.g. light moving through a medium), we need quantum mechanics for the answer.

A: The light doesn't chose. You as an experimenter chose which observable you want to measure, and thus which operator you use. Such measurement will result in a wavefunction collapsing into one of the eigenstates of this operator.
E.g. a positiin operator will give you a position, i.e. particle.
A momentum operator will give you a momentum, i.e. wavelike object.

A: Light is assumed to be particle or wave to describe the observed phenomenon. Light is what it is and doesn't choose. However, one can consider light to be a particle when the interaction is with matter & as a wave when it interacts with itself.

A: It doesn't.
Light, as you may know, is made up of photons, and photons are particles. At the same time, all particles are waves. Yes, that's right—particles are not points or spheres or anything else really solid moving around, but waves, which interact with each other in various ways.
Now, these waves may sometimes behave indistinguishably from points moving around in space, and may therefore be approximated as such—what we like to refer to as point particles—but they are fundamentally still always waves.
So, a photon is always both a wave and a particle; these are not mutually exclusive (in fact, as I have explained now, particles are a subset of waves). This is what is known as the wave–particle duality.

A: It doesn't is the short answer, as it is really neither.  Basically, waves and particles are things you see on the classical scale, they model behaviour on macroscopic scales.
Objects don't behave in a classical way any more when we shrink down to very small scales and they obey very different dynamics which seem strange to us because we do not live on that scale and are only able to access things on that scale in quite a dim way via theory and experiment.  It's kind of common sense when you think about it, just stop expecting that things will behave in a classical way when you going down to those length scales.
Also forgot the wave-particle duality, as it does not even make sense.  It's like a blind person touching an elephant on the trunk and then touching it again on the leg and saying that the elephant follows trunk-leg duality.

A:
How does light 'choose' where to be a wave and where to be a particle?

It doesn't, YOU do. That's really the entire "weirdness" of quantum right there.
It's not entirely crazy. If you measure a car with a scale it will tell you it's 1200 kg, and if you measure it with a spectrometer it will tell you its red. This is perfectly natural.
The thing that makes quantum weird is that you can measure the same thing twice and get two different answers. More weird, some of those measurements are linked to each other so if you measure one the other changes.
Its as if you measured the weight of your car and the length changed. And then you measured the length and the weight changed. This precise thing happens in quantum, for instance, the position and momentum of a particle are linked in this way
In any event, the wave-or-particle nature is entirely up to you. Which nature you see is based on the experiment you use, not the photon itself.
The idea that something you do has this "radical" effect on the outcome is what drives everyone mad in QM.

A: In fact, light is not really a wave or a particle. It is what it is; it's this strange thing that we model as a wave or a particle in order to make sense of its behaviour, depending on the scenario of interest.
At the end of the day, it's the same story with all theories in physics. Planets don't "choose" to follow Newtonian mechanics or general relativity. Instead, we can model their motion as Newtonian if we want to calculate something like where Mars will be in 2 weeks, but need to use general relativity if we want to explain why the atomic clock on a satellite runs slow compared to one on the ground.
Light doesn't "choose" to be a wave or a particle. Instead, we model it as a wave when we want to explain (or calculate) interference, but need to model it as a particle when we want to explain (or calculate) the photoelectric effect.

A: Light always behaves as a wave. Particles can be thought of as a combination of waves, a wave packet. What determines which behavior you'll get is the length scale of the system the light is interacting with and the wavelength of the impinging light.
Suppose you have a series of Bowling Balls suspended in the air making a wall, but with spaces between. Shoot a bunch of 2mm diameter ball bearings (BBs) at the bowling balls. Some will pass through the wall, hitting no bowling balls. Some will hit a ball and bounce in some direction.
Pay close attention to where the BBs come from and their initial speed and where they end up, and you will be able to tell the shape, size, and position of the bowling balls.
Reverse the problem. Have a bunch of suspended BBs in the air and shoot bowling balls at them. Each bowling ball will hit multiple BBs. The outgoing trajectory won't tell you much about the BBs.
Strike a tuning fork, it vibrates, making a characteristic sound. Play that note at high volume, you can set the tuning fork to vibrating. It doesn't start to vibrate at just any wavelength.
To a particle, you can associate the De Broglie wavelength, $h/p$, where $p$ is the momentum. The higher the momentum, the lower the wavelength, the more particle like. Whereas macroscopic but small openings can be used with light in the double slit experiment, you need electron crystallography to demonstrate the same effects with electrons: Electron diffraction
If you have a large wavelength of light, it will interact with multiple particles of a system depending on that system. If the wavelength is sufficiently small, and so the energy sufficiently high, it can interact with a single electron instead of multiple electrons, imparting all its energy to an electron and resulting in the photoelectric effect, a particle-particle scattering effect. Change the wave length and the interaction takes on a more classical form.
In addition to the wavelengths involved you want to pay attention to the number of photons available. The fewer the photons interacting with the system, the more quantum-like it is. The higher the density of photons, the more classical the light will behave. For a more detailed explanation on the barrier between quantum vs. classical behavior, see the intro and first chapter of Griffith's text on electromagnetism.
In short, the behavior you get depends on the De Broglie wavelength of the light/particle, how many particles are inbound and how the lengths scales of the target compare with the De Broglie wavelength.

A: binaryfunt and Ben Crowell's answer is closest to the truth. Let me add a few things.
You get confused because you read sentences like, light behaves as a wave when it travels in space and as a particle when it interferes with matter. That is not true. In reality light has characteristics of both waves and particles at the same time. The truth is, we do not know what actually light is, or what it is really made of.
In reality, light is not what decides or behaves different ways, it is us, the ones preparing the experiments, who decide whether we will select from the observed (both wave or particle like) nature the more interesting wave or particle like characteristics, and analyze those for certain purposes.
What we try to do, is model with our mathematical ways the real phenomenon in our physical world, light itself.
The reason you get confused is because there are two ways to really model this phenomenon:

*

*classical EM waves

*QM particles, photons
You would think they do not match, but that is not true. In reality the two methods come together perfectly, as we build up the classical EM waves from herds of QM photons.
In our currently accepted theory, the Standard Model, we talk about elementary particles, that have no internal structure, nor spatial extent, and we call them point like particles. One of these particles is the photon. We call it the quanta of the EM wave.
It is very important to see that the basic confusion lies in whether you want to analyze the wave or the particle characteristics of light in a certain experiment.
We usually model light in two ways, and that is what confuses you, these to ways are whether it travels or when it interacts with matter. This is basically a misconception, because light could be analyzed to show wave and particles characteristics both when it travels and when it interacts with matter.
It comes from a misconception to choose between travel and interaction, but for the sake of argument, lets see:

*

*travel

You can use Maxwell's original equations or use QFT to treat photons and light as excitation of the EM field, that travels through space, and this propagation is modeled in our theories as a wave. This is because this wave model is what best fits the experimental data. Now we can show that the QM or QFT field excitation model of the photon propagating through space is the same fitting the data perfectly from the experiments.
So you see light has both wave and particle characteristics even as it travels through space.

*interaction with matter

Now when a photon interacts with an atom, three things can happen:

*

*elastic scattering, the photon gives all its energy to the atom and changes angle

*inelastic scattering, the photon gives part of its energy to the atom and changes angle

*absorption, the photon gives all its energy to the absorbing atom/electron
For all three, you can see that light both shows wave and particle characteristics. It is a misconception that the experiments about interaction are about the particle characteristics alone. Even in these three cases, when light interacts with matter, it behaves as a wave, in certain cases it changes angle, goes through slits, splits into partial waves, these partial waves interact with themselves, create interference patterns. Even in the case of absorption, when the photon ceises to exist, and transforms into the kinetic energy of the electron, it shows wave nature and particle both since the absorbing atomic system and electron both have wave and particle characteristics too.
So there is no reason to really make a hard decision whether light would choose, it does not. It has both wave and particle characteristics as intrinsic, and it is up to us who prepare the experiment and analyze the data which we want to focus on.


text:
Q: Build a File Monitoring System I have just started programming and would like to implement a file monitoring system from scratch in C.
I have used the Watch Service API in java but I would like to learn how to build one from scratch. I would really appreciate some assistance and guidance.
Thanks.

A: You can:

*

*either rely on existing system calls that will push you notifications on file system modifications (eg: inotify)

*implement your own kernel module that will intercept file system modification and notify you (if you really want to reimplement the wheel)

*use a polling-approach, rebuild the filesystem tree in-memory and compare it every second or so. This will be very cpu/io/memory consuming, but it can be instructive.


text:
Q: Copy,paste and add row when selected and removed when Delete is selected I just started with vba.I am busy with a parts order sheet

I need, in the top picture, if you click the ADD button it must copy ex. I26 and L26 to the bottom sheet, to D2 and E2. Then it must go down to the next row.
Question 1: if the person has made a mistake can you code the "REMOVE" button to delete that specific row?
Question 2: is it possible to code the control button to change fill colour when it is selected?


text:
Q: Mass conservation I am trying to prove that
$$\frac{d}{dt}\int_{a(t)}^{b(t)} \rho(x, t)g(x, t)dx = \int_{a(t)}^{b(t)} \rho(x, t)\frac{D}{Dt}g(x, t)dx$$
I have tried to evaluate the integral using Liebniz' rule, so that
$$\frac{d}{dt}\int_{a(t)}^{b(t)} \rho(x, t)g(x, t)dx = \int_{a(t)}^{b(t)}\left[\rho(x, t)g(x, t)\right]_t \,dx$$
but am unsure if the rule can be applied in this manner. Would I then apply some manner of multivariate product rule?
Any help much appreciated,
Will

A: This is reynolds transport theorem. You are missing alot of assumptions here.

A: You can apply the chain rule to the fundamental theorem of calculus.  You get $$\frac{d}{dt}\int_{a(t)}^{b(t)} \rho(x, t)g(x, t)dx = \frac {db(t)}{dt}\rho(x, t)g(x, t)-\frac {da(t)}{dt}\rho(x, t)g(x, t)$$  Maybe that helps.


text:
Q: Ionic 6 - ngIf or ngSwitch inside the for loop with dynamically populated values I am new to angular and I am trying to solver for the following.  Spent almost 3 hours going through docs and YouTube videos but no luck.
Use Case - Change the button color based on the status coming form a data feed.
For example: Button is blue if the feed.status  is Open.  It is green if feed.status is closed and it is red if feed.status is paused.
Inside my component.ts file -

   feedData: any;
   show="Open";

..... more code that completes the component implementation

In my component.html file
  <ion-card *ngFor="let feed of feedData">
   <div *ngIf="show == feed.status">
    <ion-item lines="none">
       <ion-button slot="start" color="red">{{ feed.status }}</ion-button>
    </ion-item>
   </div>
  </ion-card>

The code above doesn't work.  What i really need to do is change the color based on the value stored in feed.status.   How do I go about it?

A: Following is the code
HTML
  <ion-list>
    <ion-item
      *ngFor="let f of feeds"
      [ngClass]="{
        'open-status': f.status == 'Open',
        'closed-status': f.status == 'Closed',
        'paused-status': f.status == 'Paused'
      }"
    >
      <div>{{ f.label }}</div>
    </ion-item>
  </ion-list>

CSS
.open-status{
  color:blue;
}
.closed-status{
  color: green;
}
.paused-status{
  color: red;
}

COMPONENT
import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {

  feeds = [
    {
      label: 'Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,', status: 'Open'
    },
    {
      label: 'Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,', status: 'Closed'
    },
    {
      label: 'Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,', status: 'Paused'
    },
    {
      label: 'Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,', status: 'Open'
    },
  ]

}

A: The important part of Nathash Kumar's answer is the [ngClass].
If we take your code:
<ion-card *ngFor="let feed of feedData">
   <div *ngIf="show == feed.status">
    <ion-item lines="none">
       <ion-button slot="start" [ngClass]="{
    'open-status': f.status == 'Open',
    'closed-status': f.status == 'Closed',
    'paused-status': f.status == 'Paused'
  }">{{ feed.status }}</ion-button>
    </ion-item>
   </div>
  </ion-card>

What does ngClass do? It adds the class to the button depending on the f.status value. You can access it afterwards via css and change everything needed there.
Another tip, use enums if you reuse that status more often, so you do not get in trouble with spelling mistakes.
export enum FeedStatus {
  OPEN = 'Open',
  CLOSED = 'Closed',
  PAUSED = 'Paused',
}

Than you can import it in your component file like that:
public feedStatus: typeof FeedStatus = FeedStatus;

afterwards you can access it in html via
...f.status == feedStatus.OPEN

Check https://www.vitamindev.com/angular/how-to-use-enum-in-html/ for more informations regarding the use of enums in your template.

A: ngSwitch is the right solution for this scenario.
<ion-card *ngFor="let feed of feedData" [ngSwitch]="feed.status" [routerLink]="[feed.id]">
  <ion-item lines="none">
    <div *ngSwitchCase="'Open'">
       <ion-button slot="start" color="success">{{ feed.status }}</ion-button>
    </div>
    <div *ngSwitchCase="'Close'">
       <ion-button slot="start" color="danger">{{ feed.status }}</ion-button>
    </div>
    <div *ngSwitchDefault>
       <ion-button slot="start" color="primary">{{ feed.status }}</ion-button>
    </div>
  </ion-item>
</ion-card>


text:
Q: How do I specify a multi-column index with Fluent NHibernate The goal here is have my complete database configuration and schema generation handled by fluent nhibernate.
Is there a way to to specify a multi-column index with Fluent nhibernate?
I understand that you can specify an index on a single property/column
like so :
mapping.Map(x => x.ItemDt).Index("IX_DataTransferLog_ItemDt");

how can I specify multiple columns?
If that isn't possible, is there a way to add raw SQL statements to a configuration that will be run after the schema is created/updated ?

A: In XML-mappings this can be achieved by adding index with same name to all the properties that needs to be in the index:
<property name="Name" index="MyIndex" />
<property name="RunTimeInMinutes" index="MyIndex" />

Unfortunately I do not have any project currently using Fluent NHibernate that I could test this on, but I think this works in Fluent NHibernate the same way:
mapping.Map(x => x.Name).Index("MyIndex");
mapping.Map(x => x.RunTimeInMinutes).Index("MyIndex");

If this doesn't work, you can add the raw SQL required to create the index in database-object in mapping. NHibernate will execute the SQL when database is created using SchemaExport. I don't know if there is Fluent version for mapping database-objects but you can map database-object using XML and add the mapping file to Fluent NHibernate's configuration.


text:
Q: I cant'g get virtualenvwrapper to inbstall on Ubuntu where it needs to be I have followed the instructions to the letter on the website.  The problem is inconsistency where things end up.  When I type:
which virtualenv

I get back
/usr/local/bin/virtualenv

which looks OK to me (I am not a unix expert).  But after doing
pip install virtualenvironmentwrapper

I get this:
Requirement already satisfied: virtualenvwrapper in /usr/local/lib/python2.7/dist-packages
Requirement already satisfied: virtualenv-clone in /usr/local/lib/python2.7/dist-packages (from virtualenvwrapper)
Requirement already satisfied: stevedore in /usr/local/lib/python2.7/dist-packages (from virtualenvwrapper)
Requirement already satisfied: virtualenv in /usr/local/lib/python2.7/dist-packages (from virtualenvwrapper)
Requirement already satisfied: pbr!=2.1.0,>=2.0.0 in /usr/local/lib/python2.7/dist-packages (from stevedore->virtualenvwrapper)
Requirement already satisfied: six>=1.9.0 in ./.local/lib/python2.7/site-packages (from stevedore->virtualenvwrapper)

What do you do to fix this?

A: It rurns out warpper is not that much more useful.  However, the original problem was never resolved.


text:
Q: Is it possible to substitute an HTML image with one from CSS? I'm wondering if it is possible to substitute an HTML image for one from CSS inside of a media query. When the width is 100% the images that are generally small get a little fuzzy. I know how to insert images via CSS, but I'm very new to learning responsive development. If it is possible, how would you accomplish this? Thank you all I really appreciate it.

A: Actually, it's done with HTML. Use the <picture> element. You can specify media query for determining which image to load:
<picture>
 <source srcset="mdn-logo-wide.png" media="(min-width: 600px)">
 <img src="mdn-logo-narrow.png" alt="MDN">
</picture>


text:
Q: How to make layouts show in below image in flutter? How to make this circle avatar in random position?
This my code.
I use stack inside container. Also use circle avatar inside stack and positioned widgets.
//main.dart
import 'package:application/start.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    initialRoute: '/',
    routes: {
      '/': (context) => Start(),
    },
  ));
}

//start.dart
import 'package:flutter/material.dart';

class Start extends StatefulWidget {
  @override
  _StartState createState() => _StartState();
}

class _StartState extends State<Start> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        child: AppBar(
          backgroundColor: Colors.blue,
        ),
        preferredSize: Size.fromHeight(
          5,
        ),
      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              child: Container(
                // color: Colors.purple,
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      child: CircleAvatar(
                        radius: 30,
                        backgroundColor: Colors.black,
                      ),
                      top: 10,
                      left: 50,
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: Container(
                color: Colors.red,
              ),
            ),
            Expanded(
              flex: 2,
              child: Container(
                color: Colors.green,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

It's work for make layout like show in image

A: You can use Random from dart:math to generate random numbers. Then you can use the LayoutBuilder widget to find out how much room you have. Finally, you can use the Positioned widget to position widgets exactly where you want them, in this case at your random coordinates.
Please note that I don't know the purpose of your randomness. You may want to make this a StatefulWidget and keep your random numbers between calls to build so when your state of the app changes, your random avatars stay where they are. Or maybe not. It's your choice.

import 'dart:math';

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  final random = Random();
  final avatarSize = 50.0;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: LayoutBuilder(builder: (context, constraints) {
      return Stack(
        children:[
          new Positioned(
            left: avatarSize + (constraints.biggest.width - 2 * avatarSize ) / 100.0 * random.nextInt(100),
            top: avatarSize + (constraints.biggest.height - 2 * avatarSize ) / 100.0 * random.nextInt(100),
            child: new CircleAvatar(
              radius: avatarSize / 2,
              child: new Text('1'),
              backgroundColor: Colors.yellow,
            )
        ),
        new Positioned(
          left: avatarSize + (constraints.biggest.width - 2 * avatarSize ) / 100.0 * random.nextInt(100),
          top: avatarSize + (constraints.biggest.height - 2 * avatarSize ) / 100.0 * random.nextInt(100),
          child: new CircleAvatar(
            radius: avatarSize / 2,
            child: new Text('2'),
            backgroundColor: Colors.red,
          )
        ),
        new Positioned(
          left: avatarSize + (constraints.biggest.width - 2 * avatarSize ) / 100.0 * random.nextInt(100),
          top: avatarSize + (constraints.biggest.height - 2 * avatarSize ) / 100.0 * random.nextInt(100),
          child: new CircleAvatar(
            radius: avatarSize / 2,
            child: new Text('3'),
            backgroundColor: Colors.blue,
          )
        ),
      ]);
  }));
  }
}


text:
Q: Adding a voice output to the python project i want to improve this project, i shared the link of it down below.
In the link that i shared i want to improve the project where i want to add a voice output when the digit gets recognised for example in the screnshots shown there are the numbers 1, 7 after the numbers gets recognised by the program i want the voice output to say 1 or 7 or something this way.
https://github.com/rkshiyaniya/Multiple-Handwritten-Digit-Recognition


text:
Q: MySQL LIKE IN() and using AND I am trying to condense the below query which could have unlimited options based on a web form field.  Users can input as many title keywords separated by commas.  So my query would be constructed like the below with unlimited arguments:
"SELECT title FROM titles WHERE
 title LIKE '%blue%'
 AND
 title like '%red%'
 AND
 title like '%green%'
 AND
 title like '%yellow%'
 ...";

Looking at this link, MySQL LIKE IN()?, it shows a good example of using regular expression, but it is using "OR".
SELECT * from fiberbox where field REGEXP '1740|1938|1940';

What is the equivalent of using "AND"?  For example, in quasi-SQL:
SELECT * from titles WHERE title REGEXP 'blue && red && green && yellow';

A: AND is a bit more difficult to do with regexes, and it doesn't seem to be possible with MySQL's limited regular expression syntax.  If you are using the myISAM engine or MySQL 5.6, you can use the MATCH() function to get most of what you want:
SELECT title FROM titles WHERE MATCH (title)
AGAINST ('+red* +green* +yellow*' IN BOOLEAN MODE);

However, I would recommend sticking to your simple chaining of ANDs.  It's less fragile, more powerful, and easier to code.


text:
Q: Apache Virtual Host error Before I begin to explain my issue, it's worth noting that my DNS records are setup correctly.
This is a weird error, I have a server with the ip: 82.4.165.27 hosting several virtual directories. I'm using Apache2.
My http://test.chorkley.co.uk/ url is usually setup to forward to https://test.chorkley.co.uk. That works. At the moment it simply loads the expected webpage.
So the http://test.chorkley.co.uk/ url works as expected, however the https://test.chorkley.co.uk/ does not. It incorrectly loads https://home.chorkley.co.uk/.
For some reason, the apache server doesn't recognise the *:443 version of the https://test.chorkley.co.uk/ site.
apache2ctl -S Output:
[Sat Apr 11 03:31:29.843972 2015] [core:error] [pid 11925] (EAI 2)Name or service not known: AH00547: Could not resolve host name *443 -- ignoring!
VirtualHost configuration:
*:443                  is a NameVirtualHost
         default server home.chorkley.co.uk (/etc/apache2/sites-enabled/default.conf:6)
         port 443 namevhost home.chorkley.co.uk (/etc/apache2/sites-enabled/default.conf:6)
         port 443 namevhost cloud.chorkley.co.uk (/etc/apache2/sites-enabled/default.conf:20)
*:80                   is a NameVirtualHost
         default server home.chorkley.co.uk (/etc/apache2/sites-enabled/default.conf:1)
         port 80 namevhost home.chorkley.co.uk (/etc/apache2/sites-enabled/default.conf:1)
         port 80 namevhost cloud.chorkley.co.uk (/etc/apache2/sites-enabled/default.conf:15)
         port 80 namevhost test.chorkley.co.uk (/etc/apache2/sites-enabled/default.conf:29)
         port 80 namevhost vb.chorkley.co.uk (/etc/apache2/sites-enabled/default.conf:44)
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex default: dir="/var/lock/apache2" mechanism=fcntl
Mutex mpm-accept: using_defaults
Mutex watchdog-callback: using_defaults
Mutex ssl-stapling: using_defaults
Mutex ssl-cache: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="steven" id=1000 not_used
Group: name="www-data" id=33 not_used

My file:
<VirtualHost *:80>
        ServerName home.chorkley.co.uk
        ServerAdmin admin@chorkley.co.uk
        Redirect permanent / https://home.chorkley.co.uk/
</VirtualHost>
<VirtualHost *:443>
        ServerName home.chorkley.co.uk
        ServerAdmin admin@chorkley.co.uk
        DocumentRoot /var/www/home.chorkley.co.uk
        SSLCertificateFile /home/steven/.ssl/home.chorkley.co.uk.crt
        SSLCertificateKeyFile /home/steven/.ssl/home.chorkley.co.uk.key
        SSLCertificateChainFile /home/steven/.ssl/sub.class1.server.ca.pem
</VirtualHost>

<VirtualHost *:80>
        ServerName test.chorkley.co.uk
        ServerAdmin admin@chorkley.co.uk
        DocumentRoot /var/www/test.chorkley.co.uk
        #Redirect permanent / https://test.chorkley.co.uk/
</VirtualHost>
<VirtualHost *443>
        ServerName test.chorkley.co.uk
        ServerAdmin admin@chorkley.co.uk
        DocumentRoot /var/www/test.chorkley.co.uk
        SSLCertificateFile /home/steven/.ssl/test.chorkley.co.uk.crt
        SSLCertificateKeyFile /home/steven/.ssl/test.chorkley.co.uk.key
        SSLCertificateChainFile /home/steven/.ssl/sub.class1.server.ca.pem
</VirtualHost>

A:
For some reason, the apache server doesn't recognise the *:443 version of the https://test.chorkley.co.uk/ site.

You need to change
 <VirtualHost *443>

to:
 <VirtualHost *:443>

in the vhost for test.chorkley.co.uk
(notice the missing colon in your config)


text:
Q: Handle google date strings and increment them I am using the google analytics api and it needs strings of dates (i.e. "2013-03-01") for start and end dates.
I will run queries in a loop where it pools each day and then increments it (i.e. start date in round 1 is "2013-03-01" and end date is the same, then in the second round the date is "2013-03-02").
Now the question is how can I have the string change to that? I was thinking some ubercomplicated way of using charAt() and checking if it is <30 and then convert it to a int, +1 and then toString() it again.
is there an easier way?

A: Simply use SimpleDateFormat and Calendar. Here's an example:
public static void main(final String[] args)
        throws UnsupportedEncodingException, ParseException {
    final String dateString = "2013-03-01";
    final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    final Date date = formatter.parse(dateString);
    final Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.add(Calendar.DAY_OF_MONTH, 1);
    System.out.println(formatter.format(c.getTime()));
}


text:
Q: facebook connect in symfony2 how do it? I would like on my website to allow logging in via facebook connect.
But I do not want to use FOSUserBundle
I already have an authentication database, which I did like in this link http://symfony.com/doc/2.0/cookbook/security/entity_provider.html
Creating a login through facebook connect I can only do what is in that link?
http://symfony.com/doc/2.0/cookbook/security/custom_provider.html
do I have to do it this way?
http://symfony.com/doc/2.0/cookbook/security/custom_authentication_provider.html
How do I implements this method: function loadUserByUsername ($ username)?

A: As @meze mentioned you can either use the FOSFacebookBundle or if you want to implement it yourself you can use KnpOAuthBundle


text:
Q: Jquery scrollto animation to specific coordinates So I'm trying to get a link to scroll to a certain coordinate (not an element) on the same page very slowly. I tried to look at the Jquery site but it seems the plugin site is down.
Can anyone supply a link embedded in an html sample source code as I don't know much about jquery.
This is the link for the plugin

A: Hi you dont need a plugin for that.. it might save you some overhead... please try this, i hope it adresses your issue
assuming you have the following link
click me

add the following code
$(document).ready(function(){
  $('a#button').bind('click', function(event){
    $('html,body').animate({
      scrollTop: '100'
    });
    event.preventDefault();
  });
});


text:
Q: Partitioning the vertices of an n-cube with random hyperplane cuts An evolutionary biologist asked me a question which boils down, at least in part, to what seems to me an interesting question of combinatorial/probabilistic geometry.
It is an old chestnut of a problem to ask:  into how many pieces can an n-sphere be cut by k hyperplanes?  (Here I want the hyperplanes to be honest linear subspaces, not affine ones as in the classical "lazy caterer" problem, but the flavor is much the same.)
Now suppose that instead of the sphere, I have the 2^n vertices of the n-cube, i.e. the set {-1,1}^n.  I cut this set with k random hyperplanes.  Now I have a partition of 2^n.
What do I expect this partition to look like?  E.G. how many blocks are there?  How big is the largest blocks?  Are the biggest blocks "close to each other" in the sense that you can pass from one to the other without crossing very many of the hyperplanes?  (To formalize this, one might say that the structure one is studying isn't just a partition, but a partition in which each block is identified with an element of (Z/2Z)^k, thus providing a notion of Hamming distance between block.)
I have asked this question in a rather vague way by not specifying what range of k relative to n is in play.  This should actually be considered part of the question:  what are the threshold curves in the (n,k) plane, if any, where the partition sharply changes its expected nature?  My biologist friend is certainly interested mostly in the case k > n; I think he's most interested in the case where k is bounded between n and a constant multiple of n, but I'm not sure.  I expect he would be interested to know, for instance, how big k needs to be before all blocks of the partition are singletons almost surely.
Further remarks:  though I don't think this is relevant to MBF, one could certainly pass from a discrete to a continuous setting and ask about the statistics of the partition of the volume of the unit (n-1)-sphere by the k hyperplane cuts, which would also be interesting.  Or, instead of letting the cuts be chosen randomly from a continuous distribution, you could let them be chosen from the vertices of a cube in the dual R^n; in other words, you could choose at random from hyperplanes of the form x_1 +- x_2 +- ... +-x_n.  This last version is probably closest to what MBF is actually thinking about.
Update:  A couple of people asked about the biological context.  Here's the original paper.
http://www.ploscompbiol.org/article/info%3Adoi%2F10.1371%2Fjournal.pcbi.1000202

A: I corrected an earlier version which assumed that only adjacent vertices need to be separated to guarantee the parts are singletons, which fedja pointed out was incorrect. Thanks.
Here is a partial answer to the question of how many cuts it takes before the nonempty pieces are singletons with high probability when the hyperplanes are chosen uniformly. Consider the roughly $4^n$ pairs of vertices of the cube. Each pair is separated by a hyperplane iff the partition separates all vertices. The expected number of pairs which intersect no hyperplane is at most $4^n$ times the probability that a particular edge is missed, since adjacent vertices are the least likely to be separated. The probability that none of the $k$ hyperplanes intersects an edge is $p^k$, where $p$ is the probability that each hyperplane misses the edge.
What does it take for a hyperplane to separate two adjacent vertices? These points determine a great circle, and are at angle $\arccos \frac{n-2}{n} \approx \frac{2}{\sqrt n}$. The hyperplane almost surely intersects this circle in two antipodal points. If these intersect the arc of about $\frac{2}{\sqrt n}$ radians, then the hyperplane intersects the edge. So, the probability that a random hyperplane intersects an edge is about $\frac{2}{\pi\sqrt n}$. The probability the edge is missed is the complement, about $1- \frac{2}{\pi\sqrt n}$. The probability all $k$ hyperplanes miss this edge is about $(1- \frac{2}{\pi\sqrt n})^k \approx \exp(-\frac{2k}{\pi\sqrt n})$. The expected number of pairs not separated by any hyperplane is at most about $4^n \exp(-\frac{2k}{\pi\sqrt n})$.
If you choose $k\approx c n^{3/2}$ then the expected number of pairs not separated by any hyperplane is at most $1$. For much larger $k$ the expected number of pairs of vertices in the same part, hence the probability that two vertices are in the same part, becomes small.


text:
Q: Dimension of the range of an operator and its adjoint
Proof for $\dim(R(T))=\dim(R(T^{*}))$ for a linear operator in a Hilbert space. $T$ is the operator and $T^{*}$ is its adjoint.

I would like to know about the authenticity of the following line of proof of the above fact and get directed to a reference which uses provides this line of proof (if at all it is correct).
Here goes:
Proof: From rank nullity theorem $\dim(T)+\dim(\ker(T))=\dim(V)$, where $T:V \to W$.
       From the fact that $\ker(T)$ and $\dim(T^{*})$ are orthogonal complements, and the fact that $\ker(T)$ is a subspace of $V$,
        $\dim(T^{*})+\dim(\ker(T))=\dim(V)$.
Thus, $\dim(T^{*})+\dim(\ker(T))=\dim(T)+\dim(\ker(T))$. $\dim(\ker(T))$ cancels out and we are left with,
$\dim(T^{*})=\dim(T)$...Q.E.D.


text:
Q: Android - when should i convert dp to pixel I have a custom action bar which i want a 80ish! height for it.
so i set my layouts height as 80dp with this code:
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    xdpi = displayMetrics.xdpi;
x = Math.round(80 * (xdpi / DisplayMetrics.DENSITY_DEFAULT))
... new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, x);

but its HUGE in xxxhdpi devices.
when i remove the conversion and use 80pixels value directly, it seems ok,
When to use converted dp and when to use direct pixel?
Edit:
the problem was somewhere else, i stored the "80dp" value in xml and retrieve it with "context.getResources().getDimension()", and it seems it converts the dimension to pixel internally and i was actually converting the converted value! I wonder if the same thing happens when using "sp" for fonts....

A: You're doing the right thing it's just your conversion is wrong, it should be something like this:
float scale = context.getResources().getDisplayMetrics().density;
x = Math.round(80 * scale);
... new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, x);

A: Convert dp to pixel:
public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    return px;
}

Convert pixel to dp:
public int pxToDp(int px) {
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    return dp;
}

A: Pixel to Dp converter
public static float pxToDp(float px) {
        float densityDpi = Resources.getSystem().getDisplayMetrics().densityDpi;
        return px / (densityDpi / 160f);
    }

Dp to Pixel converter
 public static int dpToPx(int dp) {
        float density = Resources.getSystem().getDisplayMetrics().density;
        return Math.round(dp * density);
    }


text:
Q: Auth0 Single Sign On between Android app and wordpress website We have implemented Auth0 and Lock on a native Android app and a wordpress website ( using the auth0 plugin )
For this puprose, two different clients have been created and the option "Use Auth0 instead of the IdP to do Single Sign On" is enabled.
The connections we use are database-username-password and facebook.
I am trying to find a way to the following:

*

*The user logs in to the Android app, either with username/password or
facebook login.

*From within the app she clicks on a link that opens
the default mobile browser ( not a webview ) and takes him to the
wordpress website.

*The user is now at the wordpress website within her mobile browser ( e.g. chrome ). Since the user has already logged in to the android app and SSO is enabled we need to automatically log her in to the website without having to enter the username/password or login to facebook ( we assume that the mobile user will not be logged in to facebook on his browser )

I have read several Auth0 SSO examples like this but everything refers to apps running on the browser ( where cookies are set and can be checked by the auth0 domain ).
I would like to know if the above scenario or a close alternative is possible and which Auth0 features I will need.


text:
Q: Is there an Enum type in PySpark? I just wondered if there is an EnumType in PySpark/Spark.
I want to add constraints on StringTypes (or other types as well) to have certain values only in my DataFrame's schema.


text:
Q: Nginx match multiple paths in location directive I have the following directives in my nginx conf, that are working correctly:
location = /favicon.ico {
    root /home/www/myapp/static/ico;
}

location ^~ /apple-touch-icon  {
    root /home/www/myapp/static/ico;
}

I would to merge those expression in one directive but I cant figure out how to correctly build the regex. I tried the following but it works only for favicon.ico and I get 404 requesting /apple-touch-icon-precomposed.png
location ~* ^/(apple-touch-icon(.)*\.png|favicon.ico) {
    root /home/www/myapp/static/ico;
}

It is a problem of what is matched I think.

A: Your regex works fine on my server. Maybe the file /home/www/myapp/static/ico/apple-touch-icon-precomposed.png just doesn't exist ?
P.S. The exact translation of your old rules into a regex is:
^/(apple-touch-icon|favicon.ico$)

P.P.S. If you have no other .png and .ico images at the top-level you could use:
^/[^/]+\.(png|ico)$