texts: Type checking to perform a variation of the strategy pattern

texts:
So, consider the following code:

public class OneConcreteTypeOfOutputFormat
{
    private Dictionary<Type, IEntityWriter> writers;
    public Dispatcher()
    {
        this.writers = new Dictionary<string, IEntityWriter();
        CreateWriters(writers);
    }

    private void CreateWriters(Dictionary<string, IEntityWriter> writers)
    {
        string nspace = typeof(OneConcreteWriter).Namespace;
        Assembly assembly = Assembly.GetExecutingAssembly();
        foreach (var writer in assembly.GetAllFromNamespace<IEntityWriter>(nspace))
            writers.Add(writer.EntityType.FullName, writer);
    }

    private bool HasWriterForAllPropTypes(IEnumerable<Entity> data)
    {
        return data.All(ent => writers.ContainsKey(ent.GetType().FullName));
    }

    public void WriteEntities(IEnumerable<Entity> entities)
    {
         Require.That(() => HasWriterForAllPropTypes(outputData));
         foreach(Entity entity in entities)
             writers[entity.GetType().FullName].Write(entity);
    }
}

Here, I am using the actual type of the Entity (which is a baseclass) to write it. I've heard that it's considered inelegant to use type-checking to perform operations, but I really don't want each Entity to write itself. This is a very easy and comfortable way to match something like this up. Do you find this clashing with the tenets of object-oriented programming? Sadly, each writer need to cast to it's specific type in the Write method.

UPDATE

Note that the code above is completely updated - changes include:

Added writer initialization code. It is delegated to a unit-tested extension method.
Changed the name of the class to reflect that it is only one of different types of output formats - so it would require more than just creating one writer for each Entity.
Added a little bit of the validation code.


texts: AT&T assembly - Basic loop & write - follow-up

texts:
This is a follow-up question to this one: AT&T Assembly - Basic loop & write

The code loops to display "Hello, World!" ten times.

I implemented the syscall instead of int $0x80, used a decrementing loop to avoid a useless instruction and commented the code. Is there any way to make it better?

When debugging with GDB, it appears exit $0 is part of l. However, I would like it to be part of _start (since l represents the loop only). Is that possible?

.section .data
  hello: .string "Hello, world!\n"
  len = . -hello

  .equ EXIT, 60
  .equ WRITE, 1
  .equ STDOUT, 1

.section .bss
  # Write a str of length len on the standard output.
  .macro write str, len
    movq $WRITE, %rax
    movq $STDOUT, %rdi
    movq \str, %rsi
    movq \len, %rdx
    syscall
  .endm

  # Exit with the specified error code
  .macro exit code
    movq $EXIT, %rax
    movq \code, %rdi
    syscall
  .endm

.section .text
  .globl _start

  # Loops to display "Hello, World!" ten times.
  _start:
     movq $10, %r8               # Counter
    l:
      write $hello, $len
      dec %r8
      jnz l

    exit $0


texts: Groovy method optimization to build > tokens

texts:
I have a string array:

def invoices = [LEDES98BI V2,
LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL,
1|20150301|INV-Error_Test1|22,
2|20150301|INV-Error_Test1|24,
3|20150301|INV-Error_Test2|26,
4|20150301|INV-Error_Test2|28,]

I tried to convert it to HasMap<String, List<List>> with key as invoice numbers(INV-Error_Test1, INV-Error_Test2) and the values are each invoice line:

[
INV-Error_Test2:[[3,20150301, INV-Error_Test2,26], [4,20150301, INV-Error_Test2,28]],
INV-Error_Test1:[[1,20150301, INV-Error_Test1,22], [2,20150301, INV-Error_Test1,24]]
]

And this is the method which converts the string array into <String, List<List>> tokens:

def extractInvoiceLineItems(def invoices) {
    Map invLineItems = new HashMap<String, ArrayList<ArrayList>>();
    def lineItems = []
    for(int i = 2; i<invoices.length; i++){
       def tokens =  invoices[i].split('\\|') as List
       if(tokens.size != 1) {
        lineItems.add(tokens)
      }
    }

    for (int i=0; i< lineItems.size; i++) {
        invNumber = lineItems.get(i).get(1)
         if(invLineItems.keySet().find{it == invNumber}) {
            templineItem = invLineItems.get(invNumber)
            templineItem.add(lineItems.get(i))
            invLineItems.put(invNumber,templineItem)
         }
        else {
            def list = []
            list.add(lineItems.get(i))
            invLineItems.put(invNumber,list)
        }
    }
invLineItems
}

I am using lots of traditional for loops and am wondering whether it can be simplified further (using closures or any other way).


texts: Book repository for storing books that are accessed by ISBN

texts:
I want to implement a book repository using a map where books can be added, removed and updated. Books in this repository should be accessed by their ISBN which is an object property. The books should not be edited from the outside of the repository, because if a book’s ISBN is changed from the outside, the ISBN used as key is out of sync with the ISBN of the book.

Another option is to use a list, so I don’t have a key that can be out of sync.

I came up with the following solution.

Book:

public class Book {
    private String isbn;
    private String title;
    private String author;
    private double price;

    public Book(String isbn, String title, String author, double price) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
        this.price = price;
    }

    public Book(Book book) {
        this.isbn = book.isbn;
        this.title = book.title;
        this.author = book.author;
        this.price = book.price;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Book other = (Book) obj;
        if (isbn == null) {
            if (other.isbn != null)
                return false;
        } else if (!isbn.equals(other.isbn))
            return false;
        return true;
    }

    // getters, setters and hashcode omitted
}

BookRepository:

public class BookRepository {
    private Map<String, Book> books;

    public BookRepository() {
        books = new HashMap<String, Book>();
    }

    public List<Book> getAllBooks() {
        return new ArrayList<Book>(books.values());
    }

    public Book getBook(String isbn) {
        if (books.containsKey(isbn))
            return new Book(books.get(isbn));

        return null;
    }

    public boolean addBook(Book book) {
        Book copy = new Book(book);

        if (!books.containsKey(copy.getIsbn()))
            return books.put(copy.getIsbn(), copy) == null;

        return false;
    }

    public boolean deleteBook(String isbn) {
        return books.remove(isbn) != null;
    }

    public boolean updateBook(Book book) {
        Book copy = new Book(book);

        if (books.containsKey(copy.getIsbn()))
            return books.put(copy.getIsbn(), copy) != null;

        return false;
    }
}


texts: Small graph API to track vertices and edges added to graph

texts:
I'm working on my Scala chops and implemented a small graph API to track vertices and edges added to graph. I have basic GraphLike Trait, and have an Undirected Graph class ( UnDiGraph) and a Directed graph class (DiGraph ) that extend the GraphLike trait.

Here is some of the listing:

trait GraphLike[T] {
    val vertices: Map[T, VertexLike[T]]
    def addEdge( a:T, b:T ): GraphLike[T]
    def addVertex( t:T ): GraphLike[T]
    def addVertex( vert: VertexLike[T] ): GraphLike[T]
    def adjacency( t:T ): Option[ List[T] ]  =
    {
      if ( vertices contains t )
        Some( vertices(t).adjList )
      else
        None
    }
    def vertNum: Integer = vertices size
    def edgeNum: Integer =
    {
      def summer( sum: Integer, ms: Map[T, VertexLike[T] ] ): Integer =
      {
        if ( ms.isEmpty )
          sum
        else
          summer( sum + ms.head._2.adjList.size, ms.tail )
      }
      summer( 0, vertices )
    }
    def getVertex( t: T ): VertexLike[T] =
    {
      vertices( t )
    }
    def edgeExists( a:T, b:T ): Boolean =
    {
      try
      {
          if( vertices( a ).adjList contains b )
            true
          else
            false
      }catch {
        case ex: NoSuchElementException => false
      }
    }
}

Here's what the DiGraph looks like:

class DiGraph[T](val vertices: Map[ T, VertexLike[ T ] ] = Map.empty ) extends GraphLike[T] {
    def makeVertex( t:T ): VertexLike[T] = new Vertex( t )

    def addEdge( a:T, b:T ): GraphLike[T] =
    {
      //Make sure vertices exist
      if( edgeExists(a, b) )
        this
      else {
        try {
          vertices(b)
          vertices(a)
        } catch {
          case ex: NoSuchElementException => println("Vertices not Found"); this
        }
        addVertex( vertices( a ) + b )
      }
    }
    def addVertex( t:T ): DiGraph[T] =
    {
      if( vertices contains t ) this
      else
      new DiGraph[T]( vertices + ( t -> makeVertex(t) ) )
    }
    def addVertex( vert: VertexLike[T] ): DiGraph[T] =
    {
      new DiGraph[T]( vertices + ( vert.apply -> vert ) )
    }
}

Vertices are stored in a Map going from type T to VertexLike[T]. VertexLike basically holds an adjacency list for the specific Vertex.

Here's what VertexLike looks like:

trait VertexLike[T]
{
  def addEdgeTo( dest: T ): VertexLike[T]
  def adjList: List[T]
  def +( dest: T) = addEdgeTo(dest)
  def apply: T
}

class Vertex[T](t: T, adj: List[T] = List() ) extends VertexLike[T]
{
    def apply() = t
    def adjList = adj
    def addEdgeTo( dest: T ) =
      if( adjList contains dest )
        this
      else
        new Vertex[T]( t, dest :: adjList )
}

(Yes, I realize the apply method in the class is useless and it only works on objects.  I realized that a little later).

Anyways, I have a sample graph where I have about 80,000 vertices. Adding the vertices to the Graph is taking just way too long. I tried to do things functionally and in an immutable way. Whenever you add a vertex or an edge to a graph, you get a new graph (I tried to make sure the constructors of the graph types weren't doing much). This is the client code that I use to create my graph from my data.

def GraphInstantiater: GraphLike[Int] =
{
  println( "Total number of Vertices: " + synMap.keys.size )
  def vertexAdder( ls: Iterable[Int], graph:GraphLike[Int] ): GraphLike[Int] =
    if( ls.isEmpty) graph else vertexAdder( ls.tail, graph.addVertex( ls.head ) )

  val gr = vertexAdder( synMap.keys, new DiGraph[Int]( Map() ) )
  println( "Vertices added. Total: %d".format( gr.vertices.size ) )
  gr
}

I know constructing new graphs will take cycles but is it really all that great given that I'm not doing much in the constructors. Would repeatedly creating the Map of vertices keep causing problems (it's one of the parameters of the graph class). Any ideas on what the bottlenecks are in this method would be much appreciated.


texts: Finding median from unsorted array with duplicate elements without sorting it

texts:
I am implementing a method to find the median of an unsorted array using a counting sort. I would happily go for a median of medians or selection algorithm for better performance but they are essentially sorting the array (or partially sorting the array if I choose to go for minHeap) which I am not in favor of.

int getRange(int *array, int count)
{
    int i, max = 0;
    for(i = 0; i < count; i++)
    {
        if(array[i] > max)
        {
            max = array[i];
        }
    }
    return max;
}

