Q:

Openstack/PackStack basic multi-node network setup

Background
After having installed OpenStack with PackStack we are left with a problem with the networking. We wanted a super-simple network with one subnet where all the virtual machines should reside, as this looked like the simplest solution. We have to begin with three nodes which is running nova.
The answer file we have used is this: answer file (pastebin)
Our setup
Three nodes with CentOS 6.5 where the nodes are connected to two switches.

eth0: public
eth1: internal network, ip 10.0.20.0/24 where node1 (10.0.20.1), node2 (10.0.20.2)...
The switch ports is not vlan tagged or trunked (unfortunately).
We want the instances to be able to communicate, but also access internet.

Security group rules
Ingress IPv4    TCP 1 - 65535   0.0.0.0/0 (CIDR)
Ingress IPv4    TCP 22 (SSH)    0.0.0.0/0 (CIDR)
Ingress IPv6    Any -       default
Ingress IPv4    TCP 22 (SSH)    10.0.20.0/24 (CIDR)
Ingress IPv4    TCP 53 (DNS)    0.0.0.0/0 (CIDR)
Egress  IPv4    Any -       0.0.0.0/0 (CIDR)
Ingress IPv4    ICMP    -       0.0.0.0/0 (CIDR)
Egress  IPv6    Any -       ::/0 (CIDR)
Ingress IPv4    Any -       default

Neutron
(neutron) agent-list
+--------------------------------------+--------------------+------------------------
| id                                   | agent_type         | host  | alive | admin_state_up
+--------------------------------------+--------------------+------------------------
| 09add8dd-0328-4c63-8a79-5c61322a8314 | L3 agent           | host3 | :-)   | True
| 0d0748a9-4289-4a5d-b1d9-d06a764a8d25 | Open vSwitch agent | host2 | :-)   | True
| 258c92fe-8e3a-4760-864e-281a47523e85 | Open vSwitch agent | host1 | :-)   | True
| 2e886dc1-af93-4f4f-b66c-61177a6c9dba | L3 agent           | host1 | :-)   | True
| 50f37a33-2bfc-43f2-9d2f-4f42564d234d | Open vSwitch agent | host3 | :-)   | True
| 535bf0a3-06aa-4072-ae5a-1b1ba1d377ab | L3 agent           | host2 | :-)   | True
| 9b17ef73-a602-4b5d-a4e9-e97445e594b4 | DHCP agent         | host1 | :-)   | True

ovs-vsctl

Host1

ovs-vsctl show
43da814e-223c-4f66-ba2d-c3c9de91e1f8
    Bridge br-ex
        Port br-ex
            Interface br-ex
                type: internal
    Bridge br-int
        Port br-int
            Interface br-int
                type: internal
        Port "tap3e0d3121-32"
            tag: 4
            Interface "tap3e0d3121-32"
                type: internal
        Port "tap4a397755-29"
            tag: 4
            Interface "tap4a397755-29"
    ovs_version: "1.11.0"

Host2

afa75816-6a40-4f0c-842f-236a3a94cd63
    Bridge br-int
        Port br-int
            Interface br-int
                type: internal
        Port "tap46f55af8-73"
            tag: 1
            Interface "tap46f55af8-73"
    Bridge br-ex
        Port br-ex
            Interface br-ex
                type: internal
    ovs_version: "1.11.0"

Out problem
Instances are not able to communicate to each other, and are not able to reach internet. Frankly we are not sure what the requirements for this is when using a multi-node nova setup when the "internal" network between the nodes is only using one link.
I think the problem is a routing problem, since we are not able to connect between the instances on different nodes, but after having read a LOT of documentation, I am not quite sure how to proseed. If I tcpdump the interface br-int I can se the ARP requests, but nothing more. That is if I try to ping from a instance on the respective host.
The question
So the question is: How can we proseed in finding the solution to this multi-node network problem, and what do we need to think about? Could it be the routing, or a misconfiguration with the host os or openstack? (Running CentOS).
Any feedback is highly appriciated, since we have been stuck at this point for a couple of weeks. Sorry for the long post, but I hope the needed information is in here. If not; dont be shy :)
Update
I have been able to fix the internal network between the nodes, so that the instances are able to communicate between the physical nodes.
- Changed the /etc/neutron/plugins/openvswitch/ovs_neutron_plugin.ini:
[database]
connection = mysql://neutron:password@127.0.0.1:3306/ovs_neutron

[OVS]
tennant_network_type = gre
tunnel_id_ranges = 1:1000
integration_brige = br-int
tunnel_bridge = br-tun
local_ip = 10.0.20.1
enable_tunneling = True

- Restarted the service on controller
cd /etc/init.d/; for i in $( ls neutron-* ); do sudo service $i restart; done )
service openvswitch restart

This were done on all the nodes and created the GRE tunnels. Although the flow did not work, so i needed to use ovs-ofctl add-flow br-tun action=normal.
The current problem that I now have is being able to route the internal subnet to internet, so that all the instances get internet access. Do I need floating ips to be able to connect to the internet? There is no patch between br-int and br-ex or the routers, so is this needed to be able to route the traffic to internet?
Can I add a default route with ip netns exec ... ip add default gw via (ip of br-ex) or do I need to add some new interfaces?

A:

As previously updated I managed to get the network up and running by using GRE tunneling instead of nova network. Nova networking seams to be a ok solution if you have a spare physical network interface, but when you dont, it does not work that well.
The GRE setup were done with the following:
    - Changed the /etc/neutron/plugins/openvswitch/ovs_neutron_plugin.ini:
[database]
connection = mysql://neutron:password@127.0.0.1:3306/ovs_neutron

[OVS]
tennant_network_type = gre
tunnel_id_ranges = 1:1000
integration_brige = br-int
tunnel_bridge = br-tun
local_ip = "internal ip"
enable_tunneling = True

- Restarted the service on controller
cd /etc/init.d/; for i in $( ls neutron-* ); do sudo service $i restart; done )
service openvswitch restart

This were of copyed onto each compute node.
The important part though when using GRE tunnels is that when you create a new network, you need to specify the segmentation id. If you try to create the network via horizon it will not work.
keystone tenant-list
admin=$(keystone tenant-list | grep admin | awk -F' |' '{ print $2 }')
neutron net-create --tenant-id $admin network --provider:network_type gre --provider:segmentation_id 3
neutron subnet-create --tenant-id $admin network 192.168.0.0/24 --getaway 192.168.0.1

You can also add a external network with the following commands:
neutron net-create ext
neutron net-list
neutron subnet-create extnet --allocation-pool start=10.0.0.10,end=10.0.0.100 --gateway=10.0.0.1 --enable_dhcp=False 10.0.0.0/24

Then we can create a new router and attach the network to this external router. This is of cource just one of many solutions.
intsubnet=$(neutron subnet-list | grep 192.168.0.0/24| awk -F' |' '{ print $2 }')
extnet=$(neutron net-list | grep ext | awk -F' |' '{ print $2 }')

neutron router-create ext-to-int --tenant-id $admin
router=$(neutron router-list | grep ext-to-int | awk -F' |' '{ print $2 }')

neutron router-interface-add $router $intsubnet
neutron router-gateway-set $router $extnet

I had in the beginning very low throughput from the instances. This got solved when I distributed new MTU (1454) with DCHP (create a dhcp configuration file under /etc/neutron/ and add dhcp-option-force=26,1454 to the the file. Update dnsmasq_config_file in /etc/neutron/dhcp_agent.ini
This worked for me and was all that were needed.


Q:

Why is "&&" being used in closure arguments?

I have two questions regarding this example:
let a = [1, 2, 3];

assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
assert_eq!(a.iter().find(|&&x| x == 5), None);

Why is &&x used in the closure arguments rather than just x? I understand that & is passing a reference to an object, but what does using it twice mean?
I don't understand what the documentation says:

Because find() takes a reference, and many iterators iterate over references, this leads to a possibly confusing situation where the argument is a double reference. You can see this effect in the examples below, with &&x.

Why is Some(&2) used rather than Some(2)?

A:

a is of type [i32; 3]; an array of three i32s.
[i32; 3] does not implement an iter method, but it does dereference into &[i32].
&[i32] implements an iter method which produces an iterator.
This iterator implements Iterator<Item=&i32>.
It uses &i32 rather than i32 because the iterator has to work on arrays of any type, and not all types can be safely copied.  So rather than restrict itself to copyable types, it iterates over the elements by reference rather than by value.
find is a method defined for all Iterators.  It lets you look at each element and return the one that matches the predicate.  Problem: if the iterator produces non-copyable values, then passing the value into the predicate would make it impossible to return it from find.  The value cannot be re-generated, since iterators are not (in general) rewindable or restartable.  Thus, find has to pass the element to the predicate by-reference rather than by-value.
So, if you have an iterator that implements Iterator<Item=T>, then Iterator::find requires a predicate that takes a &T and returns a bool.  [i32]::iter produces an iterator that implements Iterator<Item=&i32>.  Thus, Iterator::find called on an array iterator requires a predicate that takes a &&i32.  That is, it passes the predicate a pointer to a pointer to the element in question.
So if you were to write a.iter().find(|x| ..), the type of x would be &&i32.  This cannot be directly compared to the literal i32 value 2.  There are several ways of fixing this.  One is to explicitly dereference x: a.iter().find(|x| **x == 2).  The other is to use pattern matching to destructure the double reference: a.iter().find(|&&x| x == 2).  These two approaches are, in this case, doing exactly the same thing. [1]
As for why Some(&2) is used: because a.iter() is an iterator over &i32, not an iterator of i32.  If you look at the documentation for Iterator::find, you'll see that for Iterator<Item=T>, it returns an Option<T>.  Hence, in this case, it returns an Option<&i32>, so that's what you need to compare it against.

[1]: The differences only matter when you're talking about non-Copy types.  For example, |&&x| .. wouldn't work on a &&String, because you'd have to be able to move the String out from behind the reference, and that's not allowed.  However, |x| **x .. would work, because that is just reaching inside the reference without moving anything.

A:

1) I thought the book explanation was good, maybe my example with .cloned() below will be useful. But since .iter() iterates over references, you have to specify reference additionally because find expects a reference.
2) .iter() is iterating over references; therefore, you find a reference.
You could use .cloned() to see what it would look like if you didn't have to do deal with references:
assert_eq!(a.iter().cloned().find(|&x| x == 2), Some(2));


Q:

chinese character in mysql insert and phpmyadmin

i have this chinese character which i want to insert into database and browser output in correct but when data is inserted into mysql it is in different format something like this.
my chinese characters
图片库,高清图片大全,图库
and inserted into database is
å›¾ç‰‡åº“,é«˜æ¸…å›¾ç‰‡å¤§å…¨,å›¾åº“
i have tried several things like setting utf8
     mysql_set_charset("utf8", $connection);

