CALayer transforming

Question: I need to rotate a square when the user does a UIRotationGesture.
I have the gesture all set up. The problem is every time the user moves their fingers the square returns to the starting position and then animates to the new position. Rather than move from the previous position to the new position.
i.e if the rotation of the square is 90 degrees and the user continues to rotate to 100. the square will go back to 0 degrees and animate to 100.
Essentially I want the square to mirror the user when they perform a rotate gesture.
- (void)respondToGesture:(UIRotationGestureRecognizer *)rec{

NSLog(@"Rotation: %f", rec.rotation);

[self rotateWithRadian:rec.rotation];

if (rec.state == UIGestureRecognizerStateEnded) {
    NSLog(@"gesture ended");
}

}

- (void)rotateWithRadian:(float)radian{

CABasicAnimation *spin = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];

spin.removedOnCompletion = NO;

spin.fillMode = kCAFillModeForwards;

[spin setByValue:[NSNumber numberWithFloat:radian]];

[spin setDuration:1.0];

[squarelayer addAnimation:spin forKey:@"spinAnimation"];

Answer: Is there a reason you're not directly setting the layer's transform instead of using an animation?
This should do what you want:
- (void)respondToGesture:(UIRotationGestureRecognizer *)rec {
    if (rec.state == UIGestureRecognizerStateChanged) {
        CGAffineTransform currentTransform = squareLayer.affineTransform;
        squareLayer.affineTransform = CGAffineTransformRotate(currentTransform, gesture.rotation);
        gesture.rotation = 0;
    }
}

You also need to adjust squareLayer.anchorPoint if you want the rotation to happen around the centre of the user's rotation instead of the centre of the layer.
Comment: Spot on Works perfect Cheers!
Answer: There is a open source ( https://github.com/kirbyt/KTOneFingerRotationGestureRecognizer )for single finger rotation. You can check it out, will be much better. Even if you want only normal rotation gesture, you can look into the code for better rotation code. It uses center as origin.

CALayer transforming


Triggering submit button using session variable

Question: I am passing a Boolean value from one page to another using session variables in PHP , the second page is meant to display results if the form is submitted , I want to trigger the submit button if the Boolean is true and display results automatically ,(echo) but if false the page should show up as its meant to. As I'm new here, please help! Also, I am not familiar with Ajax.
Thanks
 <?php
session_start();
if(isset($_SESSION['answer'])) {

 $v11=$_SESSION['answer'];//boolean value
 }

 $q=100;
 $f=200;
 $r=300;

  ?>
  <link rel="stylesheet" type="text/css" href="../../styles/messages.css"             />

<form action=""  name = "page0" method="GET" enctype="multipart/form-    data">

   ID

  NAME
  MACH

 <input type="text" name="ID" class="rw" value="<?php       $phpvar=$v11; echo $phpvar; ?>">
 <input type="text"  name="NAME" class="rw" size="30" value="<?php $phpvar=$f; echo $phpvar; ?>">
 <input type="text"  name="MACH" class="rw" size="70"    value="<?php $phpvar=$r; echo $phpvar; ?>">

 <input type="submit" button class="button" value="Calculate" name="second_call" onclick= "document.write('<?php hello(); ?>');"  />
</form>

  <?php
 function  hello()
  {
  //some operation using values q, f, r
  echo(result);
  //i want this echo to work when i click submit on the previous page   from       where im redirecting here if v11=true
 }

 ?>

Comment: Could you post a sample of your code ?
Answer: It's very hard to get what you want to do without any code.
If you want a page to 'echo' something if Session Variable is 'true'
and display the page contents if it's not, i'd suggest the following most simple way :
    <?php

$session_value = $_SESSION["mySessionVariable"];

if { $session_value ) {
    // echo something
}else {
    // include the php file with the "normal" page
}

?>

Comment: there are some calculations happening on the redirected page which happens only when the submit button is triggered , the output of the redirected page is to be echoed!


android: transfer sqlite database from pc to device via usb programatically

Question: The situation is this. I have an application written in vb.net. it consists or two parts. One on a PC and the other on a handheld windows mobile 6 device . The desktop program transfers a SQLServer compact database to and from the handheld device using activesync via USB. Potentially we want to look into having android handheld devices also supported by this application. Now I know I can use SQLite with .net. I know I can use ADB to push and pull data (and therefore the database files) to and from the device.
What I need to know is can I access ADB directly from VB.NET as an API or SDK rather than having to do it manually.
Unless of course I'm missing something and I can copy databases to and from the device in some other way?
thanks in anticipation
Comment: the phone would need root access for you to be able to copy anything from the data folder via ADB.
Comment: @schwiz: the db doesn't need to be in the data folder, can be anywhere, i.e. pushed and pulled on the sdcard. We use the same mechanism, syncing content via desktop sync app (java swing) via adb to the device.
Comment: For anybody with similar scenario, check this solution
http://stackoverflow.com/a/18288471/2691890
Answer: There's no direct API for that. We have a similar scenario, where the user syncs content (i.e. also the database) from a desktop client (in our case Java Swing based), which utilized adb manually and it's working fine so far.
In our java client, we'd call:
private static final String ADB_PUSH = "\"" + Utility.getWorkDir() + File.separator + "adb\" -s %s push \"%s\" %s";

/**
 * Pushes a file to a connected device via ADB
 * @param deviceId Device serial number
 * @param from Path of source file (on PC)
 * @param to Path of file destination (on device)
 */
public static void push(String deviceId, String from, String to) {
    try {
        String cmd = String.format(ADB_PUSH, deviceId, from, to);
        System.out.println("adb push: " + cmd);
        Process p = Runtime.getRuntime().exec(cmd);
        InputStream is = p.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);

        String line;
        while ((line = br.readLine()) != null) {
            System.out.println("adb: " + line);
        }
    } catch (IOException e) {
        System.out.println(e);
    }
}

Comment: Hi Mathias, that sounds perfect. All I have to do now is decifer the Java code as the only Java I have done up until now is the little android I've been teaching myself. This is good news though and once I've understood your code I will see if I can make it work with .net
Answer: I think the easier way for your VB.Net application to move the database to the phone is to write or copy the sqlite-file to a (configurable) directory on a mounted phone volume (e.g. the phone's sd-card).
The Android application can then use methods like SQLiteDatabase.openDatabase with the same path to open and work with the transferred database.
Comment: Hi Josef and thanks for the answer. I have thought of that approach. I need it to mimic the process of the windows version where you simply say in the desktop program that you want to download data or upload all the data from the android device. I want to avoid putting the android device in a specific mode and have to locate the drive letter it sets up on connection to the PC. Simply plug it in and transfer data without the guy doing it needing to do any other setup is what I'm aiming for. So it's pretty much plug and play. I dont know if this is possible but I need to get as close as I can.


How to show that $\frac{f}{g}$ is measurable

Question: Here is my attempt to show that $\frac{f}{g}~,g\neq 0$ is a measurable function, if $f$ and $g$ are measurable function. I'd be happy if someone could look if it's okay.
Since $fg$ is measurable, it is enough to show that $\frac{1}{g}$ is measurable.
$$
\left\{x\;\left|\;\frac{1}{g}\lt \alpha \right\}\right.=\left\{x\;\left|\;g \gt \frac{1}{\alpha} \right\}\right., \qquad g\gt 0,\quad \alpha \in \mathbb{R},$$
which is measurable, since the right hand side is measurable.
Also, $$
\left\{x\;\left|\;\frac{1}{g}\lt \alpha \right\}\right.= \left\{x\;\left|\;g\lt\frac{1}{\alpha} \right\}\right.,\qquad g\lt 0,\quad \alpha \in \mathbb{R},$$ which is measurable since the right hand side is measurable.
 Therefore, $\frac{1}{g}$ is measurable, and so $\frac{f}{g}$ is measurable.
Comment: That is essentially correct, but you may want to first "throw out" the points where $g(x)=0$ explicitly; also, your equalities are not quite correct as stated, it would be better to write something like $$\left\{x\left| \frac{1}{g}\lt\alpha\right\}\right. = \left\{x\left| g\gt\frac{1}{\alpha}\text{ and }g\gt 0\right\}\right. \cup \left\{x\left|g\lt \frac{1}{\alpha}\text{ and }g\lt 0\right\}\right.$$instead.
Answer: Using the fact that $fg$ is a measurable function and in view of the identity $$\frac{f}{g}=f\frac{1}{g}$$ it suffices to show that $1/g$ (with $g\not=0$) is measurable on $E$. Indeed, $$E\left(\frac{1}{g}<\alpha\right)=\left\{\begin{array}{lll} E\left(g<0\right) & \quad\text{if }\alpha=0\\ E\left(g>1/\alpha\right)\cup E\left(g<0\right) & \quad\text{if }\alpha>0\\ E\left(g>1/\alpha\right)\cap E\left(g<0\right) & \quad\text{if }\alpha<0 \end{array}\right.$$ Hence, $f/g$ ($g$ vanishing nowhere on $E$) is a measurable function on $E$.
For a better understanding of what is going on, I suggest to plot the function.
Answer: The function $h(x)=\frac{1}{x}$ is continuous so is Borel measurable, and $\frac{f}{g}$ is just $f(h\circ g)$.
Answer: As you said, it suffices to show that $\dfrac{1}{g}$ is measurable.
Set $h(x)=\frac{1}{g(x)}$ if $g(x) \neq 0$ and $h(x)=0$ if $g(x)=0$
Let $a=0$ and $B=\{g=0\}$
Then $\{h>0\}=  \{x:\frac{1}{g(x)}>0\} \cap B^c$
If $a>0$ then $\{h>a\}=B^c \cap \{x:\frac{1}{g(x)}>a\}$
If $a<0$ then $\{h>a\}=(B^c \cap \{x:\frac{1}{g(x)}>a\} )\cup B$
In either case the sets are measurable because $g$ is measurable.


Android reboot command - Who calls reboot_main()?

Question: I am looking at the source for the android shell reboot command.
int reboot_main(int argc, char *argv[])

What I am not clear about is if this is a standalone binary, who calls reboot_main() ?
In a standard glibc linked binary, I was expecting to find a "main()" as the entry point for the program.

What am I missing here, could someone help me understand what is going on ?
Thanks,
vj
Answer: They are all compiled into one overall executable, with main in https://android.googlesource.com/platform/system/core.git/+/android-4.2.2_r1/toolbox/toolbox.c
Then, based on the actual program name invoked (usually argv[0]) it calls the appropriate method.
The commands are part of the build via the
#define TOOL(name) int name##_main(int, char**);

macro in toolbox.c which is used in the Android.mk file to generate tools.h.


How can i get prepared for DRUPAL-PSA-2016-001?

Question: The PSA for tomorrow left me a bit uncomfortable. Quote:

The Drupal Security Team urges you to reserve time for module updates
  at that time because exploits are expected to be developed within
  hours/days.

Does it make sense to put all sites in maintenance mode or take them offline precautionary?
Maybe creating database backups before the announcement takes place isn't a bad idea?
Is there a Drupal way of responding such a pending threat? Or should we just sit and wait what's coming?
Answer: 1) List all the Drupal 7 projects you maintain.
2) Have a list of used modules by project, you can use fllowing command
<code> drush pml --no-core --type=module --status=enabled > mylist.txt
</code>
3) Once the updates announced, you can search your modules lists to detect which project you really need to update
Comment: That's nice for environments supporting drush. We have a whole variety of clients with different server setups, a lot of them on shared hosting platforms that don't support drush.
Answer: The important is being reactive in updating the modules when the security issue is made public, which normally is not done before the new security releases for the affected modules are made available.
The new releases will be available on on Wednesday July 13, 2016 16:00 UTC; until then, you could put the site in maintenance mode, or also temporary disable the modules that aren't strictly necessary. This could avoid possible exploits, but the majority of exploits happens when the security issues are made public, which is moment when you should updated the installed modules.
Comment: Of course they won't make this public before the security fixes are available. Otherwise you would have a wild guessing hackathon on your installations, i'd guess.
Comment: Does anybody has any idea of which modules this concerns or will they announce the modules list ? As far as I can see they don't name any modules
Comment: @mchar You will know that on July 13, 2016 16:00 UTC.
Answer: Taking a backup before the security release is a good idea.
Most people can't take their site offline unless completely necessary, but if you have that option then taking it offline at 16:00 UTC while you review and apply the updates would be the very safe way of doing it.
In summary, take a backup now and make yourself available after 16:00 UTC to review which of your modules need to be updated and then apply those updates asap.