int countFreq(int *array, int size_array, int item)
{
    int i, freq = 0;
    for(i = 0; i < size_array; i++)
    {
        if(array[i] == item)
            freq++;
    }
    return freq;
}

int median(int *array, int count)
{
    int range = getRange(array, count);
    int i, mid_index, addition = 0;

    //Yes I can use calloc here
    int *freq = (int *)malloc(sizeof(int) * range + 1);
    memset(freq, 0, sizeof(int)* range + 1);

    for(i = 0; i < range + 1; i++)
    {
        //Count i in array and insert at freq[i]
        freq[i] = countFreq(array, count, i);
    }

    if(count % 2 == 0)
    {
        mid_index = count / 2;
    }
    else
    {
        mid_index = count / 2 + 1;
    }

    for(i = 0; i < range + 1; i++)
    {
        addition += freq[i];
        if(addition >= mid_index)
        {
            break;
        }
    }
    free(freq);
    return i;
}

I followed this answer to implement using C! Certainly, I want to improve upon this or maybe a better algorithm that doesn't sort the array! For me, this algorithm has some problems

What if there are just 2 elements say {10, 10000}, this will still go on for creating an array of size 10000 which essentially has zeros in it except at the last index!
I find it hard to digest the performance of this algorithm with larger arrays to sort, for now, this is O(n3) as far as I can think of.


texts: Counting the longest increasing subsequence in an array of integers

texts:
This is my finished function to find the length of the longest consecutive subsequence of an input array of integers. It's for an assessment so things like the numerical method used and the format of input are out of my hands (int LIS(int* seq, int* temp_seq, int seq_size)).  For the temp_seq parameter, the caller will pass an empty array of size seq_size.

As far as I can tell works perfectly, however, our lecturer has barely commented on how to write code that doesn't just do the job but is 'good code' (aka a large amount of the marking criteria).

Is there anything that you can see which could be improved here?

In the past I've lost marks for code that did the job, but didn't follow 'good practice' standards. I've tried to make this code as nice as I can, with a clear logical structure, good commenting etc but I always thought my code was good then because when I tested it it worked. I'm just looking for advice on the form of the code.

int LIS(int* seq, int* temp_seq, int seq_size)
{
    /*sets up variables and initial values*/
    int i, proceed_flag;
    int j = 0, count = -1;

    /*this'll be used to ensure each input element is only used once - 1 means not used*/
    int use_flag [seq_size];
    for (i = 0; i<seq_size; i++)
    {
        use_flag[i] = 1;
    }

    /*while the temp array isn't full*/
    while(j<seq_size)
    {
        i = 0;
        proceed_flag = 0;

        /*drops the next unused number into the temp array*/
        while(proceed_flag == 0)
        {
            if (use_flag[i] == 1)
            {
                temp_seq[j+1] = seq[i];
                use_flag[i] = 0;
//              printf("temp_seq = %d\n", temp_seq[j+1]);
                j++;

                proceed_flag = 1;
            }

            i++;
        }

        /*then drops all smaller numbers from the input array into the temp array*/
        for(i = 0; i<seq_size; i++)
        {
            if(temp_seq[j] > seq[i] && use_flag[i])
            {
                temp_seq[j+1] = seq[i];
                use_flag[i] = 0;
//              printf("temp_seq = %d\n", temp_seq[j+1]);
                j++;
            }
        }

        /*this counts the number of repeats - the initialisation value of -1 is just to calibrate the system
        it takes an extra loop around and gives a wrong result otherwise*/
        count++;
    }

return(count);
}


texts: How do I add memoization to this problem?

texts:
Problem
Starting in the top left corner of a 22 grid, there are 6 routes (without backtracking) to the bottom right corner.

How many routes are there through a 2020 grid?

Solution
Here is my solution

    def step(i,j):
    if(i==20 or j==20):
        return 1
    return step(i+1,j)+step(i,j+1)
print step(0,0)

But this takes too long to run, how can this be optimized?


texts:
I have a table structured like this:

UnitScanDB = {
    ["profiles"] = {
        ["Goblin"] = {
            ["Bars"] = {
                {
                    {
                        ["track"] = "Cloak of Shadows#Anti-Magic Shell#Hand of Freedom#Spell Reflection",
                    }, -- [1]
                    {
                        ["track"] = "..."
                    }, -- [2]
                    {
                        ["track"] = "..."
                    }, -- [3]
                }
            }
        }
    }
}

And I would like to convert it to this format:

UnitScanDB = {
    ["profiles"] = {
        ["Goblin"] = {
            ["Bars"] = {
                {
                    {
                        {
                            ["track"] = "Cloak of Shadows",
                        }, -- [1]
                        {
                            ["track"] = "Anti-Magic Shell",
                        }, -- [2]
                        {
                            ["track"] = "Hand of Freedom",
                        }, -- [3]
                        {
                            ["track"] = "Spell Reflection",
                        }, -- [4]
                    }, -- [1]
                    {
                     --stuff
                    }, -- [2]
                    {
                     --stuff
                    }, -- [3]
                }
            }
        }
    }
}

To do this automatically, I created this function:

function UnitScan:updater()
    local list = db:GetProfiles()
    for p, name in ipairs(list) do
        local icon = db.profiles[list[p]]["Bars"]
        for x, value in ipairs(icon) do
            for y, value in ipairs(icon[x]) do
                if (icon[x][y].track) then
                    for aura in string.gmatch(icon[x][y].track,"[^#]+") do
                        t = {}
                        t.track = aura
                        tinsert(icon[x][y], t)
                    end
                end
            end
        end
    end
end

Where

db = UnitScanDB
db:GetProfiles() = function returns all the keys in "profiles"

Is there a more elegant way to do this without using all those cycles, perhaps using the metatables?


texts:
I have a simple game where you try to go as high up with rockets as possible. I currently store 2 statistics about your playthrough:

Current altitude
Highest altitude

These statistics are stored in a Dictionary<string,float> where the string key is the name of the statistic. I have two tasks related to stats, setting the statistic, which I do as follows:

public class UpdateAltitude : View
{
    public float AltitudeFactor
    {
        get
        {
            return altitudeFactor;
        }
        set
        {
            altitudeFactor = value;
        }
    }

    [Inject]
    public IDictionary<string, float> Stats
    {
        get;
        set;
    }

    [SerializeField]
    private float altitudeFactor;

    // Update is called once per frame
    private void Update()
    {
        var altitude = AltitudeFactor * transform.position.y;
        Stats["altitude"] = altitude;
        Stats["maxaltitude"] = Mathf.Max(Stats["maxaltitude"], altitude);
    }
}

View here is a baseclass from the StrangeIOC framework that allows me to inject into Unity behaviours. The SerializeField attribute allows me to display the private field in the editor for an artist to use (Unity cannot display properties, so this is a common workaround).

The Stats dictionary is created and injected into my View instances from a StrangeIOC context like so:

var stats = new Dictionary<string, float>()
    {
        {"altitude", 0f},
        {"maxaltitude", 0f}
    };

injectionBinder.Bind<IDictionary<string, float>>().ToValue(stats).ToSingleton();

The other task, displaying the statistic, is done thusly:

public class StatLabel : View
{

    public string FormatString
    {
        get
        {
            return formatString;
        }
        set
        {
            formatString = value;
        }
    }

    [Inject]
    public IDictionary<string, float> Stats
    {
        get;
        set;
    }

    [SerializeField]
    private string statName;

    public string StatName
    {
        get
        {
            return statName;
        }
        set
        {
            statName = value;
        }
    }

    [SerializeField]
    private string formatString;

    private UILabel label;

    protected override void Start()
    {
        base.Start();
        label = GetComponent<UILabel>();
    }

    private void Update()
    {
        label.text = string.Format(FormatString, Stats[StatName]);
    }
}

Here a UILabel is essentially a TextBlock control from the NGUI framework.

My issue is that in order for an artist to work with this within the Unity Framework, they need knowledge of the exact string keys in this dictionary, an enum would be a preferable solution, because they appear in the Unity editor as a combo box of possible options, however this would couple my StatLabel class to this game's enum, and each new game would require a custom version.

I intend soon to add additional statistics, such as speed, max speed, coins, etc, so would like to know if I can improve the existing code to make it more artist-friendly, and reusable, while keeping it extensible.


texts:
I want to extract the file content into chunks with perl. I have prepared some code snippets which read a file content into chunks.
I want to know what is the best way in Perl?

Example-File-Content:

1111
2222
3333
4444
5555
6666
7777
8888
9999
1212
1313
1414
1515

Example1:

#!/usr/bin/env perl
use strict;
use warnings;

open my $fh, '<', 'DUMP' or die $!;

until(grep !defined, my @chunk = map scalar <$fh>, 1 .. 4) {
    print @chunk, "\n";
}

Output:

1111
2222
3333
4444

5555
6666
7777
8888

9999
1212
1313
1414

Example2:

#!/usr/bin/perl -w
use strict;

open my $fh, '<', 'DUMP' or die $!;

my $i;
my @details;

while(<$fh>) {
    push @details, $_;
    next if ++$i % 4;
    print @details, "\n";
    @details = ();
}

Output:

1111
2222
3333
4444

5555
6666
7777
8888

9999
1212
1313
1414

Example3:

#!/usr/bin/perl -w
use strict;

open my $fh, '<', 'details.txt' or die $!;

sub read_lines {
    my ($fh, $amnt) = @_;
    return unless defined(my $line = <$fh>);
    return (
        $line,
        $amnt > 1 ? read_lines($fh, $amnt - 1) : ()
    );
}

while(my @details = read_lines($fh, 4)) {
    print @details, "\n";
}

Output:

1111
2222
3333
4444

5555
6666
7777
8888

9999
1212
1313
1414

1515


texts:
I'm working on a project where I needed to extract the indices for the headers of a CSV file to initialise objects. I thought that I should work on my documentation process and learn how to document code, seeing as I'm always reading about people not documenting code.

/**
 * Returns the indices of searched for headers, e.g. if the file looks like this: (Name Email
 * Phone Age) and we call the method: findIndices("Name", "Age", "Email", "Phone"), if returns
 * [0,3,1,2].
 *
 * Ignores case of letters, i.e. Age and AGE "is" the same.
 *
 * @param input Strings to search for in the header
 * @return int[] with indices for the columns
*/
public int[] findIndices(String... input) throws IllegalArgumentException {
    int[] indices = new int[input.length];
    if (input.length > this.headers.length) {
      throw new IllegalArgumentException("Amount of searched for headers, " + input.length
      + ", exceeded the actual amount of headers: " + this.headers.length);
    }
    boolean found = true; // Assume we will find all headers.
    int k = 0; // Counter variable.
    for (int i = 0; i < this.headers.length; i++) {
        for (String s : input) {
            if (s.equalsIgnoreCase(this.headers[i])) {
                indices[k++] = i;
                found = true;
            } else {
                found = false;
            }
        }
    }
    if (!found) {
        throw new IllegalArgumentException(
            "One or more of input arguments could not be found in the headers.");
    }
    return indices;
}

