post value in perl cgi and HTML not inserting properly

Question: i am new to Perl and using Perl in my back end script and HTML in front end and CGI framework . Initially i am reading some details from flat file and displaying them . I am then trying to print the details in the form of checkboxes. i am using use Data::Dumper; module to check the values . however my input value of the last checkbox has an extra space as shown below
 print '<form action="process.pl " method="POST" id="sel">';
 print '<input type="checkbox" onClick="checkedAll()">Select All
';
 foreach my $i (@robos) {
    print '<input type="checkbox" name="sel" value="';
    print $i;
    print '">';
    print $i;
    print '
';
}
 print '<input type="submit" value="submit">';
 print '</form>';

 print "response " . Dumper \$data;

however in Process.pl the selected value is retrieved using
   @server = $q->param('sel');

but the response of selection is
 print "response " . Dumper \@server; => is showing [ 'ar', 'br', 'cr ' ]; which is

showing an additional space after cr . I dont know whats is wrong .
In my flat file i have
RMCList:ar:br:cr

i am then reading the details into an array and splitting using
  foreach my $ln (@lines)
  {
  if ($ln =~ /^RMCList/)
 {
@robos = split (/:/,$ln);
 }
 } #### end of for statement
shift (@robos);
print "The robos are ", (join ',', map { '"' . $_ . '"' } @robos), "\n";

This is showing the robos are:
"ar","br","cr
"

Comment: Presumably, that space is already present inside `@robos` – have you tried looking at that data? Note that you should escape your dumps: `use HTML::Entities;`, then `print encode_entities Dumper \@robos`.
Comment: yes i have looked on the content of @robos by print "the robos are @robos\n"; how will i come to know whether there is an extra space after last element
Comment: By putting quotes around each element: `print "The robos are ", (join ',', map { '"' . $_ . '"' } @robos), "\n"`
Comment: its showing a space for print encode_entities Dumper \@robos      $VAR1 = [ 'ar', 'br', 'cr ' ];
Comment: i dont understand its still showing a space . i am parsing the list from a flat file . i checked the flat file there is no space after cr.
Comment: In my flat file i have RMCList:ar:br:cr  i am then reading the details into an array and splitting using foreach my $ln (@lines)        ############################# parsing all the flatfile details ############
  {
 if ($ln =~ /^RMCList/)
  {
   @robos  = split (/:/,$ln);

  }

     } #### end of for statement

shift (@robos);  i then used ur  print join . but its showing a space after last value
Comment: How are you reading the values into `@lines`? Do the elements inside that array end with newlines? If so, does `chomp @lines` before your loop over `@lines` solve the problem?
Comment: open INFILE, "; # load file into a list of lines
 close(INFILE);
Answer: While reading the file into @lines, you forgot to remove the newline. This newline is interpreted as a simple space in a HTML document.
Remove the newlines with the chomp function like
chomp @lines;

before looping over the lines.

Actually, don't read the file into an array at all, unless you have to access each line more than once. Otherwise, read one line at the time:
open my $infile, "<", $filename or die "Cannot open $filename: $!";
my @robos;
while (my $ln = <$infile>) {
    chomp $ln;

    @robos = split /:/, $ln if $ln =~ /^RMCList/;
}


Find the user under which a Ubuntu service runs?

Question: I have a Cassandra service on my Ubuntu but I cannot figure under what user this service runs. I know how to find the owner and the permissions of files and directories. But how can I do this for a Ubuntu service. Assuming the service is just an executable file, how can I find the location of a particular service?
Comment: If the application is running - "ps" might help you, for example. Search for your process on the list and check what user owns the process.
Answer: You can use ps -ef to known who is running cassandra.
All services are located in /etc/init.d/.
If you are not running cassandra as a service, you can search where is the program with the whereis command:
$ whereis cassandra