How to filter filenames in views based on a match to currently logged username?

Question: I am quite novice to Drupal. I am trying to figure out how to create views listing files such that only those files are listed where filename contains currently logged username?
Comment: So you have a username like johnsmith and you have filenames that contain that username, like somethingjohnsmith.jpg, somethingelsejohnsmith.jpg?
Comment: exactly!!! that's what I have. And what I want is to throw into value slot of the views filter smth like [current-user:name] as suggested by NineAllexis. I have enabled PathAuto, Token, Token Filter and whatnot and still it does not work.
Comment: See my answer. PathAuto has to do with aliases and Token Filter has to do with Text format filters, as in viewing a node and replacing tokens with some data, so they won't help you here.
Answer: If you could use tokens in views filters you could do something like File: name ... contains any word ... [user:name] and that would end up in the sql as file_managed.filename LIKE '%username%' which would be cool. But you can't do that, to my knowledge.
You might achieve what you want using contextual filters having PHP code in both contextual filter and validator, maybe.
That said, depending on how much files and users you have and so on, it might be easier to tag the files with taxonomy terms. That way user wanting to change their username, eg. when they get married, won't brake your system. Also usernames having spaces, underscores, apostrophies etc. wouldn't be an issue.
Edit:
What do you know, this can be done with contextual filters! I don't know how practical or robust or performant this is but here goes:
1) Add a contextual filter of Global: null.
2) Provide some default value, doesn't matter what. For example Fixed value -> 'blaa'.
3) Specify validation criteria -> PHP code
<code>global $user;

$view->query->where = array(
    1 => array(
        'conditions' => array(
            0 => array(
                'field' => 'file_managed.filename',
                'value' => '%' . $user->name . '%',
                'operator' => 'LIKE',
            )
        ),
        'args' => array(),
        'type' => 'AND',
    )
);
return true;
</code>
I figured this out with dpm($view). If you have other filters in the Filter criteria, this code will have to take that into account. Tampering with the $view like this is not really future proof, but theoretically possible.
Comment: Thanks, Kari! I kind of figured a partial solution. You could go to contextual filters and select "use default value" if the search term is not present in the url. Then select the PHP is the type of text to define the value. Then insert the following code into the value field: name;
?>   Yet it will only allow to select files with complete match to user name. Unfortunately partial matches are not implemented in contextual filters. Id be curious if it was possible to supplement partial matching capability to this algorithm.
Comment: Great, I continued from there, see my edited answer.
Comment: You are a genius! It works!!!
Answer: You can get current logged username by using token [current-user:name] or just [user:name], provided you have Pathauto installed.
Comment: Thanks! So should I just type 'current-user:name' into the Value field of the filter?
Comment: either that or you could get the data from global $user variables. $user->name if i'm not wrong...

Oops... somebody got it already hehe
Comment: thanks :) NineAllexis. See Kari's comments above, he definitely solved it through PHP code in validator – works even my very rookie hands.


Nested form and link_to_function

Question: I've got a nested form like this :
<% form_for setup_training(@training), :url => admin_trainings_path, :html => { :class => :form } do |f| -%>

<% f.fields_for :days do |days_form| %>
    <%= render :partial => "admin/days/form_inner", :locals => { :f => days_form }%>
<% end %>

<%=  link_to_function("[+] Ajouter une date", nil, :id => "add-place-and-dates-link") do |page|
    page.insert_html :bottom, "place-and-dates-inner", :partial => "day_form", :locals => { :f => f }
end %>

<% end -%>

The first time i load my page, the first fields_for block has id 0;
The first time i click on "add a date", a new fields_for block is created with id = 1;
Then, everytime i clink on "add a date", a new fields_for block is displayed, but the id stays to 1.
An HTML example may be more explicit, here's the output i've got :

Lieu
<input class="text_field" id="training_days_attributes_0_place_id" name="training[days_attributes][0][place_id]" size="30" type="text">

Lieu
<input class="text_field" id="training_days_attributes_1_place_id" name="training[days_attributes][1][place_id]" size="30" type="text">

Lieu
<input class="text_field" id="training_days_attributes_1_place_id" name="training[days_attributes][1][place_id]" size="30" type="text">

Thank you per advance for you help!
Answer: If you have a look in your inline javascript in your page source you'll see that your link_to_function contains static html which will be be inserted into the place-and-dates-inner container. This does not change because it was build on the server and sent to the user.
To fix this you probably would be best to count client side the number of containers that have previously been inserted into the place-and-dates-inner and increment accordingly in your template. This kind of inline link_to_function stuff I always disliked to be honest.
Comment: Thank you for your answer.

In fact, i tried to use a link_to_remote function with a render update adding a new form field, but i did not know how i could pass my form (f) to it.

If you have any suggestion, feel free to enlight me ;-)
Comment: There's a couple of railscasts on this subject which should help you out. :)

http://railscasts.com/episodes?search=nested

Nested form and link_to_function


tail probability for norm of normal random vector

Question: If $x \sim \mathcal{N}(0, I)$ is an $n$ dimensional random vector. I am looking for a proof of
$$ \mathrm{Prob}\left( \lVert x\rVert^2  \ge 6n \right) \le e^{-1.5n}$$
$\lVert x \rVert^2 \sim \chi^{2}$ with $n$ degrees of freedom. So we need a tail bound on a Chi squared random variable.
Answer: Using Chebyshev's inequality
\begin{align}
\mathbb{P}(\|X\|^2 \geq k) \leq e^{-tk}\mathbb{E}[e^{t\|X\|^2}]
\end{align}
Since $\|X\|^2$ is chi-squared distributed with $n$ degrees of freedom,
$$ \mathbb{E}[e^{t\|X\|^2}] = (1-2t)^{-\frac{n}{2}}, \quad \forall t < \frac{1}{2}$$
Substituting $k = 6n $ in the first inequality,
\begin{align}
\mathbb{P}(\|X\|^2 \geq 6n) &\leq e^{-6tn}(1-2t)^{-\frac{n}{2}}\\
&= \exp\left[-n\left(6t+ \frac{1}{2}\log(1-2t)\right)\right]\\
&\leq \exp\left[- \frac{5 - \log 6}{2} n \right]  \textrm{ setting } t = \frac{5}{12}\\
&\leq e^{- 1.5n}\\
\end{align}
Comment: The chi-squared quantity is $\|X\|^2$, not $\|X\|$.
Comment: @kimchilover Fixed. Thanks for pointing it out.
Comment: That is Markov's ineq, though chebyshev's ineq itself can be derived from Markov inequality. Great anwer. Thanks.
Comment: @SPV Not sure what is the universally accepted nomenclature. Wikipedia says this is the "exponential Chebyshev's inequality". I prefer to use the more general $\mathbb{P}(|X| \geq \lambda) \leq \frac{\mathbb{E}[f(|X|)] }{f(\lambda)} $ for positive non-decreasing $f$ and $\lambda>0$, but don't know if there is a name for it.
Comment: That's Chernoff's bound https://en.wikipedia.org/wiki/Chernoff_bound.


Xamarin Forms navigation stack memory

Question: Is Xamarin Forms navigation stack garbage collected? When I click to button and open a page using Navigation.PushAsync() it will keep other page in navigation stack or relase memory?
Answer: The Navigation stack is a Stack interface, which you can generally think of like a stack of silverware in a drawer.  When you add a fork to the drawer, you put it on top of the other forks, and when you remove a fork you always remove the top one.  A stack is a first-in-last-out data type.  When you do add a fork on the top, though, all the other forks are still there below it.
This is the same with the navigation stack.  When you add a page using PushAsync(newPage), newPage is placed on the top of the navigation stack, but all the pages before it are still below it.  That way when you call PopAsync() you will return to the previous page and it won't have to completely remake it.
Comment: No problem, glad I could help!
Comment: after clicking on Back  and after going to newPage  it gives me error NulReferenceException

Xamarin Forms navigation stack memory


Show a list of records to have a join to another table using CakePHP

Question: I have an application that stores Posts and Topics and joins them using a Topic_Posts table.
The associations for the application are as follows:
Post.php
class Post extends AppModel
{
    public $name = 'Post';

    public $belongsTo = 'User';

    public $hasMany = array('Answer');

    // Has many topics that belong to topic post join table... jazz
    public $hasAndBelongsToMany = array(
        'Topic' => array('with' => 'TopicPost')
    );
}

Topic.php
class Topic extends AppModel
{
    public $hasMany = array(
        'TopicPost'
    );
}

TopicPost.php
class TopicPost extends AppModel {
    public $belongsTo = array(
        'Topic', 'Post'
    );
}