My own thoughts:

The found flag seems poorly handled.
This is part of a custom CSV-reader class, with a headers private field. This seems a bit weird to me, this could maybe be static and take a String[] as input as well.
Should this actually throw an exception or should it just return a "bad" index? But I'm using an array to represent it. Null, maybe?

Edit: Found a bug which did not show up in my unit tests due to a misunderstanding of the JUnit api, found -> !found.


texts: Group by two lists in one map using lambda

texts:
I've got two collections: collection of rules, and collection of keys that can handle specific rules. Key have method boolean canHandle(Rule) to check whether specific key can handle specific rule or not.

I need to gather these two collections into single map Map<Key, List<Rule>> bycanHandle` predicate method. I've done this so far:

Map<Key, List<Rule>> keyToRulesMapping = rules.parallelStream()
        .collect(Collectors.groupingBy(rule -> keys.stream()
                .filter(key -> key.canHandle(rule))
                .findFirst().get()));

The thing I don't like in this approach is number of traverse in key list to get the right key. In best case I have only one key that handles all rules (\$O(N)\$ where N is the number or rules). In worst case I have each key associated with it's own unique rule (becomes \$O(N^2)\$). I'm asking is there a better way to match these two lists or my approach is good enough?


texts:
I'm currently trying to learn the idiomatic way to write F# code. The code simulates a basic calculator with only binary plus, minus and unary minus.

I'd like to know if there is a better way to group union cases than the way I did it. Should the Add/Sub/MinusExpression be cases in the Expression union? Is there a better way to write the eval function?

type Expression =
    | BinExpression of BinExpression
    | UnExpression  of UnExpression
    | IntExpression of int

and BinExpression =
    | AddExpression of Expression * Expression
    | SubExpression of Expression * Expression

and UnExpression =
    | MinusExpression of Expression

let rec eval tree =
    let evalBin tree =
        match tree with
        | AddExpression(e1, e2) -> (eval e1) + (eval e2)
        | SubExpression(e1, e2) -> (eval e1) - (eval e2)

    let evalUn tree =
        match tree with
        | MinusExpression(v) -> -(eval v)

    match tree with
    | BinExpression(e) -> evalBin e
    | UnExpression(e)  -> evalUn e
    | IntExpression(v) -> v


texts:
I need to fix and maintain the master volume in PulseAudio (so that I don't blow up my speakers). E.g. call gfaaudio -v 25 to fix volume at 25%. Is there a cleaner way to get this done?

gfaaudio:

#!/bin/bash

usage="Usage: `basename $0` [-v VOL] "

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    echo $usage
    echo "  -h, --help  for help"
    exit
fi

#############################
Dcard="alsa_card.usb-Musical_Fidelity_Musical_Fidelity_V90-DAC_24_96-00-M2496"
Dout="iec958-stereo"
Dname="alsa_output.usb-Musical_Fidelity_Musical_Fidelity_V90-DAC_24_96-00-M2496.iec958-stereo"
VOL=30
#############################

while [ $# -gt 0 ]; do
    case "$1" in
        -v)
            shift
            [ $# -gt 0 ] && VOL="$1";;
        -*)
            echo "Option not supported: $1" >&2
            echo $usage >&2
            exit 1;;
        *) break;;
    esac
    shift
done

pacmd set-card-profile "$Dcard" output:"$Dout"
pacmd set-default-sink "$Dname"
[ -z "$(pidof -x gfaaudioloop)" ] || killall gfaaudioloop
gfaaudioloop "$Dname" "$VOL" &

exit

gfaaudioloop:

#!/bin/bash

if [[ $# != 2 ]]; then
    echo "number of arguments not 2" >&2
    exit 1
fi

while : ; do
    exits=$(pactl set-sink-volume "$1" "$2"%)
    exitc=$?
    [ ! -z "$exits" -o $exitc -ne 0 ] && break
    sleep 0.5
done

exit


texts: Horrible case statement for displaying a title

texts:
This thing kills me:

     def report_subtitle
        case params[:kind]
          when 'position'   then  h("for Position: #{@current_company.positions.find_by_id(params[:id])}")
          when 'grade'      then  h("for Grade: #{params[:id]}")
          when 'location'   then  h("for Location: #{Location.find_by_id(params[:id])}")
          when 'department' then  h("for Deparment: #{@current_company.departments.find_by_id(params[:id])}")
          when 'supervisor' then  h("Employees who report to #{@employees.first.supervisor.full_name}")
          when 'eeoc'       then  h("for EEOC Code: #{params[:id]}")
    end


texts:
I have black and white SDL_Surface and I'm trying to change colors, such as from black to white and from white to red.  I did it, but it is taking too long to work.

SDL_Surface* tempSurface = SDL_DisplayFormat(textSurface);
for(int i=0;i<256;i++){
    SDL_SetColorKey(textSurface,SDL_SRCCOLORKEY,SDL_MapRGB(textSurface->format,i,i,i));
    SDL_FillRect(tempSurface, 0, SDL_MapRGB(tempSurface->format, 255, i, i));
    SDL_BlitSurface(textSurface,0,tempSurface,0);
    SDL_FreeSurface(textSurface);
    textSurface=tempSurface;
    tempSurface = SDL_DisplayFormat(textSurface);
}
SDL_FreeSurface(tempSurface);

It works for a few seconds, but it needs to run very fast.  It is C code, but it is not important. SDL is compatible with both languages.

How can I optimize this algorithm? Or can you suggest another way?


texts: Project Euler #1 Sum of all the multiples of 3 or 5 below 1000

texts:
If we list all the natural numbers below 10 that are multiples of 3 or
  5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below 1000.

My solution:

#include <stdio.h>
#define TOP_LIMIT 1000

float sum_of_series(float start_from,float position,float difference)
{
    return (position/2) *
        ( 2 * start_from + (position-1) * difference);
}

int find_last_multiple(int limit,int multiplier){
    return limit - (limit % multiplier);
}

void main(void){

    float last_position_3 =
        find_last_multiple( TOP_LIMIT-1 , 3 ) / 3;

    float last_position_5 =
        find_last_multiple( TOP_LIMIT-1 , 5 ) / 5;

    float last_position_15 =
        find_last_multiple( TOP_LIMIT-1 , 15 ) / 15;

    float sum_of_series_3 = sum_of_series(3,last_position_3,3);
    float sum_of_series_5 = sum_of_series(5,last_position_5,5);
    float sum_of_series_15 = sum_of_series(15,last_position_15,15);

    float answer = sum_of_series_3 + sum_of_series_5 - sum_of_series_15;

    printf("sum of all the multiples of 3 or 5 below 1000\n");
    printf("answer = %f\n",answer);

}

I compiled it with: gcc (GCC) 4.8.3 20140624 (Red Hat 4.8.3-1)


texts: C program to count number of lines in a file

texts:
Very simple code, works fine. I'm mainly interested in the method I used to count lines. I thought about using fgetc, but I'm not even sure if it'd read the newline character, and I think it's slower too.

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1000

int main(void){
    FILE *in_file;
    char line[MAX_SIZE];

    in_file = fopen("test", "r");
    if(in_file == NULL){
        fprintf(stderr, "Unable to open file");
        exit(EXIT_FAILURE);
    }

    int counter = 0; /*Number of lines*/

    while(fgets(line, sizeof(line), in_file) != NULL){
        counter++;
    }

    printf("Number of lines in the file is %i", counter);

    return 0;
}


texts:
I'm new to OO PHP and I'm trying to create a simple properly-designed user authentication system.

What am I doing right and what not?
Is this right according to the MVC model?

Connection.class.php

<?php
class Connection {
    private $host = 'host';
    private $name = 'name';
    private $user = 'user';
    private $pass = 'pass';
    public $con;

    function __construct() {
        try {
            $this->con = new PDO("mysql:host=$this->host;dbname=$this->name;charset=utf8", $this->user, $this->pass);
            $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $ex) {
            die('Failed trying to connect to the database');
        }
    }
}

User.class.php

<?php
class User {
    private $id;
    private $username;
    private $email;
    private $password;

    function __construct($id, $username, $email, $password) {
        $this->id = $id;
        $this->username = $username;
        $this->email = $email;
        $this->password = $password;
    }

    function getId() {
        return $this->id;
    }

    function getUsername() {
        return $this->username;
    }

    function getEmail() {
        return $this->email;
    }

    function getPassword() {
        return $this->password;
    }
}

UserService.class.php

<?php
class UserService {

    protected $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function login($email, $password) {
        $stmt = $this->db->con->prepare('SELECT * FROM user WHERE email = ?');
        $stmt->execute(array($email));

        if ($stmt->rowCount() > 0) {
            //Check password here

            //Return user object and set session on success
            //$user = $stmt->fetchObject('User');
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            return new User($user['id'], $user['username'], $user['email'], $user['password']);
        }

            return false;
    }

    public function logout() { }

    public function register() { }

    public function getUser($userId) {
        $stmt = $this->db->con->prepare('SELECT * FROM user WHERE id = ?');
        $stmt->execute(array($userId));

        if ($stmt->rowCount() > 0) {
            return $stmt->fetch(PDO::FETCH_ASSOC);
        }

        return false;
    }
}

Example usage

//Include class files

$userService = new UserService($db);

if ($user = $userService->login('test@test.nl', 'testPass')) {
    echo 'Logged in as: ' . $user->getEmail();
} else {
    echo 'Invalid login';
}


texts: User agent classification using switch (true)

texts:
I've seen usage of switch(true) multiple times and have used it myself today instead of multiple elseif`s. Here is the case I used it for:

var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') != -1;
var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') != -1;
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') != -1;
var browser = null;
switch (true) {
    case isChrome:
        {
            browser = "chrome";
            break;
        }
    case isSafari:
        {
            browser = "safari";
            break;
        }
    case isFirefox:
        {
            browser = "firefox";
            break;
        }
}

My view is that much more explicit than multiple else ifs. Do you think it's a good approach?


texts: Switching functionality on and off in a Scheduled Thread

texts:
To illustrate how to do leader election with Apache Zookeeper I've created an straightforward application and I would like to have to threading part of the application reviewed.
I've created a simple class (Speaker) which outputs an unique identifier to a file on a regular interval. I've implemented the Runnable interface and start it with a ScheduledExecutorService with a fixed delay like this:

scheduler.scheduleWithFixedDelay(speaker, 0, delay, TimeUnit.MILLISECONDS);

The Speaker class also implements a Listener interface so it can register itself to a Monitor (running in a separate thread, communicating to the Zookeeper server)  which can enable or disable the output to the file.

My review question (besides general code review):  Is this the best way to start and stop functionality in a scheduled thread?

Speaker & Speaker Server:

Complete project: https://github.com/cyberroadie/zookeeper-leader

Code explanation: http://cyberroadie.wordpress.com/2011/11/24/implementing-leader-election-with-zookeeper/

public class Speaker implements Runnable, NodeMonitor.NodeMonitorListener {