Comment: Open the file `/etc/init.d/cassandra` and search if you can see a line like `daemon --user $CASS_USER` (like in this file https://gist.github.com/sgomezvillamor/5458309)
Comment: I see this: install -d -ocassandra -gcassandra -m755 `dirname $PIDFILE`. And also: start-stop-daemon -S -c cassandra -a /usr/sbin/cassandra -q -p "$PIDFILE" -t >/dev/null || return 1. It looks like it is running as a cassandra user?
Comment: But it is not running, I cannot start it due to permissions problems.
Comment: You are right !


Node.js CPU profiling

Question: Profiler results
I did some CPU profiling for node.js and got back this results using chrome dev tools, the heavy bottom up  chart is showing 93% spent on (program). What does 'program' mean in this context?
Comment: run node --inspect flag , then using chrome browser open the link for remote debugger. from the Profiler tab u can start cpu Profiler
Comment: How are you profiling Node with Chrome?
Comment: Possible duplicate of [What is "(program)" in Chrome debugger's profiler?](https://stackoverflow.com/questions/3847954/what-is-program-in-chrome-debugger-s-profiler)
Answer: According to one of the DevTools engineers:

It is non-JavaScript time. I.e. idle time + time spent on painting and such. We are working on splitting the two, so you will soon see (idle) and (program) where the latter will be native work not originating from JavaScript calls.

This response was from 2012, so they may have already split (idle) and (program) into different categories.
Source: https://groups.google.com/d/msg/google-chrome-developer-tools/zvc_Wqmie_k/XSIo69whtDYJ
See also: https://stackoverflow.com/a/12014408/1669860

Node.js CPU profiling


publish/subscribe middleware

Question: I am looking for a publish/subscribe middleware written in  Java. On Google Code, there are several middleware , but they are not well documented. So, I am facing difficulties of using those middleware.
your pointer would be appreciated.
Answer: RabbitMQ is pub/sub system that simply works. Give it a try, it's well documented and easy to kick.

publish/subscribe middleware


What are the minimum requirements for a level 3 Garrison?

Question: As of August 9th, the Demon Hunter class has been released in World of Warcraft. These characters start at level 98, and by the time they've finished their starting zone are going to be at least level 100. However, by default they aren't granted any progress in the Warlords of Draenor content - they have to start from square one.
Much of the content and/or bonuses exclusive to Garrisons can only fully be realized by a level 3 Garrison. What is the minimum amount of work I have to do to be able to upgrade my Garrison to level 3?
Comment: TL;DR: Work: some resource farming (farm treasures!). Gold: 5k for lvl 3 + building costs
Answer: First, you have to complete the intial garrison quest chain, which ends with establishing your outpost and building barracks level 1. You right away receive the quest to upgrade it to level 2 (you need 200 garrison resources for that). This can be done within 1.5h maximum, starting in your capital (tested today in the morning).
After that, you are directly offered the quest to upgrade your garrison to level 3, but you need 2000 garrison resources for that step. Farming this amount of resources the conventional way takes a lot of time. An alternative to that is buying two Huge Ogre Caches from the auction house. Not cheap, but it does the trick.
A comment from my side: You have to decide yourself if it is worth the trouble, depending on what you want to do with your demon hunter. You can participate in all raids etc. without spending many days or 10k gold on your level 3 garrison. If you only want to level your new professions, constructing the respective buildings to level 2 might suffice until the start of the expansion.
Comment: Given that level 3 garrison cost 5000 gold. You might want to do the quest chain that let you earn a Bind on Account weapon upgrade to 100 which cost 5000 gold itself plus a few other rewards. Otherwise your answer looks good.
Comment: You can circle the continent for Treasure. This gives you the required Garrison ressources in no time without spending extra Gold. The initial costs are already high enough.


Mule - Send SFTP outbound message after Collection Split

Question: I am using collection-splitter to split my List. Now how should I set the payload to SFTP outbound-endpoint.

<code>        <sftp:inbound-endpoint connector-ref="sftp-inbound" host="${SFTP_HOST}" port="${SFTP_PORT}"
        path="/files/" user="${SFTP_USER}" password="${SFTP_PASS}"
        responseTimeout="10000" pollingFrequency="30000" fileAge="20000" sizeCheckWaitTime="5000"
        archiveDir="/files/archive/" doc:name="SFTP"  >
             <file:filename-regex-filter pattern="Test(.*).zip" caseSensitive="true"/>
        </sftp:inbound-endpoint>

        <set-variable variableName="regexVal" value="${REGEX}" doc:name="Variable"/>
        <set-variable variableName="sourceFileName" value="#[flowVars.originalFilename]" doc:name="Variable"/>

        <custom-transformer name="zipTxt" class="com.mst.transform.UnzipTransformer" doc:name="Java" mimeType="image/gif">
            <spring:property name="filenamePattern" value="*.csv,*.txt" />
        </custom-transformer>

        <set-variable variableName="fileContents" value="#[payload]" />

        <collection-splitter enableCorrelation="IF_NOT_SET" />

        <logger message="#[payload]" level="INFO" doc:name="Logger"/>

        <sftp:outbound-endpoint connector-ref="sftp-inbound"
            host="${SFTP_HOST}" port="${SFTP_PORT}"
            path="/files/" user="${SFTP_USER}" password="${SFTP_PASS}"
            responseTimeout="10000" doc:name="SFTP"
            exchange-pattern="one-way"/>

 </flow>
</code>
Comment: Can you provide a little more detail around what you are trying to achieve here? What do you expect your outbound payload to look like?
Comment: And what issues are you having with the approach above?
Answer: If your payload before collection splitter is list of objects that can be consumed by SFTP outbound endpoint like InputStream, then after splitter, you can wrap logger, sftp inside processor-chain. Splitter will send each object one-by-one to processor chain. SFTP should be able to write it if its an InputSream.
<code><collection-splitter enableCorrelation="IF_NOT_SET" />

<processor-chain doc:name="Processor Chain">
        <logger message="#[payload]" level="INFO" doc:name="Logger"/>

        <sftp:outbound-endpoint connector-ref="sftp-inbound"
            host="${SFTP_HOST}" port="${SFTP_PORT}"
            path="/files/" user="${SFTP_USER}" password="${SFTP_PASS}"
            responseTimeout="10000" doc:name="SFTP"
            exchange-pattern="one-way"/>
</processor-chain>
</code>
You wouldn't need processor-chain if you just want to put one processor (eg. SFTP) after splitter.
If this doesn't work, then please add error details to question.


Inconsistent ability to resolve DNS on Ubuntu 12.10 fresh install

Question: For machines on my local network I use my router (running DD-WRT v24-sp2 (08/07/10) std-nokaid-small) to DHCP IP addresses and to resolve names.  I now frequently notice that my web browsers can't resolve these names until after I open a terminal window and dig firstname.lastname@example.com (the router) or sometimes try some other networking commands.  This happens on both wired and wifi devices on the local network.
Here is an example:
jelevin@mycomputer:~$ ping mycomputer.lan
ping: unknown host mycomputer.lan
jelevin@mycomputer:~$ host mycomputer.lan
mycomputer.lan has address 192.168.1.236
jelevin@guava:~$ ping mycomputer.lan
PING guava.family (192.168.1.236) 56(84) bytes of data.
64 bytes from guava.family (192.168.1.236): icmp_req=1 ttl=64 time=0.023 ms
...

I have reinstalled and dpkg-reconfigered resolvconf.  Here is the contents of /etc/resolv.conf
jelevin@mycomputer:~$ cat /etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 127.0.1.1
search lan

Any suggestions?  Thanks!
Answer: This is probably the known bug #1003842 (https://bugs.launchpad.net/ubuntu/+source/dnsmasq/+bug/1003842).
To work around this bug, edit /etc/NetworkManager/NetworkManager.conf and comment out the line dns=dnsmasq, then restart network-manager.


Is there a way to stream tweets using python only for specific time?

Question: I'm working on tweepy to stream tweets.
As far I know we can start the streamer and leave it running indefinitely to work with tweets.
I was looking for a way to limit this stream and exit the streamer after some time like 10 minutes or so which we can specify.
From the docs, I couldn't find anything to do so. (I may have missed too.)
How do I specify the amount of time that the streamer can keep listening to the tweets.
import json

from tweepy import StreamListener, OAuthHandler, Stream

class StdOutListener(StreamListener):
    def __init__(self):
        self.hashtag_frequency = {}

    def on_data(self, data):
        hashtags = json.loads(data)["entities"]["hashtags"]
        for hashtag in hashtags:
            text = hashtag["text"]
            self.hashtag_frequency[text] = self.hashtag_frequency.get(text, 1) + 1
        print(self.hashtag_frequency)
        return True

    def on_error(self, status):
        print(status)

listener = StdOutListener()
auth = OAuthHandler('', '')
auth.set_access_token('', '')

stream = Stream(auth, listener)

stream.filter(track=['testing'])

Answer: You could add a timer in there, something like and just add a break at the end of it
import time
t = #Add number of seconds you want the bot to run, if you want 10 minutes, than it's 600 seconds
if t != 0:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, end="\r")
        t -= 1
else:
     return

Comment: But, I'm not using  a while loop here. It is just the filter() method which is taking care of stuff.
Comment: Oh, in that case, just add a condition, that would say that ```if t =0: break```


Bash reading txt file and storing in array

Question: I'm writing my first Bash script, I have some experience with C and C# so I think the logic of the program is correct, it's just the syntax is so complicated because apparently there are many different ways to write the same thing!
Here is the script, it simply checks if the argument (string) is contained in a certain file. If so it stores each line of the file in an array and writes an item of the array in a file. I'm sure there must be easier ways to achieve that but I want to do some practice with bash loops
#!/bin/bash

NOME=$1
c=0

#IF NAME IS FOUND IN THE PHONEBOOK THEN STORE EACH LINE OF THE FILE INTO ARRAY
#ONCE THE ARRAY IS DONE GET THE INDEX OF MATCHING NAME AND RETURN ARRAY[INDEX+1]

if grep "$NOME" /root/phonebook.txt ; then
        echo "CREATING ARRAY"
        while read line
        do
                myArray[$c]=$line # store line
                c=$(expr $c + 1) # increase counter by 1
        done < /root/phonebook.txt

else
        echo "Name not found"
fi

c=0
for i in myArray;
        do
              if   myArray[$i]="$NOME" ;  then
                 echo ${myArray[i+1]} >> /root/numbertocall.txt
              fi

done

This code returns the only the second item of myArray (myArray[2]) or the second line of the file, why?
Comment: Are you running as root?  Learning to write shell scripts while logged in as root is a bit like learning to drive cars in a Formula 1 racing car; it's fast, but it is dangerous.  Don't run as root except when you absolutely have to.  Then be very, very careful.
Comment: why're you using grep -q?
Comment: oops that wasn't meant ..thanks
Comment: can not find the question in your question
Comment: thank you! Haven't thought about that
Comment: `for i in myArray` is wrong
Answer: The first part (where you build the array) looks ok, but the second part has a couple of serious errors:

for i in myArray; -- this executes the loop once, with $i set to "myArray". In this case, you want $i to iterate over the indexes of myArray, so you need to use
for i in "${!myArray[@]}"

or
for ((i=0; i<${#a[@]}; i++))

(although I generally prefer the first, since it'll work with noncontiguous and associative arrays).
Also, you don't need the ; unless do is on the same line (in shell, ; is mostly equivalent to a line break so having a semicolon at the end of a line is redundant).
if   myArray[$i]="$NOME" ;  then -- the if statement takes a command, and will therefore treat myArray[$i]="$NOME" as an assignment command, which is not at all what you wanted. In order to compare strings, you could use the test command or its synonym [
if [ "${myArray[i]}" = "$NOME" ]; then

or a bash conditional expression
if [[ "${myArray[i]}" = "$NOME" ]]; then

The two are very similar, but the conditional expression has much cleaner syntax (e.g. in a test command, > redirects output, while \> is a string comparison; in [[ ]] a plain > is a comparison).
In either case, you need to use an appropriate $ expression for myArray, or it'll be interpreted as a literal. On the other hand, you don't need a $ before the i in "${myArray[i]}" because it's in a numeric expression context and therefore will be expanded automatically.
Finally, note that the spaces between elements are absolutely required -- in shell, spaces are very important delimiters, not just there for readability like they usually are in c.
Answer: 1.-This is what you wrote with small adjustments
#!/bin/bash

NOME=$1

#IF NAME IS FOUND IN THE PHONE-BOOK **THEN** READ THE PHONE BOOK LINES INTO AN ARRAY VARIABLE
#ONCE THE ARRAY IS COMPLETED, GET THE INDEX OF MATCHING LINE AND RETURN ARRAY[INDEX+1]

c=0
if grep "$NOME" /root/phonebook.txt ; then

       echo "CREATING ARRAY...."
       IFS= while read -r line    #IFS= in case you want to preserve leading and trailing spaces
       do
             myArray[c]=$line     # put line in the array
             c=$((c+1))           # increase counter by 1
       done < /root/phonebook.txt

       for i in ${!myArray[@]}; do
             if  myArray[i]="$NOME" ;  then
                 echo ${myArray[i+1]} >> /root/numbertocall.txt
             fi
       done

else
       echo "Name not found"
fi

2.-But you can also read the array and stop looping like this:
#!/bin/bash

NOME=$1

c=0
if grep "$NOME" /root/phonebook.txt ; then

       echo "CREATING ARRAY...."
       readarray myArray < /root/phonebook.txt

       for i in ${!myArray[@]}; do
             if  myArray[i]="$NOME" ;  then
                 echo ${myArray[i+1]} >> /root/numbertocall.txt
                 break            # stop looping
             fi
       done

else
       echo "Name not found"
fi
exit 0

3.- The following improves things. Supposing a)$NAME matches the whole line that contains it and b)there's always one line after a $NOME found, this will work; if not (if $NOME can be the last line in the phone-book), then you need to do small adjustments.
!/bin/bash
PHONEBOOK="/root/phonebook.txt"
NUMBERTOCALL="/root/numbertocall.txt"
NOME="$1"
myline=""

myline=$(grep -A1 "$NOME" "$PHONEBOOK" | sed '1d')

if [ -z "$myline" ]; then
      echo "Name not found :-("

else
      echo -n "$NOME FOUND.... "
      echo "$myline" >> "$NUMBERTOCALL"
      echo  " .... AND SAVED! :-)"

fi
exit 0


Suggestions to Ensure Encapsulation

Question: In my solution I have a DLL project, say Project1, that owns a class, say class A. This class has some  properties, so vital that must only be set in this DLL. Any other projects that references this DLL can only use the getters. So far I have handled the situation by accessing the setters internally, like:
public class A
{
  int Num1
  {
    get;
    internal set;
  }

  int Num2
  {
    get;
    internal set;
  }
}

Right now I have to add another project, Project2, to the solution that not only must use class A (both getters and setter) but also, Project1 has a reference to this new project. So I decided to separate class A in a different definition dll, on the top of the hierarcy. That is the point, my problem araises. Now all the setters are invisible to Project1 and Project2. If I remove the internal accessor then setters will be available to any assembly that references the definition dll. I do not want this because the information on the class A is so important, it must not be set mistakenly.
How can I limit the access to the setters of class A from outside of Project1 and Project2?
Only solution comes to my mind is using InternalsVisibleTo. I do not know, it doesn't sound perfect. Also combining Project1 and Project2 would be another another solution, but these two are responsible for completely different tasks, it is not the best option designwise.
Answer: You can keep the internal protector on it, but give another assembly the trust to access the internal members.
[assembly: InternalsVisibleTo("AssemblyName")]

You can do this at the class level, or on the entire assembly itself if you want.
InternalsVisibleToAttribute Class
Comment: because if there comes along Project3 he would need to rebuild the DLL containing class A to add Project3 InternalsVisibleTo clause...
Comment: Ooops, sorry for not reading the last sentence of the question more closely. I think, by design, InternalsVisibleTo is still the best option. You don't want to give global access to those properties, so you want to control exactly which assemblies you trust to use it. Adding a new InternalsVisibleTo attribute for each new assembly is the best way by design
Comment: any thoughts on why the OP hesitates on this option?  it seems like the perfect fit.
Comment: designwise I am with you... practically I don't think that the OP wants to go that way :-(
Comment: @Gabriel: InternalsVisibleTo attribute seems to be a good solution with an overhead of rebuilding the dll for each projects that use class A. I just want to see if there are any other options.
Answer: you could always do something like this (a nightmare of a design but does what you asked for):
public class A
{
  int _Num1, _Num2;

  int Num1 {get {return _Num1;}; }
  int Num2 {get {return _Nun2;}; }

  protected void SetNum (int pWhich, int pV)
  {
      if ( pWhich == 1 ) {_Num1 = pV; return;}
      _Num2 = pV;
  }
}

and then you could instanciate the class normally... when you need to set the values you use reflection:
myClassA.GetType().GetMethod ("SetNum", BindingFlags.NonPublic ).Invoke (myClassA, new object[] {1, 777 });

Answer: If I'm right in assuming that Project1 does some specific stuff, and Project2 is an abstraction on top of that, then this is a candidate for inversion of control - ideally, an implementation should depend on an abstraction, not the other way around.
If things within Project2 need to control something defined in Project1, create an interface in Project2 and have Project2 talk to the interface, then implement the interface in Project1 and do all the dirty work internally.

Suggestions to Ensure Encapsulation


Using nlargest to find winner of contest

Question: I am having issues with nlargest in pandas. I can't seem to figure out why the columns for each name aren't sorting properly. nlargest only seems to work on the first column even if the second or third column has the higher scores. I am tryin to find the winner based off of who has the highest two scores. In the example below Jeff should be the winner but nlargest only applies to the first column so dan always wins. Any help would be greatly appreciated.
Sample Code:
import pandas as pd

names = []
con = int(input("Number of Contestants: "))
maxSurfers = con #number of surfers
while len(names) < maxSurfers:
        name = input(" Enter your Name: ")
        names.append(name)
        print("Contestants")
        print(names)
else:
       print("Thank You for Participating!\n")
       print("Sign up is now closed\n")

score = {}
for name in names:
    numWaves = int(input("Number of Waves for "+name+": "))
    newScores = []
    for i in range(numWaves):
        newScores.append(float(input("Enter score wave: ")))
    score[name] = newScores
#newScores - most recent entry committed to score directory

df = pd.DataFrame(score)
for (columnName, columnData) in df.iteritems():
    winner = df.nlargest(2, names)
print(winner)

Outputs:
Number of Contestants: 3
 Enter your Name: dan
Contestants
['dan']
 Enter your Name: jeff
Contestants
['dan', 'jeff']
 Enter your Name: eric
Contestants
['dan', 'jeff', 'eric']
Thank You for Participating!

Sign up is now closed

Number of Waves for dan: 5
Enter score wave: 3.0
Enter score wave: 10.0
Enter score wave: 5.6
Enter score wave: 9.5
Enter score wave: 3.0
Number of Waves for jeff: 5
Enter score wave: 10.0
Enter score wave: 3.0
Enter score wave: 3.0
Enter score wave: 9.9
Enter score wave: 3.0
Number of Waves for eric: 5
Enter score wave: 3.0
Enter score wave: 1.0
Enter score wave: 5.6
Enter score wave: 9.5
Enter score wave: 6.3
    dan  jeff  eric
1  10.0   3.0   1.0
3   9.5   9.9   9.5

Desired Output:
Number of Contestants: 3
 Enter your Name: dan
Contestants
['dan']
 Enter your Name: jeff
Contestants
['dan', 'jeff']
 Enter your Name: eric
Contestants
['dan', 'jeff', 'eric']
Thank You for Participating!

Sign up is now closed

Number of Waves for dan: 5
Enter score wave: 3.0
Enter score wave: 10.0
Enter score wave: 5.6
Enter score wave: 9.5
Enter score wave: 3.0
Number of Waves for jeff: 5
Enter score wave: 10.0
Enter score wave: 3.0
Enter score wave: 3.0
Enter score wave: 9.9
Enter score wave: 3.0
Number of Waves for eric: 5
Enter score wave: 3.0
Enter score wave: 1.0
Enter score wave: 5.6
Enter score wave: 9.5
Enter score wave: 6.3
    dan  jeff  eric
0   3.0  10.0   3.0
3   9.5   9.9   9.5

Answer: The problem is that df.nlargest with a list of columns (for the parameter columns) will first sort based on the first value in the list (dan), then by the second (jeff) and finally eric.
It is explained at the end of the documentation page for nlargest:
pandas.DataFrame.nlargest
To get the highest two values for each column try in this way:
df = pd.DataFrame(score)

winner_df = pd.DataFrame()
for (columnName, columnData) in df.iteritems():
    winner = df.nlargest(2, columnName)[columnName].reset_index(drop= True)
    winner_df[columnName] = winner

print(winner_df)

Output:
    dan     jeff    eric
0   10.0    10.0    9.5
1   9.5     9.9     6.3

Comment: Awesome, thank you! You've set me in the right direction. However, I am unable to get the same results when testing the code you suggested. How were you able to get it to work without defining df? Also I'm assuming that the .reset_index(drop= True) is what references each column without hard coding the names of each contestant. Is that correct?
Comment: you have to define df as in your code, mine was just and addition. Reset_index is needed just to make the winner_df rows all with the same index. Hope this helps
Comment: Okay that's what I thought and did but when I run the code I and print winner, only the last contestant is displayed. Sorry I've been coding for less than a week all of this is pretty new to me.
Comment: No problem :)  Try to print `winner_df` instead of `winner` at the end of the for loop (see the updated answer)
Answer: Here is how I changed the code.
Changed to:
df = pd.DataFrame(score)
winner_df = pd.DataFrame()
for (columnName, columnData) in df.iteritems():
    winner = df.nlargest(2, columnName)[columnName].reset_index(drop= True)
    winner_df[columnName] = winner
print(winner)

Which outputs:
Number of Waves for dan: 3
Enter score wave: 3.0
Enter score wave: 3.0
Enter score wave: 3.0
Number of Waves for jake: 3
Enter score wave: 10.0
Enter score wave: 9.9
Enter score wave: 3.0
Number of Waves for jeff: 3
Enter score wave: 4.0
Enter score wave: 3.0
Enter score wave: 5.0
0    5.0
1    4.0
Name: jeff, dtype: float64

Note sure what is wrong.
Comment: just do `print(winner_df)` instead of `print(winner)`


Cyclic group of order 15

Question: I'm reviewing for the math GRE (it's been 8+ years since I took abstract algebra) and came across this question:

A cyclic group of order 15 has an element $x$ such that the set $\{x^3, x^5, x^9 \}$ has exactly two elements. The number of elements in the set $\{x^{13n}: n \text{ a positive integer } \}$ is what?

Can someone show me how to approach this problem, and what concepts are in play here?
Comment: two of the elements have to be equal... And you know that in a group of order $15$ you have $x^{15}=e$... From there you can figure which two elements are equal...
Comment: Why don't you just write down the sets $\{x^3,x^5,x^9\}$ for all $15$ elements in your group and see what you get?
Answer: You have $3$ possibilities:
$$x^3=x^5 \Rightarrow x^2=e \,.$$
In this case since $x^{15}=e$ it follows that $x=e$, which is not possible (since you only get one value in your set).
$$x^5=x^9 \Rightarrow x^4=e \,.$$
Again, this implies that $x=e$, not possible.
$$x^3=x^9 \Rightarrow x^6=e \,.$$
Thus, $x^3=x^{\operatorname{gcd}(6,15)}=e$. This means that $x$ must have order $1$ or $3$, but again $x=e$ is not possible.
Thus, $x$ is an element of order $3$ in your group, and from there it is easy: $x^{13n}=x^{13m} \Leftrightarrow 3|13(m-n)  \Leftrightarrow 3|m-n$... So how many distinct values do you get?
Answer: If an element $a$ generates the whole group, then consider $x=a^5$.  Then you've got $x^3=e=\text{the identity}$ and $x^9=e$.
Answer: The order of $x^{13}$ is the same as the order of $x$ because $\gcd(13,15)=1$. As others have already mentioned, $x$ has order 3. Hence the set has 3 elements.
Comment: Shouldn't it be $\gcd(13,3)$ since the order of $x$ is $3$?

Cyclic group of order 15


Does the CSR(Certificate signing request) file used for creating developer or distribution certificate and push certificate has to be same?

Question: So when creating a new push certificate can I use a new CSR file.Does the CSR file used for creating developer or distribution certificate and push certificate has to be same?
Will push notifications work if they are different?
Comment: Correct. CSRs are for getting new certificates. Certificates are used to establish trust. The certificates used for APNS establish trust independently of those used for app signing.
Comment: No, you can use different ones
Comment: So they doesn't have to be same? @allenh
Answer: Apple's certificate process is similar to other certificate systems. When you make the CSR your own system actually generates a public and private key pair. The CSR contains the public key. Apple uses that public key to make a certificate. A certificate is more or less a way of publishing a public key along with some related information about that key, and of verifying that the issuing entity (Apple in this case) represents that this information is valid.
Since each certificate has their own public-private key pair, then your push certificate and developer and distribution certificates can all use different CSRs. Each certificate is used to authenticate and secure that particular item.
Your development or distribution profile is used to connect the application ID (aka Bundle ID in some documentation) with your developer or distribution certificates. Your APNS push certificate is made with your application ID, so that ties it to your app in that way.
So it's the application ID that connects these things together in the Apple system.
In short you can use the same or different CSR as you wish. (Although security people would prefer you use a different CSR for each one.)


Whats a condition for positive semi-definiteness for given real symmetric matrix in terms of matrix elements?

Question: Let us consider we have a real, symmetric matrix $W \in \mathcal{R}^{n \times n}$.
Is there a linear condition (linear equation or linear inequality in terms of the matrix elements ($w_{11}, w_{12} \, ... w_{nn} $)) that is necessary and sufficient to guarantee that the matrix $W$ will be semi-definite?
Essentially, I am looking for some theorem that is linear in terms of the matrix elements (therefore, something like the determinant will not work since it is nonlinear in terms of the elements of $W$) that lets me check if $W$ (real, symmetric) is a covariance matrix.   Does such a condition even exist?
I found a theorem that comes very close to meeting all my requirements.  "Diagonally dominant " real symmetric matrices are always postive-semidefinite. The diagonal dominance requires, for every row, the sum of magnitudes of all off-diagonal elements be less than the diagonal element. This is a set of $n$ linear inequalities.
But all covariance matrices are not diagonally dominant. So this does not cover the space of all covariance matrices.
I appreciate the help!
Comment: $2^n - 1$ polynomial inequalities, $n$ of them linear. I don't think you can do better than that. You want the positive semidefinite cone to be a polyhedron.
Comment: What are the $2^n$ -1 inequalities  ?  Could you please clarify ?
Comment: Take a look at [this](https://en.wikipedia.org/wiki/Sylvester%27s_criterion). The inequalities are: $\binom{n}{1}$ diagonal entries must be nonnegative, $\binom{n}{2}$ determinants of $2 \times 2$ "principal" submatrices must be nonnegative, and so forth till the one and only determinant is nonnegative. Only the first $n$ inequalities are linear in the matrix entries. The determinant is a degree-$n$ polynomial in the matrix entries.
Answer: No such linear inequalities exist, because their existence would wrongly imply that
$$
\left\{(x,y)\in\mathbb R^2:\ 0\le x\le1,\ \pmatrix{x&y\\ y&1}\succeq0\right\}
=\left\{y^2\le x\le1\right\}
$$
is a polytope.


how to insert data from file line by line into request in python code

Question: I need to insert data from file line by line in python request
example
user.txt
1
2
3

and script to open file user.txt
user=open("user.txt","r").readlines()

and request
r = request.get('http://example.com/r='+user)

how to make can request line by line user.txt in request
example
http://example.com/r=1
http://example.com/r=2
http://example.com/r=3

not like this
http://example.com/r=['1','2','3']

Comment: Have you learnt about loops?
Comment: how to do that?
Comment: @VickyzSetiawan How to learn? Read the [tutorial](https://docs.python.org/3/tutorial/index.html).
Answer: You could iterate over the lines you've read:
with open("user.txt","r") as f:
    for line in f:
        r = request.get('http://example.com/r=' + line)
        # do something with r

Comment: the code only read the last line in user.txt only example.com/r=3 not line by request like example
Comment: @VickyzSetiawan You nee to use `r` in each iteration of the loop, as the comment says
Answer: You can use cycle like this:
with open("user.txt","r") as users:
    for user in users.readlines():
        response = request.get('http://example.com/r=' + user)
        # do something with the response, ex store response.json() somewhere

Comment: @enzo What do you mean by that? oO
Comment: −1 because you're fake.
Comment: the code only read the last line in user.txt only example.com/r=3 not line by request like example
Comment: Did you store the response somewhere? You should add some code instead of `# do something with the response, ex store response.json() somewhere`
Comment: i'm store the response into function i wat to try again with your code. thanks
Comment: after add your code into fuction still only read last line
Comment: Could you please update the question to show what you want to do with the request results?


Vue.js tree view with data from AJAX call

Question: So I'm just starting to play with Vue.js and was trying to get the tree view from Vue.js working.
Fetching the data with an AJAX call and displying it is working great.
Here's my problem: I cant figure out how to show/hide elemnts. I was trying to do it the same way as it is shown on the Vue seie: see here
All i'm getting is one "open" variable, and not for each category one.
Of course every time i toggle it all items are shown/hidden.
I hope this makes it clear:
<code>{
  "open": false,
  "list": {
        "categories": [
          {
            "id": 1,
            "name": "Some Category",
            "created_at": "2015-12-31 10:10:58",
            "updated_at": "-0001-11-30 00:00:00",
            "items": [
              {
                "id": 1,
                "category_id": 1,
                "name": "Some Item",
                "description": "Lorem",
                "price": 10,
                "created_at": "2015-12-31 10:11:45",
                "updated_at": "-0001-11-30 00:00:00"
              },
              {
                "id": 8,
                "category_id": 1,
                "name": "Some Item",
                "description": "Lorem",
                "price": 10,
                "created_at": "2015-12-31 11:56:44",
                "updated_at": "2015-12-31 11:56:44"
              },
              {
                "id": 32,
                "category_id": 1,
                "name": "aa",
                "description": "        \r\n    ",
                "price": 122,
                "created_at": "2016-01-07 14:46:43",
                "updated_at": "2016-01-07 14:46:43"
              }
            ]
          },
          {
            "id": 2,
            "name": "Some Category",
            "created_at": "2015-12-31 10:10:58",
            "updated_at": "-0001-11-30 00:00:00",
            "items": [
              {
                "id": 2,
                "category_id": 2,
                "name": "Some Item",
                "description": "Lorem",
                "price": 30,
                "created_at": "2015-12-31 10:11:45",
                "updated_at": "-0001-11-30 00:00:00"
              },
              {
                "id": 3,
                "category_id": 2,
                "name": "Some Item",
                "description": "Lorem",
                "price": 20,
                "created_at": "2015-12-31 10:13:06",
                "updated_at": "-0001-11-30 00:00:00"
              }
            ]
        }
     ]
  }
}
</code>
I spend the whole day trying to figure this out...
Thanks in advance for your help!
Answer: Finally got Vue.set working:
<code>toggle: function (category) {
    if(! category.open)
    {
        Vue.set(category, 'open' , false)
    }
    category.open = !category.open
},
</code>


Get an object parameter value inside a jQuery function inside an object's method

Question:
I have this:
function test1()
{
    this.count = 0;
    this.active = 0;
    this.enable = function () {this.active = 1;}
    this.disable = function () {this.active = 0;}
    this.dodo = function ()
                {
                    $("html").mousemove(function(event) {
                        // I want to get here the "active" param value;
                    });
                }
    this.enable();
    this.dodo();
}

instance = new test1();
instance.disable();

Let's say I want to check the active param of the test1 class in the commented place. How can I get it there ?
Thanks!
Answer: If you want access to all the member variables of the higher scope, you just need to save the this pointer from that scope into a local variable so you can use it inside the other scope:
function test1() {
    this.count = 0;
    this.active = 0;
    this.enable = function () {this.active = 1;}
    this.disable = function () {this.active = 0;}
    var self = this;
    this.dodo = function () {
        $("html").mousemove(function(event) {
            // I want to get here the "active" param value;
            alert(self.active);
        });
    }
    this.enable();
    this.dodo();
}

instance = new test1();
instance.disable();

Answer: this.dodo = function ()
            {
                var active = this.active;

                $("html").mousemove(function(event) {
                    alert(active);
                });
            }

Answer: When you call a function 'this' refers to the object the function was invoked from, or the newly created object when you use it together with the keyword new. For example:
var myObject = {};
myObject.Name = "Luis";
myObject.SayMyName = function() {
    alert(this.Name);
};

myObject.SayMyName();

Note in JavaScript there are multiple ways to declare, define, and assign fields and methods to objects, below is the same code written more similarly to what you wrote:
function MyObject() {
    this.Name = "Luis";
    this.SayMyName = function() {
        alert(this.Name);
    };
}

var myObject = new MyObject();
myObject.SayMyName();

And yet another way to write the same thing:
var myObject = {
    Name: "Luis",
    SayMyName: function() {
        alert(this.Name);
    },
};

myObject.SayMyName();

There are also several different ways to invoke a function.


timer scheduled swift - error with self identifier

Question: im trying to make a "sleep" function for real time updating my UI display with updating variables.
using xcode 9.2 swift 4
//sleep function for UI display
func sleep(time: Double, closure: @escaping (Timer) -> (Void) ) {
    var timer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(closure), userInfo: nil, repeats: false)
    timer.invalidate()
}

i get this error:

Use of unresolved identifier 'self'

thanks a million!
Comment: Invalidating a timer right after being created is pointless. The closure is not executed before the timer **fires**.
Comment: Where did you put this function?
Answer: A selector statically identifies a function. You can't make a selector out of an argument.
Perhaps something like this would be better:
func sleep(time: Double, closure: @escaping (Timer) -> (Void) ) {
    _ = Timer.scheduledTimer(withTimeInterval: time, repeats: false) { timer in
        closure(timer)
    }
}

Answer: Regarding your error this function is might be outside of a class that is why self is unresolved identifier. Function should be inside the class body.
Next point is you are making selector in wrong way. Selector will be a method defined in same class.
Another point is you are invalidating the timer in next line so it will never execute.
If your app supports iOS Version >= 10.0.
func sleep(time: Double, closure: @escaping (Timer) -> (Void) ) {
    Timer.scheduledTimer(withTimeInterval: time, repeats: false) { (timer) in
       closure(timer)
    }
}

If your app supports iOS Version < 10.0
In your class make few properties:
typealias TimerCallBack = (_ timer: Timer) -> Void
var timer: Timer!
var callBack: TimerCallBack!

Then
func sleep(time: Double, closure: @escaping TimerCallBack) {
     self.callBack = closure
     self.timer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(timerFired(_:)), userInfo: nil, repeats: false)
}

@objc func timerFired(_ timer: Timer) {
    if callBack != nil {
        callBack(self.timer)
    }
}


Passing the collection of selected values from a Select2-Multi DropDownList to a Controller

Question: So I'm working up a example of the Select2 to use in a project and I'm missing a piece. I'm not sure how the selected dropdownlist collection will get back to the controller. I've tried several combinations of Automobiles and SoldAutomobiles and the Controller always show no data when I break in the Submit Action Method.
View
@model Select2Demo.Models.Auto.Dealership

@{
    ViewBag.Title = "Auto Home Page";
}

<link href="~/Content/css/select2.css" type="text/css" rel="stylesheet" />

<link href="~/Content/bootstrap.css" type="text/css" rel="stylesheet" />
<link href="~/Content/select2-bootstrap.css" type="text/css" rel="stylesheet" />

Select2 Multi-Select Example

@using (Html.BeginForm("Submit", "Auto"))
{

                    @Html.LabelFor(model => model.Automobiles)

                    @Html.DropDownListFor(model => model.Automobiles, new SelectList(Model.Automobiles, "Id", "Make", Model.SoldAutomobiles), new { multiple = "multiple", @id = "ddlCars" })

            <input type="submit" value="Submit" class="btn btn-primary btn-lg submit-btn"/>

}

Controller
public class AutoController : Controller
{
    public ActionResult Index()
    {
        List<Automobile> autos  = new List<Automobile>();
        Automobile auto = GetAuto(1,"Chevy");
        autos.Add(auto);
        auto = GetAuto(2, "Ford");
        autos.Add(auto);
        auto = GetAuto(3, "Audi");
        autos.Add(auto);
        auto = GetAuto(4, "Toyota");
        autos.Add(auto);
        auto = GetAuto(5, "Duster");
        autos.Add(auto);
        auto = GetAuto(6, "Esteem");
        autos.Add(auto);
        auto = GetAuto(7, "Fiero");
        autos.Add(auto);
        auto = GetAuto(8, "Lancer");
        autos.Add(auto);
        auto = GetAuto(9, "Phantom");
        autos.Add(auto);

        Dealership dealership = new Dealership {Automobiles = autos};
        return View(dealership);
    }

    public ActionResult Submit(Dealership dealer)
    {
        Dealership dealership = new Dealership {SoldAutomobiles = dealer.SoldAutomobiles};

        return View("Index", dealership);
    }

    private static Automobile GetAuto(int id, string make)
    {
        return new Automobile {Id = id, Make = make};
    }
}

Classes
public class Automobile
{
    public int Id { get; set; }
    [Display(Name = "Make")]
    public string Make { get; set; }
}

public class Dealership
{
    public List<Automobile> Automobiles { get; set; }
    public List<Automobile> SoldAutomobiles { get; set; }
}

UPDATED With Working Code Changes.
View
@model Select2Demo.Models.Auto.Dealership

@{
    ViewBag.Title = "Auto Home Page";
}

Select2 Multi-Select Example

@using (Html.BeginForm("Submit", "Auto"))
{

                    @Html.LabelFor(model => model.Automobiles)

                    @Html.ListBoxFor(model => model.SelectedAutomobiles, new SelectList(Model.Automobiles, "Id", "Make"), new { multiple = "multiple", @id = "ddlCars" })

            <input type="submit" value="Submit" class="btn btn-primary btn-lg submit-btn"/>

}

Model
public class Automobile
{
    public int Id { get; set; }
    [Display(Name = "Make")]
    public string Make { get; set; }
}

public class Dealership
{
    [Display(Name = "Available Auto Makes")]
    public List<Automobile> Automobiles { get; set; }
    public int[] SelectedAutomobiles { get; set; }
}

Comment: check this:http://www.intertech.com/Blog/selecting-multiple-items-using-select2-in-mvc-5/
Comment: Thanks I reviewed that earlier this evening. The way he is doing it is saving the selected values as a comma separated string. I didn't want to go that route because I will have much more data to move around with the live product
Comment: created a filddle if some one needs it https://dotnetfiddle.net/pooH4S#
Comment: https://github.com/ashgadala/Select2-Multi-Select-ASPNET-Core/tree/master
Answer: You need a valid property to bind to (currently your trying to bind a <select> which post back a simple array of the selected option values to a collection of complex objects)
public class Dealership
{
  public int[] SelectedCars { get; set; }
  public List<Automobile> Automobiles { get; set; }
}

and in the view
@Html.ListBoxFor(m => m.SelectedCars, new SelectList(Model.Automobiles, "Id", "Make"))

Note if the values of SelectedCars matches any of the values of the options, then those options will be selected in the view when the page is rendered (e.g. if model.SelectedCars = new int[] { 2, 6 }; then "Ford" and "Esteem" will be selected.
Comment: Disregard I just noticed you changed the control to a ListboxFor rather than a DropDownListFor, After making that change it works as expected. Thanks
Comment: Thanks Steven, that got me most of the way there. I have the selected values but it only seems to load one of them when the view loads after the submit even though all of the selected items are in the object.
Answer: Use an array to get the values of your drop-down list.
  public int[] CountryId { get; set; }

And on mvc view, do the following,
<select asp-for="CountryId" id="CountryId" class="form-md-line-input no-hint"
        asp-items="@Model.CountrySelectListItems">
    <option value="">Select A Country</option>
</select>


At What Sector is it Reasonable to Acquire Scrap Recovery Arm?

Question: The scrap recovery arm costs 50 scrap and Gives you +10% scrap on acquisition other than selling items (rounded down.)  Given that you have to spend scrap to earn scrap, at what sector does it make sense to invest in the SRA?  I'd imagine you'd want to have a significant gain to make up for early scrap disadvantage.
This question's answer will vary based on difficulty, as that impacts scrap rewards as well as the necessity for early scrap.
Comment: @Ender - Whilst I generally don't buy the Scrap Arm over other options available, the blue-option it adds to 'Asteroid Field' events gives you a guaranteed amount of between 18-41 scrap. I've found on runs where I've obtained it even at late as sector 5 it's paid for itself fairly quickly.
Comment: Also worth mentioning is that you can sell it for 25 scrap in sector 7.
Comment: These blue events really need to be mentioned in the answer, 41 scrap from one blue event that *you wouldn't otherwise get* is a major factor in the item paying for itself.
Comment: The item requires you to get 500 scrap before it even pays for itself, I wouldn't get it past sector two if I was planning on actually ever gaining anything at all from it. Personally I never get it at all.
Comment: I was unaware of blue options given by it. nice
Comment: Considering what Studoku said, then if we take for granted the sale of the arm, it pays for itself way earlier (after getting 250 scrap).
Answer: In the first couple sectors, I think you easily make about 100 scrap per sector.  As you move up, that amount increases to 200 or 300 per sector (assuming you are defeating all ships rather than fleeing or avoiding them).  So I'd say that as long as you get it before the end of sector 4, it definitely pays for itself.  After that, it gets to be risky, but could still pay for itself even if you pick it up in sector 5 or early sector 6.
There is also the opportunity cost of taking an equipment slot and not having the 50 scrap to spend on something else.  I'd probably rate it as awesome in sector 1-3, good in 4, and iffy beyond that.
Comments talk about the Asteroid Field event, but I think that is rare enough that I wouldn't really take it into account.  I've bought the arm numerous times, and gotten to take advantage of that event in maybe 10% of them.
Comment: @IQAndreas or any other economic theory, since O.C is central to almost all of them.
Comment: "There is also the opportunity cost..." - looks like someone's been studying game theory.
Comment: In sector 1 and maybe sector 2, scrap is so precious that I'd consider passing up a scrap recovery arm in a store in favor of, say, upgrading your shield system.
Answer: Although bwarner has answered this question, there are some points where my experience (unlocking all ships, all achievements, completing the game numerous times on Hard/with AE) has made me consider the real answer a bit different.
The real answer is (IMVHO): it depends.
As already pointed out, since you buy SRA for 50 and can later resell it for 25, with the scrap reward @ 10% it only takes 250 scrap collected to make it viable. Collecting that much scrap is usually very easy, especially on Easy and Normal it can be done without much trouble in a single Sector 7 run (if it's done efficiently). I agree that AF event rewards ain't big enough to justify having SRA on board.
There are, however, other concerns.

on Easy and Medium you don't need that much scrap and you don't need scrap that much; I've been able to finish Easy/Medium runs with >1000 scrap left - after you learn how to play, you can safely approach Rebel Flagship with only 3 shields, engines within L4-L6 range, without any "advanced" stuff, with only L2 support systems and Cloak + teleporter and/or missiles. I usually skip drone system entirely, unless I get a free Repair Drone by the way; summing up, the actual reward for having SRA is very low in terms of gameplay - but...
since SRA increases your overall scrap, it increases your overall score; there ain't any other upgrade in the entire game like it! (You can even have two or three SRAs if you have a bit of luck) On the other hand -
while it does take an augment slot, there ain't that many useful augments out there. Most of them are overpriced and provide only minor convenience to the player. The only thing useful enough for me is the Pre-Igniter, at times when I have Glaive or any other heavy-duty guns. Period.
on Hard, the actual rewards from having SRA are quite low (due to reduced scrap rewards), and the price is quite high (you're really have to penny-pinch on Hard, 50 scrap is enough to buy you a gun or a crew member when you're short on it); I usually skip it in any sector after the 2nd for this reason. However,
if you already have 2 augs (one starting, one bought) before buying SRA and you decide to buy it early, as a 3rd aug, you're losing chance to collect augs in events, with the obvious result of not being able to use them nor sell them (as you can't place augs 'in cargo').

So, to sum up: it depends. If you're aiming for a high score and feel confident with the game, have a decent enough array of weaponry, 3-4 Zoltans on board and got good luck before you got to the shop, you should get SRA - or even multiple SRAs if you're lucky enough, since they're stackable. If you're a casual player, you can take one if you have 0-1 aug already. Since I stopped playing below Hard and the risk factor increases too much with improper gear there, I skip it entirely after sector 2 - it's much more important to spend that scrap on things increasing survivability than income, since it's no longer about "how much scrap I'll be able to collect?" but rather about "how to not get reduced from 30HP to 0 in one combat" (early encounters with ships with Vulcan and Breach Missiles targeting my engines come to mind...); on the other hand, since you'll be selling some of the initial augments for scrap and free aug space, you can take 1 SRA if you get it in Sec 1/2.


Check statement for a loop only once

Question: Let's say I have following simple code:
useText = True

for i in range(20):
    if useText:
        print("The square is "+ str(i**2))
    else:
        print(i**2)

I use the variable useText to control which way to print the squares. It doesn't change while running the loop, so it seems inefficient to me to check it every time the loop runs. Is there any way to check useText only once, before the loop, and then always print out according to that result?
This question occurs to me quite often. In this simple case of course it doesn't matter but I could imagine this leading to slower performance in more complex cases.
Comment: why not use two loops?
Comment: So how does useText change if it does change? is this example like a simple UI where useText is a toggle and the for loop is in a main run loop somewhere? I'm just trying to put this in a context.
Answer: The only difference that useText accomplishes here is the formatting string. So move that out of the loop.
fs = '{}'
if useText:
    fs = "The square is {}"

for i in range(20):
    print(fs.format(i**2))

(This assumes that useText doesn't change during the loop! In a multithreaded program that might not be true.)
Answer: The general structure of your program is to loop through a sequence and print the result in some manner.
In code, this becomes
for i in range(20):
    print_square(i)

Before the loop runs, set print_square appropriately depending on the useText variable.
if useText:
    print_square = lambda x: print("The square is" + str(x**2))
else:
    print_square = lambda x: print(x**2)

for i in range(20):
    print_square(i)

This has the advantage of not repeating the loop structure or the check for useText and could easily be extended to support other methods of printing the results inside the loop.
Comment: Thanks. That seems the most elegant solution to me, because it avoids re-writing the whole loop again (if you were to make a for-loop inside the if-statement).
Answer: If you are not going to change the value of useText inside the loop, you can move it outside of for:
if useText:
    for i in range(20):
        print("The square is "+ str(i**2))
else:
    for i in range(20):
        print(i**2)

Answer: We can move if outside of for since you mentioned useText is not changing.
Answer: If you write something like this, you're checking the condition, running code, moving to the next iteration, and repeating, checking the condition each time, because you're running the entire body of the for loop, including the if statement, on each iteration:
for i in a_list:
    if condition:
        code()

If you write something like this, with the if statement inside the for loop, you're checking the condition and running the entire for loop only if the condition is true:
if condition:
    for i in a_list:
        code()

I think you want the second one, because that one only checks the condition once, at the start. It does that because the if statement isn't inside the loop. Remember that everything inside the loop is run on each iteration.

Check statement for a loop only once


ng-click and child selectors

Question: I have an owl carousel that doesn't fire events on the cloned items.
So, as solution people propose to move the event from direct target to its parent one:
from:
$('#multiple-carousel .item').click(function () {
        alert("click");
});

to:
$('#multiple-carousel').on('click', '.item', function () {
    alert("click");
});

Could I similarly change from my code:

...

to something like:

...

Comment: are you using `ng-repeat` for the slider items by any chance?
Comment: no, I use server side foreach
Comment: Can you include part of code you use to generate items (server-side foreach)? You return HTML?
Answer: The second parameter in jquery's .on is the filter which descendants will trigger the event, however, events in AngularJS are usually handled via directives ( ng-click in this case ) which do not support the same functionality as jQuery does.
You can add click event with angular.element, however if you want to use directive ( which is the right thing to do ), you have to do something like this:
$scope.myClick = function(event) {
    if (event.target.className === 'item') {
    // do smth
    }
}

See this answer to see the difference between event.currentTarget and event.target .

ng-click and child selectors


Python print function does not return the updated variable

Question: I am learning Python and something related to print confused me. Not sure if someone asked the same question already:
>>> x = 1
>>> x, y = x + 2, print(x)
1

I understand that output 1 is the side effect of Python's print function. But why doesn't it print 3? I was expecting 3 because x is updated in the second line? I was thinking it is equivalent to (apparently, wrong):
>>> x = 1
>>> x = x + 2
>>> x
3
>>> y = print(x)
3

I would like to understand the logic behind this print function. Why doesn't it print the updated x value?
I am new to the programming world, so any insight is highly appreciated!
Answer: Everything on the right-hand side is evaluated first. You can use the python byte-code dissasembler to see what is happening:
>>> import dis
>>> dis.dis('x, y = x + 2, print(x)')
  1           0 LOAD_NAME                0 (x)
              2 LOAD_CONST               0 (2)
              4 BINARY_ADD
              6 LOAD_NAME                1 (print)
              8 LOAD_NAME                0 (x)
             10 CALL_FUNCTION            1
             12 ROT_TWO
             14 STORE_NAME               0 (x)
             16 STORE_NAME               2 (y)
             18 LOAD_CONST               1 (None)
             20 RETURN_VALUE
>>>

Note, x + 2 and print(x) are evaluated first. The BINARY_ADD and CALL_FUNCTION occur before the two STORE_NAMEs.
Note, you can think of this as the equivalent of building a tuple first,
temp = (x + 2, print(x))

and then simply:
x, y = temp

However, note, according to the dissasembler, no actual intermediate tuple is created. The call stack is used to store the intermediate values. This is a compiler optimization. However, the optimization does not work for tuples greater than length 3, so using 4, you'll see an intermediate tuple is create:
>>> dis.dis('foo, bar, baz, bang  = bang, baz, bar, foo')
  1           0 LOAD_NAME                0 (bang)
              2 LOAD_NAME                1 (baz)
              4 LOAD_NAME                2 (bar)
              6 LOAD_NAME                3 (foo)
              8 BUILD_TUPLE              4
             10 UNPACK_SEQUENCE          4
             12 STORE_NAME               3 (foo)
             14 STORE_NAME               2 (bar)
             16 STORE_NAME               1 (baz)
             18 STORE_NAME               0 (bang)
             20 LOAD_CONST               0 (None)
             22 RETURN_VALUE
>>>

Note the BUILD_TUPLE and UNPACK_SEQUENCE, which is the general way that unpacking works in Python. It's just the compiler optimizes the common cases of two-or-three with the ROT_TWO and ROT_THREE op codes.
Note, since the right-hand side is evaluate first, this allows for the Python swap idiom to work!
x, y = y, x

If this were equivalent to:
x = y
y = x

You would lose the value for x instead of swapping!
Comment: wow, your explanation has the depth. I never heard of this byte-code dissasembler but it is a very helpful tool to understand Python's underlying activities. Much appreciated
Answer: >>> x = 1
>>> x, y = x + 2, print(x)
1

print(x)
outputs the value stored in x assigned by you
for printing 3 you need to
print(y)
as y stores the value of x+2
Answer: Because python processes line by line (meaning after the whole line, process it), so x haven't updated yet, so that's why it's not working as expected, but if you do ; (semicolon) it will work, because semicolon ; is basically a separator of lines too, so basically everything after ; is taken as a new line, demo:
>>> x=1
>>> x, y = x + 2,0; print(x)
3
>>>

Issue is that y is gonna be 0:
>>> y
0
>>>

Because i do so, you have to have a value,
But if you care, delete it:
>>> x=1
>>> x, y = x + 2,0; print(x)
3
>>> del y
>>> y
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    y
NameError: name 'y' is not defined
>>>

Answer: The value on the left hand side of an assignment doesn't get updated until everything on the right hand side is done processing.That's why X is not yet 3 when you try to print it on the right hand side.


How to merge many files together?

Question: I have around 58,000 txt files that have the prefix ppdb- in a directory. I want to merge all of them into one file. Wgen I try to merge them using cat ppdb-* >> out.txt it gives me an error saying "-bash: /usr/bin/cat: Argument list too long".
Is there a way to merge all the files together efficiently?
Comment: Have a look at [Cannot merge files using cat ; Argument list too long](https://unix.stackexchange.com/questions/167137/cannot-merge-files-using-cat)
Comment: This answer is covered by this similar question with the same bash error: https://askubuntu.com/a/949552/167115
Comment: _Is there a way to merge all the files together efficiently?_ Your question is not a duplicate of the link a give. Maybe there is a way of doing the concatenation more efficiently (the two answers use `cat`).
Answer: Read man find xargs and do something like: (UNTESTED, remove echo when your tests succeed)
find . -maxdepth 1 -name 'ppdb-*' -print0 |\
  xargs -0 -r echo cat >out.txt

How to merge many files together?


How to determine the installed webpack version

Question: Especially during the transition from webpack v1 to v2, it would be important to programmatically determine what webpack version is installed, but I cannot seem to find the appropriate API.
Answer: Version Installed:
Using webpack CLI: (--version, -v  Show version number [boolean])
webpack --version

or:
webpack -v

Using npm list command:
npm list webpack

Results in name@version-range:
<projectName>@<projectVersion> /path/to/project
└── webpack@<version-range>

Using yarn list command:
yarn list webpack

How to do it programmatically?
Webpack 2 introduced Configuration Types.

Instead of exporting a configuration object, you may return a function
  which accepts an environment as argument. When running webpack, you
  may specify build environment keys via --env, such as --env.production
  or --env.platform=web.

We will use a build environment key called --env.version.
webpack --env.version $(webpack --version)

or:
webpack --env.version $(webpack -v)

For this to work we will need to do two things:
Change our webpack.config.js file and use DefinePlugin.

The DefinePlugin allows you to create global constants which can be
  configured at compile time.

-module.exports = {
+module.exports = function(env) {
+  return {
    plugins: [
      new webpack.DefinePlugin({
+        WEBPACK_VERSION: JSON.stringify(env.version) //<version-range>
      })
    ]
+  };
};

Now we can access the global constant like so:
console.log(WEBPACK_VERSION);

Latest version available:
Using npm view command will return the latest version available on the registry:

npm view [<@scope>/]<name>[@<version>] [<field>[.<subfield>]...]

For webpack use:
npm view webpack version

Comment: So webpack has no API that returns it's version and I have to use a shell command?
Comment: this works fine via the cli.... but how would one do this programmatically? (aka: inside a script file)
Comment: I have included a way to programmatically extract webpack's version and use it as a global constant inside any file.
Comment: well, I had to type `npx webpack --version`
Comment: @doberkofler has the (now correct) answer, and it's even marked as the right answer! https://stackoverflow.com/a/52143627/3221576

You can't rely on `webpack -v` because that assumes your current shell's `webpack` is the same as what's running in your program.
Answer: Just another way not mentioned yet:
If you installed it locally to a project then open up the node_modules folder and check your webpack module.
< /node_modules/webpack/package.json
Open the package.json file and look under version
Answer: For those who are using yarn
yarn list webpack will do the trick
$ yarn list webpack
yarn list v0.27.5
└─ firstname.lastname@example.com
Done in 1.24s.

Answer: webpack 4 now offers a version property that can be used!
Comment: What this means is that wherever you have the `webpack` variable provided (like in your setup/config file) you can just call `webpack.version` and you'll get back a version string of the form `"x.y.z"`.
Answer: If using Angular CLI v7+, the webpack version is printed in the output of ng version:
-> ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 7.0.6
Node: 11.0.0
OS: darwin x64
Angular: 7.1.0
... animations, cdk, common, compiler, compiler-cli, core, forms
... http, language-service, material, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.10.6
@angular-devkit/build-angular     0.10.6
@angular-devkit/build-optimizer   0.10.6
@angular-devkit/build-webpack     0.10.6
@angular-devkit/core              7.0.6
@angular-devkit/schematics        7.0.6
@angular/cli                      7.0.6
@ngtools/webpack                  7.0.6
@schematics/angular               7.0.6
@schematics/update                0.10.6
rxjs                              6.3.3
typescript                        3.1.6
webpack                           4.19.1

Comment: In angular 10, webpack is not listed with `ng version`. If you're using custom webpack config with `@angular-builders/custom-webpack`, try `npm list webpack`, it showed me the used version of webpack.
Answer: In CLI
$ webpack --version

webpack-cli 4.1.0

webpack 5.3.2

In Code (node runtime)
process.env.npm_package_devDependencies_webpack // ^5.3.2

or
process.env.npm_package_dependencies_webpack // ^5.3.2

In Plugin
compiler.webpack.version // 5.3.2

Answer: Put webpack -v into your package.json:
{
  "name": "js",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack -v",
    "dev": "webpack --watch"
  }
}

Then enter in the console:
npm run build

Expected output should look like:
> npm run build

> firstname.lastname@example.com build /home/user/repositories/myproject/js
> webpack -v

4.42.0

Answer: npm webpack --version
works for me and it throws something like:
PS C:\Users\alfon\OneDrive\Escritorio\sandbox\fimusicv4\with-redux-app> npm webpack --version
npm WARN config global --global, --local are deprecated. Use --location=global instead.
8.5.5
Comment: FYI This ignores the webpack parameter and prints your npm version.
Comment: `npm run webpack --version`


When is buckshot preferable to slugs with shotguns in Battlefield 3?

Question: In what situations is it better to use buckshot than slugs with shotguns in Battlefield 3?
In close quarters battles, 6/11 pellets need to hit for a 1 hit kill… and that falls off quickly, to the point where at even moderate distances it takes 3 or 4 shells to kill an opponent.
Slugs, however, are guaranteed one hit kill in close quarters, and still deal an appreciable amount of damage at range.
Moreover, even in close quarters, I feel like I get more killing hits with slugs than with shot.
So: when does it make sense to use buckshot?
Answer: First off, a small rundown on buckshot pellets per shotgun vs slug rounds per shotgun as seen on wikia (Buckshot / Slugs):
Buckshot Pellets  /  Shotgun  /  Damage based on Distance
----------------------------------------------------------
 11 pellets          SPAS-12       18.0 - 6.0 / pellet
 9 pellets           SAIGA12K      18.0 - 6.0 / pellet
 9 pellets           DAO-12        18.0 - 6.0 / pellet
 10 pellets          M1014         18.0 - 6.0 / pellet
 12 pellets          870MCS        18.0 - 6.0 / pellet
 7 pellets           USAS-12       18.0 - 6.0 / pellet
 8 pellets           MK3A1         18.0 - 6.0 / pellet
 12 pellets          M26 MASS      18.0 - 6.0 / pellet

// Headshot Bonus : 2.40x

 Slug Rounds      /  Shotgun  /  Damage based on Distance
----------------------------------------------------------
  1 round            SPAS-12       100 - 40 (pump-action)
  1 round            SAIGA12K      75 - 37.5 (semi-automatic/auto)
  1 round            DAO-12        75 - 37.5 (semi-automatic/auto)
  1 round            M1014         75 - 37.5 (semi-automatic/auto)
  1 round            870MCS        100 - 40 (pump-action)
  1 round            USAS-12       75 - 37.5 (semi-automatic/auto)
  1 round            MK3A1         75 - 37.5 (semi-automatic/auto)
  1 round            M26 MASS      100 - 40 (pump-action)

// Headshot Bonus : Insta-kill?

That being said, in my opinion, in close quarters when your reticle is mainly on the target when you're using buckshot (especially on the area above the waist), its usually a instant-kill for me, and I'm not even aiming the weapon.
But if I chose to aim, or have my reticle generally focused on the enemy torso at close range, I would be able to also instantly kill someone at close range.
From your question, however, it is also debatable on your definition of "close range", which is usually 25metres and below in-game (for me).
I would also -- if given the limited choices of a buckshot and slug shotgun only in the entire game -- choose the:
Slug for a long range engagement such as a long-reaching room or a wide area, because you can at least aim and be guaranteed to kill something in here.
Buckshot for tight corners and small rooms within 25m because its a confirmed kill usually at such low ranges.
Hope that answers your question.
Comment: This. Hip-firing with slugs is significantly less effective than with buckshot. And hip-firing is necessary when surprised.


In c++ how do I read from file x,y coordinates of a rectangle?

Question: The data is in the form:

0,0    2,0    2,4    0,4 (there are tabs in between each pair)
5,5    7,5    7,9    0,9

where they are the first two lines of the text file, each representing a triangle.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int x1, x2, x3, x4, y1, y2, y3, y4;
    string coordinates;
    ifstream myfile;
    myfile.open("coordinates.txt");
    string line = myfile.getline();
    myfile>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4;
    cout << line;
}

I tried several ways to get the data into the relevant integers but with no luck. Can someone please help?
Comment: Something like. myfile>>x1>>x2>>x3>>x4;
Comment: What ways have you tried?  I only see you reading one line into a string.  If you show us your code actually trying, we can correct you on where you're actually having trouble.
Comment: Ah forgot to mention. I already added fstream and used the >> operator, however I don't know how to deal with the tabs and the commas and the return in between lines.
Comment: You're not asking a specific question.  Show us your attempts at using the operator << in your code snippet so we can see how you're doing it, and tell us how you attempted to debug it and what values you see.  Also, have you tried to follow a basic file I/O tutorial?
Answer: C++'s stream input mechanisms are, quite frankly, incredibly annoying to use.  If you're able to use a very recent version of C++, you might consider using regular expressions.  Fetch the line from the stream using getline and then using a regex expression on each line.. something like ^(?:(\d+),(\d+)\t){3}(\d+),(\d+)$.
Failing that, sscanf can also be used, and while it's not as C++ as you might want, it's much easier to understand than the corresponding stream operations IMO.
Comment: I believe that a regular expression and the code to use the regular expression would be overkill in the OP's case.
Comment: Regex struck me as overkill too, until I started working with Perl.  Now that I know regex, I'm constantly frustrated by its clunkiness in C++ and Java.  In perl the parsing code would be `($x1, $y1, $x2, $y2,  $x3, $y3, $x4, $y4) = $line =~ /^(?:(\d+),(\d+)\t){3}(\d+),(\d+)$/`
Answer: You could use operator >>:
myfile >> x1;

Note that you should include <fstream>.
Answer:
I already added <fstream> and used the >> operator, however I don't know how to deal with the tabs and the commas and the return in between lines.

The problem is not with the tabs or the newline (because they are considered whitespace by the stream which are extracted and discarded as part of a sentry operation to formatted I/O). The problem is with the commas, because they are not extracted. Doing, for example in >> x >> y will leave y uninitialized if there is a non-numeric character in the stream after the previous extraction to x.
You need a way to extract the comma after the first extraction of the integer. The most simple technique would be to use a dummy char variable to extract into:
int x1, y1;
char dummy;

if (myfile >> x1 >> dummy >> y1)
{
    // ...
}

Comment: Thanks I think this will do
Answer: Just a short program I had to write maybe you can use some of it:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main()
{
  ifstream inFile;
  float num1, num2, num3, num4, num5, sum, avg;

  cout << "Reading data from the Z:CLM1.dat file:\n\n";

  // Open the file.
  inFile.open("Z:\\CLM1.dat");

  // Read the five numbers from the file.
  inFile >> num1;
  inFile >> num2;
  inFile >> num3;
  inFile >> num4;
  inFile >> num5;

  // Close the file.
  inFile.close();

  // Calculate the sum of the numbers.
  sum = num1 + num2 + num3 + num4 + num5;
  avg = sum / 5;

  // Display the five numbers.
  cout << setprecision(3) << fixed << "Number 1 is " << num1 << "\n"
       << "Number 2 is " << num2 << "\n"
       << "Number 3 is " << num3 << "\n"
       << "Number 4 is " << num4 << "\n"
       << "Number 5 is " << num5 << "\n"
       << endl;

  // Display the sum of the numbers.
  cout << "The sum of the 5 numbers is: " << sum << endl;
  cout << "The average of these 5 numbers is: " << avg << endl;
  getchar();
  return 0;
}

Answer: You say you want to read data into individual integers, but you're reading the entire first line into a string and then displaying it.
If you want to read integers from a text file, which are separated by whitespace characters (spaces, tabs, or newlines), then the operator >> is all you need:
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
    // Read in the entire file to a string
    string fileContents;

    ifstream fin;
    fin.open("myfile.txt");
    if(fin.is_open())
    {
        getline(fin,fileContents,'\x1A');
        fin.close();
    }

    // Use the string to init an istringstream from which you can read
    istringstream iss(fileContents);

    // Read from the file contents
    int x,y,z;

    iss >> x;
    iss >> y;
    iss >> z;

    // Display the integers
    cout << x << ' ' << y << ' ' << z << '\n';

    return 0;
}

Note that I use a stringstream to read the entire contents of the file into memory first, and then read from that stream.  That is an optional step, which I do simply because I prefer the habit of opening and closing the file as quickly as possible before doing any additional work on the contents.  This might not be ideal if the file is extremely large.  You can use the same operator >> with the ifstream object inside the braces between where you open and close the file, and leave out the stringstream entirely, as demonstrated below:
int main()
{
    int x,y,z;

    // Open the file
    ifstream fin;
    fin.open("myfile.txt");
    if(fin.is_open())
    {
        // Read from the file contents
        fin >> x;
        fin >> y;
        fin >> z;

        fin.close();
    }

    // Display the integers
    cout << x << ' ' << y << ' ' << z << '\n';

    return 0;
}

Also note that there is no validation to ensure that you're not trying to read past the end of the file, that what you're reading are in fact integers, that you're only reading a certain number of them, etc.  For that, I would advise that you first read up on some simple input validation tutorials.


Notice: Array to string conversion

Question: if (isset($_POST['emaildistribution']))
{
    echo implode(',', $_POST['emaildistribution']);
}

$first_name = $_POST['Fname'];
$last_name = $_POST['Lname'];
$city = $_POST['city'];
$department = $_POST['department'];
$day = $_POST['day'];
$tick = $_POST['tick'];
$staffName = $_POST['staffName'];
$permissions = $_POST['permGranted'];
$PersonalComp = $_POST['PersonalComp'];
$deskPhone = $_POST['deskPhone'];
$mobPhone = $_POST['mobPhone'];
$field = $_POST['field'];
$submit = $_POST['confirm'];

$headers = 'Content-Type: text/html; charset=ISO-8859-1' . "\r\n";
$message = '';
$message .= '
';
$message .= "
First Name: 	" . strip_tags($_POST['Fname']) . "
";
$message .= "
Last Name: 	" .  strip_tags($_POST['Lname']) . "
";
    $message .= "
Location: 	" . strip_tags($_POST['city']) . "
";
    $message .= "
Department: 	" . strip_tags($_POST['department']) . "
";
    $message .= "
Date: 	" . $_POST['day'] . "
";
    $message .= "
Permissions as Other User: 	" . strip_tags($_POST['tick']) . "
";
    $message .= "
Other User: 	" . $_POST['staffName'] . "
";
    $message .= "
Permissions: 	" . strip_tags($_POST['permGranted']) . "
";
    $message .= "
Hardware: 	" . $_POST['PersonalComp'] . "
";
    $message .= "
New Equipment: 	" . strip_tags($_POST['deskPhone']) . "
";
    $message .= "
Desk Phone: 	" . $_POST['mobPhone'] . "
";
    $message .= "
Mobile Phone : 	" . strip_tags($_POST['field']) . "
";
    $message .= "
Email Distribtuion Groups : 	" . ($_POST['emaildistribution']) . "
";
    $message .= "
";
$message .= "";

if(isset($submit)) {

    // EDIT THE LINES BELOW AS REQUIRED WHENEVER EMAIL CHANGES
    mail($email_to,$email_subject,$message,$headers);
    echo "
Thank you! Your message has been sent.
";
}

?>

If i use serialize the code executes perfectly, but i dont want all the extra information it sends because it doesnt look tidy. Is there a simple way that i can convert emaildistribution which is an array into a string so it is passed by POST? I am new to PHP.
Answer: implode is your friend here. Instead of just echoing the value, use it:
if (isset($_POST['emaildistribution']))
{
    $_POST['emaildistribution']) = implode(',', $_POST['emaildistribution']);
}

Notice: Array to string conversion


Disable weekdays and holidays in jQuery datepicker issue in WooCommerce

Question: I have a custom woocommerce filter function which use the jQuery-ui datepicker. I would like to customize the options with the code below but it just make the datepicker disappear, even when I try to enqueue the script. This code is customized from this answer:
Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?
Below is the code for the delivery-date.js that I enqueue in my php also below.

  /*====================================================
      Delivery date Code
      Only two weeks booking time allowed.
      Diallowed days Sunday = 0, Saturday = 6
    Dates Disallowed by m/d - 1,1 | 1,26 | 2,16 | 3,8 | 4,14 | 4, 16 | 4,17 | 5,1 | 6,3 | 6,9 | 10,9 | 12,25 | 12, 26
  =====================================================*/
  jQuery(function($){
      $('#datepicker').datepicker({
      maxDate: '+2W',
      beforeShowDay: noWeekendsOrHolidays
    });

    var natDays = [ [1,1], [1,26], [2,16], [3,8], [4,14], [4, 16], [4,17], [5,1], [6,3], [6,9], [10,9], [12,25], [12, 26] ];

    function nationalDays(date) {
      for (i = 0; i < natDays.length; i++){
        if (date.getMonth() == natDays[i][0] - 1
          && date.getDate() == natDays[i][1]) {
          return [false, natDays[i][2] + '_day'];
        }
      }
      return [true, ''];
    }

    function noWeekendsOrHolidays(date) {
      var noWeekend = $.datepicker.noWeekends(date);
      if (noWeekend[0]) {
        return nationalDays(date);
      } else {
        return noWeekend;
      }
    }
  });

I am trying to merge that in this answer code:
Time loop for WooCommerce checkout select option from date picker input field
But it doesn't work.
Answer: Your array is quiet different than the one used in:
Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?
To make it work with your custom array in Wordpress / Woocommerce you will need to make some changes. In the below code, I have merged the 2 Javascript functions in one:
jQuery(function($){
    var natDays = [ [1,1], [1,26], [2,16], [3,8], [4,14], [4, 16],
        [4,17], [5,1], [6,3], [6,9], [10,9], [12,25], [12, 26] ]; // Holidays

    // No weekends and no holidays
    function noWeekendAndHolidays(date) {
        // No Holidays
        var nationalDays = [];
        for (i = 0; i < natDays.length; i++)
            if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == natDays[i][1]) {
                nationalDays = [false, ''];
                return false; // stop the loop
            }
        if( ! nationalDays[0] )
            nationalDays = [true, ''];

        // No weekends (or no holidays)
        var noWeekend = $.datepicker.noWeekends(date);
        if (noWeekend[0])
            return nationalDays;
        else
            return noWeekend;
    }

    // Jquery-ui datepicker
    $("#datepicker").datepicker({
        beforeShowDay: noWeekendAndHolidays,
        maxDate: '+2W',
    });
});

This just works now with your custom array and the jQuery-ui datepicker is displayed correctly.

To merge it in my other answer code you will have it this way:
 // Enable available jQuery datepicker script in Wordpress
add_action( 'wp_enqueue_scripts', 'enabling_date_picker' );
function enabling_date_picker() {

    // Only on front-end and checkout page
    if( is_admin() || ! is_checkout() ) return;

    // Load available datepicker jQuery-ui plugin script
    wp_enqueue_script( 'jquery-ui-datepicker' );
}

// Add and display custom checkout fields + jQuery script
add_filter( 'woocommerce_checkout_fields' , 'brown_remove_billing_postcode_checkout' );
function brown_remove_billing_postcode_checkout( $fields ) {
    // Your Settings
    $start_hour = 11; // start time (in hours)
    $end_hour = 16; // end time (in hours)
    $offset = 1; // One hour before slot time (can be a float number like 1.5
    // date_default_timezone_set ('Africa/Kampala'); // The timezone
    date_default_timezone_set('Australia/Brisbane');

    // Initializing variables
    $hour = 3600; // 1 hour in seconds
    $day = $hour * 24; // 1 day in seconds
    $now = strtotime("now"); // Now time
    $real_now = $now + ($offset * $hour); // Now time + offset
    $today_date = date("Y-m-d"); // today date
    $tomorrow_date = date("Y-m-d", strtotime("+1 day")); // tomorow date
    $today_time = strtotime($today_date); // Today time at 00:00 in seconds
    $tomorrow_time = strtotime($tomorrow_date); // Tomorrow time at 00:00 in seconds
    $start_time = $today_time + ( $start_hour * $hour ); // Start datetime in seconds
    $end_time = $today_time + ( $end_hour * $hour ); // End datetime in seconds
    $today_slots = $default_slots = $option_days = array();

    // Add Delivery day field (with jquery-ui datepicker enabled)
    $fields['billing']['billing_delivery_day'] = array(
        'label'         => __('Delivery Day', 'woocommerce'),
        'placeholder'   => _x('Date for your delivery', 'placeholder', 'woocommerce'),
        'required'      => true,
        'id'            => 'datepicker', // Enable jQuery datepicker for this field
        'class'         => array('form-row-first'),
        'clear'         => false,
        'autocomplete'  => false,
        'type'          => 'text'
    );
   // Add Delivery hour slots
    $fields['billing']['billing_delivery_hour'] = array(
        'label'        => __('Delivery Time', 'woocommerce'),
        'required'     => true,
        'class'        => array('form-row-last'),
        'clear'        => false,
        'autocomplete' => false,
        'type'         => 'select',
        'options'      => array( '' => __('Select time for your delivery') ),
    );

    // Making the delivery hour slots <option> arrays for Javascript
    for($i = $start_time; $i <= $end_time; $i += 1800 ){ // 1800 seconds is half an hour
        $key     = date('H:i', $i);
        $value   = date('h:ia', $i);

        // Today available hour slots array
        if($real_now < $i)
            $today_slots[$key] = $value;

        // Default hour slots array
        $default_slots[$key] = $value;
    }

    // The correct start date and time (today or tomorow) for Javascript
    $date = $real_now < $end_time ? $today_date : $tomorrow_date;
    $dtime = $real_now < $end_time ? date("Y-m-d\TH:i:s", $today_time) : date("Y-m-d\TH:i:s", $tomorrow_time);

    ?>

    <?
    return $fields;
}

Code goes in function.php file of your active child theme (or active theme).
Tested and works.


AttributeError: 'BaseQuery' object has no attribute 'whoosh_search'

Question: I am using Flask (python), creating whooshe search, I have followed all steps from this link,  also tried from other links too, but every time at end I came to this error:
results = BlogPost.query.whoosh_search('cool')
AttributeError:'BaseQuery' object has no attribute 'whoosh_search'

Here is my model code:
class BlogPost(db.Model):
    __tablename__ = 'blogpost'
    __searchable__ = ['title', 'content']
    __analyzer__ = StemmingAnalyzer()
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Unicode) # Indexed fields are either String,
    content = db.Column(db.Text) # Unicode, or Text
    created = db.Column(db.DateTime, default=datetime.utcnow)