then chenaged the collation from swidish to utf general
then checked the details with this command which proved that my charcter is correctly set to utf8
   SHOW CREATE TABLE tablea;

   CREATE TABLE `tablea` (
   `id` int(12) NOT NULL AUTO_INCREMENT,
   `tiya` text CHARACTER SET utf8 NOT NULL,
   PRIMARY KEY (`id`),
  ) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

can anyone suggest where to solve chinese charracter issue .my insert is this
         mysqli_query ($con,"INSERT INTO tablea (tiya) VALUES ('$tit')");

A:

All of your entire environment must be utf-8-capable. The file encoding of you php-file must be utf-8. The web server (apache?) must serve utf-8. Your mysql table must have utf-8 as charset. You connection(s) must be utf-8.
If one in the chain is missing, you get the above results. Additionaly: if you tried to fiddle around with character conversion inbetween, this is probably mixed up entirely. Once the above chain is set up properly, no char conversion is needed at all.


Q:

Xcode 9 simulator doesn't save userdefaults

Maybe it's the same issue as this one. But few of the solutions that I have tried don't work.
The simulator don't save userdefaults on Xcode Version 9.0 beta 6 (9M214v).
I had Xcode 8 as well (together with 9) but removed it.
the code that I'm using:
UserDefaults.standard.setValue("1234567", forKey: "phone")
if let phone = UserDefaults.standard.value(forKey: "phone") as? String{
  //some code here
}

Additionally I have tried:
UserDefaults.standard.set("1234567", forKey: "phone")
if let phone = UserDefaults.standard.object(forKey: "phone") as? String{
  //some code here
}

A:

There are a lot of misunderstandings about what synchronize does and how user defaults are written. Before guessing at how things work, always check the current maintainer's commentary about it. He's pretty clear about things. His analogy to git is also somewhat useful, and see his notes about iOS 8 changes. NSUserDefaults changes way more than you would think it would for such an old piece of tech.
The short and long of it is that calling synchronize is almost never needed in a production app. (In fact, there's recurring discussion about deprecating and removing it.) As the docs note:

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

And even those cases mostly relate to macOS.

For applications running on iOS 9.3 and later / macOS Sierra and later, -synchronize is not needed (or recommended) even in this situation [synchronizing between processes], since Key-Value Observation of defaults works between processes now, so the reading process can just watch directly for the value to change. As a result of that, applications running on those operating systems should generally never call synchronize.

BUT.....
The usual problem people have with user defaults in the simulator is that they kill the app (hitting stop, restarting the app, crashing) before the write takes place. In production this generally isn't an issue. If you crash right around the time you're writing to user defaults, it's pretty likely you were in a poorly defined state anyway, so whether you wrote garbage, or wrote something good, or didn't write anything is all kind of a toss-up of what you would prefer. But when developing, program termination happens all the time, and often this leads to not writing out the user defaults.
Now one often-seems-to-work solution is to sprinkle synchronize all over the place. But for the most part that just slows your code down. If it works, fine. But in the majority of projects I've worked on, the real solution was just to take a breath before killing the app. It doesn't need a lot of time; just don't kill the app before it has a chance to write the thing you were saving before relaunching to check if it saved.


Q:

securing iphone + web app

I have an iphone app that retrieves and send data to a server that uses python.
What measures could i take in order to prevent security risks?
I an not handling extremely sensitive data but i wouldn't want people sniffing the contents.
Is using SSL enough to prevent most risks?
Thanks

A:

If you don't have super-sensitive data, you can also use HMAC messages in order to query your server. I've done this with several projects before.
The message sent to the server may be a little more heavy-weight but is a viable option if you don't want to go with getting a SSL certificate.


Q:

Why would the Iconians want to visit Toronto City Hall?

In the TNG episode "Contagion", the sister ship of the Enterprise-D, the USS Yamato, is destroyed.  An investigation into the cause leads the Enterprise to a planet in the Neutral Zone whose existence proves that the mythical "Iconians" — technologically-advanced beings who were purportedly able to hop nearly instantaneously from planet to planet — were real.
On Iconia, Picard, Data, and Worf enter a control room in which an inter-planetary gateway appears.  It seems to cycle between a number of pre-programmed destinations around the galaxy.
I watched the episode today and — being a Toronto resident at the moment — I was very surprised to see that one of the destinations is Toronto City Hall.  In the screen capture below, Worf is standing beside the gateway.  The two semi-circular towers and central pod of City Hall are clearly visible, as are the arches over the reflecting pool in Nathan Phillips Square (which City Hall is a part of).

Here is a photo of City Hall from almost the same angle:

The "Toronto" destination doesn't seem to be random necessarily, since the scene in the episode shows the gateway cycling between what appears to be a fixed number of destinations.
My question is:
Why would the Iconians want to visit Toronto City Hall (or whatever the building is supposed to represent here)?
I am interested in both in-universe and out-of-universe aspects of this issue.  Was this indeed Toronto in-universe, or was it supposed to represent somewhere else?  Out-of-universe, how did an image of Toronto City Hall come to be on The Next Generation as an alien vacation spot?
Having done a bit of research, I should add that I am already aware of the following dubious comment in the Memory Alpha article on the episode:

A stock photograph of Toronto City Hall was viewed through the Iconian gateway as a potential destination for the Iconians.  Due to the advanced age of the gateway, it is unlikely that this photograph was intended to represent the Earth city.

I can certainly accept that the building is not City Hall in-universe, but I find this unsupported comment dubious because of the way at which it arrives at its conclusion.  There is no indication in the episode that the imagery in the gateway is from the time that the gateway was built.  On the contrary, the images seem to be current, including the Enterprise-D bridge itself:

This comment aside, is there any information on the in-universe and out-of-universe reasons for why Toronto makes a cameo here?

A:

Another explanation is the Iconian gateway was semi-intelligent (think a dumbed down version of the Guardian of Forever) and could sense which species was accessing the portal. The gateway would then offer a (random?) location on that species' homeworld as a potential destination.
I don't think the image of Toronto City Hall necessarily implies the gateway permitted time travel into the past. It's not too farfetched that Toronto City Hall would still be standing in the future - after all, the Golden Gate Bridge has certainly survived into the 24th century.

A:

I have several in-universe theories:
Theory 1: Starfleet Conspiracy
In the non-canon TNG comic 'An Inconvenient Truth', it appears that the members of the Starfleet Conspiracy had an Iconian Gateway.  Now, we don't actually know where their base was:

it was located either on or in Earth or a near by body.

(Source)
If we assume that it was located on Earth, it could be that the base was somewhere near Toronto and the gateway on Iconia was pointing to that entrance.  A bit of a dodgy theory I concede, as the question then is raised of why it didn't just point directly to the gateway.
Theory 2: Time Travel
This concept is mentioned briefly on Memory Alpha (emphasis mine):

One of the images in "Contagion" is clearly recognizable as the city
  hall buildings of Toronto, Ontario in Canada. One could presume then
  that the city hall buildings remained standing in Toronto through the
  centuries or the Gateways traveled through time as well.

So, the Iconians may have set up this gateway to this particular location, knowing that in the future it would be a large business center on the planet Earth.
Theory 3: Future Plans
We know that the Iconians were a race which visited other planets and were spread throughout the galaxy.  It is possible that they had plans of visiting Earth, before the rest of the galaxy ganged up on them and bombarded them from space.  They just had not gotten around to visiting Earth yet and the place they chose was pure coincidence that Toronto City Hall was right in front of it.
This is my favourite theory and, although not supported by much evidence, is probably the most reasonable I expect.
Theory 4: Someone was tampering with the gateway
We see that in the DS9 episode To The Death that the Dominion get a gateway and seemingly manipulate it so they have access to several major sites, including Starfleet headquarters, Paris, Dozaria, Paris, Bajor and Cardassia.  Now, it seems unlikely to me that the Iconians would just happen to set this gateway to provide access to such strategically important areas during the Dominion War: it is most likely that the Dominion had manipulated it.  Hence, I propose this theory that someone else had found the Iconian gateway setup and had been playing with it, perhaps accidentally (or even intentionally) setting one of the destinations as being Toronto City Hall and then walking through, perhaps to a completely different setting!
Theory 5: It's not Toronto!
On the Memory Alpha page for the actual episode (Contagion) the following is suggested:

A stock photograph of Toronto City Hall was viewed through the Iconian
  gateway as a possible destination for the Iconians. Due to the
  advanced age of the gateway, it seems unlikely that this photograph
  was intended to represent the Earth city.

So, perhaps it wasn't even Toronto, but was some other planet altogether!
This is supported by a TOS comic where we see Toronto City Hall, but it isn't Toronto City Hall!:

(Source)
 Theory 6 (Kudos RobertF)
As explained in RobertF's answer (please upvote it!) it may have been that the Iconian Gateway was intelligent enough to detect the homeworlds of the crew and so portrayed it there.  Remember that the Iconian gateway also showed the Enterprise-D bridge - it seems a bit peculiar that it would show that merely by chance!

I acknowledge that I have only addressed the in-universe side of the question and I'll keep searching for relevant information about the out-of-universe decision to choose this site.


Q:

What program could I use on debian to countdown the time?

I'm trying out the http://www.pomodorotechnique.com/ technique and I'm looking for a GUI clock applet to keep track of the time.
I've tried timer-applet found by apt-cache search gnome timer but I'm looking for something more visually appealing - can anyone recommend a program?

A:

kteatime (from KDE, but should work under Gnome) is quite nice: http://runme.org/project/+kteatime/
But timer-applet also looks nice, so I'm not sure what you mean by "visually appealing". Could you explain?
If you want something simple but nice, you could also just write a shell script that plays a melody (random, if you want) every 25 minutes, or pops up a nice image...


Q:

Do we have to define one-to-many relationship natively in a db if we use @OneToMany annotation

I'm using hibernate 3.3.1 along with PostgreSQL 9.3 and I've written the following mapping:
@Entity
@Table(name = "player_account")
public class PlayerAccount {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @ManyToOne(targetEntity = Player.class, fetch = FetchType.EAGER)
    @JoinColumn(name="player_id")
    private Player player;
    //GET, SET methods
}

The question is do we actual have to specify that many-to-one raltionship in the database when we're creating a table? I mean to define a references in the following way:
CREATE TABLE player_account (
  SERIAL UNIQUE,
  player_id integer REFERENCES players
);

A:

No you don't need to define in database; but that foreign key column should be present in table. i.e. player_id should be present in player_account table.


Q:

Number of ways I can create positive 5-number integers (which are multiples of 5)

I've been unable to grasp how the following problem can solved:
Imagine all the positive integers you can create with 5 numbers (each of these 5 numbers has to be different), like 53486 or 91670. How many of these 5-number integers are multiples of 5?
So, essentially, I have to pick a number for 5 positions. The only numbers that can exist on position #5 are 0 and 5 (since it has to be a multiple of 5), and the number on position #1 can be anything but a 0 (or else I'd get a 4-number integer).
My real problem is, if I pick a 0 for position #5, then I still have 9 possible choices for position #1, but if I pick 5 for position #5, I only have 8 choices for position #1 (since the 5 was chosen and the 0 can never be on position #1). Regardless of what I choose for positions #1 and #5, I  will have 8 choices remaining for position #2, 7 choices for position #3 and 6 choices for position #4 (which I can calculate through 8 * 7 * 6).
But how do I handle the fact that position #1 can either have 9 or 8 possibilities, depending on what I pick for position #5? I apologize if this is a bit basic, but I'm being largely self-taught here, and no one I know is able to give me an answer.

A:

Do two cases:
Case 1:  Position $5= 0$.
then there are $9$ options for position $1$. And $8,7,6$ for positions $2-4$.
So there are $9*8*7*6$ ways to do this.
Case 2:  Position $5=5$.
There are $8$ options for position $1$ (it can't be $5$ or $0$).  And there are $8,7,6$ for position 2-4$.
So there are $8*8*7*6$ ways to do this.
So the total number of ways is $9*8*7*6 + 8*8*7*6$.
=====
Another way of putting it.
There are $9$ ways to choose position 1, if position 5 is $0$ and $8$ ways to choose position 1, if position 5 is $5$ and position 5 must be either $5$ or $0$.
So.... there are $17$ ways to choose position 1 and 5 and to think of them as a single unit with $17$ options.
So the ways to do it is $$\text{# of options for positions 1 and 5}\times \text{# of options for position 2}\times \text{# of options for position 3}\times \text{# of options for position 4} = 17*8*7*6$$.


Q:

Application window sent behind other windows on closing different thread (C#)

I'm writing a Windows Forms Application in C#.NET
On startup, the application displays a splash screen which is running in a separate thread.  Whilst the splash screen is showing, the main application is initialising.
Once the main application has finished initialising, the main form of the application is displayed, and the splash screen still shows over the top.
Everything so far is as expected.
Then, the Splash screen is closed, which causes that thread to exit.  For some reason, at the point, the main application windows gets sent behind all other open Windows, notably the Windows Explorer window where you clicked the .exe file to run the application in the first place!
What could be causing the windows to suddenly jump "behind" like this?

A:

Try calling .Activate() on your main window when your thread closes.
It's never been active, and thus has low Z-Order, so whatever is higher will naturally be above it. I had to fix this exact scenario in our app.
Don't forget! You may need to marshal the call to the correct thread using an Invoke()!


Q:

Service Application in WSS 3.0 doesn't save password

i'm trying to set service application account in WSS 3.0 for default application pool which hosts portal site.
But when i choose not to use default account and add another managed account, after the page refresh it shows me that this settings wasn't saved.
Still in IIS snap-in i see that application pool used credentials i put in CA.
Any information about this behaviour will be usefull.
Thanks.

A:

Do you find errors in your ULS logs that say "Access denied" or "unexpected error"? If so, check if your farm account has write permission on %windir%\tasks. You could also run psconfig, which will set the permissions for that account.


Q:

Using Javas System.out.format to align integer values

I am trying to produce right aligned numbers looking a bit like this:
  12345
   2345

but I clearly does not understand the syntax. I have been trying to follow these instructions. and Come up with the following attempt (it is integers so d and I want width 7 and 0 decimals):
public class test {

    public static void main( String[] args ) {
        System.out.format("%7.0d%n", 12345);
        System.out.format("%7.0d%n",  2345);
    }
}

but no matter what I do I seem to end up with IllegalFormatPrecisionException. Is there a way to do this using this tool? If not how else would you do it?

A:

You can do something like this:
public class Test {
    public static void main( String[] args ) {
        System.out.format("%7d%n", 12345);
        System.out.format("%7d%n",  2345);
    }
}

Essentially this code asks Java to pad the string with spaces so that the output is exactly 7 characters.


Q:

Lock buttons for further release in iOS

I've re-read apple's guides and there are no answer for me: my app is divided on levels -- first, second etc. User can't buy new level unless previous has not completed. I want to use built-it IAP and my problem - i've designed app for more than 10 levels, but really completed only a few -- should I remove all other levels buttons from main screen or I can left it in place with "disable" mode? I'm interesting in app review and possibility rejecting of app.

A:

It is possible that your app will be rejected if there are some buttons can not be clicked. Instead of leaving some buttons disabled, you'd better add some message to them, such as a lovely "Coming soon" screen will be a good idea and safe (See how the level-based game doing, Angry Bird or Cut the Rope).


Q:

Cloud Hosting for PHP - Explain away my fears?

So I've always relied on more traditional hosting when it comes to hosting my websites - either with shared or dedicated hosting. The time has come (or maybe it came long ago) for me to consider the cloud. But with the cloud come a few concerns (all arising out of my own ignorance) and I'm hoping StackOverflow can put my fears to rest.
While I've heard some answers to my questions in the past, I'm hoping to get enough feedback, and also hopefully provide a valuable resource to any others out there like me.
1) First off - how does it all work? I mean, I get the network of clouds, spinning them up and down as I need it. But until now, I've always opened up an FTP client, connected to my server and uploaded my website. My guess is this all works the same way with the cloud, but how is it all managed? How do I update files and how would I delete them? Would an FTP client suffice for the simple file-management of a website?
2) A lot of shared hosts use PHP4, and allow PHP5 with the right extension - how does this, and all the PHP extensions work? How would I turn on the mod_rewrite extension, for example? How would I select my version of PHP? Can I curl?
3) What about things like cron jobs, or administrating a mysql database? Can I access my database via a phpmyadmin interface, or via the MySQL Query Browser?
4) Lastly, how does the cost really compare to shared hosting? I know it all depends on traffic, so to phrase my question differently, where do the cost lines intersect (if at all?) For example, if I pay $100/month for a dedicated server, and can support 300,000 page visits, or 2-3 page visits per second, what would the cost be for similar usage?
As always, I appreciate the help, and hope it's enough to encourage me to use the cloud. It's so fancy!