    private String message;
    private String processName;
    private long counter = 0;
    private volatile boolean canSpeak = false;

    public Speaker(String message) throws IOException, InterruptedException, KeeperException {
        this.message = message;
         this.processName = getUniqueIdentifier();
    }

    private static String getUniqueIdentifier() {
        String processName = ManagementFactory.getRuntimeMXBean().getName();
        String processId = processName.substring(0, processName.indexOf("@"));
        return "pid-" + processId + ".";
    }

    public void run() {
        try {
            if (canSpeak) {
                handleTask();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void handleTask() throws IOException {
        FileWriter fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(message + ": " + counter++ + " " + processName + "\n");
        out.close();
    }

    @Override
    public void startSpeaking() {
        this.canSpeak = true;
    }

    @Override
    public void stopSpeaking() {
        this.canSpeak = false;
    }

    @Override
    public String getProcessName() {
        return processName;
    }
}

Speaker Server:

public class SpeakerServer {

    final static Logger logger = LoggerFactory.getLogger(SpeakerServer.class);

    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private static NodeMonitor monitor;

    private static void printUsage() {
        System.out.println("program [message] [wait between messages in millisecond]");
    }

    public static void main(String[] args) {
        if (args.length < 2) {
            printUsage();
            System.exit(1);
        }

        long delay = Long.parseLong(args[1]);

        Speaker speaker = null;

        try {
            speaker = new Speaker(args[0]);
            monitor = new NodeMonitor();
            monitor.setListener(speaker);
            monitor.start();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
        scheduler.scheduleWithFixedDelay(speaker, 0, delay, TimeUnit.MILLISECONDS);
        logger.info("Speaker server started with fixed time delay of " + delay + " milliseconds.");
    }
}


texts:
It solves the problem listed here. How can I make this more efficient?

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static int getIndex(int x, int lastAns,Integer size) {
        return ((x ^ lastAns) % size);
    }

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int q = in.nextInt();

    LinkedList<Integer>[] sequenceList = new LinkedList[n];
    int lastAns = 0;
    while(q-- != 0) {
        int queryType = in.nextInt();
        int x = in.nextInt();
        int y = in.nextInt();
        int index = getIndex(x, lastAns, n);
        if(queryType == 1) {
            if(sequenceList[index] == null) sequenceList[index] = new LinkedList<Integer>();
            sequenceList[index].add(y);
        } else if(queryType == 2) {
            lastAns = sequenceList[index].get(y % sequenceList[index].size());
            System.out.println(lastAns);
        }
    }
  }
}


texts: Asynchronously wait for a task to complete and do some async action while waiting

texts:
I have a long-running task. My goal is to create a method that will allow me to:

Asynchronously wait for this task to complete
While waiting on a task, do some async action once in a while. This
'action' basically tells some remote service that task is not dead
and still executing.

I've written the following code to solve this problem. Please have a look and share your thoughts!

public delegate Task AsyncAction();

public static class TaskExtensions
{
    public static async Task<bool> TimeoutAfter(this Task task, TimeSpan timeout)
    {
        var timeoutCancellationTokenSource = new CancellationTokenSource();

        var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token)).ConfigureAwait(false);
        if (completedTask == task)
        {
            timeoutCancellationTokenSource.Cancel();
            await task.ConfigureAwait(false);
            return true;
        }
        else
        {
            return false;
        }
    }

    public static async Task AwaitWithTimeoutCallback(this Task task, TimeSpan timeout, AsyncAction onTimeout)
    {
        while (true)
        {
            var completed = await task.TimeoutAfter(timeout).ConfigureAwait(false);
            if (completed)
            {
                break;
            }

            await onTimeout().ConfigureAwait(false);
        }

        await task.ConfigureAwait(false);
    }
}

Usage:

var task = Task.Delay(TimeSpan.FromSeconds(15));

task.AwaitWithTimeoutCallback(TimeSpan.FromSeconds(5), () =>
{
    Console.WriteLine("Waiting...");
    return Task.FromResult(true);
})
.Wait();


texts: Compute arithmetic sum of a constant difference sequence

texts:
3.1

  Write a program that computes the arithmetic sum of a constant
  difference sequence:

D0 = A
Dn+1 = Cdn + B

  Run the following values and compare to the closed form solution:

Maximum index = 10,000, a = 1:0; c = 5; b = 2^-15

I am not sure I perfectly understand the problem above or how to confirm that I have the correct answer, but I wrote the following short program and I would appreciate any feedback.

(defun d-n-plus-1 (d-n c b) (+ (* d-n c) b))

(defun d-depth (depth d-n c b a)
  (if (equal depth 0) (d-n-plus-1 d-n c b)
    (d-depth (1- depth)
         (if (null d-n) a (d-n-plus-1 d-n c b))
         c b a)))

(format t "result: ~a ~%" (d-depth 10000 nil 5 (expt 2 -15) 1))

In addition, I wrote a version that just uses a loop.  I'm not crazy about "loop for x from 1 to depth" or that I used setq in this version.  Can you think of a better way?  Any other suggestions for this version are also welcome.

(defun d_n+1 (d_n c b) (+ (* d_n c) b))

(defun d-depth (depth d_n c b)
  (loop for x from 0 to depth do
    (setq d_n (d_n+1 d_n c b)))
  d_n)

(format t "result: ~a ~%" (d-depth 10000 1 5 (expt 2 -15)))


texts:
I've solved the Word Squares problem:

  Given a set of words (without duplicates), find all word squares you can build from them.

  A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).

  For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically.

 b a l l
 a r e a
 l e a d
 l a d y

but the following code, had a runtime so slow that I ended up in the bottom 10% of submissions speed wise. I was wondering if there's anything I'm doing in the code that's a performance killer / any way I could improve my algorithm to speed it up.

from collections import defaultdict

class Solution(object):
    def make_defaultdict(self):
        return defaultdict(self.make_defaultdict)

    def make_trie(self, words):
        trie = self.make_defaultdict()

        for word in words:
            cur = trie
            for l in word:
                cur = cur[l]
            cur['end'] = True

        return trie

    def search_trie(self, trie, search_str):
        matches = []
        sub_trie = trie

        for l in search_str:
            if l not in sub_trie:
                return []
            sub_trie = sub_trie[l]

        q = [(search_str + k, sub_trie[k]) for k in sub_trie.keys()]
        while q:
            fragment, sub_trie = q.pop(0)

            if 'end' in sub_trie:
                matches.append(fragment)
            else:
                q.extend([(fragment + k, sub_trie[k]) for k in sub_trie.keys()])

        return matches

    def make_square(self, pos, square, size, trie):
        if pos == size:
            return [square]

        for i in range(pos, size):
            search_str = ''.join([w[i] for w in square])
            candidates = self.search_trie(trie, search_str)

            if not candidates:
                return []

            result = []
            for candidate in candidates:
                result.extend(self.make_square(pos + 1, square + [candidate], size, trie))

            return result

    def wordSquares(self, words):
        all_squares = []
        trie = self.make_trie(words)

        for word in words:
            all_squares.extend(self.make_square(1, [word], len(word), trie) )

        return all_squares

Any thoughts on how to speed it up?


texts: Thread-safe singleton class using std::shared_ptr in C++(11)

texts:
What I am trying to accomplish is to create an efficient thread-safe singleton base class (as stated in the title).

So this is my singleton class, which is used via inheritance (see below).

#pragma once
#ifndef SINGLETON_HEADER_INCLUDED
#define SINGLETON_HEADER_INCLUDED
#include <memory>

template <class T>
class singleton
{
public:
        static T *get_instance(void)
        {
                if(instance.get() == 0 || instance == (NULL && 0) || !instance) {
                        instance = std::shared_ptr<T>(new T());
                }
                return instance;
        }

        static delete_instance(void)
        {
                delete instance;
                instance = (NULL && 0);
                return;
        }

protected:
        singleton(void);
        virtual ~singleton(void);

private:
        singleton(const singleton&);
        singleton& operator = (const singleton&);

        static volatile std::shared_ptr<T> instance;
};

template <class T> template *singleton<T>::instance = 0;

#endif

Here is the class in use:

#include "singleton.hpp"

class opengl_renderer : public singleton<opengl_renderer>
{
        friend class singleton<opengl_renderer>;
        etc...
};

So basically, I am looking for some tips and reviews on my class -> I feel as if it isn't working the way I imagine it should. But it is functional at its current state.


texts: Thread safe lock-free stack using win32 threading primitives

texts:
class CSList
{
public:
    CSList()
    {
        ::InitializeSListHead(&m_head);
    }

    USHORT Depth()
    {
        return ::QueryDepthSList(&m_head);
    }

    PSLIST_ENTRY Flush()
    {
        return ::InterlockedFlushSList(&m_head);
    }

    PSLIST_ENTRY First()
    {
        return ::RtlFirstEntrySList(&m_head);
    }

    PSLIST_ENTRY Push(PSLIST_ENTRY ListEntry)
    {
        return ::InterlockedPushEntrySList(&m_head, ListEntry);
    }

    PSLIST_ENTRY Pop()
    {
        return ::InterlockedPopEntrySList(&m_head);
    }

private:
    SLIST_HEADER m_head;
};

template <typename T>
class TSimpleStack
{
public:
    typedef struct DATA_ENTRY : SINGLE_LIST_ENTRY
    {
        T Data;
        DATA_ENTRY(const T& val) : Data(val)
        {
            SINGLE_LIST_ENTRY::Next = NULL;
        }
    } *LPDATA_ENTRY;

    ~TSimpleStack()
    {
        while (m_list.Depth() > 0)
        {
            LPDATA_ENTRY lpEntry = (LPDATA_ENTRY) m_list.Pop();
            if (lpEntry != NULL)
            {
                lpEntry->~DATA_ENTRY();
            }
            _aligned_free(lpEntry);
        }
    }

    USHORT Count()
    {
        return m_list.Depth();
    }

    LPDATA_ENTRY Push(const T& data)
    {
        LPVOID lpMemBuff = _aligned_malloc(sizeof(DATA_ENTRY), MEMORY_ALLOCATION_ALIGNMENT);
        LPDATA_ENTRY lpEntry = new (lpMemBuff) DATA_ENTRY(data);
        return (LPDATA_ENTRY)m_list.Push(lpEntry);
    }

    BOOL Pop(T& outVal)
    {
        BOOL bOut = FALSE;
        if (m_list.Depth() > 0)
        {
            LPDATA_ENTRY lpEntry = static_cast<LPDATA_ENTRY>(m_list.Pop());
            if (lpEntry != NULL)
            {
                outVal = lpEntry->Data;
                lpEntry->~DATA_ENTRY();
                _aligned_free(lpEntry);
                bOut = TRUE;
            }
        }
        return bOut;
    }

private:
    CSList m_list;
};


texts:
I have this code that generates a utilization report for a company I am interning for that uses a time-tracking app called Harvest.

var config = require('./config');
var request = require('request');
var moment = require('moment');
var pageNumber, pages;
var userArray = [];
var iteration = 0;
var pageNumber = 1;