I am having error on this:
@app.route('/search')
def search():
    results = BlogPost.query.whoosh_search('cool')
return results

Answer: I have also seen this error.Then I found the error is in models.py.You should add the whooshalchemy.whoosh_index(app, BlogPost) at the end of the model code.
Answer: I ran in to a similar issue if anyone falls down thsi rabbit hole.
In my case, i found that in my models.py i was importing from sqlalchemy and using the declarative_base as a base for each model.
ie:
from sqlalchemy import Column, Integer, DateTime, Text, Boolean
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Book(Base):

while in my routes.py I was importing flask-sqlalchemy where you use db.Model as the base:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db.init_app(app)

class Book(db.Model):

There have been some similar answers on some other posts as well but it looks like when using flask-whooshalchemy or its similar variants (whooshalchemy3, whooshalchemyplus) using db.Model as the base is the correct way to init the model to have the appropriate attributes.
hopefully that helps someone down the road.


What causes the noise coming from this radiator valve?

Question: There's a hot water wall-hung radiator in my kitchen that produces a constant ticking noise when water is flowing. The noise is coming from the valve area, removing the thermostat does not influence the noise. Pushing the little rod on the valve with the thermostat removed only makes the noise louder.
I recorded the noise, amplified it and placed it here.
Is this noise indicative of a defective valve?
Comment: Hello, and welcome to Stack Exchange. With the thermostat in place, does the noise change when you change the thermostat setting? (A picture of the thermostat and valve would help; edit it into your question.)
Comment: I added a picture of the thermostat & valve in my original post. Turning the thermostat knob does not influence the noise, but I have a strong suspicion the thermostat itself may be broken (the pin-pusher floats freely. I don't think that's supposed to be the case)
Answer: That's an odd noise, it sounds like something's loose inside the pipe and rattling around. Might be a piece of rust or gunk. If you remove the thermostat head and press the rod down completely, the rattling should cease because the valve is closed and there's no water flow. If the noise continues, that indicates the valve isn't closing properly.