A:

I'd vote for Cloud Sites http://www.rackspace.com/cloud/cloud_hosting_products/sites/
I'd imagine the methods used to manage your site (in the case of Cloud Sites) would be very similar to that of your traditional shared hosted with something like Plesk or CPanel installed.


Q:

How to verify whether Site seal logo is preseneted in my site or not by selenium?

I have to capture Site seal. Which provided by third party for my site has been validated and is secured for online transactions. I couldn't capture its element id. If i right click it shows an alert "This Site Seal is protected". Is any way i can capture this by selenium.
you can find site seal below the bottom pan in this URL:https://www.grandstadium.tv/Default.aspx

A:

The HTML for the Site Seal is:

Unfortunately it does not have an ID for locating the element, however you could use the following XPath to locate it:
//img[@src='https://seal.networksolutions.com/images/prorecgreen.gif']

So your check might be:
assertVisible | //img[@src='https://seal.networksolutions.com/images/prorecgreen.gif']


Q:

When is a magneto more efficient than an alternator?

A magneto is device similar to an alternator for creating electrical energy.  Many small gas engines, including several road worthy motorcycles, use them to generate electrical energy.  They can be used for supplying spark or charging a battery.
I am guessing that efficiency (i.e. cost or power demand) plays the major role in deciding to use a magneto or an alternator. When is a magneto more efficient than an alternator? Is there some general rule of thumb used to decide which to use on an application?

A:

Magnetos are used to provide spark to spark plugs in an engine that does not require electronic fuel injection and variable valve timing. Or more accurately: a magneto can be used in the case where you simply need to fire spark plugs and not much else. They're simpler than alternators and thus more reliable, but a magneto the size of an alternator won't be able to produce nearly as much current as the alternator, making it useless in passenger cars. A magneto simply can't supply enough amps to charge a 12V battery capable of supporting your lights, stereo, engine management and electric windows.
Interesting fact: magnetos are used in some race cars in lieu of an alternator as part of a crank-fired spark plug setup. this is because this setup creates much less parasitic drag on the engine, thus freeing up more of the horses to turn the wheels.


Q:

php include failing?

I have this code:
if (file_exists(CHAL_DIR . $row['filename'])) { // Check if the file exists or not.
                         if(!include('' . CHAL_DIR . $row['filename'])) { // Include the Challenge's class file.
                            echo "Include failed.";
                         } else {
                            echo "I win.";
                         }

                    } else {
                         echo "File " . CHAL_DIR . $row['filename'] . " does not exist.";
                    }

But it is not printing any errors? It seems like it just kills the php code after that include? It doesnt even print Include failed.

A:

It depends on the content of the included file: if it has an exit call or any other sort of termination, then PHP will stop there.


Q:

reading DB credentials from props file in lift scala

I am just started working with Scala and lift frame work. i am trying to connect my DB using normal JDBC. i wish to read my DB credentials from the default.props file. i tried the following code so far:
in my default.props file:
db.class=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost/scalatest
db.user=root
db.password=

And in my boot.scala file i am trying to do the JDBC connection like this:
val filename = "/src/main/resources/props/default.props"
Props.whereToLook = () => ((filename, () => Full(new FileInputStream(filename))) :: Nil)

val DBDriver = Props.get("db.class").toString
val DBURL =  Props.get("db.url").toString
val DBUsrName =  Props.get("db.user").toString
val DBPass = Props.get("db.password").toString

Class.forName(DBDriver)
val conn  = DriverManager.getConnection(DBURL,DBUsrName, DBPass)

but while running the server using container:start command, fileNotFoundException is showing. can anybody tel what i have to do here. thanx in advance.

A:

Delete the line where you change Props.whereToLook. It should already be set to the right values. (more info on the Lift wiki)
A note: The contents of the src/main/resources folder will normally be added directly into your classpath at runtime. So the file src/main/resources/props/default.props should be available via a call to someClassInYourProject.getResourceAsStream("/props/default.props"). Don't try to refer to a file in your source directory at runtime, as it will only ever cause headaches later on.


Q:

Find first and last week days according to locale

I'm trying to find first and last week days based on the locale.
In U.S. week starts on Sunday, but in other countries it could start on Monday or even Saturday.
setlocale(LC_ALL, "en_US.UTF-8");
date_default_timezone_set("America/New_York");

$start_week = (new DateTimeImmutable());
$start_week = $start_week->modify('this week');
$end_week = $start_week->modify('this week +6 days');

$interval = new DateInterval('P1D');
$week_range = new DatePeriod($start_week, $interval, $end_week);

foreach($week_range as $week_day) {
  // $week_day starts with Monday, supposed to be Sunday
}

A:

One way to do this is to use the IntlCalendar class. It has a method getFirstDayofWeek(), which returns an integer, corresponding to the DOW_ constants in IntlCalendar:

const integer DOW_SUNDAY = 1 ;
const integer DOW_MONDAY = 2 ;
const integer DOW_TUESDAY = 3 ;
const integer DOW_WEDNESDAY = 4 ;
const integer DOW_THURSDAY = 5 ;
const integer DOW_FRIDAY = 6 ;
const integer DOW_SATURDAY = 7 ;

Use that to add days to the start day when calling DateTimeImmutable::modify() for the start day. See it in action with three locales (i.e. en_US, es_ES, sw_KE) in this phpfiddle.
$locale = 'es_ES'; //Spain Spanish locale
$cal1 = IntlCalendar::createInstance(NULL, $locale);
$firstDayOfWeek = $cal1->getFirstDayOfWeek();
$daysToAdd = $firstDayOfWeek - 2; //difference from US M-Sunday
echo 'locale: '.$local.' first day of week: '.$cal1->getFirstDayOfWeek().' days to add: '.$daysToAdd.'
';
$start_week = new DateTimeImmutable();
$start_week = $start_week->modify('this week +'.$daysToAdd.' days');
$end_week = $start_week->modify('+6 days');
$interval = new DateInterval('P1D');
$week_range = new DatePeriod($start_week, $interval, $end_week);

foreach($week_range as $week_day) {
    echo 'week day: '.$week_day->format('l m/d/Y').'
';
}


Q:

Ubuntu Firewall: How to drop all TCP reply packets from an IP address

I've got two Ubuntu boxes, A and B.
A is starting a TCP connection to B.
I want A's TCP SYN packet to arrive at B, but when B's SYN/ACK reply packet comes back to A, I want A's firewall to drop it.
What's the easiest way to accomplish this?

A:

The following iptables rule will drop ACK's from host A:

iptables -A INPUT -s ip.of.host.a/32 --protocol tcp --tcp-flags ACK ACK -j DROP

--tcp-flags is documented in the man page for iptables-extensions:

[!] --tcp-flags mask comp
      Match when the TCP flags are as specified. The first argument mask is the flags which we should examine, written as a comma-separated
  list, and the second argument comp is a comma-separated list of flags
  which must be set. Flags are: SYN ACK FIN RST URG PSH ALL NONE. Hence
  the command
 iptables -A FORWARD -p tcp --tcp-flags SYN,ACK,FIN,RST SYN

will only match packets with the SYN flag set, and the ACK, FIN and RST flags unset.


Q:

resConfigs per build type

How can I override the resConfigs per build types? I read that flavors would allow that, but I don't use them. I just want for my debug build another set of supported languges.
Here is what I tried:
buildTypes {
    debug {
        resConfigs "de", "en" // allow also german in debug builds
    }
    release {
        signingConfig signingConfigs.release
        resConfigs "en"       // english only releases
    }
}

Any simple idea how I can achieve that?

A:

For some reason the individual buildType configs doesn't support the resConfigs command as you point out, but defaultConfig does and then you can use this trick to manipulate it per build type even without flavors configured:
android {
    defaultConfig {
        resConfigs "en"
    }
    applicationVariants.all { variant ->
        if (variant.buildType.name.equals("debug")) {
            variant.mergedFlavor.resourceConfigurations.add("de")
        }
    }
}


Q:

Which is better of the two: effects happening before rolling, or after rolling?

Plenty of systems use both types of abilities "before a participant A rolls, add bonus/effect to opposed number/roll of Participant B" or "If a participant A would succeed, add bonus/effect to opposed number/roll of participant B and re-evaluate the situation"
I have been wondering which type of ability is the better one for players to use, or are they equal when considering optimization, system mastery and probability.
I think both kinds are present in the latest 5e dnd. For example you can see within fighter's archetype, battle master superiority die maneuvers to have both kinds. This is just for referencing an example but I want to keep this system neutral.

A:

The latter is strictly better. In cases where you have limited resources involved, you can choose whether or not to use them based on the roll, i.e. how much you think you need the effect. For example, only using a bonus when the roll isn’t good enough but close, or only using a penalty when the roll succeeds but only barely—cases where the bonus or penalty actually changes the result.
Whether or not you know the target number is irrelevant—knowing it allows you to be precise in your judgment, but even if you don’t, you can usually tell when using the effect is worthwhile, or at least tell when it clearly won’t be. For example, when a natural-1 is an auto-fail or a natural-20 is an auto-success, clearly expending some resource to apply a bonus or penalty is a waste of time.
When there aren’t limited resources involved, it doesn’t matter (and should just be a passive bonus).


Q:

Automatic Ejabberd clustering with EC2 (Amazon Web Services)

Using Ejabberd in EC2 as an XMPP server to send real-time information to clients...
How it is possible to set up clustering so that if the load on the server gets too much, Auto Scaling will create a new EC2 instance that is part of the Ejabberd cluster?
The documentation I've read suggests that you must already have the machines and manually configure each new one to be added to the cluster. Surely though you don't have to be running redundant EC2 instances just in case?

A:

You'll need to do this manually, however a single ejabberd server can handle quite a lot of traffic.  Each server adds a significant amount of available connections to your cluster, so it's not a common task.
That said, I'd really be careful running ejabberd in EC2.  I've been doing it for about a year, and we fight mnesia network partitioning pretty regularly.  Clustered ejabberd servers don't work very reliably in the EC2 network.


Q:

Is there a better way to coerce an integer to a floating point in Ruby besides .round(1)?

Just what the question says in the title. I have a pair of integers, I want to convert it to a floating point so that I can do floating point math on it (to get a nice percentage).
Right now my code looks like this.
(failure_and_run_count[:failure].round(1) / failure_and_run_count[:run].round(1)) * 100.0

Someone please tell me there is a nicer way to coerce the ints inside of failure_and_run_count to floating points.

A:

Two possible options:
The Float method takes its argument and converts it to a floating-point number, terminating the program with an error if that conversion fails.
(failure_and_run_count[:failure] / Float(failure_and_run_count[:run])) * 100.0

to_f: Converts the number to a Float. If the number doesn’t fit in a Float, the result is infinity.
(failure_and_run_count[:failure] / failure_and_run_count[:run].to_f) * 100.0

A:

There's the method to_f for the purpose:
1.to_f # => 1.0
1.to_f.class # => Float

In your example:
failure_and_run_count[:failure] / failure_and_run_count[:run].to_f * 100.0

Only one operand needs to be explicitly coerced to Float since the other is automatically coerced when you call the / method.
Pay attention because nasty things could happen:
''.to_f # => 0.0
nil.to_f # => 0.0
'foo'.to_f # => 0.0


Q:

A failed communication attempt

I wanted to talk to them about a majestic animal, but they laughed at me how could I find such an animal majestic. I told them what they are not allowed to do, but they insisted that they will do it anyway.
Despite all this, I still wanted to try to befriend them, so I promised I will bring presents to them. This is when they first panicked and then angrily chased me away.
Who was I talking to, and why did we misunderstand each other so much?

A:

You were talking to

German people.

However,

 you are relatively inexperienced in german yourself, and made many common englishmen's mistakes (like abusing cognates) while learning it, leading to all these misunderstandings.

For example, firstly,

you said "Eagle" or "Igel" when you meant "Adler", and was misunderstood as saying that hedgehogs were majestic animals.

Then,

When they said it wasn't majestic, you said "nicht müssen" (translating "not" and "must" individually) where you should have said "nicht dürfen". Instead of "must not", they understood "don't have to", so they continued.

You, aware of these misunderstandings, didn't blame them and instead tried to befriend them by promising a gift. However,

the word "gift" in German means "poison", so you went from being just a weird guy who likes hedgehogs to a psychopath who threatens people with poison (presumably because they don't share his affinity for hedgehogs).

And thats's when they panicked and started chasing you away.

A:

Haven't figured out the animals, but...
Your friend is misunderstanding you so much because

he's German. "Gift" is the German word for "Poison".


Q:

How do I load a java class (not a servlet) when the tomcat server starts

I need to continuously update and query a mysql database (and I don't think I need a servlet to do this, just a regular java class).  But I don't know how to call that class or run it when the servlet starts.

A:

Let that class implement ServletContextListener. Then you can do your thing in contextInitialized() method.
public class Config implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        // Webapp startup.
    }

    public void contextDestroyed(ServletContextEvent event) {
        // Webapp shutdown.
    }

}

Register it in web.xml as follows to get it to run:
<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

Or if you're already on Servlet 3.0, then just use @WebListener annotation on the class.


Q:

Change elements of activity_main by click from recyclerView in Kotlin

I need to change color of Button element from activity_main.xml by clicking the element in RecyclerView. The hex color value should be taken from selected item parameters.
Just because I'm new to Kotlin, do not understand how to perform it.

Here is MainActivity:
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        doAsync {
            val json  = URL("https://api.jsonbin.io/b/5e299cea5eae2c3a26db9cdf/2").readText()
            d("daniel", "json? $json")
//            val dataList: ArrayList<String> = ArrayList()
            uiThread {
                val stations = Gson().fromJson(json, Array<Stations>::class.java).toList()
                ElementsList.apply{
                    layoutManager = LinearLayoutManager(this@MainActivity)
                    adapter = ElementsAdapter(stations)
                }
            }
        }
    }
}

Here is ElementsAdapter (recyclerView):
class ElementsAdapter(private val stations: List<Stations>) : RecyclerView.Adapter<ElementsAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_sample, parent, false)

        return ViewHolder(view)
    }

    override fun getItemCount() = stations.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val stationItem = stations[position]
        val highlightColor = stationItem.properties.color
        val colorFilter = Color.parseColor(highlightColor)
        holder.nameStation.text = stationItem.properties.color
        holder.lineColor.setColorFilter(colorFilter, PorterDuff.Mode.SRC_ATOP)
        holder.view.setOnClickListener{
            val curValue = holder.adapterPosition
            val selectedValue = stations[curValue].name

//              something should be done here to change button's color

        }
    }

    class ViewHolder(val view: View): RecyclerView.ViewHolder(view){
        val nameStation: TextView = itemView.name_station
        val lineColor: ImageView = itemView.line_color
    }

}

A:

Follow below steps to achieve this
Step - 1: Change your ElementsAdapter's constructor to receive Activity instance like below:
class ElementsAdapter(private val context: Context, private val stations: List<Stations>) : RecyclerView.Adapter<ElementsAdapter.ViewHolder>() {

    ....

}

Step - 2: Create a callback function in MainActivity to change button's color
class MainActivity : AppCompatActivity() {

    ....

    fun updateButtonColor(hexColor: String) {

        // update button's color here
    }
}

And pass the activity instance during creation of adapter
adapter = ElementsAdapter(this@MainActivity, stations)

Step - 3: Inside onBindViewHolder's OnClickListener call the activity's updateButtonColor with appropriate HEX_COLOR
holder.view.setOnClickListener{
    val curValue = holder.adapterPosition
    val selectedValue = stations[curValue].name

    //something should be done here to change button's color

    (context as MainActivity).updateButtonColor(HEX_COLOR)
}