let reqURL = 'https://api.harvestapp.com/v2/users?page=1&per_page=100';
let reqURL2 = 'https://api.harvestapp.com/v2/time_entries?from=' + new moment().day(-1).format('YYYY-MM-DD') + '&to=' + new moment().day(5).format('YYYY-MM-DD') + '&page=1&per_page=100';

var options = {
    url: reqURL,
    headers: {
      'Authorization': 'Bearer' + ' ' + config.token,
      'Harvest-Account-Id': config.accountID,
      'User-Agent': config.userAgent
    }
  };

  var options2 = {
    url: reqURL2,
    headers: {
      'Authorization': 'Bearer' + ' ' + config.token,
      'Harvest-Account-Id': config.accountID,
      'User-Agent': config.userAgent
    }
  }

  function callback1(error, response, body) {

    if (!error && response.statusCode == 200) {
      info = JSON.parse(body);
      pages = info.total_pages;

      for(x = 0; x < info.users.length; x++) {
        userArray[iteration] = new Object(),
        userArray[iteration].id = info.users[x].id,
        userArray[iteration].name = info.users[x].first_name + ' ' + info.users[x].last_name
        userArray[iteration].billableHours = 0;
        userArray[iteration].totalHours = 0;
        iteration++;
      };

      if(pageNumber < info.total_pages) {
        pageNumber++;
        options.url = 'https://api.harvestapp.com/v2/users?page=' + pageNumber + '&per_page=100';
        request(options, callback1);
      } else {
        pageNumber = 1;
      }

    };

  };

  request(options, callback1);

  function callback2(error, response, body) {
    if (!error && response.statusCode == 200) {

      info = JSON.parse(body);
      pages = info.total_pages;

      for(y = 0; y < info.time_entries.length; y++){

        for(x = 0; x < userArray.length; x++) {

          if(info.time_entries[y].user.id == userArray[x].id) {
            userArray[x].totalHours += info.time_entries[y].hours;

            if(info.time_entries[y].billable) {
              userArray[x].billableHours += info.time_entries[y].hours;
            }
            break;

          }

    }

  }
  if(pageNumber < info.total_pages) {
    pageNumber++;
    options2.url = 'https://api.harvestapp.com/v2/time_entries?from=' + new moment().day(-1).format('YYYY-MM-DD') + '&to=' + new moment().day(5).format('YYYY-MM-DD') + '&page=' + pageNumber + '&per_page=100';
    request(options2, callback2);
  } else {
    removeUsers(userArray, 'totalHours', 0);
  }

}

 }

 request(options2, callback2);

 function removeUsers(array, attribute, value) {
 var i = array.length;

while(i--) {
  array[i].utilization = Math.ceil(100*(array[i].billableHours/40));

  if(array[i] && array[i].hasOwnProperty(attribute) && (arguments.length > 2 && array[i][attribute] === value)){
    array.splice(i,1);
  }

}
console.log(array);
}

I'm sorry about the spacing down here, for some reason it wouldn't recognize it as code. If anyone has any optimization ideas those would be much appreciated.


texts: Script to push data from one database via api to another

texts:
I'm still a beginner so any pointers to make this code more professional/production ready are appreciated. The tokens and database connections have been anonymized.
The script is working, its goal is to copy prices from one database and push them via api into another database.
This data is monthly price data that usually arrives early in the month. So march prices arrive somewhere early march, but usually not on the first. They are then supposed to be pushed to the destination database via rest api.

The catch is that we never know when the prices arrive in the source database, so the idea is to run this script daily via task scheduler and only push the data to the destination database once when they arrive, but we have to make sure that the data is not pushed twice and duplicates are created.
I achieved this by only pushing when the data is in the source database, but not yet in the destination databse via IF check.

I feel like this code is not very pythonic and lacking some possible error catchings for it to be ran automatically on a daily basis. Any pointers are appreciated.

import json
import pandas as pd
import pyodbc
import sqlalchemy
import datetime
import sys
import requests
import pdb
import pymysql

#RPA API Connector
target_url = "exampleurl"
target_token = "exampletoken"
target_headers = {"AUTH-TOKEN": target_token, "Content-Type": "application/json"}

#Store todays date in variable
now = datetime.datetime.now()

#connecting to source DB
def connect_mssqlserver():
    engine_stmt = ("mssql+pyodbc://@server/database?driver=SQL+Server")
    engine = sqlalchemy.create_engine(engine_stmt)
    engine.connect()
    return engine
#connect to destination DB
def connect_mysqlserver():
    engine_stmt = ('mysql+pymysql://user:password@server:host/database')
    engine = sqlalchemy.create_engine(engine_stmt)
    engine.connect()
    return engine
def create_df(query, engine):
    #save table to df
    df = pd.read_sql(query, engine)
    return df

#store source data in df
source_df = create_df("SELECT * FROM PriceMonthly", connect_mssqlserver())
#Some dataframe modification to fit destination format
source_df = source_df[source_df.Year == now.year]
source_df['Tax'].fillna(0, inplace=True)
source_df['Year'] = source_df['ImportFileName'].str[0:4].astype(int)
source_df['Month'] = source_df['ImportFileName'].str[4:6].astype(int)

#store destination table in dataframe
dest_df = create_df("SELECT * FROM prices", connect_mysqlserver())
#Filter both dataframes by current year and month
source_df = source_df[(source_df.Year == now.year) & (source_df.Month == now.month)]
dest_df = dest_df[(dest_df.Year == now.year) & (dest_df.Month == now.month)]

#Logic to check if data is in source and not yet in destination, only then push via api
if source_df.empty == False and dest_df.empty == True:
    print('Data will be pushed')
    data = source_df.to_json(orient = "records")
    data = json.loads(data)
#This loop is used for chunking as API times out when pushing a lot of data at the same time
    url = 'price'
    j = 0
    i = 400
    length = len(data)
    while j <= length:
        print(j,i)
        data2 = data[j:i]
        target_response = requests.put(target_url + url + "/json", json=data2, headers=target_headers)
        assert target_response.status_code == 200, f"{target_url + url} -> Expected 200, but received {target_response.status_code}"
        j = i
        i = i+400
elif dest_df.empty == False:
    print("Data Already At Destination")
elif source_df.empty == True:
    print("No Data In Source")
else:
    print("issue")


texts:
I've created a WPF program which can draw lines and circles on a canvas. It works well, but I don't think it's the best solution. How can I make it work better? How would you create this program?

MainWindow class:

public partial class MainWindow : Window
    {
        DrawCircle dc;
        DrawLine dl;
public MainWindow()
        {
            InitializeComponent();
        }

        private void cVas_MouseMove(object sender, MouseEventArgs e)
        {
                switch (rbLine.IsChecked)
                {
                    case true:
                        if (dl != null)
                            dl.MouseMove(Mouse.GetPosition(cVas));
                        break;
                    default:
                        if (dc != null)
                            dc.MouseMove(Mouse.GetPosition(cVas));
                        break;
                }
        }

        private void cVas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            switch (rbLine.IsChecked)
            {
                case true:
                    dl = new DrawLine(this);
                    dl.MouseDown(Mouse.GetPosition(cVas));
                    break;
                default:
                    dc = new DrawCircle(this);
                    dc.MouseDown(Mouse.GetPosition(cVas));
                    break;
            }

        }

        private void cVas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            dc = null;
            dl = null;
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                cVas.Children.Clear();
        }
    }

DrawLine class (the DrawCircle is similar to this):

class DrawLine
    {
        private Line myLine;
        MainWindow mw;

        public DrawLine(MainWindow mw)
        {
            this.mw = mw;
        }

        public void MouseDown(Point mousePoint)
        {
            myLine = new Line();
            myLine.Stroke = Brushes.Black;
            myLine.StrokeThickness = 2;
            myLine.X1 = myLine.X2 = mousePoint.X;
            myLine.Y1 = myLine.Y2 = mousePoint.Y;
            mw.cVas.Children.Add(myLine);
        }

        public void MouseUp()
        {
            myLine = null;
        }

        public void MouseMove(Point mousePoint)
        {
            if (myLine != null)
            {
                (mw.cVas.Children[mw.cVas.Children.IndexOf(myLine)] as Line).X2 = mousePoint.X;
                (mw.cVas.Children[mw.cVas.Children.IndexOf(myLine)] as Line).Y2 = mousePoint.Y;
            }
        }
    }

XAML:

<Window x:Class="WPFdraw.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" KeyDown="Window_KeyDown">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="20"></RowDefinition>
        </Grid.RowDefinitions>
        <Canvas Grid.Row="0" Background="Transparent" Name="cVas" Width="Auto" Height="Auto" MouseMove="cVas_MouseMove" MouseDown="cVas_MouseDown" MouseUp="cVas_MouseUp"></Canvas>
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <RadioButton Grid.Column="0" GroupName="tool" IsChecked="True" Name="rbLine" VerticalAlignment="Center">Line</RadioButton>
            <RadioButton Grid.Column="1" GroupName="tool" Name="rbCircle" VerticalAlignment="Center">Circle</RadioButton>
            <Button Name="btn" Grid.Column="2" Content="klikk" ></Button>
        </Grid>
    </Grid>
</Window>


texts:
I have 16 methods in Java that return int values. I need to find the one that returns the highest value.

I initially implemented this:

private int best() {
    int max = playGame(ONES);
    max = Math.max(max, playGame(TWOS));
    max = Math.max(max, playGame(THREES));
    max = Math.max(max, playGame(FOURS));
    max = Math.max(max, playGame(FIVES));
    max = Math.max(max, playGame(SIXES));
    max = Math.max(max, playGame(SEVENS));
    max = Math.max(max, playGame(EIGHTS));
    max = Math.max(max, playGame(THREE_OF_A_KIND));
    max = Math.max(max, playGame(FOUR_OF_A_KIND));
    max = Math.max(max, playGame(FULL_HOUSE));
    max = Math.max(max, playGame(SMALL_STRAIGHT));
    max = Math.max(max, playGame(LARGE_STRAIGHT));
    max = Math.max(max, playGame(ALL_DIFFERENT));
    max = Math.max(max, playGame(CHANCE));
    max = Math.max(max, playGame(ALL_SAME));
    return max;
}

To make this slightly better, I could reduce one comparison by comparing two methods simultaneously.

private int best() {
    int max1 = Math.max(playGame(ONES), playGame(TWOS));
    int max2 = Math.max(playGame(THREES), playGame(FOURS));
    int max3 = Math.max(playGame(FIVES), playGame(SIXES));
    int max4 = Math.max(playGame(SEVENS), playGame(EIGHTS));
    int max5 = Math.max(playGame(THREE_OF_A_KIND), playGame(FOUR_OF_A_KIND));
    int max6 = Math.max(playGame(FULL_HOUSE), playGame(SMALL_STRAIGHT));
    int max7 = Math.max(playGame(LARGE_STRAIGHT), playGame(ALL_DIFFERENT));
    int max8 = Math.max(playGame(CHANCE), playGame(ALL_SAME));
    int max11 = Math.max(max1, max2);
    int max12 = Math.max(max3, max4);
    int max13 = Math.max(max5, max6);
    int max14 = Math.max(max7, max8);
    int max21 = Math.max(max11, max12);
    int max22 = Math.max(max13, max14);
    int max = Math.max(max21, max22);
    return max;
}