When a user views a topic e.g. /topics/view/topicname I want to show all the posts that contain that Topic.
So far I have the following method in my TopicsController for the view:
public function view ( $slug )
{
    $topic = $this->Topic->find('first', array('conditions'=>array('Topic.slug'=>$slug)));
    $this->set('topic', $topic);
    $this->set('title_for_layout', $topic['Topic']['title'] . ' – Topics');

    $this->paginate = array
    (
        'Post' => array
        (
            'limit'=>15,
            'conditions'=>array
            (
                'Post.status'=>array(1,2),
                'TopicPost.topic_id' => $topic['Topic']['id'],
            ),
            'order'=>array('Post.datetime'=>'desc'),
            'contain'=>array('User'=>'Profile', 'TopicPost')
        )
    );

    $posts = $this->paginate('Post'); // this one

    $this->set('posts', $posts);

}
And so that I can use Posts and TopicPosts I have added: public $uses = array('Topic','TopicPost','Post'); to the top of the controller and made all models act as containable.
So basically I need to find Posts that have a match in the database model TopicPosts for the id of the topic I'm viewing.
Comment: Heh, it's nice that you added bounty reputation, but this is really bugging me. It should work! Can you post a pastie of your database structure with some sample data? And the updated code you have would also be useful.
Comment: This SQL would build the DB http://pastebin.com/qm72Rz6k and i've updated the code in the OP to be what I have now!
Comment: Also just to note the DB structure and relationships work fine as I can pull the topics for a post fine using TopicPost so I KNOW that works, it's just getting Posts for a topic that seems to be not working...
Comment: Another update of my answer..wish me luck :P
Comment: YES! :) error free. Thanks pal.
Answer: I just couldn't get it to work the "proper" way. I'm not sure if this is a bug in cake or something, but the paginate function simply refuses to budge.. The proper way to do this would probably be to write your own paginate function in your Post model, there is some info on how to do that in the cookbook.
Meanwhile, I offer you the workaround below. It's not optimal (at least not without caching) but it works. You can do it the proper way when/if you run into performance problem, but until then, this code below should do it.
public function view ( $slug )
{
    $topic = $this->Topic->find('first', array('conditions'=>array('Topic.slug'=>$slug)));
    $this->set('topic', $topic);
    $this->set('title_for_layout', $topic['Topic']['title'] . ' – Topics');

    // step 1: get post IDs related to your topic
    $postIDs = $this->Topic->TopicPost->find
        (
            'list',
            array
            (
                'fields'        => array('TopicPost.post_id'),
                'conditions'    => array('TopicPost.topic_id' => $topic['Topic']['id'])
            )
        );

    $this->paginate = array
    (
        'Post' => array
        (
            'limit'=>15,
            'conditions'=>array
            (
                'Post.status' => array(1,2),
                // step 2: include them in your paginate conditions
                'Post.id' => $postIDs,
            ),
            'order' => array('Post.datetime'=>'desc'),
        )
    );

    $posts = $this->paginate('Post');

    $this->set('posts', $posts);
}

(Please note that I've stripped some of the stuff in my tests as I didn't have some of the stuff in your app, so don't forget to put it back)
Comment: Boom seems to have fixed it the error :) Any ideas on how to get the part of ONLY showing posts that are in the join table?
Comment: @Cameron: Hm, forgot about that..are you getting your posts in the first query? What is the output when you do a `debug($topic)` If you have your posts there, you could do a Set::extract() to get all post IDs and then add them to your pagination conditions.
Comment: Hmm that seems sloppy... Can't I just find the Posts that have a relationship to the topic in TopicPosts?
Comment: @Cameron: I've updated the post with possible answer to your question. Would something like this suffice?
Comment: Gives me this error: `Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'TopicPost.topic_id' in 'where clause'` I've even added the TopicPost model to the uses var at the top of the controller so not sure what else to do?
Comment: Here is the SQL for that error: `SQL Query: SELECT `Post`.`id`, `Post`.`user_id`, `Post`.`datetime`, `Post`.`modified`, `Post`.`title`, `Post`.`slug`, `Post`.`content`, `Post`.`status`, `Post`.`latitude`, `Post`.`longitude`, `User`.`id`, `User`.`username`, `User`.`password`, `User`.`email`, `User`.`status`, `User`.`code`, `User`.`lastlogin`, `User`.`created` FROM `db52704_favorr`.`posts` AS `Post` LEFT JOIN `db52704_favorr`.`users` AS `User` ON (`Post`.`user_id` = `User`.`id`) WHERE `Post`.`status` IN (1, 2) AND `TopicPost`.`topic_id` = 1 ORDER BY `Post`.`datetime` desc LIMIT 15`
Comment: @Cameron: Are you sure you've copied the 'contain' line as well?
Comment: Yes that contain is there. If I comment out the TopicPost line in the conditions then I can debug and I get this statement: http://bin.cakephp.org/view/2082480982 as you can see TopicPost is not in the code AT ALL! Can you see anything wrong with the associations?
Comment: I've even made sure all my models have `public $actsAs = array('Containable');` but the contain isn't the issue as it's the conditions that causes the error...
Comment: @Cameron: How about with the update above? :) I don't think all of your models need Containable in this case, but if you want to add it to *all* models, simply add it to your AppModel.
Comment: Still get the same error! Added that code to the Post model as well.
Comment: @Cameron: I really don't know why that shouldn't work..maybe you should try to isolate the relevant code into a standalone app and try debugging from there.
Answer: I think you have a problem with your model relationships, I don't understand why you have a HABTM relationship on the posts model, when you are actually emulating this (using the Has-many-through method) on the TopicPost model itself. If you don't want to use the HABTM behaviour built into cake (and I don't blame you), you should setup relationships like this:
class PostTopic extends AppModel { // note PostTopic, name should be alphabetical
    public $belongsTo = array('Post', 'Topic');
}

class Post extends AppModel {
    public $hasMany = array('PostTopic');
}

class Topic extends AppModel {
    public $hasMany = array('PostTopic');
}

Then to fetch the IDs of posts or topics that relate, you simply load the PostTopic class and do a search:
// ie in Post Controller
$this->paginate($this->Post->PostTopic, array('PostTopic.topic_id' => $post['PostTopic']['topic_id']));

I have a similar setup on my site, where users can add a product to their inventory, It's kind of a HABTM relatipnship but with more data attached to it. See the Product, Inventory and Users models here for a more complicated example.
Comment: That last bit of code is wrong! The topic_id isn't the id of the current post!
Comment: @Cameron well you're supposed to replace it with the right variable, it will probably be `$post['PostTopic']['topic_id']` or something.
Comment: How would I do this with a paginate then?
Comment: Updated answer. It's quite simple once you get your head around has-many-through relationships in cake.
Comment: Well the method is in the TopicsController not the PostsController as I'm getting Posts for the Topic I'm viewing which is what the issue was as it seemed as though Cake couldn't understand the associations even though they are correct.
Comment: In that case just change `$this->Post` to `$this->Topic`! Also your associations were incorrect. [See here](https://github.com/Dunhamzzz/Consumer-Love/blob/master/Controller/UsersController.php#L185) for an example of where I'm doing the exact same thing you're trying to achieve; and for gods sake, play with the code to try to understand what it's doing instead of asking for answers on a plate, you'll never learn anything that way.
Comment: If my associations are incorrect how come it's working the way Hannibal Lecter has done it then all my data requests work fine across the app? And I have played with the code, who do you think wrote the code in the first place to get stuck :/
Comment: It works but look how much he's hacked it, I've done it in one line!
Comment: I've tried but I get this error: Undefined index: topic_id [APP/Controller/TopicsController.php, line 91] with this code: `$posts = $this->paginate($this->Topic->TopicPost, array('TopicPost.topic_id' => $topic['Topic']['topic_id'])); $this->set('posts', $posts);`
Comment: You need to replace `$topic['Topic']['topic_id']` with `$topic['Topic']['id']` - or whatever variable contains the topic ID you are looking for.
Comment: Okay that worked! What about adding all those extra params in though that I had? As I don't understand how to use them with the way in which you have implemented the paginate method. ALSO I haven't amended my associations and it still worked... so?
Comment: Read how to setup pagination params in the manual. I'm done here.
Comment: It doesn't work though -> http://stackoverflow.com/questions/10303905/cakephp-paginate-controller-with-custom-conditions#comment13262637_10303905
Answer: From question comment:

Also just to note the DB structure and relationships work fine as I
  can pull the topics for a post fine using TopicPost so I KNOW that
  works, it's just getting Posts for a topic that seems to be not
  working...

Right, because you setup the HABTM for Post->Topic, but not for Topic->Post. The 2.0 book defines an example just like yours (but using recipes and ingredients) to describe the use case.

The main difference between hasMany and HABTM is that a link between
  models in HABTM is not exclusive. For example, we're about to join up
  our Recipe model with an Ingredient model using HABTM. Using tomatoes
  as an Ingredient for my grandma's spaghetti recipe doesn't "use up"
  the ingredient. I can also use it for a salad Recipe.

The same can be said for a Post using a Topic (your name for a tag/category). And just like their example:

Remember to define a HABTM association in the Ingredient model if
  you'd like to fetch Recipe data when using the Ingredient model.

Or, in your case, the Topic model.
So here's the models that you should use:
class Post extends AppModel
{
    public $name = 'Post';

    public $belongsTo = 'User';

    public $hasMany = array('Answer');

    // Has many topics that belong to topic post join table... jazz
    public $hasAndBelongsToMany = array(
        'Topic' => array('with' => 'TopicPost')
    );
}

class Topic extends AppModel
{
    // Has many posts that belong to topic post join table... jazz
    public $hasAndBelongsToMany = array(
        'Post' => array('with' => 'TopicPost')
    );
}

Now, you don't really need TopicPost unless you are doing something special, but it is fine as it is. And, though you can use that model for adding Topics to to a post (or vice-versa), I'd suggest you use the build in method of handling HABTM saves. Review this page for details on saving HABTM.
If you decide to remove it, make sure you define the join tables and conditions for the HABTM options in each model per the docs
Comment: Updated my model to look like yours and I still get the same error as before!
Comment: @Cameron what error? That you are not getting `Post`s for a `Topic` via `Topic->find()`?


Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis?

Question: I have a set of 20 variables that I have put through factor analysis in SPSS. For purposes of the research, I need to develop 6 factors. SPSS has shown that 8 variables (out of 20) have been loaded with low weights or have been loaded equally by several factors, so I have removed them. The remaining 12 variables have been loaded in pairs of 2 in the 6 factors, which is perfect structure -- just as I wanted, but now, one of the professors working with me wants me to find justification why (or under what conditions) it is appropriate to keep only 2 items per factor, since it is commonly known that factor analysis is useful with results 3 or more items loaded, per factor.
Can anyone help me out with this issue, preferably with a published reference as well?
Comment: "At least 3 items per factor" is a warranted recommendation. If you have, after factor rotation, results with 2 or one items in a factor, either 1) get more variables which you expect to be loaded by that factor, or 2) redo the analysis and extract less factors, or 3) leave the results as is but don't interpret the "needy" factor, saying "I believe that factor exists, but since it isn't currently supported by items enough I drop it from interpretation and from results". All these 2 recommendations are different, though.
Comment: See also, in addition to the answers here, stats.stackexchange.com/a/198684/3277 (poit 5) why "At least 3 loaded items per factor" is reasonable requirement.
Comment: A single item factor is also acceptable if that item has a higher factor loading.
Answer: Two or three items per factor is a question of identification of your CFA (confirmatory FA) model.
Let us for simplicity assume that the model is identified by setting the variance of each factor to 1. Assume also that there are no correlated measurement errors.
A single factor model with two items has two loadings and two error variances to be estimated = 4 parameters, but there are only 3 non-trivial entries in the variance-covariance matrix, so you don't have enough information to estimate the four parameters that you need.
A single factor model with three items has three loadings and three error variances. The variance-covariance matrix has six entries, and careful analytic examination shows that the model is exactly identified, and you can algebraically express the parameter estimates as functions of the variance-covariance matrix entries. With more items per single factor, you have an overidentified model (more degrees of freedom than parameters), which usually means you are good to go.
With more that one factor, the CFA model is always identified with 3+ items per each factor (because a simple measurement model is identified for each factor, so roughly speaking you can get predictions for each factor and estimate their covariances based on that). However, a CFA with two items per factor is identified provided that each factor has a non-zero covariance with at least one other factor in population. (Otherwise, the factor in question falls out of the system, and a two-item single factor model is not identified.) The proof of identification is rather technical, and requires good understanding of matrix algebra.
Bollen (1989)  fully and thoroughly discusses the issues of identification of CFA models in chapter 7. See p. 244 specifically regarding three- and two-indicator rules.
Comment: This was a very apt answer. I would only comment (for the OP's sake) that the OP asked about exploratory FA (EFA). It is logical that EFA should have "3+ loaded items per factor" since CFA expects it; only that you didn't say about it in your answer.
Answer: I never heard about the "3 items per factor" criterium. I would reverse the question and ask your professor to come up with a sound reference for this statement.
Besides that, "for purposes of the research, I need to develop 6 factors." is a weird thing to say.
The basic purpose of factor analysis is 1) find out how many factors (often psychological traits) underlie a (larger) number of measured variables. Then 2), based on the factor loadings, one tries to describe what these factors really are.
You don't "develop" 6 factors, you're "trying to measure" 6 factors.
However, cross loadings (variables loaded by several factors) present are often an indication that the factors are "trying to correlate" with each other. Which makes sense since we know that basically everything correlates with everything in the real world. Implementing this observation in your analysis by using an oblique (instead of the orthogonal varimax) rotation often gets rid of many cross loadings. IMHO, it is more sound theoretically too.
Give that a shot, you may end up with more items per factor. That may (partly) solve your problem too.
Comment: Thank you very much for your comment, why six factors I can explain with a model that I am using, my professor is not against 6 factor explanation, however he wants explanation when is it OK to use factor analysis that has only 2 items per factor. This still remains the question.
Comment: Welcome to the site, @pythonforspss.org, there's a lot of good info here, +1. A couple of notes: I have heard it said several times that you need at least 3 variables per factor, but I don't know what the (or if there actually is any) substantive reason for this rule. I edited the OP's Q to make the English smoother; I put in the phrase you quote to replace what was there beforehand. This may well not have been ideal (I wasn't sure how to translate what I thought the OP might be trying to say), but if so it's my fault, not Mitja's. Remember that English is not the 1st language of many users.
Comment: the three items per factor is a common belief, and tends to cause problems at review stage (as it is a common belief). That being said, if your communalities are high (>0.7) then you probably don't have an issue.
Comment: My communalities are 0.5 or higher ...
Comment: `factors are "trying to correlate" with each other` is a mystic formulation. Factors correlate or don't correlate according to how we rotate (model) them. Quite high "cross-loadings" are possible with orthogonal factors with a variable having high communality.
Comment: For reference, I know that at least Yong & Pierce, 2013 references at least three variables per factor, with two variables acceptable with correlations with each other above .70.
Answer: I have the same problem now. Here is an article which recommends to use at least 3 items per factor. In exceptional cases, however, you might use to items per factor (p.60). http://www.sajip.co.za/index.php/sajip/article/download/168/165
My case seems to be exceptional, since there are only two variables in my web-based experiment, that provide information on player's strategy and strategy power. May be it could help you too to legitimize the use of 2 items for some factors.
Comment: This website has a number of references supporting the minimum of three variables per factor rule: https://www.encorewiki.org/display/~nzhao/The+Minimum+Sample+Size+in+Factor+Analysis