Q:

What is the "Twin Ciel" theory?

Given the highly positive response to my last question: Who stole my candy?, there seems to be a lot of speculation around this "Twin Ciel" theory or the idea of there being 2 Ciels.
So with that in mind, I am posting a follow-up question to that to ask for the full explanation of the theory and what this means for the series.
Can anyone shed some light, links, etc?

A:

So the twin Ciel theory has been floating around the fandom for a few years but has recently gained much more evidence in the last few chapters.
"The Double-Ciel Theory: A Kuroshitsuji Mystery" on Blogspot is the most in-depth explanation I could find, though it doesn't contain any recent evidence. To sum up the theory, some believe that Ciel

 is not the actual Ciel Phantomhive, but the younger more sickly twin of the real Ciel who was sacrificed.

In addition to the evidenced in that blog post, the most recent chapters show

 Agni looking at pictures of Ciel's family and saying "It can't be," then running off to protect Soma. He finds Soma with a gun at his head, and the person fires but misses and shoots Soma's hand. Soma then says "Why?" Now flash forward and "twin" Ciel and Sebastian come home to find the scene before them. Soma sees "twin" Ciel and hits him. Ciel also sees a bit of the picture Agni was looking at and says "it can't be," and then asks Sebastian "you wouldn't lie to me would you?" Which brings up the fact that Sebastian has never called "twin" Ciel, "Ciel"; only "young master".

These are by far the most compelling evidence so far the author has pushed towards supporting the twin theory.


Q:

How to set delay show and hide with JS

I have my code in below, I want to delay 3 seconds before the show in and when showing 3 texts is done, the last text will hide after 3 seconds (not repeat). My code not working as I want.
And I want to add some CSS show and hide effect like this:
But I don't know how I can do it.
Can you help me?
Thanks

var x = document.getElementById('x'),
    s = ['Hello', 'What can I help you ?', 'Click me to get some help!'];
(function loop() {
    s.length && (x.innerHTML = s.shift(), setTimeout(loop, 3000));
    return false;
})();
.speech-bubble {
 position: relative;
  padding:20px;

}

.speech-bubble:after {
content: '';
    position: absolute;
    right: 0;
    top: 50%;
    width: 0;
    height: 0;
    border: 10px solid transparent;
    border-left-color: #00aabb;
    border-right: 0;
    margin-top: 15px;
    margin-right: -10px;
}

span#x {
    color: white;
    font-family:roboto;
    padding: 20px;
    background: #00aabb;
    position: absolute;
    border-radius:5px;
    right: 0px;
    top: 50%;
}
.hideclass{display:none;}

A:

Try the following code:

var x = document.getElementById('x');
    s = ['Hello', 'What can I help you ?', 'Click me to get some help!'];
    var times=0;
(function loop() {
    var loops=setTimeout(loop, 3000);
    if (times==3){
    clearTimeout(loops);
    $('#animate').addClass('bounceOut faster');
    }
    else{
      s.length && (x.innerHTML = s.shift(), loops);
      setTimeout( function(){$('#animate').removeClass('bounceIn faster');}, 2000);
      $('#animate').addClass('bounceIn faster');
    }
    times++;
    return false;
})();
.speech-bubble {
 position: relative;
  padding:20px;

}

.speech-bubble:after {
content: '';
    position: absolute;
    right: 0;
    top: 50%;
    width: 0;
    height: 0;
    border: 10px solid transparent;
    border-left-color: #00aabb;
    border-right: 0;
    margin-top: 15px;
    margin-right: -10px;
}

span#x {
    color: white;
    font-family:roboto;
    padding: 20px;
    background: #00aabb;
    position: absolute;
    border-radius:5px;
    right: 0px;
    top: 50%;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css" rel="stylesheet"/>

times is used to count the loop count.
clearTimeout is to be done with loop.
$('#animate').removeClass('infinite bounceIn'); is to remove bounceIn animation
$('#animate').addClass('bounceOut'); is to add bounceOut animation
For faster animation, setTimeout is used to add delay.

var x = document.getElementById('x');
    s = ['Hello', 'What can I help you ?', 'Click me to get some help!'];
    var times=0;
(function loop() {
    var loops=setTimeout(loop, 3000);
    if (times==3){
    clearTimeout(loops);
    $('#animate').addClass('bounceOut faster');
    }
    else{
      s.length && (x.innerHTML = s.shift(), loops);
      setTimeout( function(){$('#animate').removeClass('bounceIn faster');}, 2000);
      $('#animate').addClass('bounceIn faster');
    }
    times++;
    return false;
})();
.speech-bubble {
 position: relative;
  padding:20px;

}

.speech-bubble:after {
content: '';
    position: absolute;
    right: 0;
    top: 50%;
    width: 0;
    height: 0;
    border: 10px solid transparent;
    border-left-color: #00aabb;
    border-right: 0;
    margin-top: 15px;
    margin-right: -10px;
}

span#x {
    color: white;
    font-family:roboto;
    padding: 20px;
    background: #00aabb;
    position: absolute;
    border-radius:5px;
    right: 0px;
    top: 50%;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css" rel="stylesheet"/>

Edit: for adding delay go add delay-xs on div class with x as the number of seconds you would like to delay. Don't forget to also update the timeout so that the animation work as intended.
Updated in snippet on

If you want to remove the delay just add the delay-1s on remove class in snippet. And add as needed.


Q:

comparing a list of tuples python

I have a list of tuples in python of the form [(word, sym) , (word, sym)....].
Let's assume the symbol is either A or B. I want to return all words for which  the list contains two tuples of the form ("example", A) and ("example", B). So basically one word paired with BOTH A and B. I'm assuming this can be done using list comprehension. I can do this to get all words where the symbol is A:
[x[0] for x in self.list if x[1] == "A"]
and in a similar fashion obtain the list of words where the symbol is B however, I'm not sure how to compare the two lists.
Would I simply use if word in listA and word in listB?

A:

Assuming order is unimportant, this is a great use case for set intersections:
setA = {word for word, sym in self.list if sym == "A"}
setB = {word for word, sym in self.list if sym == "B"}

AB_words = setA & setB  # Preserves only those words found in both input sets

Then if you need to test if any given word is a common word, it's a trivial set membership test:
if word in AB_words:


Q:

SQL server update a column group by

TableA
int  class del
null  13
null  13
null  13
12    13
null  23
null  23
null  87
null  74
null  74
null  65
32    65

So, I want to populate del = 'A' where for a given class, its all int is null else it should populate B.
Expected result:
TableA
int  class del
null  13    B
null  13    B
null  13    B
12    13    B
null  23    A
null  23    A
null  87    A
null  74    A
null  74    A
null  65    B
32    65    B

A:

update
    TableA
set
    del = Case
            when mcolint is null Then 'A'
            Else 'B'
    End
from
    TableA T
inner join
    (
        select
            class,
            MAX(colint) mcolint
        from
            TableA
        group by
            class
    ) T1
on
    T.class = T1.class


Q:

Is it possible to refer to a collection of definitions in JSON Schema?

I am constructing a schema using JSON-schema, part of which describes mathematical operations (such as add, multiply, subtract, divide, etc).
These operations can take operands that are variables, but they can also take instances of themselves. That is "add" and "multiply" types may be represented as follows:
"add": {
    "description": "The mathematical operation of adding two or more operands together",
    "type": "array",
    "minItems": 2,
    "items": {
        "anyOf": [
            { "$ref": "#/definitions/variable" },
            { "$ref": "#/definitions/subformula" },
            { "$ref": "#/definitions/add" },
            { "$ref": "#/definitions/multiply" },
            { "$ref": "#/definitions/subtract" },
            { "$ref": "#/definitions/divide" },
            { "$ref": "#/definitions/sum" },
            { "$ref": "#/definitions/maximum" },
            { "$ref": "#/definitions/average" }
        ]
    }
},
"multiply": {
    "description": "The mathematical operation of multiplying two or more operands together",
    "type": "array",
    "minItems": 2,
    "items": {
        "anyOf": [
            { "$ref": "#/definitions/variable" },
            { "$ref": "#/definitions/subformula" },
            { "$ref": "#/definitions/add" },
            { "$ref": "#/definitions/multiply" },
            { "$ref": "#/definitions/subtract" },
            { "$ref": "#/definitions/divide" },
            { "$ref": "#/definitions/sum" },
            { "$ref": "#/definitions/maximum" },
            { "$ref": "#/definitions/average" }
        ]
    }
}

For JSON such as:
"add": [ 5, 6, "multiply": [ 2, 3 ] ]

This list of type references is similar for every operation and sub-formula. This is rather cumbersome in the case that more operations might be added they need to be added to this list at every place that the list occurs...
Is it possible to somehow markup the operations such that I could refer to them as a group, something like the following:
"add": {
    "description": "The mathematical operation of adding two or more operands together",
    "type": "array",
    "minItems": 2,
    "items": {
        "anyOf": [
            { "$ref": "#/definitions/variable" },
            { "$ref": "#/definitions/subformula" },
            { "$ref": "#/definitions/operations/" } //note the trailing '/'
        ]
    }
},
"multiply": {
    "description": "The mathematical operation of multiplying two or more operands together",
    "type": "array",
    "minItems": 2,
    "items": {
        "anyOf": [
            { "$ref": "#/definitions/variable" },
            { "$ref": "#/definitions/subformula" },
            { "$ref": "#/definitions/operations/" } //note the trailing '/'
        ]
    }
}

A:

You are already using definitions. The value of a key in the definitions key word must be a JSON Schema. As such, you can combine anyOf and $ref similar to how you have done already.

The "definitions" keywords provides a standardized location for schema
  authors to inline re-usable JSON Schemas into a more general schema.
  The keyword does not directly affect the validation result.
This keyword's value MUST be an object. Each member value of this
  object MUST be a valid JSON Schema.

https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-9
"items": {
  "$ref": "#/definitions/myOtherGroup",
}

...

"definitions": {
  "operations": {
    "anyOf": [
      { "$ref": "#/definitions/add" },
      { "$ref": "#/definitions/multiply" },
      { "$ref": "#/definitions/subtract" },
      { "$ref": "#/definitions/divide" },
      { "$ref": "#/definitions/sum" },
      { "$ref": "#/definitions/maximum" },
      { "$ref": "#/definitions/average" }
    ]
  }
  "myOtherGroup": {
    "anyOf": [
      { "$ref": "#/definitions/variable" },
      { "$ref": "#/definitions/subformula" },
      { "$ref": "#/definitions/operations" },
    ]
  }
}

You would just need to change the name of "myOtherGroup" to whatever you want to call it. I'm assuming your other definitions are already there but you just didn't include them in your question (which is fine for this purpose).


Q:

Implementation of skyline query or efficient frontier