I mentioned 16 methods as playGame(CONSTANT) callbacks different methods based on the constant.
However, this code is still bad. What could be a better way to achieve this?


texts:
Many a times, I've had the need to use a permutations with replacement function.

So, I've written a function to do just that:

from sys import setrecursionlimit
setrecursionlimit(10 ** 9)

def permutations_with_replacement(n: int, m: int, cur=None):
    if cur is None:
        cur = []

    if n == 0:
        yield cur
        return

    for i in range(1, m + 1):
        yield from permutations_with_replacement(n - 1, m, cur + [i])

if __name__ == '__main__':
    n = int(input("Please enter 'N': "))
    m = int(input("Please enter 'M': "))

    for i in permutations_with_replacement(n, m):
        print(*i)

There's a better way to do this if we used itertools.product, but there's no fun in that!

from itertools import product

def permutations_with_replacement(n, m):
    for i in product(list(range(1, m + 1)), repeat=n):
        yield i

if __name__ == '__main__':
    n = int(input("Please enter 'N': "))
    m = int(input("Please enter 'M': "))

    for i in permutations_with_replacement(n, m):
        print(*i)

I don't like the way I've implemented cur in my code. Is there any better way to do that?


texts:
This is my code for sending mail in HTML format:

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
    public void sendMail(String m_from,String m_to,String m_subject,String m_body){
      try {
          Session m_Session;
          Message m_simpleMessage;
          InternetAddress m_fromAddress;
          InternetAddress m_toAddress;
          Properties m_properties;

          m_properties     = new Properties();
          m_properties.put("mail.smtp.host", "smtp.gmail.com");
          m_properties.put("mail.smtp.socketFactory.port", "465");
          m_properties.put("mail.smtp.socketFactory.class",
                                     "javax.net.ssl.SSLSocketFactory");
          m_properties.put("mail.smtp.auth", "true");
          m_properties.put("mail.smtp.port", "465");

          m_Session=Session.getDefaultInstance(m_properties,new Authenticator() {
               protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("xxxxx","yyyyy"); // username and the password
               }
          });

          m_simpleMessage  =   new MimeMessage(m_Session);
          m_fromAddress    =   new InternetAddress(m_from);
          m_toAddress      =   new InternetAddress(m_to);
          m_simpleMessage.setFrom(m_fromAddress);
          m_simpleMessage.setRecipient(RecipientType.TO, m_toAddress);
          m_simpleMessage.setSubject(m_subject);

          m_simpleMessage.setContent(m_body, "text/html");
          //m_simpleMessage.setContent(m_body,"text/plain");

          Transport.send(m_simpleMessage);
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
  }

  public static void main(String[] args) {
      SendMail send_mail    =   new SendMail();
      String empName = "Antony Raj S";
      String title ="Hi !"+empName+"";
      send_mail.sendMail("anto@gmail.com", "anthony@slingmedia.com", "Please apply for leave for the following dates", title+"
by
HR");
    }
}

This works fine, but is there any other better way to do the same or how can I make the same code still better one? I get all the values like from address, SMTP host, port from the contex.xml file which is there in conf folder of Tomcat, so please do suggest anything better.


texts:
I was looking at other people code and I realized that mine is not so neat after all.

In this version, I included a base case for the merge part (when there is only 2 elements to merge, just sort it normally). I do not know this is a good idea or not, never seen it in other people' codes.

This is the first time I implemented this algorithm.  I hope you can help me out with this code so it could look more readable.

class MergeSort
{
    public static void Standard() {
        int[] A = new int[] {234, 31, 41, 59, 26, 41, 58, 90, 103, 14, 1235, 2134, 12, 673, 234, 234, 64, 23, 132, 432, 123};
        int last_Index = A.Length-1;

        SplitMerge(A, 0, last_Index);
        foreach (int i in A)
            Console.Write(i + " ");
    }

    //Here is the recursive split merge
    private static void SplitMerge(int[] A,int iBegin,int iEnd) {
        //Base case. Every  recursive has a base case
        if (iBegin == iEnd) return;

        //Calculate the middle index here. This work for odd number array.
        int Middle = (int)Math.Floor((double)(iEnd + iBegin)/2);

        //split left
        SplitMerge(A, iBegin, Middle);

        //split right
        SplitMerge(A, Middle+1, iEnd);

        //merge left and right
        MergeLeftRight(A, iBegin, Middle, iEnd);

    }

    //This is the merge
    private static void MergeLeftRight(int[] A, int iBegin, int iMid, int iEnd) {
        //If we are comparing just 2 numbers, just compare them already xD
        if (iBegin == iMid) {
            int temp_Num = A[iBegin];
            if (A[iBegin] >= A[iEnd]) {
                A[iBegin] = A[iEnd];
                A[iEnd] = temp_Num;
            }
            return;
        }

        //Create a temporary list to store numbers
        List<int> temp = new List<int> {};

        //Declare the last index of left array, we will go to this but will not pass this
        int left_End = iMid;

        //Same as above. This is for the right array
        int right_End = iEnd;

        //Left array start from iBegin, but Right array must start fron left_End+1
        iMid++;

        //Check the number in left and right arrays and sort them while both array still has elements inside
        while ((iBegin <= left_End) && (iMid <= right_End)) {
            if (A[iBegin] <= A[iMid]) {
                temp.Add(A[iBegin]);
                iBegin++;
            }
            else {
                temp.Add(A[iMid]);
                iMid++;
            }
        }

        //If right array is empty, add all leftover elements from left array to the list
        while (iBegin <= left_End) {
            temp.Add(A[iBegin]);
            iBegin++;
        }

        //Same as above loop. Add all leftover elements from right array to the list.
        while (iMid <= right_End) {
            temp.Add(A[iMid]);
            iMid++;
        }

        //Put everything back in the original array, merge everything. Since we are going from right to left
        //We need to reverse the List.
        temp.Reverse();
        foreach (int i in temp) {
            A[iEnd] = i;
            iEnd--;
        }
    }
}


texts:
I need to figure out if any anagram of the string can be a palindrome or not.

Ideas:

It relies on two observations:

Frequency of every character in the string is even, if length of the string is even.
Frequency of every character in the string is even except for one character, where frequency must be odd if the string length is odd.

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

bool sortAsc(char c, char d) { return c<d; }
int main() {
    string s;
    cin>>s;
    sort(s.begin(), s.end(), sortAsc);
    int flag = 0;
    string::size_type i=0;

    //Even - number of characters whose frequencies are even
    //Odd - number of characters whose frequencies are even
    int even=0, odd=0;

    //The number of times the loop runs is size-1
    //because of the reason below
    while(i<s.size()-1) {
        int temp=0;

        //checking if the next char is same as current
        //if i will be size-1 then s[i+1] will be out of bound
        while(s[i]==s[i+1]) {
            ++temp;
            ++i;
        }

        //if the last element has only one occurrence
        //then it should be counted as a character with odd occurrence
        if(i==s.size()-2) {
            //don't increment temp if
            //i is the second last element, just skip everything outside
            if(s[i]!=s[i+1]) { ++odd; ++i; continue;}
        }

        ++temp;
        if(temp%2==0) { ++even; } else { ++odd; }
        ++i;
    }

    if(s.size()%2==0 && odd == 0 || s.size()%2 != 0 && odd == 1)
        flag=1;
    else
        flag=0;

    //I could have directly echoed them to console
    //but its just the way here
    if(flag==0)
        cout<<"NO";
    else
        cout<<"YES";

    return 0;
}

As you can see the following block is only used once but condition is checked in every iteration.

if(i==s.size()-2) {

    if(s[i]!=s[i+1]) { ++odd; ++i; continue;}

}

It just just there because s[i+1] if i==size will return error.

Question:

Is there any way I can loop until the last index and can still check if the last element has any occurrences?
Can it be done better without the initial sorting?


texts: What's wrong with static utility classes, versus beans?

texts:
My inclination is to make these methods static:

package net.bounceme.dur.usenet.driver;

import java.util.List;
import java.util.logging.Logger;
import javax.mail.Folder;
import javax.mail.Message;
import javax.persistence.*;
import net.bounceme.dur.usenet.model.Article;
import net.bounceme.dur.usenet.model.Newsgroup;

class DatabaseUtils {

    private static final Logger LOG = Logger.getLogger(DatabaseUtils.class.getName());
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("USENETPU");
    private EntityManager em = emf.createEntityManager();

    public int getMax(Folder folder) {
        int max = 0;
        String ng = folder.getFullName();
        String queryString = "select max(article.messageNumber) from Article article left join article.newsgroup newsgroup where newsgroup.newsgroup = '" + ng + "'";
        try {
            max = (Integer) em.createQuery(queryString).getSingleResult();
        } catch (Exception e) {
            LOG.info("setting max to zero");
        }
        LOG.severe(folder.getFullName() + "\t" + max);
        return max;
    }

    public void persistArticle(Message message, Folder folder) {
        em.getTransaction().begin();
        String fullNewsgroupName = folder.getFullName();
        Newsgroup newsgroup = null;
        int max = getMax(folder);
        TypedQuery<Newsgroup> query = em.createQuery("SELECT n FROM Newsgroup n WHERE n.newsgroup = :newsGroupParam", Newsgroup.class);
        query.setParameter("newsGroupParam", fullNewsgroupName);
        try {
            newsgroup = query.getSingleResult();
            LOG.fine("found " + query.getSingleResult());
        } catch (javax.persistence.NoResultException e) {
            LOG.fine(e + "\ncould not find " + fullNewsgroupName);
            newsgroup = new Newsgroup(folder);
            em.persist(newsgroup);
        } catch (NonUniqueResultException e) {
            LOG.warning("\nshould never happen\t" + fullNewsgroupName);
        }
        Article article = new Article(message, newsgroup);
        em.persist(article);
        em.getTransaction().commit();
    }

    public void close() {
        em.close();
        emf.close();//necessary?
    }
}

However, I'm quite sure that I'm in the minority!  Why?

A quick look at Math shows that this isn't a strange or odd approach.  The object itself keeps no state, really, so why would a bean or POJO be preferred to static methods?


texts: Conjugate gradient method for a sparse matrix

texts:
I am very new to Rust. I have written a conjugate gradient algorithm function for CsMatrix structure from nalgebra