Calculating Sample Size from Power Calculator

Question: I am trying to calculate sample size based on required effect size for my test (site found here: http://www.sample-size.net/sample-size-means/)
My inputs are as follows:
α (two-tailed) = .05
β = 0.100
Split of Test Vs. Control = .5
Desired Effect Size = .03
Standard deviation of the outcome in the population =
My confusion is in regards to this last step - is this the pooled Standard Deviation of my two groups?  Not sure what to input here...any help would be appreciated!
Answer: Yes, it is. This particular sample size calculator does not allow including unequal variances in the treatment and control group.
If you expect and plan for this, then first of all, congratulations - you are being more statistically sophisticated than most researchers. In such a case, get a friendly statistician to hack together a few lines of R to run a simulation-based sample size calculation.
Comment: Hi Stephan - so this calculator is calculating Cohen's D effect size.  With that in mind, I am confused if I should be putting in "1" or the pooled variance of my two samples...
Answer: As indicated by Stephan, this is the pooled standard deviation. If the effect size that you have specified is a Cohen's d type effect size, then use 1 as your standard deviation. I assume you are aware that this is a very small effect size you are designing your study to detect? You are also designing for a high level of power (1-$\beta$). The two of these combined will result in your needing a very large sample size. Designing for power = .80 is common but this is simply a convention created by Cohen and more power is always better!
Comment: If you are not using Cohen's d, then your effect size should be your expected mean difference and the standard deviation should be your expected (population) within-group (pooled) standard deviation.
Comment: Hi DBwilson - this is great and I believe this calculator is Cohen's D.  Why exactly does that mean SD is "1" and not pooled SD?
Comment: 1 Is the pooled SD. That is, with a Cohen's d, you've rescaled the data to have a pooled SD of 1. The reason this calculator has the option to specify the SD is so that you can use something other that the Cohen's d.


Azure Synapse, Data Duplication Issue in PySpark When Reading and Writing to Delta Lake

Question: I'm working on a PySpark data pipeline that reads Salesforce User data from an Azure Data Lake Storage Gen2 "bronze" layer, transforms the data, and then writes it to a "silver" layer in Delta Lake. The problem I'm facing is that, despite using the dropDuplicates(["Id"]) function in PySpark to remove any duplicate records based on the "Id" column, I'm still encountering duplicate "Id" records in my "silver" layer. This duplication issue persists even after repeated runs of the pipeline, and it's causing significant problems in downstream analyses and processes that rely on this data.
To handle the potential issue of duplicate records, I included the dropDuplicates(["Id"]) function in my PySpark script. This function is used after the union operation, which combines the existing "silver" data with the new "bronze" data. My expectation was that this function would ensure that any duplicate records (based on the "Id" column) would be removed from the combined dataset before it is written back to the "silver" layer in Delta Lake.
Here is a snippet of the relevant code:
# Combine the bronze and silver data and deduplicate based on the "Id" column
deduplicated_df = bronze_df.union(silver_df).dropDuplicates(["Id"])

# Write the deduplicated data to the silver layer
deduplicated_df.write.format("delta").mode("overwrite").save(prod_user_silver_path)

Sample data after running pipelines 3x:

The result I was expecting was a "silver" layer dataset with no duplicate "Id" records. However, what I'm actually seeing is duplicate "Id" entries in the "silver" layer despite using dropDuplicates(["Id"]). This discrepancy between my expected and actual outcomes is the core issue I'm trying to resolve.
Any thoughts?
Comment: please provide sample input data of bronze and silver layer.
Comment: is there any partition on any column? try  this `bronze_df.union(silver_df).repartition("Id").dropDuplicates(["Id"])`.
Answer: @jayashankarGS
Thank you for your response and the suggestions you provided. I appreciate your help. While I did get the correct output in the dataframe after following your suggestions, I still encountered duplicates when using the data in PowerBi. However, I was able to find a solution to this issue recently.
To resolve the problem, I modified my approach by writing the data from the Delta back to a single Parquet file, overwriting any existing data. I then stored this Parquet file in my "gold" layer. This additional step ensured that the duplicates were eliminated, and the data in my "gold" layer was clean and free of any duplicate "Id" records.
Thank you once again for your assistance.
Answer: I have reproduced your code in my environment, it worked successfully.

After dropping duplicates.

For you it still getting duplicates in end table, below are the possible causes.

Data type mismatch.

Print schema of both dataframe.
bronze_df.printSchema()
silver_df.printSchema()

If there is mismatch between these columns datatype use below code.
from pyspark.sql.functions import col

bronze_df = bronze_df.withColumn("Id", col("Id").cast("string"))
silver_df = silver_df.withColumn("Id", col("Id").cast("string"))

deduplicated_df = bronze_df.union(silver_df).dropDuplicates(["Id"])

2.Data partitioning
Duplicate records might exist in single partition even though you deduplicate overall dataset.
you can use below code for above issue.
deduplicated_df = bronze_df.union(silver_df).repartition("Id").dropDuplicates(["Id"])

Spaces in the data.

code:
sp_df.withColumn("Id",trim(col("Id"))).dropDuplicates(["Id"]).show()

If you still not getting expected results by following above ways.
Try this.
bronze_df.union(silver_df).groupBy(col("Id")).agg(first(col("name")))


Checking for null arrays in an PSObject

Question: How would I go about Checking for Null or empty in an Object that has multiple arrays?
<code>$buildings.North = {bld1,bld2,bld3}
$buildings.South = {}
$buildings.East = {bld5,bld6}
$buildings.West = {bld7,bld8,bld9,bld10}
</code>
I started out with a if / elseif to go through each one, but that would be 16 combinations of this:
<code>if ($Buildings.North.count -eq "0" -and $Buildings.South.count -ge "1" -and $Buildings.East.count -ge "1" -and $Buildings.West.count -ge "1" ){set-function -OPT1 $Buildings.South -OPT2 $Buildings.East -OPT3 $Buildings.West }
elseif ($Buildings.North.count -ge "1" -and $Buildings.South.count -ge "1" -and $Buildings.East.count -ge "1" -and $Buildings.West.count -ge "1" ){set-function -OPT1 $Buildings.North -OPT2 $Buildings.South -OPT3 $Buildings.East -OPT4 $Buildings.West}
elseif ($Buildings.North.count -eq "0" -and $Buildings.South.count -eq "0" -and $Buildings.East.count -eq "0"  -and $Buildings.West.count -eq "0"){#empty do nothing}
elseif ($Buildings.North.count -eq "0" -and $Buildings.South.count -eq "0" -and $Buildings.East.count -ge "1" -and $Buildings.West.count -ge "1" ){set-function -OPT3 $Buildings.East -OPT4 $Buildings.West}
</code>
Since you could have hundreds of options in a object, that could be a lot of code. I also tried to build the cmd, out of a string:
<code>$cmd = ' -Location $Loc'
if ($Buildings.North.count -ge "1"){ $cmd += ' -OPT1 $Buildings.North ' }
elseif ($Buildings.South.count -ge "1"){$cmd += ' -OPT2 $Buildings.South'}
elseif ($Buildings.East.count -ge "1"){$cmd += ' -OPT3 $Buildings.East'}
elseif ($Buildings.West.count -ge "1"){$cmd += ' -OPT4 $Buildings.West'}
Set-Function $cmd
</code>
Not much success with this approach either. There has to be a better way to do this sort of checking, help finding it would be most appreciated.
Answer: this should work:
<code>$cmd = ' -Location `$Loc'
if ($Buildings.North.count -ge "1"){ $cmd += ' -OPT1 `$Buildings.North ' }
elseif ($Buildings.South.count -ge "1"){$cmd += ' -OPT2 `$Buildings.South'}
elseif ($Buildings.East.count -ge "1"){$cmd += ' -OPT3 `$Buildings.East'}
elseif ($Buildings.West.count -ge "1"){$cmd += ' -OPT4 `$Buildings.West'}
Invoke-Expression "Set-Function $cmd"
</code>
Comment: Invoke-Expression! ahh! That works for getting the function to work. Thank you. Do you happen to have any ideas on how to check for null (or not null) in this type of object setup. I'm starting to use objects more and more, and I cannot think of a way to do these sorts of check short of really long if/elseif conditions.
Answer: <code>$Opts = @{
OPT1 = $buildings.North
OPT2 = $buildings.South
OPT3 = $buildings.East
OPT4 = $buildings.West
}

$opts.GetEnumerator() |
foreach {if (-not $_.value){$opts.Remove($_.Name)}}

Set-Function @Opts
</code>
FWIW
Answer: <code>#Create Test Object
$buildings = New-Object -TypeName psobject -Property @{'North'=@('a','b');'south'=@('x');'West'=@()}

#Returns arrays that are not 0 in count
$buildings | Get-Member -MemberType NoteProperty | ? {($buildings.($_.name)).count}
</code>

Checking for null arrays in an PSObject


Playing audiofiles one by one?

Question: I'm newbie in java. So the program should take the user entered text and if there is "a" it gonna play a-sound, if there is "b" it gonna play b-sound.And it must play this sounds one by one even if there are multiple "a" or "b". Here is my code:
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button bStart = (Button) findViewById(R.id.bStart);
    final EditText etStart = (EditText) findViewById(R.id.etStart);
    final EditText etFinish = (EditText) findViewById(R.id.etFinish);
    final char[] arr = etStart.getText().toString().toCharArray();
    final MediaPlayer as = MediaPlayer.create(R2d2Activity.this, R.raw.as);
    final MediaPlayer bs = MediaPlayer.create(R2d2Activity.this, R.raw.bs);
    final SoundPool sp;
    final int a;
    final int b;
    final int t;
    sp = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
    a = sp.load(this, R.raw.as, 1);
    b = sp.load(this, R.raw.bs, 1);
    final String value = etStart.getText().toString();
    final Thread timer = new Thread(new Runnable() {
        @Override
        public void run() {
        try {
        Thread.sleep(1300);
        // Do some stuff
        } catch (Exception e) {
        e.getLocalizedMessage();
        }
        }
        });
    bStart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int n = 0;
            String value;
            String first;
            value = etStart.getText().toString();
            // TODO Auto-generated method stub
                           //actual code
            for (int i=0; i<value.length(); i++){
                first = etStart.getText().toString().substring(i, i+1);
                if(first.contentEquals("a")){
                    as.start();
                    as.setOnCompletionListener(new OnCompletionListener(){
                        public void onCompletion(MediaPlayer arg0) {
                            //when finished

                             }
                    });

                        }else{
                            }
                if(first.contentEquals("b")){
                    bs.start();

                        }else{
                            }

            }

        }
    });