I know there must be an easy answer to this but somehow I can't seem to find it...
I have a data frame with 2 numeric columns.
I would like to remove from it, the rows, which have the property, that there exists at least one other row in the data frame, with both column values bigger than the ones in this row.
So if I have
    Col1 Col2
1     2    3
2     4    7
3     5    6

I would like to remove the first row, because the second one fulfills the property and keep only rows 2 and 3.
Thanks a lot!

A:

That problem is called a "skyline query" by database administrators (they may have other algorithms) and an "efficient frontier" by economists.
Plotting the data can make it clear what we are looking for.
n <- 40
d <- data.frame(
  x = rnorm(n),
  y = rnorm(n)
)
# We want the "extreme" points in the following plot
par(mar=c(1,1,1,1))
plot(d, axes=FALSE, xlab="", ylab="")
for(i in 1:n) {
  polygon( c(-10,d$x[i],d$x[i],-10), c(-10,-10,d$y[i],d$y[i]),
  col=rgb(.9,.9,.9,.2))
}

The algorithm is as follows: sort the points along the first coordinate,
keep each observation unless it is worse than the last retained one.
d <- d[ order(d$x, decreasing=TRUE), ]
result <- d[1,]
for(i in seq_len(nrow(d))[-1] ) {
  if( d$y[i] > result$y[nrow(result)] ) {
    result <- rbind(result, d[i,])  # inefficient
  }
}
points(result, cex=3, pch=15)

A:

Edit (2015-03-02): For a more efficient solution, please see Patrick Roocks' rPref, a package for "Database Preferences and Skyline Computation", (also linked to in his answer below). To show that it finds the same solution as my code here, I've appended an example using it to my original answer here.

Riffing off of Vincent Zoonekynd's enlightening response, here's an algorithm that's fully vectorized, and likely more efficient:
set.seed(100)
d <- data.frame(x = rnorm(100), y = rnorm(100))

D   <- d[order(d$x, d$y, decreasing=TRUE), ]
res <- D[which(!duplicated(cummax(D$y))), ]
#             x         y
# 64  2.5819589 0.7946803
# 20  2.3102968 1.6151907
# 95 -0.5302965 1.8952759
# 80 -2.0744048 2.1686003

# And then, if you would prefer the rows to be in
# their original order, just do:
d[sort(as.numeric(rownames(res))), ]
#            x         y
# 20  2.3102968 1.6151907
# 64  2.5819589 0.7946803
# 80 -2.0744048 2.1686003
# 95 -0.5302965 1.8952759

Or, using the rPref package:
library(rPref)
psel(d, high(x) | high(y))
#             x         y
# 20  2.3102968 1.6151907
# 64  2.5819589 0.7946803
# 80 -2.0744048 2.1686003
# 95 -0.5302965 1.8952759

A:

Here is an sqldf solution where DF is the data frame of data:
library(sqldf)
sqldf("select * from DF a
 where not exists (
   select * from DF b
   where b.Col1 >= a.Col1 and b.Col2 >  a.Col2
      or b.Col1 >  a.Col1 and b.Col2 >= a.Col2
 )"
)


Q:

Change/Replace Href parameter with jquery

I have a URL parameter that I want to replace based on whether a checkbox has been checked:
<input id="acknowledge" type="checkbox" checked="checked" name="acknowledge" tabindex="">I accept

Add another institution

I want to replace p_acknowledge parameter to be p_acknowledge=N if the checkbox is not checked and p_acknowledge=Y if it is checked.
It always return p_add_institution?id=55&p_acknowledge=Y even if the checkbox is not checked.
Also, when I hover over the link, I want to have the proper URL showing up as well.
http://jsfiddle.net/u89usjnj/5
Any help would be appreciated and if anyone can explain why it the parameter is not switching to N
Thanks

A:

// Input with id acknowledge on change event
$("input#acknowledge").change(function(){

    // Fetch checkbox is checked or not
    var status = this.checked;

    // Decide what to set in href Y or N based on status
    var yorn = (status?"Y":"N");

    // Update the link using .attr
    $("#add-institution").attr("href", "p_add_institution?id=55&p_acknowledge="+yorn);
})

Play Here
FYI:

Rule of thumb is: .prop() method should be used for boolean attributes/properties and for properties which do not exist in html
  (such as window.location). All other attributes (ones you can see in
  the html) can and should continue to be manipulated with the .attr()
  method.
  (http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/)


Q:

What should I pass for the WWW-Authenticate header on 401s if I'm only using OpenID?

The HTTP spec states:

10.4.2 401 Unauthorized
The request requires user authentication. The response MUST include a WWW-Authenticate
  header field (section 14.47) containing a challenge applicable to the requested resource.

If the only login scheme I support is OpenID (or CAS, or OAuth tokens, &c.), what should I put in this field? That is, how do I indicate that the client needs to pre-authenticate and create a session rather than try to send credentials along with each request?
Before you answer, "don't send a 401; send a 3xx redirecting to the OpenID login page," what about for non-HTML clients?  How, for example, would Stack Overflow do an API that my custom software could interact with?

A:

According to RFC2617 the auth-scheme can be anything; if you really want a 401 you're not technically breaking spec by making something up like WWW-Authenticate: OpenID realm="My Realm" location="http://my/login/location". Having said that, behaviour of other people's code when you do that is of course undefined. :-)

A:

There is an OAuth Discovery spec that would indicate what to put into the WWW-Authenticate header -- if the spec were not obsolete without a replacement spec yet.


Q:

How do I write a loop function as a recursive function?

Well, I've been trying to rework this many times. Though, at one point I thought the longestSequence function would help, since it displays the longest hailstone sequence. Though, I can't seem to figure out how to find, or store the value it used to find that.If someone could explain how, I would appreciate it.
int longestSequence(int n)
{
    int u = n;

    if(u == 1)
    {
        return 1;
    }
    else
    {
        return max(hailstoneLength(u), longestSequence(u-1));
    }
}

The part I'm having trouble with is my longest start sequence:
int hailLongestSeq(int n)
{
    int k;
    int longest = 0;
    for(int j = 1; j <= n; j++)
    {
        if(hailstoneLength(j) > longest)
        {
            longest = hailstoneLength(j);
            k = j;
        }
    }
    return k;
}

I'm not sure how to make this into a recursion, I noticed for some recursions I saw people using for loops still, but I was sure we weren't supposed to use loops.
It may be a dumb question, but is there a formula to translating for loops to recursions, if anyone knows one?
The expected out put is like this:
The longest hailstone sequence starting with a number up to 10 has length 20.
The longest hailstone sequence starting with a number up to 10 begins with 9.
as 9's sequence has a length of 20 numbers, and is the longest from 1 to 10.

A:

Yes every for loop can be translated to recursive call, obviously like this:
for (i=0; i<N; i++) {
  body;
}

translate it to:
func(int i) {
  if (i<N) { body; func(i+1) }
  else return;
}

func(0);

This can be easily extended to any for loop computation (add parameters if needed, return value, etc).


Q:

JavaScript function returning NaN even though value is a number

I am working on a course assignment where random questions are asked with 4 possible answers each. (This all runs in the console only, working with alert()).
My issue is with the score of the user. It is supposed to increment by 1 with each correct iteration and I attempted resolving this using a function, but the function returns NaN and I simply can't see the problem. Please have a look.
//Start by creating objects to contain the questions and answers
var Questions = function(question, answerq1, answerq2, answerq3, answerq4) {
  this.question = question;
  this.answerq1 = answerq1;
  this.answerq2 = answerq2;
  this.answerq3 = answerq3;
  this.answerq4 = answerq4;
};

//create the questions
var question1 = new Questions('What is the fastest land animal in the world?', 'a dog', 'deer', 'cheetah', 'leopard');

//create a function that displays the question and present the possible answers as multiple option
function displayQandA() {
  var test = 'question' + 1;
  console.log(test);
  if (test === 'question1') {
    console.log(question1.question);
    var q10a = [question1.answerq1, question1.answerq2, question1.answerq3, question1.answerq4];
    //correct answer in array
    var correct = q10a[2];
    for (var i = 0; i < q10a.length; i++) {
      console.log([i] + ' ' + q10a[i]);
    }
    captureAnswer(q10a.indexOf(correct));
  } else {
    displayQandA();
  }
};
displayQandA();

//to hold score accumulation
var s = 0;
//function to increase score per correct answer
function incrementScore() {
  s++;
  return s;
};

//function to prompt user to enter/capture the answer & check whether its correct or not
function captureAnswer(el) { //el is the parameter from the random question function
  var promptAnswer = prompt('Capture your answer here');

  if (promptAnswer === 'exit') {
    console.log('You entered ' + promptAnswer);
    console.log('Bye, thanks for playing');
  } else if (promptAnswer == el) {
    console.log('You entered ' + promptAnswer);
    console.log('Your answer is correct!');
    incrementScore();
    console.log('Your score is ' + s);
    displayQandA(); //calling random question function
  } else if (promptAnswer !== el) {
    console.log('You entered ' + promptAnswer);
    console.log('Your answer is wrong!');
    console.log('Your score remains ' + s);
    displayQandA(); //calling random question function
  }
};

A:

This is because you call displayQandA before assigning s = 0. The function already reads s (yielding undefined) and increments it (yielding NaN). var s; is hoisted up, so it’ll start as undefined. s = 0; actually won’t be executed until after you type "exit" in the prompt. Simply move var s = 0; to the top of your code.


Q:

Uploading multiple image to server without accessing same session with two ajax call simultaneously ?

I am trying to upload multiple image using ajax call, but when two ajax call request same session, its , my login get logs out, so I am trying to upload it in synchronous way using ajax.
How i should upload it with ajax with making async

A:

Chrome: Synchronous XMLHttpRequest on the main thread is deprecated
  because of its detrimental effects to the end user's experience. For
  more help, check https://xhr.spec.whatwg.org/.

Since Synchronous XMLHttpRequest is deprecated in Chrome and Firefox, you can do something that feels synchronous like this:
async function sendRequest() {
    let response = await this.$http.get('/someUrl')
    console.log(response.body)
}


Q:

String Var with int var

I want to have a string variable showing next to my int variable but it doesn't seem to work.
public class ThreeLittleNumbers {
    public static void main(String[] argts) {
        String as = "Number 1: ";
        String bs = "Number 2: ";
        String cs = "Number 3: ";
        int a = 1;
        int b = 3;
        int c = 5;
        String tot = "Total: ";
        System.out.println(as+a);
        System.out.println(bs+b);
        System.out.println(cs+c);
        System.out.println(tot);
        System.out.print(a+b+c);
    }
}

A:

If I understand your question, then this
System.out.println(tot);
System.out.print(a + b + c);

should be
System.out.print(tot);
System.out.println(a + b + c);

When I make the change above, I get output like you seem to be asking for -
Number 1: 1
Number 2: 3
Number 3: 5
Total: 9