fn conjugate_gradient(m: &CsMatrix<f64>, rhs: &DVector<f64>, tol: f64, max_iter: Option<u32>) -> DVector<f64> {
    let n_iters = max_iter.unwrap_or(1000);
    println!("Iters: {}", n_iters);

    let mut x: CsVector<f64, Dynamic> = rhs.clone().into();
    let mut r: CsVector<f64, Dynamic> = rhs.clone().into();
    r = r.add(&(m.mul(&x).mul(-1.0_f64)));
    let mut p: CsVector<f64, Dynamic> = r.clone();
    let mut r2 = r.values_mut().fold(0.0_f64, |acc, x| acc + (*x)*(*x));

    for _ in 0..n_iters {
        let m_p: DVector<f64> = m.mul(&p).into();
        let p_full: DVector<f64> = p.clone().into();
        let a = r2/(p_full.dot(&m_p));
        x = x.add(&(p.clone().mul(a)));
        r = r.add(&(m.mul(&p).mul(-a)));
        let r2_new = r.values_mut().fold(0.0_f64, |acc, x| acc + (*x)*(*x));

        println!("Residual {}", r2_new);

        if r2_new < tol {
            return x.into();
        }
        let b = r2_new/r2;
        p = r.add(&(p.mul(b)));
        r2 = r2_new;
    }
    println!("Maximum number of iteration reached.");
    x.into()
}