How to make hotot autologin and minimize on start?

Question: Every restart I have to click 'sign in with twitter' to log in my twitter account. I read somewhere that it is possible to log in automatically but can't find out how.
Answer: You can do this but with the lastest version of Hotot (0.9.8 or 0.9.9, I don't remember). But this one has not been pushed in Canonical PPAs yet. They still have got the 0.9.7 version which has got the problem that you describe. Perhaps this latest version will be on Quantal PPAs, who knows ?
However, you can still use the development version or building Hotot from sources. See the Hotot's downloads page for further details.
Comment: Yeah, you're right. I had hotot 0.9.7. I added development repo and installed 0.9.8.7. It's doing what I was looking for and works properly. Thanks.


Noise insulation of apartment right above noisy pub

Question: How good can you isolate an apartment that's right above a very noisy rocker's pub? Could we install a thicker floor, or would the noise go through the walls anyway?
What material would work best here? I am willing to replace the existing floor (which needs replacement anyway).
Comment: Move or go and join them. Even if you insulated the floor the noise would propagate through the walls and through the atmosphere...
Comment: Hello, and welcome to Home Improvement. Blocking sound across a large existing floor is going to be tough, especially from the top. Could you install materials from the space below?
Comment: @DanielGriscom: unhappily no.
Comment: @SolarMike: I'm not living there. Just shopping for a new home. It's a pity because the  apartment in question would be a gem, if it were not for the noise. I assume the good price is due to this issue.
Answer: While it's possible to improve the situation by doing things to the floor and walls, it's never going to be great. From your comment it looks like you're looking at this apartment as a potential place to live, not as a place you live in already, so my advice is to go someplace else unless you find the current noise level acceptable, and just want advice to improve it.
Comment: Yes, I'm not living there.
Answer: You fix bad acoustics like that, the same way you fix bad access to public transit -- by not moving there.  You're ahead of this game, and not the poor sop who missed the noise level because they saw it during the day, or missed the poor transit access because he let the realtor drive him around.
There's simply no way to do it using commonly available materials.  Sound is measured in decibels, which is an exponential scale.  Every increase of 10db represents 10 TIMES the sound energy.  20db = 100x, 30db = 1000x.  That's why your stereo (which gets pretty loud) has a thin little 16ga cord (the smallest legal size), but the big Marshall amp racks at a concert venue have power cables the size of your thumb.
If they have 120db going down in that bar, to get to a sleepable 50db, you're talking about 10,000,000x, and you'd have to dampen 99.99999% of the energy. Not with big springs and vacuum chambers could you do this.


Unix Pipeling "AWK" - The summation whilst matching

Question: Below I have some raw data. My goal is to match 'column one' values and have the total number of bytes in a single line of output for each ip address.
For example output:
18.104.22.168 6654
126.96.36.199 328
18.104.22.168 84700

Raw Data:
188.8.131.52 328
188.8.131.52 328
18.104.22.168 329
126.96.36.199 367
184.108.40.206 5302
126.96.36.199 328
188.8.131.52 84700

Can anyone advise me on how to do this.
Answer: Using an associative array:
awk '{a[$1]+=$2}END{for (i in a){print i,a[i]}}'  infile

Alternative to preserve order:
 awk '!($1 in a){b[++cont]=$1}{a[$1]+=$2}END{for (c=1;c<=cont;c++){print b[c],a[b[c]]}}' infile

Another way where arrays are not needed:
awk 'lip != $1 && lip != ""{print lip,sum;sum=0}
     {sum+=$NF;lip=$1}
     END{print lip,sum}' infile

Result
188.8.131.52 6654
18.104.22.168 328
220.127.116.11 84700

Comment: better replace `$NF` by `$2` to keep it simple and understandable no?


Get package name for a function in go language

Question: I need to get the package name for a function in Go.
For example if Println is the input then the output must be fmt. If StatusText is the input then the output must be net/http.
What is the right method to achieve this?
Comment: You might be able to get better answers if you add information why you need this functionality. Have you checked http://godoc.org/golang.org/x/tools/cmd/godoc?
Comment: I need to get the documentation only for a function. But the thing is i know only the function name but not the package to which it belongs.
Comment: Give a try to `godoc -q Println | sed -n -e '/Functions/,$p' | head -n 2`
Answer: From your comment it seems that you're looking for a command line tool like godoc but which instead of requiring something like godoc net/http StatusText you want to be able to just use doc StatusText and have it find http.StatusText for you (and possibly other foo.StatusText functions as well).
Rob Pike's doc tool can do exactly that, it looks through all packages in your GOPATH. (Although it's output isn't just the package name as your original question asks for).
You can get and install doc with: go install robpike.io/cmd/doc
Or are you actually looking for a way of getting this information from within Go code rather than the command line?
Comment: Note that the doc tool will be part of the upcoming Go 1.5 release, so with a standard release you will be able to write "go doc Println".


help with steam

Question: when I run steam my computer it keep saying that I don't have the latest Nvidia drivers.
I use Additional drives and it said that I have the latest one. I UN-install and re-install the divers but it still say the same thing. please help. Sorry I'm new to Linux and Ubuntu.
Comment: Welcome to askubuntu , Don't worry we are here to help you.
Comment: If you are new to linux, I guess you should not be testing Steam :) Sorry to say so, but Steam is not production ready so don't expect miracles.
Answer: Have you tried installing the newest experimental drivers? Perhaps named nvidia-experimental-NNN? I haven't tried this, but I read that it can fix the graphics driver issues with steam.
Answer: First go to dash and search Additional  Drivers,  open it . It will check your system and suggest to install missing drivers. You will get list of different Nvidia drivers , But you have to select only recommanded version.

help with steam