Another option would be to use printf and something like
System.out.printf("%s %d%n", tot, a + b + c);


Q:

Overlay divs without leaving the parent

How can I make two divs function normally on top of each other without using absolute positioning? I need it to stay within the parent so when the parent moves or resizes it does the same
Code: (Using Bootstrap 4)

    Text or Image here

    <button class="btn w-50 btn-outline-secondary rmv-col">
      Remove
    </button>
    <button class="btn w-50 btn-outline-secondary edit-col">
      Edit
    </button>

So, I'm trying to make to the button group(.col-btns) overlay his sibling .col-content, is that possible while maintaining his reference to the parent container?
I know I could use a negative top margin, but the value of the margin has to be equal its current height since it will vary, and its height has to be equal its parent height which also varies, is that possible?
Fiddle : http://jsfiddle.net/8as9dmf2/
Here's an example of why I need it to keep its parent's reference (my actual context): http://jsfiddle.net/n0m4cu5s/15/
Maybe it can only be done with Javascript?

A:

You could make the container .outer-col a grid container.
Then you can assign both the content and buttons to the same grid-row and grid-column.
Example:

.outer-col {
  display: grid;
}

.col-content,
.col-btns {
  grid-column: 1/-1;
  grid-row: 1;
  transition: opacity .5s ease;
}

.col-btns {
  opacity: 0;
}

.outer-col:hover .col-btns {
  opacity: .75;
}

.outer-col:hover .col-content {
  opacity: 0;
}
<link href="http://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>

    Text or Image here

    <button class="btn w-50 btn-outline-secondary rmv-col">
      Remove
    </button>
    <button class="btn w-50 btn-outline-secondary edit-col">
      Edit
    </button>


Q:

Как  создать архив, используя только php?

Возможно ли только при помощи php создать архив на веб-сайте ОС linux. Что я хочу:

Создать архив. ОС debian. Нужно заархивировать папку, лежащую в корневой директории сайта. Примерные пути:
скрипт => сайт\папка\папка\папка\скрип.php
директория => сайт\нужная_папка

Скачать.

Удалить архив.

Кроме стандартных функции ничего использовать нельзя. Как можно его заархивировать?

A:

Вот Вам вполне стандартный класс... Возможно это расширение нужно будет включить в php.ini. Хотя у меня оно и без того работает.


Q:

Form without a border style

I've stumbled upon a problem. I'm using 'FormBorderStyle.None', and when I click the icon of my running application on the taskbar it does not minimize like it should, although when I use anything BUT 'FormBorderStyle.None', it seems to work perfectly. Please advice me of a good way to tackle this problem. Thanks!

A:

You must override CreateParams:
public partial class Form1 : Form {
    protected override CreateParams CreateParams {
        get {
            CreateParams par = base.CreateParams;
            par.Style = par.Style | 0x20000; // Turn on the WS_MINIMIZEBOX style flag
            return par;
        }
    }
}

Check this thread for an explanation.


Q:

How to get url from 'link' element in Selenium IDE

I want to get (and store to variable) url of one hyperlink (link) on the web page. Is it possible to get it in the Selenium IDE?
In my test I have to verify, if link exists, then store url from this link and use it later in the test.
Thanks.

A:

driver.findElement(By.xxx).getAttribute('href');

A:

Although this question was originally asked for the IDE, I just came here through Google searching for the same answer for Python.
The one above gives
AttributeError: 'WebElement' object has no attribute 'getAttribute'

because for Python it is
driver.find_element(By.xxx).get_attribute('href')


Q:

Windows Phone 8.1 Camera Initialisation - Access Denied Exception

Using the 8.1 MediaCapture classes for Windows Phone.
Have declared the capabilities for "Audio" and "Webcam", which 90% is what would be the cause of the exception.
Kicker is, it works perfectly in the WP emulator, but breaks on an actual device.
Exact exception is here :

I have added a mountain of checks to make sure we aren't re-initializing the already initialized camera or trying to read before the initializations.. etc (as I assumed the issue was being caused by) So it is very unlikely to be that.
    private async Task InitializeCameraAsync()
    {
        if (_isInitialized)
        {
            Debug.WriteLine("Skipping unnecessary initialization");
            return;
        }

        Debug.WriteLine("Initializing camera media capture...");
        _deviceCapture = new MediaCapture();
        await _deviceCapture.InitializeAsync(new MediaCaptureInitializationSettings
        {
            VideoDeviceId = _cameraInfoCollection[_currentVideoDevice].Id,
            PhotoCaptureSource = PhotoCaptureSource.VideoPreview,
            AudioDeviceId = _microphoneInfoCollection[_currentAudioDevice].Id
            StreamingCaptureMode = StreamingCaptureMode.Video
        });
        Debug.WriteLine("Initialized camera media capture!");

        // For code completion only, unlikely to be relevant

        // Set up low-lag photo capture
        if (IsNotUsingInstantCapture)
        {
            Debug.WriteLine("Preparing low-lag photo capture");
            var imageEncoding = ImageEncodingProperties.CreateJpeg();
            imageEncoding.Width = PhotoCaptureWidth;
            imageEncoding.Height = PhotoCaptureHeight;
            _lowLagPhotoCapture = await _deviceCapture.PrepareLowLagPhotoCaptureAsync(imageEncoding);
        }

        _isInitialized = true;
        Debug.WriteLine("Initialized camera!");
    }

_mediacapture is then being bound to the .source of a xaml CaptureElement to show a preview.

A:

It was a temporary bug with the Windows api. It was fixed with the Windows Phone 8.1 update that was released the 24th of september 2014.


Q:

WifiManager addNetwork return -1 in Marshmallow

In my application i want to connect to specific wifi connection. My application is working fine till version 19. when install application android 6.0 , addNetwork always return "-1".
Below is the code i am using.
private int configureNetworkAndReturnId() {

    WifiConfiguration config = new WifiConfiguration();
    config.BSSID = "xx:xx:xx:xx:xx:xx";
    config.SSID = "\"" + "Name" + "\"";
    config.priority = 1;
    config.status = WifiConfiguration.Status.ENABLED;
    // Set connection configuration to require encryption
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

    config.preSharedKey = "xxxx";

    final int newId = wifiManager.addNetwork(config);
    Log.d(TAG, "Created new network configuration, ID: " + newId + ", Config: " + config);

    return newId;
}

Since above method is returning -1, when i call boolean isEnabled = wifiManager.enableNetwork(id, true); application is struck .
Anyone faced same issue?

A:

If network id is -1, then read the network id from the existed configured network. If it is available in network list it return the id.
int newId = wifiManager.addNetwork(config);
        if (newId == -1) {
            // Get existed network id if it is already added to WiFi network
            newId = getExistingNetworkId(SSID);
            Log.d(TAG, "getExistingNetworkId: " + newId);
        }

private int getExistingNetworkId(String SSID) {
    List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
    if (configuredNetworks != null) {
        for (WifiConfiguration existingConfig : configuredNetworks) {
            if (SSID.equalsIgnoreCase(existingConfig.SSID)) {
                return existingConfig.networkId;
            }
        }
    }
    return -1;
}


Q:

Why doesn't this block of code work?

I've mocked up some code here
var common = common || {};

(function(NAMESPACE) {

  NAMESPACE = {
    isIE: function() {
        return true;
    }
  };

  main();

})(common);

function main() {
    console.log(common.isIE());
  return 'Hello, World!';
}

I would like to understand a couple of things,
1) Why isn't this working, I guess it has something to do with how scoping is "decided" and IIFE, but not entirely sure.
2) How to make this code work?

A:

common which passed as argument named NAMESPACE needs to be extended instead of assigning new value.
So Object.assign can help here.
var common = common|| {};

(function(NAMESPACE) {

  Object.assign(NAMESPACE,{
    isIE: function() {
        return true;
    }
  });

  main();

})(common);

function main() {
    console.log(common.isIE());
  return 'Hello, World!';
}


Q:

drupal 7. how to refactor a form array

I am creating a wizard from the Drupal example file and would like to refactor the segments of code that are repeated when setting up items like options and radios.
I have already tried a simple function passing "ordinary" and "preferential" but can't find a way to make it work.
Can someone give me an idea of the best way to do this?
unfactored code is as below:
function services_wizard_share_capital_classes($form, &$form_state) {

$form['share_classes']['type_of_class'] = array(
'#type' => 'select',
'#title' => t('What type of share will this class be?'),
'#options' => array(
  1 => t('Ordinary'),
  2 => t('Preferential'),
),
);

$form['ordinary']['share_type'] = array(
'#type' => 'item',
'#description' => t("You chose Ordinary Shares"),
'#states' => array(
  'visible' => array(
    ':input[name="type_of_class"]' => array('value' => '1'),
  ),
),
);

$form['preferential']['share_type'] = array(
'#type' => 'item',
'#description' => t("You chose Preferential Shares"),
'#states' => array(
  'visible' => array(
    ':input[name="type_of_class"]' => array('value' => '2'),
  ),
),
);
return $form;
}

A:

I'm not sure about this being the best way but it's certainly a way to refactor your code:
function _services_wizard_share_capital_classes_add_el(&$form, $name, $description, $index) {
  $form[$name]['share_type'] = array(
    '#type' => 'item',
    '#description' => t($description),
    '#states' => array(
      'visible' => array(
        ':input[name="type_of_class"]' => array('value' => "$index"),
      ),
    )
  );
}

function services_wizard_share_capital_classes($form, &$form_state) {
  // Other code

  _services_wizard_share_capital_classes_add_el($form, 'ordinary', 'You chose Ordinary Shares', 1);
  _services_wizard_share_capital_classes_add_el($form, 'preferential', 'You chose Preferential Shares', 2);
  // etc...
}


Q:

Canvas starts to lag after some time

Reproduction: focus your mouse on canvas , then spin your mouse in circles for ~15 sec. At first you'll notice how things are smooth. After some time it starts to lose its smoothness and becomes really laggy.
Part of the js function came from the following answer
Make moving Rect more smooth

var canvas = document.getElementById('canvas');
var ctx = document.getElementById('canvas').getContext('2d');

var x;
var y;

var tx = tx || 0;
var ty = ty || 0;

var xDir;
var yDir;

function followMouse(e) {
  x = e.offsetX;
  y = e.offsetY;
  moveObject();
}

function moveObject() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  var scale =  0.2 * Math.max(canvas.width, canvas.height);
  xDir = 0;
  yDir = 0;
  xDir = (x - tx) / scale;
  yDir = (y - ty) / scale;
  tx = tx != x ? tx + xDir : tx;
  ty = ty != y ? ty + yDir : ty;
  ctx.fillRect(tx - 25, ty + 25, 50, 10);
  if (tx != x || ty != y) {
    window.requestAnimationFrame(moveObject);
  }
}