Vector-vector (dot) product seems to be missing in the library (transpose didn't help).

I struggle with the concept of ownership, so any comment on bad usage of cloning, references, mutability, etc. would be helpful.
Also, if anyone with experience with nalgebra could suggest a better approach to using sparse matrices that would be very nice.


texts:
I've been doing some research around how to best make use of the WebP images (with fallback) in React. Most solutions point to something similar to what I've written below. That means if I have a lot of images I have to export the same image twice in assets.js (both PNG and WebP), import twice and provide two Image props for the same image.
This feels very inefficient. Is this an uncommon way of working with images? Is there a better way for working with images that live locally?
assets.js - where I collect all my assets and export them as strings. Imagine this list being really lengthy.
export { default as image1 } from "./assets/image-1.png";
export { default as image1Webp } from "./assets/image-1.webp";

In the file I import the assets I need for that page
import {
    image1,
    image1Webp
} from "./assets";

The component + props
<Image
  src={image1Webp}
  fallback={image1}
  alt="Lorem"
/>

Image.js component
const Image = ({
  src,
  fallback,
  type = 'image/webp',
  ...delegated
}) => {
  return (
    <picture>
      <source srcSet={src} type={type} />
      <img src={fallback} {...delegated} />
    </picture>
  );
};

Some things I've tried:
Generally the recommended way is to add images to a React project is to use require(img/path). So I tried things like appending .png or .webp to the base URL, inside the Image component. so I only need to define one string and then the component handles the splitting.
e.g. pseudocode:
export const toWEBP = (src) => {
  const location = src.split(".")
  return `${location}.webp`
}


texts:
A have a model with a dynamic field like so:

def resolveClient() {
    if (prevCall && prevCall.client) {
        return prevCall.client
    } else {
        return client
    }
}

Pretty simple. However, using a dynamic field makes me unable to do queries at the database level. I can't query using HQL or Criteria. This seems to be impacting performance pretty heavily. What's a better method to do something like this?


texts: Find numbers that are palindromic in consecutive number bases

texts:
I want to generate numbers which are palindromic in three or more
  consecutive number bases in the most optimal, fastest way (up to some
  range). I do not count trivial one digit palindromes.

  (When I say 3 or more, I mean 3 and 4, as it is not known if a solution for 4 or more bases exists)

I'm basically generating palindromes in number base \$b\$, and then converting and checking whether it is also palindromic in \$b+1, b+2, \dots\$

Are there any ways to noticeably speed up my code?

# Converts any number n to any base b (*), Source: [1]
# https://stackoverflow.com/a/28666223/5821790
def numberToBase(n, b):
    if n == 0:
        return [0]
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return digits[::-1]

# Generates palindromes in base b (*), Source: [2]
# https://math.stackexchange.com/q/2494909
def palgen(b):
    i = 1
    while True:
        ii = b * i
        r = range(i, ii)
        for j in r:
            s = numberToBase(j, b)
            yield s + s[-2::-1]
        for j in r:
            s = numberToBase(j, b)
            yield s + s[::-1]
        i = ii

# Checks if the list is palindromic, Source: [3]
# https://stackoverflow.com/a/30340347/5821790
def isPalindrome(s):
    if len(s) <= 1:
        return True
    return s[0] == s[-1] and isPalindrome(s[1:-1])

# converts number in base b (*) to integer
def listToInt(digitList, base):
    l = len(digitList)
    value = 0
    for i, val in enumerate(digitList):
        value += val*base**(l-i-1)
    return value

# returns current time
def getTime():
    return strftime("( %H:%M:%S )", gmtime())

###################################################################
# Searches for numbers palindromic in 3 or more consecutive bases #
###################################################################

from time import gmtime, strftime
from math import sqrt, floor

bound = 10**8                       # numbers up to
baseBound = floor(sqrt(bound))      # bases up to (bound, can be improved)
print(getTime(), "Starting with:" ,baseBound, bound)

for b in range(2, baseBound):
    for i, s in enumerate(palgen(b), 1):

        # convert palindrome s_b to integer x and check if out of bound
        x = listToInt(s, b)
        if (x > bound): break

        if (len(s) > 1): # one digit palindromes do not count (trivial)

            # checks if the palindrome x is also palindromic in more bases
            if (isPalindrome(numberToBase(x, b+1))):
                if (isPalindrome(numberToBase(x, b+2))):
                    print(getTime(), b, x, len(s))

                    if (isPalindrome(numberToBase(x, b+3))):
                        print(b, x, len(s), "*** AT LEAST FOUR IN A ROW ***")

  What are some things here that can be improved, and how, following
  good practice?

(Beside mathematical aspects which include the bound above which no more examples are found, the fact that only odd digit length palindromes form consecutive triples, and the facts that some examples follow a pattern that can be generated.)

Sources: [1] [2] [3]

Outputs: [10^9, ~ 3 hours: 1200 bases] and [10^12, ~ 3 hours: 100 bases]


texts: HTMLAudioElement sound delay on keyboard clicks

texts:
I am using Vue.js to play mp3 sounds on keyboard clicks. Even though each mp3 is less than 40 KB, there is a 95ms delay on heroku, on each request.

Is there a way to download sounds when dom is ready and not when clicking the buttons?

 let a = 'sound1.mp3',
        b = 'sound2.mp3';
    new Vue({
        created() {
            this.onKeyDown = this.onKeyDown.bind(this);
            document.getElementById('btn-sound').addEventListener('keydown', this.onKeyDown);
        },
        destroyed() {
            document.getElementById('btn-sound').removeEventListener('keydown', this.onKeyDown);
        },
        methods: {
            playSound(sound) {
                if (sound) {
                    var audio = new Audio(sound);
                    audio.play();
                }
            },

            onKeyDown(e) {
                switch (e.keyCode) {
                    case 12:
                        this.playSound(a);
                        break;
                    case 13:
                        this.playSound(b);
                        break;

                }

            }

        }
    });


texts: Functions for scanning command line options

texts:
I know that getopts is available but I wanted to write my own as a way of improving my bash.  Below I show two function definitions and an example of the use of them in a bash script.  Finally I show the output of the script.

Please comment.

#!/bin/bash
# Produce a string variable which can be used by function isoption
# to give calling scripts an easy way to determine what options are
# are provided in its command line regardless of their order.
# Call this function as:
#
#   mygetopts "$@"
#
# Non-option arguments in the command line of the caller are
# passed back to the caller in array NONOPTARGS and can be used like this:
#
#   name=NONOPTARGS[0]
#
# NOTE: Option globbing is not allowed

function mygetopts ()
{
# Initialize a string variable which will be made to contain all
# option names in "$@".  Since this string will be used by function
# isoption a weird variable name is used to avoid collision with
# variable names in calling script since it cannot be made local.

    O1P2T3I4O5N6="-"    # O1P2T3I4O5N6 is avaiable to caller
    declare -i i=0      # i is local to function

    if [[ "$1" == "-h" || "$1" == "--help" ]]; then
        echo "Usage: $0 \"\$@\"" >&2
        return 1
    fi

    for arg in "$@" ; do    # arg will be each positional parameter
        if [[ ${arg:0:1} == - ]]    # if $arg begins with -
            # Pack all option names separated by -
            then O1P2T3I4O5N6=${O1P2T3I4O5N6}${arg:1}-

            else NONOPTARGS[i++]=$arg
        fi
        #echo "O1P2T3I4O5N6  =$O1P2T3I4O5N6"
        #echo "NONOPTARGS = ${NONOPTARGS[@]}"
    done
    return 0
}

function isoption ()
{

    if [[ $O1P2T3I4O5N6 =~ ^.*-${1}-.*$ ]]
        then return 0
        else return 1
    fi
}

#!/bin/bash
# Example of using functions mygetopts and isoption to provide easy
# access to all command line options as well as non-option arguments
# regardless of their order.
#
# To use these functions place the file MYFUNCTIONS in your $HOME
# directory and source it in your bash script before using the
# functions.  Alternately it can be sourced by your .bash_profile

set +vx         # Change + to - to enable tracing
echo
echo These $# command line arguments are provided:
echo "$@"

. ~/MYFUNCTIONS # source the function definitions
echo
echo These functions are defined:
compgen -A function # Show what functions are defined
echo
mygetopts "$@"  # Call mygetopts with all command line arguments

echo mygetopts returns this string with all options separated by -
echo O1P2T3I4O5N6 = $O1P2T3I4O5N6   # Show the string of all options

echo Examples of the use of isoption function:
if isoption f; then echo f found ; else echo f Not found; fi
if isoption z; then echo z found ; else echo z Not found; fi
if isoption abcd; then echo abcd found ; else echo abcd Not found; fi
if isoption abcde; then echo abcde found ; else echo abcde Not found; fi
echo
echo Examples of the accessing of non-option arguments:
inputfilename=${NONOPTARGS[0]}
outputfilename=${NONOPTARGS[1]}
echo inputfilename=$inputfilename
echo outputfilename=$outputfilename

***13:00:47 617 ~/work>testmygetopts -bde -f infile -abcd -x outfile -y

These 7 command line arguments are provided:

-bde -f infile -abcd -x outfile -y

These functions are defined:

isoption
mygetopts

mygetopts returns this string with all options separated by -

O1P2T3I4O5N6 = -bde-f-abcd-x-y-

Examples of the use of isoption function:

f found
z Not found
abcd found
abcde Not found

Examples of the accessing of non-option arguments:

inputfilename=infile
outputfilename=outfile


texts:
Description of challenge:

  Using names.txt (right click and 'Save Link/Target As...'), a 46K text
  file containing over five-thousand first names, begin by sorting it
  into alphabetical order. Then working out the alphabetical value for
  each name, multiply this value by its alphabetical position in the
  list to obtain a name score.

  For example, when the list is sorted into alphabetical order, COLIN,
  which is worth \$3 + 15 + 12 + 9 + 14 = 53\$, is the 938th name in the
  list. So, COLIN would obtain a score of \$938 × 53 = 49714\$.

  What is the total of all the name scores in the file?

I quickly created a solution: it was fairly easy, but I am specifically concerned about the performance, which I am unsure of. What I do know is:

string.split(): \$O(n)\$
Arrays.sort(): \$O(n \log n)\$ Worst Case
Remaining code: \$O(nm)\$, where \$n\$ is the length, and \$m\$ is the average length of the names

The code is below:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class ProjectEuler22 {

    private static final String filePath = "names.txt";
    private static final int ASCII_VALUE_TO_INT = 64; // naming

    public static void main(String[] args) {
        long time = System.nanoTime();
        String[] names = readAllNames().split("\",\"");
        names[0] = names[0].substring(1);
        int length = names.length; // extra "
        names[length - 1] = names[length - 1].substring(0,
                names[length - 1].length()); // extra "
        Arrays.sort(names);
        int total = 0;
        for (int i = 0; i < length; i++) {
            total += getValueOfName(names[i], i + 1);
        }
        time = System.nanoTime() - time;
        System.out.println("The result is: " + total + "\nTime taken (ns): "
                + time);
    }

    private static String readAllNames() {
        try (BufferedReader reader = new BufferedReader(
                new FileReader(filePath))) {
            return reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Gets the value of the given string. If there are characters other than
     * [A-Z], then it will ignore it. Note that the problem file only contains
     * names with all caps.
     *
     * @param string
     *            the name to get the value of
     * @param i
     *            the index of the name
     * @return the value of the name
     */
    private static int getValueOfName(String string, int i) {
        char[] array = string.toCharArray();
        int sum = 0;
        for (char c : array) {
            if (Character.isUpperCase(c)) {
                sum += c - ASCII_VALUE_TO_INT;
            }
        }
        return sum * i;
    }

}

Output:

   The result is: 871198282
 Time taken (ns): 19757146

Time taken seems to be around 20_000_000 nanoseconds.

Specific concerns:

Is there a better way to solve this? (As said above)
Where it says the // naming comment, is the naming fine? Anywhere else where the naming is off?
Anything else?


texts: Chain-of-Responsibility in C++11 using smart pointers

texts:
I have implemented the CoR pattern in c++11 using smart_ptr for association between chain of receivers. The client owns all the receiver objects(which can be created and destroyed at runtime) and the receiver object maintain weak_ptr for subsequent request handler.

// ChainOfResponsibility.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <memory>
#include <tuple>
#include <string>
#include <iostream>
#include <vector>

// Event, sent from sender to many receivers. The first parameter decides who should handle.
using Event = std::tuple<int, std::string>;

//Abstract class which manages the link to the subsequent classes.
class Handler {
public:
    Handler(std::shared_ptr<Handler> successor = nullptr) :m_successor(successor) {}
    virtual void handle(Event e) = 0;
    virtual  ~Handler() {}
protected:
    std::weak_ptr<Handler> m_successor;
};

//clients need to implement handle function
class Agent : public Handler {
public:
    Agent(std::shared_ptr<Handler> successor = nullptr):Handler(successor) {}
    void handle(Event e) override {
        if (std::get<0>(e) == 1) {
            std::cout << "Agent handled the request: " + std::get<1>(e) << std::endl;
        }
        else {
            try {
                std::shared_ptr<Handler> ptr(m_successor);
                ptr->handle(e);
            }
            catch(std::bad_weak_ptr) {
                std::cout << "No successor handler" << std::endl;
            }
        }

    }

    virtual  ~Agent() override {}
};

class Supervisor : public Handler {
public:
    Supervisor(std::shared_ptr<Handler> successor = nullptr) :Handler(successor) {}
    void handle(Event e) override {
        if (std::get<0>(e) == 2) {
            std::cout << "Supervisor handled the request: " + std::get<1>(e) << std::endl;
        }
        else {
            try {
                std::shared_ptr<Handler> ptr(m_successor);
                ptr->handle(e);
            }
            catch (std::bad_weak_ptr) {
                std::cout << "No successor handler" << std::endl;
            }
        }

    }
    virtual  ~Supervisor() override {}
};

class Boss : public Handler {
public:
    Boss(std::shared_ptr<Handler> successor = nullptr) :Handler(successor) {}
    void handle(Event e) override {
        if (std::get<0>(e) == 3) {
            std::cout << "Boss handled the request: " + std::get<1>(e) << std::endl;
        }
        else {
            try {
                std::shared_ptr<Handler> ptr(m_successor);
                ptr->handle(e);
            }
            catch (std::bad_weak_ptr) {
                std::cout << "No successor handler" << std::endl;
            }
        }

    }
    virtual  ~Boss() override {}
};

int main() {

    //three receivers owned by the client
    auto boss = std::make_shared<Boss>();
    auto supervisor = std::make_shared<Supervisor>(boss);
    auto agent = std::make_shared<Agent>(supervisor);

    //events
    std::vector<Event> events;
    events.push_back(std::make_tuple(1, "Technical support"));
    events.push_back(std::make_tuple(2, "Billing query"));
    events.push_back(std::make_tuple(1, "Product information query"));
    events.push_back(std::make_tuple(5, "Police issue"));
    events.push_back(std::make_tuple(3, "Enterprise client request"));

    for (auto e : events) {
        agent->handle(e);
    }

    //receivers may be released at run time.
    boss.reset();

    for (auto e : events) {
        agent->handle(e);
    }

    return 0;
}

Please review this and suggest me the improvemnt.

Assumption: Performance is not a primary concern.

Please suggest me an elegant implementation if you have seen somewhere else.


texts:
As request of Simon's comment:

Direction.java

package net.woopa.dungeon.datatypes;

import java.util.Random;

public enum Direction {
    NORTH, EAST, SOUTH, WEST;
    private static Random rnd = new Random();

    static public Direction randomDirection() {
        return Direction.values()[rnd.nextInt(4)];
    }

    // Rotate 90 degrees clockwise
    public Direction rotate90() {
        return values()[(ordinal() + 1) % 4];
    }

    // Rotate 180 degrees
    public Direction rotate180() {
        return values()[(ordinal() + 2) % 4];
    }

    // Rotate 270 degrees clockwise (90 counterclockwise)
    public Direction rotate270() {
        return values()[(ordinal() + 3) % 4];
    }

    public Boolean isHorizontal() {
        return this == EAST || this == WEST;
    }

    public Boolean isVertical() {
        return this == NORTH || this == SOUTH;
    }

    public int dx(int steps) {
        if (this == EAST) {
            return steps;
        }
        if (this == WEST) {
            return -steps;
        }
        return 0;
    }

    public int dy(int steps) {
        if (this == NORTH) {
            return steps;
        }
        if (this == SOUTH) {
            return -steps;
        }
        return 0;
    }

    public int forwards_x(int n) {
        if (this == EAST) {
            return n + 1;
        }
        if (this == WEST) {
            return n - 1;
        }
        return n;
    }

    public int forwards_y(int n) {
        if (this == NORTH) {
            return n + 1;
        }
        if (this == SOUTH) {
            return n - 1;
        }
        return n;
    }

    public int backwards_x(int n) {
        if (this == EAST) {
            return n - 1;
        }
        if (this == WEST) {
            return n + 1;
        }
        return n;
    }

    public int backwards_y(int n) {
        if (this == NORTH) {
            return n - 1;
        }
        if (this == SOUTH) {
            return n + 1;
        }
        return n;
    }

    public int left_x(int n) {
        if (this == NORTH) {
            return n - 1;
        }
        if (this == SOUTH) {
            return n + 1;
        }
        return n;
    }

    public int left_y(int n) {
        if (this == EAST) {
            return n + 1;
        }
        if (this == WEST) {
            return n - 1;
        }
        return n;
    }

    public int right_x(int n) {
        if (this == NORTH) {
            return n + 1;
        }
        if (this == SOUTH) {
            return n - 1;
        }
        return n;
    }

    public int right_y(int n) {
        if (this == EAST) {
            return n - 1;
        }
        if (this == WEST) {
            return n + 1;
        }
        return n;
    }
}

What are your thoughts about this class?  The main grip I have personally is the left_y, right_x, etc methods. The code works, and here is some example of its usage below. But I feel there may be a better way?

Example usage:

Direction dir = Direction.randomDirection();
if (grid.get(dir.left_x(x), dir.left_y(y)).equals(CoreMaterial.WALL) && grid.get(dir.right_x(x), dir.right_y(y)).equals(CoreMaterial.WALL) && grid.get(dir.backwards_x(x), dir.backwards_y(y)).equals(CoreMaterial.FLOOR) && grid.get(dir.forwards_x(x), dir.forwards_y(y)).equals(CoreMaterial.FLOOR)) {
    StandardMethods.build_door(dir, new Vector2D(x, y), CoreMaterial.CAKE, grid);
}

The above example has a location (x,y) for a door on a grid and then checks around it to ensure that there are doors either side and floors the other two either sides?

Symbols:

. = floor

# = wall

+ = door

Example:

.#.
.+.
.#.

This would be okay for the placing of the door.


texts:
I tried to write a script which takes a list of URLs, checks if their FreeDNS record points to the current IP, and updates the record if not.

Intended use is that the script will be run periodically to keep FreeDNS always pointing to the dynamic IP.

Also, a log is kept so the user may later inspect what the script did.

# List of domains that should point to the current IP
freedns_domains = set(["foo.example.com"])

# FreeDNS API endpoint, accessible from https://freedns.afraid.org/api/ (use the ASCII one)
freedns_check_url = "https://freedns.afraid.org/api/?action=getdyndns&sha=REDACTED"

# It is assumed that this address responds with a page containing only the IP address
ip_check_url = "https://ident.me/"

def log(message):
    """
    Appends a string to the logfile (hardcoded as log.txt).
    :param message: The message to be appended. Linebreaks are your responsibility.
    """
    with open("log.txt", "a") as f:
        f.write(message)

import datetime
now = datetime.datetime.now()
log("\n\n" + str(now) + ": Script executing,")
import urllib.request
current_ip = urllib.request.urlopen(ip_check_url).read().decode("utf-8")
log(" IP: " + current_ip)

log("\n\tGetting FreeDNS records...")
import urllib.request
records_raw = urllib.request.urlopen(freedns_check_url).read().decode("utf-8").split("\n")
log(" Found " + str(len(records_raw)) + ".")

for raw_record in records_raw:
    parts = raw_record.split("|")

    domain = parts[0]
    current_freedns_ip = parts[1]
    freedns_update_url = parts[2]

    if domain not in freedns_domains:
        log("\n\t\t" + domain + " is not on the watch list, skipping.")
    else:
        log("\n\t\t" + domain + " (" + current_freedns_ip + ") is on the watch list...")

        if current_ip == current_freedns_ip:
            log(" IPs already match, moving on.")
        else:
            log(" IPs don't match, updating...")
            urllib.request.urlopen(freedns_update_url)
            log(" done.")

log("\n\tScript exited gracefully.")

I know that instead of hard coding freedns_domains, it would be more user-friendly to read them from a text file. I haven't done that since I didn't want to deal with the extra complexity of checking if the input file is full of garbage.

Besides this, in what ways can this script be improved?