The problem is that it starts playing audio files all at one time. I tried to add some OnCompletionListener, but I don't know what to do with it. Help me please.
Comment: Use a line listener and you'll get events on start and stop. Then you have to make the method wait (example: http://stackoverflow.com/questions/289434/how-to-make-a-java-thread-wait-for-another-threads-output).
Answer: What you can do is
//define a variable to be used as index.
int audioindex = 0;
//Extract the files id into an array
int[] audioFileIds=new int[]{R.raw.as,R.raw.bs};

Then in your MediaPlayer onCompletionListener put something like following.
then in your OnCompletionListener.
mp.setOnCompletionListener(new OnCompletionListener(){
    // @Override
    public void onCompletion(MediaPlayer player) {
    // File has ended, play the next one.
   FunctionPlayFile(audioFileIds[audioindex]);
   audioindex+=1; //increment the index to get the next audiofile
     }
});

Playing audiofiles one by one?


content consists of more divs

Question: The problem is when the content consists of more divs, nested divs like this:

Content
more stuff
more contents

Any ideas on how I make my regexp work with nested tags?
Thanks
Comment: Don't use regex to parse XML, use DOM. Allow me to recommend this article: http://stackoverflow.com/a/8412989/5290909
Comment: Where you mentioned regex?
Answer: Try a parser instead:
require_once "simple_html_dom.php";
$text = 'foo
Content
more stuff

 bar
even more
 baz
yes
';
$html = str_get_html($text);
foreach($html->find('div') as $e) {
    if(isset($e->attr['id']) && preg_match('/^t\d++/', $e->attr['id'])) {
        echo $e->outertext . "\n";
    }
}

Output:

Content
more stuff

yes

Download the parser here:http://simplehtmldom.sourceforge.net/
Edit: More for my own amusement I tried to do it in regex. Here's what I came up with:
$text = 'foo
Content
more stuff

 bar
even more

      baz
yes
aaa
bbb
ccc
bbb
aaa

';
if(preg_match_all('#
[^<>]*(
]*>(?:[^<>]*|(?1))*
)[^<>]*
#si', $text, $matches)) {
    print_r($matches[0]);
}

Refer this page

content consists of more divs


Passing a List to another class

Question: I know some codes here are not clear. I'm still in the process of trying out things. I've got three questions, why does an error shows up when adding a string in my list? How do I pass the List in Class1 to my main class? And is my syntax correct in List passArr? Not sure if I should add parenthesis at the end of passArr.
class Class1
{
    public static List<string> passArr
    {
        get;
        set;
    }

    public static void passIt()
    {
        passArr.Add("A"); //Error: Object reference not set to an instance of an object
    }
}

Main Class
class Program
{
    static void Main(string[] args)
    {
        Class1.passIt();
        List<string> passArr1 = Class1.passArr;
        foreach (string s in passArr1)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }
}

Answer: You're never creating a list, so the passArr property (which needs renaming, by the way) always has a value of null. You need something like:
Class1.passArr = new List<string>();

at some point. Another alternative would be to make it a read-only property backed by a field with an initializer:
private static readonly List<string> passArr = new List<string>();
public static List<string> PassArr { get { return passArr; } }