function resizeCanvas() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
};

canvas.addEventListener('mousemove', _.throttle(function(e) {
  followMouse(e);
}, 30));

window.addEventListener('resize', resizeCanvas, false);

resizeCanvas();
html,
body {
  margin: 0;
  height: 100%;
}

canvas {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<canvas id="canvas"></canvas>

A:

This happens as for each mousemove a new loop is started. These loops will accumulate and eventually slow things down.
To solve you can implement cancelAnimationFrame() by doing:
...
var timer;

function followMouse(e) {
  x = e.offsetX;
  y = e.offsetY;
  cancelAnimationFrame(timer);
  moveObject();
}

Then store timer reference in the main loop:
...
timer = requestAnimationFrame(moveObject);

This will abort the current request for frame update and allow you to start a new loop without accumulating calls.
For this reason you would also have to initialize x and y since they are not initialized otherwise until the mouse has been moved (which is of course no guarantee).
var x = 0;
var y = 0;

Note: A side-effect of this correction is that now the movement is only calculated once per frame. When accumulated the movement got calculated many times per frame. To compensate adjust the scale to a lower value (shown below).
Modified example

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var x = 0;
var y = 0;

var tx = tx || 0;
var ty = ty || 0;

var xDir;
var yDir;

var timer;

function followMouse(e) {
  x = e.clientX;
  y = e.clientY;
  cancelAnimationFrame(timer);
  moveObject();
}

function moveObject() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  var scale = 0.02 * Math.max(canvas.width, canvas.height);
  xDir = 0;
  yDir = 0;
  xDir = (x - tx) / scale;
  yDir = (y - ty) / scale;
  tx = tx != x ? tx + xDir : tx;
  ty = ty != y ? ty + yDir : ty;
  ctx.fillRect(tx - 25, ty + 25, 50, 10);
  if (tx != x || ty != y) {
    timer = requestAnimationFrame(moveObject);
  }
}

function resizeCanvas() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
};

canvas.addEventListener('mousemove', _.throttle(function(e) {
  followMouse(e);
}, 30));

window.addEventListener('resize', resizeCanvas, false);

resizeCanvas();
html,
body {
  margin: 0;
  height: 100%;
}

canvas {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<canvas id="canvas"></canvas>


Q:

Play framework: JSON Reads for a single-attribute case class

I'm trying to create a JSON Reads implicit for a case class that contains a single attribute, but I'm getting an error "Reads[Nothing] doesn't conform to expected type". Here's teh codes:
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._
import play.api.libs.json.{JsPath, Json, Reads}

case class Feedback(message: String)
object Feedback {
  implicit val reads: Reads[Feedback] = (
      (JsPath \ "message").read[String](maxLength[String](2000))
    )(Feedback.apply _)
}

Why isn't this working? If I add extra attributes to the case class and multiple .read calls joined with and it works...

A:

Json combinators doesn't work for single field case class.
You can do the following:
import play.api.libs.json.Reads._
import play.api.libs.json.{__, Reads}

case class Feedback(message: String)
object Feedback {
  implicit val reads: Reads[Feedback] = (__ \ "message")
    .read[String](maxLength[String](2000)).map {message => Feedback(message)}
}

It's because of a limitation in the current Macro implementation. You can read more about it here: Pacal is the writer of this API


Q:

How to create multiple jquery form fields and insert in mysql database, without using mysql_real_escape_string

I need to create dynamic text fields with a button (which simply adds a new row of dynamic text fields). Then I need to INSERT the data in a in the database. I borrowed an example of what I need done from someone else's question, the problem is, it uses  mysql_real_escape_string, which is now depreciated. I am new to this, so could you tell me what I would use instead of the  mysql_real_escape_string?

$(function(){
    $('p#add_field').click(function(){
        counter += 1;
        $('#container').append(
        'Hobby No. ' + counter + '
'
        + '<input id="field_' + counter + '" name="dynfields['+counter+'][name]' + '" type="text" />
' +
        + '<input id="field_' + counter + '" name="dynfields['+counter+'][surname]' + '" type="text" />
' +
        + '<input id="field_' + counter + '" name="dynfields['+counter+'][age]' + '" type="text" />
' +
        + '<input id="field_' + counter + '" name="dynfields['+counter+'][gender]' + '" type="text" />
');

    });
});
</script>
if (isset($_POST['submit_val'])) {
    if ($_POST['dynfields']) {
        foreach ( $_POST['dynfields'] as $key=>$fieldArray ) {

            $keys = array_keys($fieldArray);
            $values = array_map("mysql_real_escape_string",$fieldArray);

            $query = mysql_query("INSERT INTO my_hobbies (".implode(',',$keys).") VALUES ('".implode('\',\'',$values)."')", $connection );
        }
    }

    echo "
" . count($_POST['dynfields']) . " Hobbies Added
";

    mysql_close();
}

A:

Your problem has nothing to do with jQuery and the form. It is just highly recommended to prevent SQL injection, an attack in which an attacker injects SQL commands into your DB Query by posting it in your form. That's why any data that comes from an untrusted source (eg html form) should be sanitized or at least escaped.
Here is a good explanation what SQL injection is and how it works.
As for your question: You can use mysqli_real_escape_string.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", $mysqli->sqlstate);
}

$city = $mysqli->real_escape_string($city);

/* this query with escaped $city will work */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}

$mysqli->close();
?>


Q:

Hex tile systems and the efficient use of classes

So I've built myself a system of classes for what I think is an efficient way to describe an entity that would live in my game.
Is this an effective approach or am I creating entities that are too large in size? I want the game to be able to run well even with an inane amount of tiles.
I read the post (Map with 20 million tiles makes game run out of memory, how do I avoid it?) about having one million tiles and memory problems and I'm worried that my tile system I've created using the entity system will not be able to handle such large sized maps as there is so much information to be processed.
To give you an idea about what each component of a Hex Entity holds, the sprite comp maintains the following variables: the texture, position, rotation, height and width; while the hex comp of the hex entity maintains: the position, the coordinates on the board, the orientation, and what hex's are adjacent to it. Should i simplify the date types

A:

It is hard to say what exactly will suit your situation. Your setup is very memory inefficient, if you want millions of hexes as much data as possible should be implicit, that means you should store hexes in an array where each array entry maps to a specific position.
But do you need millions of hexes? If you have only got a few thousand hexes your current system may be fine.


Q:

Are all pseudo randomly generated numbers within a given period unique?

This will of course depend on the algorithm generating the pseudo random numbers, but what I'm wondering is whether practical, usable pseudo-random number generating algorithms exist that never repeat the same number twice until their period is up.

A:

I doubt that such a PRNG exists, since it is simply not a very good PRNG. Not only do you know something about the next number in the sequence (whereas in a PRNG the whole point is that you don't know anything about the next number), but the longer the sequence gets, the more you know!
This is just a bad PRNG.
What you are talking about seems to be more a (pseudo-)random permutation than a (pseudo-)random number sequence.

A:

As the accepted answer correctly notes, that would be a horrible PRNG.  You want the period of the generator to be many orders of magnitude larger than the number of values it generates; your proposal is that they be equal.
But your question was not "critique this idea" but rather

does a practical, usable pseudo-random number generating algorithms exist that never repeat the same number twice until their period is up.

Sure, that's easy.  Here's one:

Choose the period you want. Call it p.
Plainly the number of values that the PRNG generates must be not less than p, because otherwise by the pigeonhole principle, it repeats an output in fewer than p steps.  Let's suppose that the number of possible values the PRNG generates is also p, and that it generates numbers from 0 to p-1.
Now our algorithm is simple. We have two seeds, which we call s and i, both between 0 and p-1. s can be anything. i must be any number coprime to p.  The nth element generated by the PRNG with seeds s and i is (n * i + s) % p.  That is, multiply i by n, add s, and take the remainder when that value is divided by p.
That gives you a sequence of incredibly crappy pseudo-random numbers that repeats with period p and never generates the same number within the period, and each number is between 0 and p-1.  Enjoy.
Let's work an example. p=10, i=3, s=5, the sequence is 5, 8, 1, 4, 7, 0, 3, 6, 9, 2 and then it repeats.
Notice that the low bit of the sequence produced by this algorithm toggles on each subsequent step; that's really bad!
You asked if any algorithm exists, not if any good algorithm exists.

That was really crappy. Can we do better?
Basically what you're asking is "I need a random permutation of this set".  There are lots of good algorithms for that.  Since there are p! permutations of a set with p unique items, what you have to do is uniformly choose a number between 0 and p!-1, and then generate a permutation from that number.
Generating the random seed is your problem; I describe how to turn it in to a permutation in my lengthy series on interesting properties of permutations, which you can read here:
https://ericlippert.com/2013/04/15/producing-permutations-part-one/


Q:

I have created a Staff table. It has a self reference key

create table STAFF
(
     StaffID    TINYINT IDENTITY NOT NULL,
     StaffName  varchar(20) NOT NULL,
     Phone      varchar(10) NOT NULL,
     Gender     char(01),
     DoB        date NOT NULL,
     Mentor     TINYINT,
     Payment_ID TINYINT NOT NULL,

     constraint staff_pk primary key (StaffID),
     constraint staff_fk
         foreign key (Payment_ID) references PAYMENT(Payment_ID),
     constraint mentor_fk
         foreign key (Mentor) references staff(StaffID)
);

Table was created successfully. But when I'm going to insert values like this:
insert into STAFF
values ('Adeesha', '077282018', 'M', '1997-11-30', '', '5'),
       ('Kavitha', '0772556899', 'F', '1956-11-28', '', '4'),
       ('Patee Aiya', '0775669844', 'M', '1954-01-04', '', '3'),
       ('Chanuka', '0772562984', 'M', '1997-02-24', '', '2'),
       ('Umesha', '0723328284', 'F', '1997-11-26', '', '3');

I get the following error:

Msg 547, Level 16, State 0, Line 1
  The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "mentor_fk".
  The conflict occurred in database "F_T", table "dbo.STAFF", column 'StaffID'.

A:

An empty string ('') is not the same as NULL.  You should use NULL:
insert into STAFF(StaffName, Phone, Gender, DoB, Mentor, Payment_ID)
    values ('Adeesha', '077282018', 'M', '1997-11-30', NULL, 5),
           ('Kavitha', '0772556899', 'F', '1956-11-28', NULL, 4),
           ('Patee Aiya', '0775669844', 'M', '1954-01-04', NULL, 3),
           ('Chanuka', '0772562984', 'M', '1997-02-24', NULL, 2),
           ('Umesha', '0723328284', 'F', '1997-11-26', NULL, 3);

Notes:

When using insert, list all the columns being inserted into the table.  This is a best-practice.
Do not insert into the identity column.  It is generated automatically.
Use NULL to mean NULL rather than an empty string.  They are not the same.
If a value is a number, do not enclose it in single quotes.