(This complies with naming convention in terms of case, but it's still not a meaningful name, of course.)
Comment: you want Class1.PassArr, your passArr is now a private list with a getter
Comment: Thanks for the fast reply! I tried changing my List passArr1 = Class1.passArr to your answer, an error occured that says Class1 does not contain a definition for 'passArr1'.
Comment: Sorry, I changed the wrong code. However, when I tried implementing Jon Skeet's fix, the error "Object reference not set to an instance of an object." still showed up.
Comment: https://pastebin.com/aWhfu8UM What is wrong with my code, if you can assist please.
Comment: @Si8: That's not the way the site works. If you have a different question, post it separately.
Comment: Thanks for response. I was able to figure it out . I had to instantiate the list first.
Answer: Thanks to Jon Skeet and Sayse for the answers. It's all now clear to me, the real problem is I'm trying to add something in the list (using passIt method) without creating a new object for the list.
Here's my new code:
Main Class
class Program
{
    static void Main(string[] args)
    {
        Class1 cs = new Class1();
        cs.passIt();
        foreach (string s in cs.passArr)
        {
            Console.WriteLine("Inside main: " + s);
        }
        Console.ReadLine();
    }
}

Class1
class Class1
{
    public List<string> passArr
    {
        get;
        set;
    }

    public void passIt()
    {
        passArr = new List<string>();
        passArr.Add("A");
    }
}

Comment: I realize this is an OLD question. But for the beginner programmer, try instantiating the list in a constructor: `public Class1() { passArr = new List(); }`

Passing a List to another class


smallest footprint for Web Application server?

Question: There are times when you need to spare hardware resources (either
to keep using legacy hardware, to play the embedded card, or just
to be efficient because a large footprint is trashing CPU caches,
leading to unacceptable levels of idle-states).
In this spirit, some efforts have been made to make 'light' ports
of Java or Mono (C# for Linux), and they range in the 80-50 MB
(instead of the 100-200 MB).
Add a Web server (Apache, IIS, etc.) to the scripting engine and
you can happily dive into the GB (IIS + .Net) only to load the
tool in memory.
Anybody with more modest tools in the specs area?
Answer: lighttpd + django should be pretty lightweight.
Comment: Good point! That's much better than the mainstream solutions.
Comment: Oops! Just forgot G-WAN's 120 KB. Hard to beat this one.
Answer: nginx is known for it's superb performance and low resource usage (about 2.4 MB the last time I heard of it). The down side is, you appearently have to recompile the whole server, if you want to include a new module.
As for languages, I always like to point everyone (especially web developers) to haXe, for a number of reasons. In this case, because the NekoVM is a possible target. It has quite a low footprint, decent speed and allows in-memory persistency. However there's currently no way to run NekoVM on an nginx server. Which gives you the chance to step in and become a hero ;-)
Also haXe's C++ backend will soon be worked on to be suitable for web server development. As you seem to have experience with C++, this may be of interest to you.
greetz
back2dos
Answer: It's difficult to find comparisons which help to decide, but the tests below use the same tool and procedure used by the Open-Source Phoronix benchmark.
Here are a couple of performance/CPU/RAM comparisons of Nginx, Lighttpd and G-WAN available here and there.
Both tests use different clients (ab is single-thread and weighttp, made by Lighttpd, is multi-thread), different CPUs (an i3 dual-Core CPU vs a XEON CPU with 6 Cores) and different versions of the servers, but the hierarchy is the same (except for the memory footprint: in this matter, the second test's winner is different from the first test).
The smallest footprint comes with G-WAN (a 150 KB process) which supports Java, C, C++, D, and Objective-C scripts natively while others require to use FastCGI backends.


Is there an equivalent to "continue" (python) in rebol?

Question: I am converting some python code to rebol, and I just came across a "continue" instruction.  It interrupts  the processing of a loop, going to the next iteration of the loop.
I find this word quite elegant and readable.
I came across some answers there: (in French), but nothing really "elegant":
http://pl.legoff.free.fr/dotclear/vf/index.php/post/2003/01/05/Equivalent-d-un-Continue-ou-Next-dans-une-bouc
As this converation is about 10 years old, maybe some improvements were made in Rebol since?
Answer: You can do it in Rebol2 using exceptions:
continue: does [throw 'continue]

loop 2 [
    catch [
        print {"This'll print", {DocKimbel} said.}
        continue
        print {"This won't print", {DocKimbel} said.}
    ]
]

In case you have custom exceptions to handle in the loop, you can use the /name refinement as in catch/name [...] 'continue to avoid catching other exceptions. It is even possible to override iterators to do it transparently for you, but at the cost of some slower performances.
Comment: The /name refinement was not so obvious, it worked after some RTFM, though:

`
    continue: does [throw/name 'continue 'keepgoing]
    repeat i 10 [ catch/name [
        prin i if (i = 5) [continue]
        prin i ]
    keepgoing ]
`

returns:

112233445667788991010

, as expected. – pierre 5 mins ago
Answer: CONTINUE is not in Rebol2.  But it's in Rebol3 and works just fine:
loop 2 [
    print {"This'll print", {HostileFork} said.}
    continue
    print {"This won't print", {HostileFork} said.}
]

You'll get the output:

"This'll print", {HostileFork} said.
  "This'll print", {HostileFork} said.

There is no way, as far as I know, to implement a continue in Rebol2.
Okay, building on @DocKimbel's answer a bit, you could do this in Rebol2:
old-loop: :loop

loop: func [count [integer!] block [block!]] [
    old-loop count [catch block]
]

continue: does [throw 'continue]

loop 2 [
    print {"This'll print", {HostileFork} said.}
    continue
    print {"This won't print", {HostileFork} said.}
]

Note: the internal implementation method for BREAK and CONTINUE does use the same mechanism as THROW in Rebol...which is relatively lightweight and not exception handling.  So important to know is that THROW is not what you should be using for errors...and modern Rebol builds (Ren/C) will not even allow you to throw one.  You should use FAIL instead.
Answer: In R2 LOOP 1 works too, with less overhead than CATCH
loop 1 [
    print {"This'll print", {DocKimbel} said.}
    break
    print {"This won't print", {DocKimbel} said.}
    ]

Comment: Yes, but this does not behave like I wish, and like python does: continue doesn't break out of the loop, it keeps going for next iterations of the loop.


Commerce Line Item Taxonomy Reference Filtered by Product Selection

Question: Here's the scenario:

I'm selling furniture. I have a chair we'll call Mission Chair.
The Mission Chair comes in oak or maple, both are priced differently. I have a field in my product
I have a product display created which references these 2 products
Customers need to choose 1 of 5 stain colors, but each type of wood has 5 different choices (and they're not the same choices)
The stain choice is required, but does not affect the price.

In my Product Variation Type, I have a term reference field which is referencing a Wood Species vocabulary.
I assume I would create a term reference field on the line item type where they would make the stain color choice. What I need to figure out is how do I do some kind of contextual filter to only show the stains available for the chosen wood species? (which is a taxonomy term on the chosen product - not the display, the product variation)
Should the stains be child terms in the same vocabulary as the wood species, or should it be a separate vocabulary with an additional term field that references a specific wood species (taxonomy reference, the same vocabulary the product variation uses) for each stain color term, and then filter on that somehow?
Comment: Are you trying to use the standard Commerce Add to Car form (which has support for multiple attributes, and some limitations) or did you come up with a custom add to cart form?
Comment: The standard Add to Cart form - just need to figure out how to do some kind of contextual filter - maybe using a views field on the line item type so I can do a contextual filter?
Answer: You have two basic approaches you can use: either treat the stain color as a customization or treat it as a second attribute.  Which you pick depends on a little on your backend process needs and the experience you want to provide.
If you use a second attribute and have a product variation for each stain in each wood, Commerce's default add to cart form should provide the user experience you are describing. You might find it helpful to take a look at this tutorial.
If you want to treat stain as a customization you'll likely want a couple extra modules -- in particular Commerce Customizable Product.  Commerce Guys have a tutorial covering that scenario.
Comment: Trying to avoid creating product variations for this - I have enough other variations to worry about which I didn't mention :-)
Comment: Than you'll want to treat them as product customizations (which probably makes some sense).
Comment: I found this thread (https://www.drupal.org/node/1873396) which probably describes a situation somewhat similar to mine. I don't need to adjust the price based on the stain color - I just need some way of triggering a filter of the line item taxonomy reference field (or views field which would be a list of filtered taxonomy terms) based on a chosen term from the product variation - does that make sense?


Fake documentation/code generator or rewriter

Question: This is a serious question, but the intent is not very serious; it's actually a joke I wanted to play on someone and while thinking about it I got quite interested.
Everyone knows http://pdos.csail.mit.edu/scigen/ I suppose: i was wondering ; is there any kind of code + documentation generator? Something which generates 'plausible' looking (doesn't even have to work) Java code and code documentation for instance?
Seems like a very interesting project to me and I couldn't find anything on Google. Does something like this exist?
Edit: something which would refactor a codebase beyond recognition would be good too; kind of a Markov chain for programming.
Answer: Well you could try Mechanical Turk if you have a budget for your practical joke. If you are more into an automated solution, a dissociated press type of algorithm would work.  Call me old fashioned, but I prefer the real thing to what these previous two methods could do.
Comment: Well, as you might've guessed from my post; it actually now went from a practical joke to real interest if something like this might be possible to do. I mean, sure, not for 'real', but so it looks plausible to the untrained (or just uninterested) eye, like SCIGen.


Pseudo random ordering of integers

Question: I remember an old retro effect for a screen resolution of $320\times 240$. You would iterate the pixels in a linear fashion so there are $76800$ pixels. You could iterate then one by one starting at pixel  $0$ and ending with pixel $76800-1$. However, there was some clever trick using an and mask and multiplication or addition with some magic constants. I don't remember the specifics. This resulted in a pseudo-random iteration over the pixels. No pixel was ever visited twice and all pixels were visited. How can this be done? How should I approach this problem? What is this problem called?
Answer: There are several methods. For example, it turns out that $p=76800+1$ is prime; therefore one can take any $k$ with $1\le k<p$ and then has that $ki\equiv kj\pmod p$ implies $i\equiv j\pmod p$. Especially, $ki\bmod p$ iterates over $\{0,\ldots,p-1\}$ as $i$ runs from $0$ to $p-1$:
#define K 47465
#define P (320*240+1)
ki = K;
for (;;) {
   setpixel(ki-1);
   ki += K;
   if (ki>=P) {
       ki -= P;
       if (ki==0) break;
   }
}

(I defined $K$ to be close to th egolden ratio times $p$).
This is not "good" pseudorandom however as the pixels appear "too" uniformly.
Comment: thanks for your answer. I tried it on real quick and it really iterates through each pixel exactly once. Impressive! But it has a very regular pattern for all values of K i tried, since each pixel is K pixels apart. Perhaps this is the base of the algorithm and then some other operation can make it more irregular?
Comment: I found this interesting link http://en.wikipedia.org/wiki/Linear_congruential_generator
Comment: I tried with a=4013, c=4223, m=76800 just to give some numbers that satisfied the constraint specified. But the period was 1024 and not 76800... Perhaps I'm missunderstanding something, but the LCG feels relevant.
Answer: This is done by using a Linear Congruential Generator (LCG). It's a very basic pseudo-random generator. The state is contained entirely in the last produced number and the next random number in the range is obtained as.
$x_{n+1} = (ax_n + c) \mod m;$
Where $a$, $c$, and $m$ are constants that can be used to very the series. Also $x_0$ is the seed or initial value.
Also the series is know to have a period of $m$ if and only if (from the wikipedia page)

$c$ and $m$ are relatively prime,
$a - 1$ is divisible by all prime factors of $m$
$a - 1$ is a multiple of $4$ if $m$ is a multiple of $4$.

For this particular case, as the period should be $320 \times 240=76800$ we let

$m = 76800$
$c$ can be set to any value not sharing any divisiors with $m$ such as $7$.
$a = 3 \times 5 \times 4 \times k + 1$ where $k$ is any multiplier larger than 1.

Varying $x_0, c, k$ should give various interesting dissolve effects.
I wrote a small C-program with c = 7, k = 77 and a = 3 * 5 * 4 * k + 1

#include <unistd.h>
// Linear Congruential Generator
int main() {
    const int w = 320, h = 240;
    const int m = w * h;
    const int c = 7;
    const int k = 77;
    const int a = 3 * 5 * 4 * k + 1;
    const int speed = 1500;
    unsigned int buffer[w * h];
    int index = 0;
    int i;

    for (i = 0; i < m; i++) {
        buffer[index] = 0xffffffff;
        index = (a * index + c) % m;
        if (i % speed == 0) write(STDOUT_FILENO, buffer, sizeof(buffer));
    }

    for (i = 0; i < m; i++) {
        buffer[index] = 0xff000000;
        index = (a * index + c) % m;
        if (i % speed == 0) write(STDOUT_FILENO, buffer, sizeof(buffer));
    }
}

Test it like so:
$gcc a.c && ./a.out | ffplay -f rawvideo -pixel_format rgb32 -video_size 320x240 -i -

Pseudo random ordering of integers


The expected log-Likelihood in Kullback Leibler Divergence

Question: Given a true normal distribution $g(x)$ with mean $\mu_G$ and variance $\sigma_G$, and a model $f(x)$, the KL divergence involves the expected log-likelihood $\mathbb{E}_G[log f(x|\theta]$. The likelihood function is given by
$$log f(x|\mathbb{\theta})=-\frac{1}{2}log(2\pi\sigma^2)-\frac{(x-\mu)^2}{2\sigma^2}$$
I read, that $\mathbb{E}_G[log f(x)|\theta]$ equals
$$-\frac{1}{2}log(2\pi\sigma^2)-\sigma_G^2+\frac{(\mu-\mu_G)^2}{\sigma^2}$$
but I do not understand how this result($\sigma_G^2+\frac{(\mu-\mu_G)^2}{\sigma^2}$) is obtained.
Answer: Hint:
\begin{align}
\int (x - \mu)^2 g(x) dx &= \int (x -\mu_G + \mu_G - \mu)^2 g(x) dx \\
&= \int(x - \mu_G)^2 g(x) dx + \int (\mu_G - \mu)^2 g(x) dx + 2\int (x - \mu_G)(\mu_G - \mu)g(x) dx \\
&=\sigma_G^2 + (\mu_G - \mu)^2 + 0
\end{align}


How can I determine the vector the the solutions to $A\overrightarrow { x } = 0$ lie on?

Question: This question was taken from MIT OCW and Introduction to Linear Algebra by Gilbert Strang
Write the dot product of $(1,4,5)$ and $(x,y,z)$ as a matrix multiplication of $A\overrightarrow { x } $. The matrix $A$ has one row. The solutions to $A\overrightarrow { x } = 0$ lie on a ____ perpendicular to the vector ____. The columns of $A$ are only in ____-dimensional space.
What I understand thus far and what I need clarification on:
1) The solutions to $A\overrightarrow { x } = 0$ lie on a plane. However, the answer saids: "...on a plane in three dimensions". Why?
2) ...perpendicular to the vector ____.
I don't understand this part. The solution to this is the $0$ vector, no?
3) The columns of $A$ are only in one-dimensional space, since matrix $A$ is $[1,4,5]$
Answer: The dot product of n-tuples (scroll down to Tuples under Vectors) is given by $$\vec a \cdot \vec b = (a_1, a_2, \dots, a_n) \cdot (b_1, b_2, \dots, b_n) = a_1b_1 + a_2b_2 + \cdots + a_nb_n$$
This can be calculated by converting the vectors $\vec a$ and $\vec b$ into column matrices: $\mathbf a = \pmatrix{a_1 \\ a_2 \\ \vdots \\ a_n}$ and $\mathbf b = \pmatrix{b_1 \\ b_2 \\ \vdots \\ b_n}$.  Then $$\mathbf a^T\mathbf b = \pmatrix{a_1b_1 + a_2b_2 + \cdots + a_nb_n} = \pmatrix{\vec a \cdot \vec b}$$
If we think of $n$-tuples as arrow vectors in Euclidean space, then we can test for perpendicularity (denoted $\vec a\ \bot\ \vec b$) of two vectors by using the dot product and noting that $$\vec a\ \bot\ \vec b \iff \vec a \cdot \vec b = 0$$
Now let's look at the dot product of $(1,4,5)$ and $(x,y,z)$.  Your question asks about solutions to $(1,4,5)\cdot (x,y,z)=0$.  Using the above relationship between the dot product and perpendicularity we can see that the solution set to this equation is all of the vectors perpendicular to $(1,4,5)$.
I don't know how far you've gotten into Linear Algebra, but because $3$-tuples are members of $\Bbb R^3$, which is a $3$-dimensional space, the subspace of $\Bbb R^3$ perpendicular to a given nonzero vector will be a $2$-dimensional space: i.e. a plane.  That's what the solution set is here.
Does that help you understand your questions better at all?
Comment: Yes, I appreciate your input.
Answer: The dot product satisfies $\boldsymbol{x} \cdot \boldsymbol{y} = \|\boldsymbol{x}\|\|\boldsymbol{y}\|\cos \theta$, where $\|\boldsymbol{x}\|$ denotes the Euclidean length of the vector $\boldsymbol{x}$ and $\theta$ is the angle between them. Thus, if $\boldsymbol{x} \cdot \boldsymbol{y}= 0$ then the two vectors are perpendicular. The condition that $A \cdot \boldsymbol{x} = 0$ thus means that $A = (1,4,5)$ is perpendicular to $\boldsymbol{x}$.
Comment: So, the solutions to $A\overrightarrow { x } = 0$ are perpendicular to $\overrightarrow { x }$?
Comment: The solutions *are* the possible values of $\vec x$.  The solutions are perpendicular to $(1,4,5)$.


Sender address rejected: not owned by user

Question: I've a Postfix installation in my SBC running Parabola GNU/Linux-libre (Arch and ALARM-based) plus Dovecot.
It works pretty well, and I've set up an account in Thunderbird. The only issue I've found is that when sending emails I get:
Sender address rejected: not owned by user megver83

And I have looked for the solution everywhere, for e.g.

Postfix rejects sender address
`Sender address rejected: not owned by user` in Postfix
Postfix sender address rejected / using multiple addresses

but nothing, it's really insane. Sometimes in the issues they solve are by using MySQL but pitifully MySQL doesn't work in my server, so I've installed PostgreSQL just in case.
mail.log:
Aug 28 16:27:30 localhost postfix/smtpd[12064]: connect from gateway[192.168.50.1]
Aug 28 16:27:31 localhost postfix/smtpd[12064]: Anonymous TLS connection established from gateway[192.168.50.1]: TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)
Aug 28 16:27:31 localhost postfix/trivial-rewrite[12070]: warning: do not list domain eumela.ga in BOTH mydestination and virtual_alias_domains
Aug 28 16:27:31 localhost postfix/trivial-rewrite[12070]: warning: do not list domain eumela.ga in BOTH mydestination and virtual_mailbox_domains
Aug 28 16:27:31 localhost postfix/smtpd[12064]: NOQUEUE: reject: RCPT from gateway[192.168.50.1]: 553 5.7.1 <email@example.com>: Sender address rejected: not owned by user megver83; from=<firstname.lastname@example.com> to=<firstname.lastname@example.com> proto=ESMTP helo=<[192.168.50.10]>
Aug 28 16:27:33 localhost postfix/smtpd[12064]: disconnect from gateway[192.168.50.1] ehlo=2 starttls=1 auth=1 mail=1 rcpt=0/1 quit=1 commands=6/7

Here^ I tried to auto send me a mail, but happens with all the addresses I write to.
$ postconf -n
alias_database = $alias_maps
alias_maps = hash:/etc/postfix/aliases
append_dot_mydomain = no
biff = no
broken_sasl_auth_clients = yes
command_directory = /usr/bin
compatibility_level = 2
daemon_directory = /usr/lib/postfix/bin
data_directory = /var/lib/postfix
debug_peer_level = 2
debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5
home_mailbox = Maildir/
html_directory = no
inet_interfaces = all
inet_protocols = ipv4
mail_owner = postfix
mailbox_size_limit = 134217728
mailq_path = /usr/bin/mailq
manpage_directory = /usr/share/man
message_size_limit = 134217728
meta_directory = /etc/postfix
mydestination = localhost.$mydomain, localhost, $mydomain, smtp.$mydomain
mydomain = eumela.ga
myhostname = pi.eumela.ga
myorigin = $mydomain
newaliases_path = /usr/bin/newaliases
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix
relay_domains = *
relayhost =
sample_directory = /etc/postfix
sendmail_path = /usr/bin/sendmail
setgid_group = postdrop
shlib_directory = /usr/lib/postfix
smtp_tls_note_starttls_offer = yes
smtp_tls_security_level = may
smtpd_helo_required = yes
smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain =
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_sender_login_maps = $virtual_mailbox_maps
smtpd_tls_cert_file = /etc/letsencrypt/live/smtp.eumela.ga/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/smtp.eumela.ga/privkey.pem
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_security_level = may
unknown_local_recipient_reject_code = 550
virtual_alias_maps = hash:/etc/postfix/virtual
virtual_mailbox_domains = hash:/etc/postfix/virtual-mailbox-domains
virtual_mailbox_maps = hash:/etc/postfix/virtual-mailbox-users

Answer: your SASL config parameters look proper - Postfix will rely on Dovecot for the authenticating part. I presume your authentication is working[1]. The user you authenticate with can differ from the email sender address. You want to tell Postfix which authenticated users do map to additional senders. It's by the way the same for receiving, where you can alias recipients to system users in /etc/aliases or via other means.
These lines show where to look
smtpd_sender_login_maps = $virtual_mailbox_maps
virtual_mailbox_maps = hash:/etc/postfix/virtual-mailbox-users

And edit the file accordingly, for example
#  envelope sender   owner (SASL login names)
email@example.com   user

Then run postmap -f /etc/postfix/virtual-mailbox-users and reload the postfix service. After this, postfix will allow you to send with the mapped entries.
[1]: for example: userdb {driver = passwd} and passdb {driver = pam} which would point to system user auth - or virtual users via passwd/userdb-file or SQL backend
Comment: This was the answer that I've been looking for all.  Thank you!
Answer: Oh, I see it was an issue with the master.cf file. Where it says:
  -o smtpd_helo_restrictions=reject_sender_login_mismatch

And just commented it
#  -o smtpd_helo_restrictions=reject_sender_login_mismatch

Comment: This is working, but unsecure workaround. Proper solution is to create sender map, as described here: https://serverfault.com/a/658688/36982
Comment: I replaced my front door and now my key doesn't work  ---  Re: You'll have to go to the hardware store and get a new key cut.   ---- Never mind, I just removed the lock.


images are not loading python

Question: hello i coded this simple game when it normal it working but when i make it inside a function to make other screens but player and enemy images are not loading and i don't know why so i searched every web and i could not find an answer and i think finding answer from a coder is better so please help me
here is my code
import pygame, sys
import math
from pygame import mixer
import random

# initialize the pygame
pygame.init()

# the screen                      #width height
screen = pygame.display.set_mode((1080, 800))  # Y and X

# Background
background = pygame.image.load("background.jpg")

# Background sound
mixer.music.load("background.wav")
mixer.music.play(-1)

# Title and Icon
pygame.display.set_caption("Space invadars")
icon = pygame.image.load("icon.png")
pygame.display.set_icon(icon)

# Player
playerImg = pygame.image.load("player.png")
playerX = 500
playerY = 700
playerX_change = 0

# Ememy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 1

for i in range(num_of_enemies):
    enemyImg.append(pygame.image.load("enemy.png"))
    enemyX.append(random.randint(0, 1016))
    enemyY.append(random.randint(10, 100))
    enemyX_change.append(0.7)
    enemyY_change.append(40)

# Bullet
bulletImg = pygame.image.load("bullet.png")
bulletX = 0
bulletY = 700
bulletX_change = 0.8
bulletY_change = 3
bullet_state = "ready"

# kills
kills_value = 0
kills_value_font = pygame.font.Font("Alien.ttf", 32)

textX = 10
textY = 10

# Game Over text
game_over_font = pygame.font.Font("Alien.ttf", 72)

def show_kills(x, y):
    kills = kills_value_font.render("Aliens Killed :" + " " + str(kills_value), True, (25, 184, 255))
    screen.blit(kills, (x, y))

def game_over_text():
    game_over_text = game_over_font.render("GAME OVER ", True, (25, 184, 255))
    screen.blit(game_over_text, (350, 400))

def player(x, y):
    screen.blit(playerImg, (x, y))

def enemy(x, y, i):
    screen.blit(enemyImg[i], (x, y))

def fire_bullet(x, y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bulletImg, (x + 16, y + 10))

def isCollision(enemyX, enemyY, bulletX, bulletY):
    distance = math.sqrt((math.pow(enemyX - bulletX, 2)) + (math.pow(enemyY - bulletY, 2)))
    if distance < 27:
        return True
    else:
        return False

def space_invadors():
    global playerX,playerY,playerX_change,bulletY,bulletX,bullet_state,kills_value,enemyY,enemyX,enemyX_change,playerImg
    while True:
        # screen
        screen.fill((29, 41, 81))
        # Background image
        screen.blit(background, (0,0))
        screen.blit(playerImg,(0,0))
        screen.blit(bulletImg, (0,0))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

            # if keystroke is pressed check whether its right or left
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    playerX_change = -1
                if event.key == pygame.K_RIGHT:
                    playerX_change = +1
                if event.key == pygame.K_SPACE:
                    if bullet_state == "ready":
                        bullet_sound = mixer.Sound("laser.ogg")
                        bullet_sound.play()
                        bulletX = playerX
                        fire_bullet(bulletX, bulletY)

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    playerX_change = 0

        # keeping the player inside the game cords
        playerX += playerX_change

        if playerX <= 0:
            playerX = 1016
        elif playerX >= 1016:
            playerX = 0
        # Bullet movement
        if bulletY <= 0:
            bulletY = 700
            bullet_state = "ready"
        if bullet_state == "fire":
            fire_bullet(bulletX, bulletY)
            bulletY -= bulletY_change
            # keeping the player inside the game cords

            playerX += playerX_change

            if playerX <= 0:
                playerX = 1016
            elif playerX >= 1016:
                playerX = 0
            # Bullet movement
            if bulletY <= 0:
                bulletY = 700
                bullet_state = "ready"
            if bullet_state == "fire":
                fire_bullet(bulletX, bulletY)
                bulletY -= bulletY_change

            # enemy movement

            for i in range(num_of_enemies):

                # Game Over
                if enemyY[i] > 645:
                    for j in range(num_of_enemies):
                        enemyY[j] = 2000
                    game_over_text()
                    break

                enemyX[i] += enemyX_change[i]
                if enemyX[i] <= 0:
                    enemyX_change[i] = 0.7
                    enemyY[i] += enemyY_change[i]
                elif enemyX[i] >= 1016:
                    enemyX_change[i] = -0.7
                    enemyY[i] += enemyY_change[i]
                # collision
                collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
                if collision:
                    dieing_sounds = mixer.Sound("gotcha-bitch.mp3")
                    dieing_sounds.play()
                    bulletY = 700
                    bullet_state = "ready"
                    kills_value += 1
                    enemyX[i] = random.randint(0, 1016)
                    enemyY[i] = random.randint(10, 100)
                enemy(enemyX[i], enemyY[i], i)

        (playerX, playerY)
        show_kills(textX, textY)
        pygame.display.update()

pygame.display.update()
space_invadors()

Answer: Try inserting the images in the functions. For example. Change this:
def player(x, y):
    screen.blit(playerImg, (x, y))

to this:
def player(x, y, playerImg):
    screen.blit(playerImg, (x, y))

Or maybe better:
def blit_img(x, y, img):
    screen.blit(img, (x, y))

blit_img(10, 20, playerImg)
blit_img(30, 20, enemyImg[0])
blit_img(60, 20, enemyImg[1])

images are not loading python


WooCommerce : set TAX on product page

Question: I'd like to set a specific Tax on each product.
I see i can create tax classes, but i'm going to have many different taxes, one per product, on more than 300 products.
Is it possible to set the tax % on the product page when i create it ?
Do you know a plugin for that ?
Comment: You can set the tax class via the function set_tax_class() on a product when you save it.  Hook into the save_post hook to set the tax class. https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html
Comment: thanks for your reply @AndrewSchultz, so i need to code something custom ? or is there a plugin for that ?
Comment: I don't know of any plugins that would do that it seems like a unique case that you have.
Answer: What want to do is to calculate Tax Based On SKU and not shipping address.
So i need to have a field on product page where i can enter a TVA number, manually.
Do you think it's possible ?
OR an other way maybe :
- have one taxe class
- in the tax class add many taxes rates with all the same country code, and no zip code
- create a field in the product page to assign the right tax rate for the product (instead of assign a class rate)
What do you think about that ?

WooCommerce : set TAX on product page


Identifying Modes

Question: I'm getting introduced to modes and got a small homework assignment to identify the modes of some short melodies. The problem is I'm not sure that I'm following the guideline correctly, and I can't ask my teacher because he's currently on a leave and I have to upload the solution to the school's website.

I solved it as if the last note, B flat, was the "root" of the mode and find its relations with the other notes, which would mean the first melody (I think) is in Dorian mode. Am I doing it correctly? In general does "do" represent the root/tonic of a scale or a mode?
Answer: You're doing it 100% correctly, yep!
"Do" is just a solfége term for tonic, so in this case this is a B-flat mode. Since we have Df and Af, we're looking at B-flat Dorian.
Comment: There are basically two systems. In *fixed* systems, "do" is always C. In *movable* systems, "do" is always the tonic.
Comment: I was taught that "Do" corresponds to the C note and it's not just a term for tonic.
Comment: ok that makes sense wasnt aware of the movable system
Comment: There's Bb and Eb in there too, making the parent key Ab, (four flats)  thus Bb Dorian. But I guess with Ab and Db in there, these two are a given.
Answer: It's in Dorian correct. The G note gives it away.
here are the degrees also.
Bflat(TONIC)
C(SUPERTONIC)
Dflat(MEDIANT)
Eflat(SUBDOMINANT)
F(DOMINANT)
G(SUBMEDIANT)
Aflat(LEADING TONE)
Comment: How does the G note give it away?
Comment: Presumably because Gf would mean it was just natural minor/Aeolian.
Comment: Only insofar as 6 rises to ♭7. ♭6 was standard _ficta_ for Dorian mode.

Identifying Modes


How to configure public ip on azure

Question: I have configure public ip on azure in my environment but when i check outside this environment it's not working so my question is how to set globally public ip on azure.
Comment: Welcome to Stackoverflow! Can you please elaborate your question having your effort like code or something so that people could get your problem early and help you? Thanks!
Answer: Add two more tips, to check the public IP address works, you need open NSG inbound rule (3389 for RDP), also use PSPing instead of ICMP PING tool.
Answer: Just login to portal. select VM. In settings go to PIP (Public IP)
Mark for it. This is you have done.
Now check whether you have open ports and IPs for same under NSG or sort of security groups. If it is public IP then you should be able to ping.
Please check for same.
Thanks
Comment: This is incorrect. ICMP is not permitted from outside of Azure.

How to configure public ip on azure


IOS UICollectionView throws assertion when using two collection views

Question: I have two UICollectionViews in a single UIViewController. I am separating them by tag number so that I can use the data source and delegate methods for both. However, when I run the code it crashes with the Exception:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist: <NSIndexPath: 0xc000000000200016> {length = 2, path = 0 - 1}'.
I looked this up in the forum and most people say you need to invalidate then reload the UIControllerView but in my case this is not working.
Anyone have idea how to fix this issue ?
Here is my code:
-(void)viewDidLoad {

    self.socialMediaGrayIcons = [[NSMutableArray alloc] initWithObjects:[UIImage imageNamed:@"fb-gray.png"],
                            [UIImage imageNamed:@"twitter-gray.png"],
                            [UIImage imageNamed:@"insta-gray.png"],
                            [UIImage imageNamed:@"sms-gray.png"],
                            [UIImage imageNamed:@"email-gray.png"], nil];

    // setup collection view
    self.avatarCollectionView.tag = 200;
    self.socialMediaCollectionView.tag = 201;

    UINib *cellNib = [UINib nibWithNibName:@"NibCell" bundle:nil];
    [self.avatarCollectionView  registerNib:cellNib forCellWithReuseIdentifier:@"cvCell"];
    [self.socialMediaCollectionView  registerNib:cellNib forCellWithReuseIdentifier:@"smCell"];

    // setup collection view layout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setItemSize:CGSizeMake(40, 40)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];

    [self.avatarCollectionView setCollectionViewLayout:flowLayout];
    [self.socialMediaCollectionView setCollectionViewLayout:flowLayout];

    [self.avatarCollectionView reloadData];
    [self.avatarCollectionView.collectionViewLayout invalidateLayout];

    [self.socialMediaCollectionView reloadData];
    [self.socialMediaCollectionView.collectionViewLayout invalidateLayout];
}

....

#pragma mark UICollectionView DataSource and Delegate mathods
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView.tag == 200)
    {
        return self.children.count;
    } else if (collectionView.tag == 201){
        return self.socialMediaGrayIcons.count;
    }

    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell;

    if (collectionView.tag == 200)
    {
        static NSString *cellIdentifier = @"cvCell";
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

        Child *currentChild = [self.children objectAtIndex:indexPath.row];

        UIImage *curImage = [UIImage imageWithData:currentChild.thumbnail];
        UIImageView *thumbView = (UIImageView *)[cell viewWithTag:100];

        if (curImage != nil)
        {
            [thumbView setImage:curImage];

        }
    } else if (collectionView.tag == 201){

        static NSString *cellIdentifier = @"smCell";
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

        UIImage *curImage = (UIImage*) [self.socialMediaGrayIcons objectAtIndex:indexPath.row];
        UIImageView *thumbView = (UIImageView *)[cell viewWithTag:101];

        if (curImage != nil)
        {
            [thumbView setImage:curImage];

        }
    }

    return cell;
}

Comment: Don't use tags. Simply store each of your collection views as properties and then compare the received collectionview argument against the property to determine which collection view you are being asked about
Comment: There's some evidence here that your `numberOfItemsInSection` is falling through to the nonsensical `return 1` at the bottom and that one of the arrays has 0 elements.
Comment: This [Answer](http://stackoverflow.com/questions/18371184/how-do-i-add-two-collectionviews-on-one-viewcontroller)  cover your question. hope it helps...
Answer: Taking @Paulw's good advice looks like this:
@property(weak,nonatomic) IBOutlet UICollectionView *collectionViewA;
@property(weak,nonatomic) IBOutlet UICollectionView *collectionViewB;

Your datasource methods have to be religious about always dividing in two branches of a conditional based on the collection view they were passed, and always using one datasource array in one and the other in the other.
You can enforce this religion by always getting your datasource via a convenience method, like this...
- (NSArray *)datasourceForCollectionView:(UICollectionView *)collectionView {
    if (collectionView == self.collectionViewA) {
        return self.children;
    } else { // NOTICE - no else-if, there's no other valid condition
        return self.socialMediaGrayIcons;
    }
}

Use it everywhere, as in...
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self datasourceForCollectionView:collectionView].count;
}

Comment: How would I use the convenience method for - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath where one of the array's holds UIImage objects and the other Child objects ?
Comment: Get the array using the convenience method before the condition. Then reference the array at indexPath.row and cast that element as appropriate in each branch.
Comment: still same crash after making your suggested changes
Comment: Add an exception break point to identify the line. I'll be at a dev machine again in about an hour
Comment: I put an exception break point and it doesn't show the line .. it still breaks in main.
Comment: Hmm.  Can you comment out everything pertaining to layout and just reload data for both?  Same thing?
Comment: ok, so I took out these lines and it stopped crashing:   [self.avatarCollectionView setCollectionViewLayout:flowLayout]; [self.socialMediaCollectionView setCollectionViewLayout:flowLayout]; Why would the flow layout cause this issue
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/139860/discussion-between-joel-parker-and-danh).


Why am I getting "Access Denied" on /user/login?

Question: Not sure what happened with my Drupal site, but I can't log in :s
When I go to /user/login, /user, /?q=user, /admin, whatever I just get "Access Denied", never presented with a Login form. Server response is 403.
Drupal 6 site.
Comment: You are seeing the Drupal-generated Access denied page or a some other 403 page ?
Answer: Probably your IP has been blocked as a potential source of flooding/DoS attack. This may happen if there were a lot of requests from the same IP.
That happened to my company's site once when we rearranged our LAN structure so all intranet users could only access the site through proxy server, and proxy server IP was blocked by Drupal automatically.
You need to check flood table - there must be a record with your IP. Just delete that record or all records (DELETE from `flood`).
Comment: makes sense, but flood is empty :s
Comment: Then maybe it is a network problem? Some proxy/firewall. If it is only 403 response for the login page, then maybe it is some custom module or something in `.htaccess`