texts: Split a char array with NUL terminators and inner delimiters

texts:
I get as an input a char array in this format:  "key = value\0key = value...\0" (last pair is ended with 2 NUL terminators - one is the pair end + one is the whole string end)

and I want to split it into pairs of {key, value} in order to print them.

This is my approach; is there a better way (strtok-like) to do so?

char str [] =   "line 1 = But I set fire to the rain\0line 2 = Watched it pour as I touched your face\0line 3 = Well, it burned while I cried\0line 4 = 'Cause I heard it screaming out your name, your name!\0";
char * p = str;
char key[10], value[128], * delimiter;

while(*p){
    memset(key,     0, sizeof(key));
    memset(value,   0, sizeof(value));

    delimiter = strchr(p, '=');
    strncpy(key, p, delimiter - p);
    // not sure where the NUL terminator is, so use strcpy
    strcpy(value, 1 + delimiter);

    printf("key: %s\n   value: %s\n", key, value);
    p += strlen(p) + 1;
}

I'm copying the pairs into temp arrays so I could process them later...


texts: Image cache for lots of images using WeakReference on C#

texts:
I'm developing an application to manage a player card-library from an online game. Each card has an image that is stored on disk with a numeric code, for example, the card with ID=1234 has his image stored as 1234.png and all the images are stored on the same folder.

As of now there are more than 3500 images for a total of 1 GB of hard disk usage.

The app doesn't need all the images loaded on memory, but depending on the context it may need from 8 to 100 images loaded on screen, and the next moment it may need a 100 different images.

As of now the images are loaded using IValueConverter and DataTemplate without storing on code behind the image, so everytime an image is needed, it is loaded from disk.

That is the current state of the project.

Now this is the code that I want to implement:

public class ImageAccessor
{
    private string Filepath;
    private Dictionary<int, WeakReference> References;

    public ImageAccessor(string filepath)
    {
        Filepath = filepath;
    }

    public BitmapImage GetImage(int id)
    {
        BitmapImage image = null;
        WeakReference reference = null;

        if (!References.TryGetValue(id, out reference))
        {
            image = GetFromDisk(id);
            reference = new WeakReference(image);
            References[id] = reference;
        }
        else
        {
            image = reference.Target as BitmapImage;
            if (image == null)
            {
                image = GetFromDisk(id);
                reference.Target = image;
            }
        }

        return image;
    }

    private BitmapImage GetFromDisk(int id)
    {
        Uri uri = new Uri(Filepath + id + ".png");
        return new BitmapImage(uri);
    }
}

I don't want to implement a singleton of that class but for now let's assume that my project always uses the same instance.

Everywhere that I read about WeakReference they recommend using it for "a single large object", but what if I want to use it on "a lot of relative small-medium size objects (200~500kb each)". Except from the advice of using them for big objects, those images meet the rest of the requirements:

Having all of them all the time on memory would be very costly (1GB on RAM)
Some images may not be used for the entire life of the app
Some images may be used only one or a couple of times
Some images may be used lots of times

And by using an image I mean displaying it on a Image control

I've never worked with weak references, and I still need to do some benchmarks to see if they are worth it, but I want to know if this code:

Is safe?
May incur on memory problems?
It can be improved?

For the sake of simplicity assume this:

The filepaths will always be correct
Every ID will correspond to an existing image always
Images will not be modified


texts:
I just solved Project Euler 38 and was wondering if you guys could provide some suggestions on how to speed it up. I've tried adding extra conditions but they increase the time. Any ideas on how to optimize the numbers I'm checking would be appreciated.

from timeit import default_timer as timer

def create_pandigital_multiple(original_number):
    num = str(original_number)
    digits = range(1, 10)
    if len(num) >= 5:
        return 0
    else:
        temp = 2
        while len(num) < 9:
            num += str(original_number * temp)
            temp += 1
        if sorted([int(x) for x in num]) == digits:
            return int(num)
        else:
            return 0

start = timer()
ans = 0
for k in range(9, 10**5):
    if create_pandigital_multiple(k) > greatest:
        ans = create_pandigital_multiple(k)

elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts: Algorithm to determine if binary tree is a Binary Search Tree (BST)

texts:
Continuing with algorithms I've implemented a binary search tree validator. I don't like the two boolean variables within NodeFollowsBSTContract as it feels too complicated. I feel like it should be cleaned up but don't see how, yet.
Also, before each recursive step down, to check child nodes, a new list is created. Is there's a better way to implement this check that doesn't repeatedly create new lists?
public class BinaryTreeNode
{
    public BinaryTreeNode Left { get; set; }
    public BinaryTreeNode Right { get; set; }

    public int? Value { get; }

    public BinaryTreeNode(int value)
    {
        Value = value;
    }
}

public class ValidateBST
{
    BinaryTreeNode _root;
    public ValidateBST(BinaryTreeNode root)
    {
        _root = root;
    }

    public bool IsBinarySearchTree()
    {
        if ((_root.Left?.Value ?? 0) <= (_root.Value)
            || (_root.Right?.Value ?? 0) > (_root.Value))
        {
            var listIncludingRootValue = new List<int>()
            {
                _root.Value.Value
            };

            var leftLegValid = NodeFollowsBSTContract(_root.Left, new List<int>(), new List<int>(listIncludingRootValue));

            var rightLegvalid = NodeFollowsBSTContract(_root.Right, new List<int>(listIncludingRootValue), new List<int>());

            return leftLegValid && rightLegvalid;
        }
        else
        {
            return false;
        }
    }

    private bool NodeFollowsBSTContract(BinaryTreeNode node, List<int> parentSmallerValues, List<int> parentLargerValues)
    {
        if (node == null)
        {
            return true;
        }

        bool isLessThanAllParentLargerValues = !parentLargerValues.Any()
            || parentLargerValues.Where(value => node.Value.Value <= value).Count() == parentLargerValues.Count;

        bool isGreaterThanAllParentSmallerValues = !parentSmallerValues.Any()
            || parentSmallerValues.Where(value => node.Value.Value > value).Count() == parentSmallerValues.Count;

        if (!isLessThanAllParentLargerValues || !isGreaterThanAllParentSmallerValues)
        {
            return false;
        }

        if (node.Left != null)
        {
            var updatedLargerValues = GenerateUpdatedLists(node.Value.Value, parentLargerValues);
            var updatedSmallervalues = new List<int>(parentSmallerValues);

            if (!NodeFollowsBSTContract(node.Left, updatedSmallervalues, updatedLargerValues))
            {
                return false;
            }
        }

        if (node.Right != null)
        {
            var updatedvalues = GenerateUpdatedLists(node.Value.Value, parentSmallerValues);

            if (!NodeFollowsBSTContract(node.Right, updatedvalues, parentLargerValues))
            {
                return false;
            }
        }

        return true;
    }

    private List<int> GenerateUpdatedLists(int addValue, List<int> values)
    {
        var updatedValues = new List<int>(values)
        {
            addValue
        };

        return updatedValues;
    }
}


texts:
I am practicing interview questions, I wrote this code to perform BFS and DFS on a graph in Python.

How can it be optimized, and how can it be made more readable?

class Graph:
    def __init__(self):
        self.graph = defaultdict(list)

    def add_edge(self, u, v):
        self.graph[u].append(v)

    def dfs(self, node):
        visited = [False for i in range(len(self.graph))]
        stack = []
        stack.append(node)
        visited[node] = True
        while stack:
            node = stack.pop()
            print node
            for i in self.graph[node]:
                if visited[i] == False:
                    visited[i] = True
                    stack.append(i)

     def Bfs(self, node):
        visited = [False for i in range(len(self.graph))]
        queue = []
        queue.append(node)
        visited[node] = True
        while queue:
            node = queue.pop(0)
            print node
            for i in self.graph[node]:
                if not visited[i]:
                    queue.append(i)
                    visited[i] = True


texts:
How could I possibly shorten / clean this up?  I suppose mainly clean up the loop at the start asking whether they would like to scramble the code.

def userAnswer(letters):
    print("Can you make a word from these letters? "+str(letters)+" :")
    x = input("Would you like to scrample the letters? Enter 1 to scramble or enter to guess :")
    while x == '1':
        print(''.join(random.sample(letters,len(letters))))
        x = input("Would you like to scrample the letters? Enter 1 to scramble or enter to guess :")
    word = input("What is your guess? :")
    word = word.lower()
    if checkSubset(word, letters) == True and checkWord(word) == True:
        print("Yes! You can make a word from those letters!")
    else:
        print("Sorry, you cannot make that word from those letters")

userAnswer("agrsuteod")


texts: Unity3d class that inherits from button and add OnHold Event

texts:
I made my own class that inherits from button and has an OnHold event. It seems to work ok but I'm wondering if I can improve it or if you can spot any glaring mistakes that I made.

Here is the code:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
[AddComponentMenu("UI/Hold Button")]
public class HoldButton : Button
{
    private bool isBeingPressed;
    private float currTime;
    private static float TimeMax = 2;
    private bool startTimer;
    public ButtonHoldEvent onHold { get; set; }
    public override void OnPointerDown(PointerEventData eventData)
    {
        startTimer = true;
        currTime = 0;
    }
    public override void OnPointerUp(PointerEventData eventData)
    {
        startTimer = false;
        currTime = 0;
        isBeingPressed = false;
    }
    void Update()
    {
      if(startTimer)
        {
            currTime += Time.deltaTime;
            if(currTime >= TimeMax)
            {
                isBeingPressed = true;
            }else
            {
                isBeingPressed = false;
            }
        }
        if (isBeingPressed)
        {
            onHold.Invoke();
        }
    }

    public class ButtonHoldEvent : UnityEvent
    {
        public ButtonHoldEvent() : base()
        {

        }
    }
}


texts:
See Wikipedia - Multiton Pattern for details on the intent.

Here's the class:

/**
 * Holds a thread-safe map of unique create-once items.
 *
 * Contract:
 *
 * Only one object will be made for each key presented.
 *
 * Thread safe.
 *
 * @param <K>
 * @param <V>
 */
public class Multiton<K, V> {
  // Map from the key to the futures of the items.
  private final ConcurrentMap<K, Future<V>> multitons = new ConcurrentHashMap<K, Future<V>>();
  // A Prayer is used to construct the Callable that is attached to the FutureTask.
  private final Prayer prayer;

  public Multiton(Creator<K, V> creator) {
    // Create the prayer to the creator.
    this.prayer = new Prayer(creator);
  }

  /**
   * There can be only one.
   *
   * Use a FutureTask to do the creation to ensure only one construction.
   *
   * @param key
   * @return
   * @throws InterruptedException
   * @throws ExecutionException
   */
  public V getInstance(final K key) throws InterruptedException, ExecutionException {
    // Already made?
    Future<V> f = multitons.get(key);
    if (f == null) {
      // Plan the future but do not create as yet.
      FutureTask<V> ft = new FutureTask<V>(prayer.pray(key));
      // Store it.
      f = multitons.putIfAbsent(key, ft);
      if (f == null) {
        // It was successfully stored - it is the first (and only)
        f = ft;
        // Make it happen.
        ft.run();
      }
    }
    // Wait for it to finish construction and return the constructed.
    return f.get();
  }

  /**
   * Use a Prayer to pass the key to the Creator.
   *
   * @param <K>
   * @param <V>
   */
  private class Prayer {
    private final Creator<K, V> creator;

    public Prayer(Creator<K, V> creator) {
      this.creator = creator;
    }

    public Callable<V> pray(final K key) {
      return new Callable<V>() {

        @Override
        public V call() throws Exception {
          return creator.create(key);
        }

      };
    }

  }

  /**
   * User provides one of these to do the construction.
   *
   * @param <K>
   * @param <V>
   */
  public abstract static class Creator<K, V> {
    // Return a new item under the key.
    abstract V create(K key) throws ExecutionException;

  }

}

I use it to ensure I only create one JAXBContex for each class:

/**
 * Create just one JAXB context for each class.
 */
private static final Multiton<Class, JAXBContext> contexts = new Multiton<Class, JAXBContext>(new Creator<Class, JAXBContext>() {

  @Override
  JAXBContext create(Class key) throws ExecutionException {
    try {
      // Get it out of my Multiton
      return JAXBContext.newInstance(key);
    } catch (JAXBException ex) {
      // Pass it back as an Execution Exception.
      throw new ExecutionException("Failed to create JAXB Context for class "+key.getName(), ex);
    }
  }

});

/**
 * Uses a Multiton to create a JAXB context for the object.
 *
 * @param it - The object to create the context for.
 * @return - the unique JAXB context.
 * @throws InterruptedException - Interrupted.
 * @throws ExecutionException - Something else went wrong (cause is wrapped)
 */
private static JAXBContext createJAXBContext(Object it) throws InterruptedException, ExecutionException {
  return contexts.getInstance(it.getClass());
}

My Questions:

Is this a Multiton as described by the article? I.e. Will it only ever create just one instance of the object?
Is it thread-safe?
Am I being offensive using a Prayer object to request an object from the Creator?
If the answer to 3 is no - should I make my create method of the Creator take a Prayer as a parameter rather than a K key - just for the belly laugh of course?

NB: The idea of using a FutureTask came from a nice answer by assylias on thread-safe multitons. All I've really done is make it generic and plumbed in the ability to pass a Creator.


texts: Project Euler 5: Smallest multiple in Functional Programming (fp)

texts:
I wanted to practice functional programming (fp) without using any library but using vanilla JS only. So I took the a problem from project euler:

/*jshint esversion: 6*/
(function () {
  'use strict';
  const leastCommonMultiple = (n, multiple, max) => n === max ?
    multiple :
    leastCommonMultiple(n + 1, multiple * (n + 1) / greatestCommonDivisor(
      multiple, (n + 1)), max);

  const greatestCommonDivisor = (a, b) => 0 === b ? a : greatestCommonDivisor(
    b, a % b);

  console.log("Solution: ", leastCommonMultiple(1, 1, 20));
})();

Is there a way to write leastCommonMultiple with less parameters and still be consistent with fp? Any other improvement suggestions are welcomed as well!


texts: Resolving multiple "paths" in nested attributes

texts:
I need to resolve "multiple paths" specified like so:

p1 = 'item.element.[compact|fullsize].documents.[note|invoice]'

A list like this is expected:

['item.element.compact.documents.note', 'item.element.fullsize.documents.note',
 'item.element.compact.documents.invoice', 'item.element.fullsize.documents.invoice']

Code:

def resolve_paths(path):
    parts = path.split('.')
    depth = len(parts)
    new_paths = []
    for level, part in enumerate(parts):
        mult_branches = re.findall(r'\[(\w+)(?:\|(\w+))*\]', part)
        if mult_branches:
            mult_branches = flatten_iterable(mult_branches)
            for branch in mult_branches:
                interm_path = '.'.join(parts[:level] + [branch] + parts[level+1:])
                new_paths.extend(resolve_paths(interm_path))
            return new_paths
        elif level == depth - 1:
            new_paths.append(path)
    return new_paths

Several tests I wrote for this function pass, but I'm not entirely happy with this solution, it's somewhat convoluted. Better solutions? Simplifications?


texts: Project Euler code evaluation - digit fifth powers

texts:
This is for Project Euler #30:

  Surprisingly there are only three numbers that can be written as the
  sum of fourth powers of their digits:

  \$1634 = 1^4 + 6^4 + 3^4 + 4^4\$
    \$8208 = 8^4 + 2^4 + 0^4 + 8^4\$
    \$9474 = 9^4 + 4^4 + 7^4 + 4^4\$

  As \$1 = 1^4\$ is not a sum it is not included.  The sum of these numbers
  is \$1634 + 8208 +  9474 = 19316\$.

  Find the sum of all the numbers that can be written as the sum of
  fifth powers of their digits.

list = []
2.upto(1_000_000) do |num|
 list << num if num.to_s.split("").map(&:to_i).map { |num| num ** 5 }.inject(:+) == num
end

puts list.inject(:+)

This works, and I am here for three reasons:

I use map twice, and this smells but I don't know an easier/better way.
How does the & work? Notice I do map(&:to_i) and inject(:+).  I have seen examples of this but don't know why they are different and what is going on.
Any suggestions on code improvements?


texts: Simple Go Linux daemon to send/receive gob-encoded data on a socket

texts:
I'm currently working on a linux daemon and would like some feedback. The program is a simple unix socket server that sends around gob encoded messages. I'm still getting the hang of concurrency in go and I'm not terribly confidant the socket server is passing around messages properly especially on shutdown. Hopefully, I'm not doing anything too egregious.

EDIT: I rewrote most of the server code after getting a burst  of inspiration from this post. I fell back to a previous iteration that didn't use channels to communicate errors and connections. Instead it just uses a callback for errors in much the same way it does for regular messages. Finally, I then wrote units tests for the whole thing.

I'll remove the old code. Any feedback would still be appreciated.

server.go

package network

import (
    "encoding/gob"
    "errors"
    "net"
    "sync"
)

var (
    ErrNoMessageHandler = errors.New("server: message handler not specified")
)

type Options struct {
    Network string
    Address string
}

type Server struct {
    opts  *Options
    lis   net.Listener
    mh    func(interface{}) interface{}
    eh    func(error)
    quit  bool
    conns sync.WaitGroup
}

func NewServer(opts *Options) *Server {
    return &Server{opts: opts}
}

func (s *Server) OnMessage(handler func(interface{}) interface{}) {
    s.mh = handler
}

func (s *Server) OnError(handler func(error)) {
    s.eh = handler
}

func (s *Server) Listen() error {
    lis, err := net.Listen(s.opts.Network, s.opts.Address)
    if err != nil {
        return err
    }
    s.lis = lis
    return nil
}

func (s *Server) Network() string {
    return s.lis.Addr().Network()
}

func (s *Server) Address() string {
    return s.lis.Addr().String()
}

func (s *Server) Serve() error {
    if s.mh == nil {
        return ErrNoMessageHandler
    }
    for {
        conn, err := s.lis.Accept()
        if err != nil {
            if s.quit {
                return nil
            }
            return err
        }
        s.conns.Add(1)
        go s.handle(conn)
    }
}

func (s *Server) Close() error {
    s.quit = true
    err := s.lis.Close()
    s.conns.Wait()
    return err
}

func (s *Server) handle(conn net.Conn) {
    defer s.cleanup(conn)

    dec := gob.NewDecoder(conn)
    var req interface{}
    if err := dec.Decode(&req); err != nil {
        if s.eh != nil {
            s.eh(err)
        }
        return
    }

    res := s.mh(req)

    enc := gob.NewEncoder(conn)
    if err := enc.Encode(&res); err != nil {
        if s.eh != nil {
            s.eh(err)
        }
        return
    }
}

func (s *Server) cleanup(conn net.Conn) {
    conn.Close()
    s.conns.Done()
}

client.go

package network

import (
    "encoding/gob"
    "net"
)

type Client struct {
    opts *Options
}

func NewClient(opts *Options) *Client {
    return &Client{opts: opts}
}

func (c *Client) Send(req interface{}) (res interface{}, err error) {
    conn, err := net.Dial(c.opts.Network, c.opts.Address)
    if err != nil {
        return nil, err
    }
    defer conn.Close()

    enc := gob.NewEncoder(conn)
    err = enc.Encode(&req)
    if err != nil {
        return nil, err
    }

    dec := gob.NewDecoder(conn)
    err = dec.Decode(&res)
    if err != nil {
        return nil, err
    }

    return res, nil
}


texts: Store history data using customization features of a profesionnal software

texts:
Context

My company uses a system that has access to the state of different items in the plant.

This software can be customized, by executing a single VBScript function, at a given interval.

The values taken by different variables in the system can be accessed using HMIRuntime.Tags("tagName").Read

Purpose

For trending purposes, I would like to store the values of some tags.

Code

Function action
    Const ForReading = 1
    Const ForAppending = 8

    Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
    Dim objFileToRead : Set objFileToRead = oFS.OpenTextFile(parameterListPath, ForReading)
    Dim params: Set params = CreateObject("System.Collections.ArrayList")

    objFileToRead.SkipLine 'Ditch first line (header)

    Do Until objFileToRead.AtEndOfStream
        params.add objFileToRead.ReadLine
    Loop
    objFileToRead.Close

    Dim param, new_value, current_time, objFileToWrite

    current_time = CStr(HMIRuntime.Tags("Time").Read)+","
    For Each param In params
        If Trim(CStr(HMIRuntime.Tags(param).Read)) = "" Then
            new_value = "no_value"
        Else
            new_value = Trim(Replace(CStr(HMIRuntime.Tags(param).Read),Chr(0),Chr(32)))
        End If
        Set objFileToWrite = oFS.OpenTextFile(Replace(archivePath,"{0}",param), ForAppending)
        objFileToWrite.WriteLine current_time + new_value
        objFileToWrite.Close
    Next
End Function

Expected take-ways from the review

Performance: The solution I chose, creating, then appending values in a text file is slow as hell, and I would like to improve that (with the limitation of having to use VBScript).
General quality of the code: As an industrial guy, I know VBA a bit, and I tried to make work with VBScript, but I am sure there is a lot of room for improvement.

Thanks a lot to the reviewers :)


texts: Restricted file upload to remote the Ruby way

texts:
I am using a Rails web app on the machine webapp, from which I call an action, that pushes a file to a remote server backend. Due to security reasons, we are using SSH keys and put the public part into user@backend:~/.ssh/authorized_keys. The keys are restricted, so the Rails app does not have full control over user, like this:

from="webapp",command="touch datafile; cat > datafile" ssh-rsa ...

The Ruby method looks like this

def self.push_file
  errors = `cat datafile | ssh -i id_rsa user@backend 'true' 2>&1`
  raise errors unless errors.empty?
end

What the Ruby code does is, it cats the file and then connects to backend via SSH, where it executes the "command" true, which then executes the command specified in the user@backend:~/.ssh/authorized_keys file (create datafile, write content). Lastly, the stdout is overwritten by stderr, so I can notice errors, which may occurr.

The solution works (it might be noteworthy, that datafile is always <100KiB), but seems dirty in three ways:

I am not using SCP for doing what is essentially a copy.

Possible fix: Find a way to restrict SCP to allow exactly this operation, nothing else

I am using neither Net::SSH nor Net::SCP, but instead raw commands, the first is due to the need of pipes in order to execute the first command on webapp and the second one on backend; and the latter due to the non-restriction of SCP.
stdout is overwritten by stderr in order to capture errors (least problematic, I know about popen)

Any suggestions on how to make the solution cleaner?


texts:
I just finished a program that is a simple Swing GUI. It takes in user info, such as password and username, turns them into strings, and puts them in a text file called nuserInfo.txt.

I just want corrections on how the code works and what I can do to improve my saving, GUI, and code in general. I'll post all the code below (just one class). Feel free to make any remarks, comments, criticism, or ask any questions in the comments below.

CreateAccount class:

package passwordProgram;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;

public class CreateAccount implements ActionListener {

    JFrame frame;
    JPanel panel;
    JTextField username;
    JPasswordField password;
    JPasswordField confirmPassword;
    JLabel warningLabel;

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        CreateAccount window = new CreateAccount();
        window.go();
    }

    public void go() {
        frame = new JFrame("Create a new account");
        panel = new JPanel();

        panel.setLayout(new GridBagLayout());

        frame.getContentPane().add(BorderLayout.CENTER, panel);
        panel.setBackground(Color.ORANGE);

        JLabel userLabel = new JLabel("Username:");
        JLabel passwordLabel = new JLabel("Password:");
        JLabel confirmPasswordLabel = new JLabel("Confirm Password:");
        username = new JTextField(15);
        password = new JPasswordField(15);
        confirmPassword = new JPasswordField(15);

        GridBagConstraints right = new GridBagConstraints();
        right.anchor = GridBagConstraints.WEST;
        GridBagConstraints left = new GridBagConstraints();
        left.anchor = GridBagConstraints.EAST;

        right.weightx = (int) 2;
        right.fill = GridBagConstraints.REMAINDER;
        right.gridwidth = GridBagConstraints.REMAINDER;
        // actual GUI

        panel.add(userLabel, left);
        panel.add(username, right);
        panel.add(passwordLabel, left);
        panel.add(password, right);
        panel.add(confirmPasswordLabel, left);
        panel.add(confirmPassword, right);

        frame.setSize(300, 250);
        frame.setVisible(true);

        JButton createAccount = new JButton("Create this account");
        frame.getContentPane().add(BorderLayout.SOUTH, createAccount);
        createAccount.addActionListener(this);

        warningLabel = new JLabel();
        frame.getContentPane().add(BorderLayout.NORTH, warningLabel);
    }

    // This is where the problem is!
    public void actionPerformed(ActionEvent event) {
        if (!(Arrays.equals(password.getPassword(), confirmPassword.getPassword()))) {
            warningLabel.setText("Your passwords do not match! Please try again.");
        } else if (password.getPassword().length < 1) {
            warningLabel.setText("That password is not long enough! Please try again!");
        } else {
            try {
                FileWriter writer = new FileWriter(new File("nuserInfo.txt"));
                writer.write(username.getText() + "/" + password.toString());
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


texts:
This is one of my first Python scripts and I was wondering if it meets the correct conventions. Also are there things that you would write different? I am looking for some good comments so I can start to improve my Python code from the start. (I was not supposed to use imports here)

Here's my implementation of Simplified DES:

__author__ = 'ßaron'

FIXED_IP = [2, 6, 3, 1, 4, 8, 5, 7]
FIXED_EP = [4, 1, 2, 3, 2, 3, 4, 1]
FIXED_IP_INVERSE = [4, 1, 3, 5, 7, 2, 8, 6]
FIXED_P10 = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
FIXED_P8 = [6, 3, 7, 4, 8, 5, 10, 9]
FIXED_P4 = [2, 4, 3, 1]

S0 = [[1, 0, 3, 2],
      [3, 2, 1, 0],
      [0, 2, 1, 3],
      [3, 1, 3, 2]]

S1 = [[0, 1, 2, 3],
      [2, 0, 1, 3],
      [3, 0, 1, 0],
      [2, 1, 0, 3]]

KEY = '0111111101'

def permutate(original, fixed_key):
    new = ''
    for i in fixed_key:
        new += original[i - 1]
    return new

def left_half(bits):
    return bits[:len(bits)/2]

def right_half(bits):
    return bits[len(bits)/2:]

def shift(bits):
    rotated_left_half = left_half(bits)[1:] + left_half(bits)[0]
    rotated_right_half = right_half(bits)[1:] + right_half(bits)[0]
    return rotated_left_half + rotated_right_half

def key1():
    return permutate(shift(permutate(KEY, FIXED_P10)), FIXED_P8)

def key2():
    return permutate(shift(shift(shift(permutate(KEY, FIXED_P10)))), FIXED_P8)

def xor(bits, key):
    new = ''
    for bit, key_bit in zip(bits, key):
        new += str(((int(bit) + int(key_bit)) % 2))
    return new

def lookup_in_sbox(bits, sbox):
    row = int(bits[0] + bits[3], 2)
    col = int(bits[1] + bits[2], 2)
    return '{0:02b}'.format(sbox[row][col])

def f_k(bits, key):
    L = left_half(bits)
    R = right_half(bits)
    bits = permutate(R, FIXED_EP)
    bits = xor(bits, key)
    bits = lookup_in_sbox(left_half(bits), S0) + lookup_in_sbox(right_half(bits), S1)
    bits = permutate(bits, FIXED_P4)
    return xor(bits, L)

def encrypt(plain_text):
    bits = permutate(plain_text, FIXED_IP)
    temp = f_k(bits, key1())
    bits = right_half(bits) + temp
    bits = f_k(bits, key2())
    print permutate(bits + temp, FIXED_IP_INVERSE)

def decrypt(cipher_text):
    bits = permutate(cipher_text, FIXED_IP)
    temp = f_k(bits, key2())
    bits = right_half(bits) + temp
    bits = f_k(bits, key1())
    print permutate(bits + temp, FIXED_IP_INVERSE)

encrypt('11101010')
decrypt('10100010')


texts:
I want to output only the roles that contain the same group as the user.

// User can be part of many groups
const user = {
  groups: ["group2"]
};

// Roles can have many groups
// What you see here is the output or 2 different data source
// Thats why we have group duplication inside different role
const roles = [{
  name: "role1",
  groups: [{
    id: "group1"
  }]
}, {
  name: "role2",
  groups: [{
    id: "group1"
  }, {
    id: "group2"
  }]
}];

const result = roles.filter(role => role.groups.filter(group => user.groups.indexOf(group.id) > -1).length)
console.log(result);

Is there a better way by using reduce or something else?


texts: Deleting a Specific Node from a Linked List

texts:
My go at creating a function to remove a specific node from a linked list:

void deleteSpecific(DataType N, Node *&H, Node *&T)
{
  if (H == nullptr) // 1. Check Whether List Is Empty (head == NULL)
  { // If It's Empty Then, Display The Following And Terminate The Function.
    std::cout << std::endl << std::endl;
    std::cout << "\t" << "-> LL| ERR: The List Is Empty. Deletion Not Possible.";
    std::cout << std::endl << std::endl;
    return;
  }
  Node *TMP1 = H, *TMP2; // If It's Not Empty Then, Define Two Node Pointers Temp1 And Temp2 And Put Head In Temp1 Only.
  while (TMP1->data != N) // Keep Moving Temp1 Until it reaches to exact node to delete
  {
    if (TMP1->next == nullptr) // If Node is not found in list then display the message and exit the loop and function.
    {
      std::cout << std::endl << std::endl;
      std::cout << "\t" << "-> LL| ERR: Given Node Not Found. Deletion Not Possible.";
      std::cout << std::endl << std::endl;
      return;
    }
    TMP2 = TMP1;
    TMP1 = TMP1->next;
  }
  if (H->next == nullptr)
  {
    H = nullptr;
    delete TMP1;
  }
  else if (TMP1 == H)
  {
    H = H->next;
    delete TMP1;
  }
  else if (TMP1->next == nullptr)
  {
    TMP2->next = nullptr;
    T = TMP2;
    delete TMP1;
  }
  else
  {
    TMP2->next = TMP1->next;
    delete TMP1;
  }
}

Is The logic of the code correct? I've tried it with multiple inputs and it works, however are there any special cases that you can notice that'll not work with this?


texts: Print tree level by level including Empty node

texts:
Here is my code to print tree in a level by level way. It needs to print an empty node as well to keep tree structure like full binary tree for elegancy reasons.

I'm wondering if anything you think could improve, including the efficiency and not sure if any bugs (I did testing, not found bugs). I'm especially wondering if for part of code -- "print the remaining all empty leaf node part" could be optimized (I mean if any smarted way to optimize the while loop to cover all logic, and skip this code snippet especially handling the last level).

The tree I tested in this example looks like:

 1
/ \
2  3
/\ /\
4  5 6

Here is the related output:

[1]
[2, 3]
[4, '$', 5, 6]
['$', '$', '$', '$', '$', '$', '$', '$']

class Node:
    def __init__(self):
        self.value = 0
        self.left = None
        self.right = None

def printTree(root):
    buf = []
    output = []
    if not root:
        print '$'
    else:
        buf.append(root)
        count = 1
        nextCount = 0
        while count > 0:
            node = buf.pop(0)
            if node:
                output.append(node.value)
                count -= 1
            else:
                output.append('$')
            if node and node.left:
                buf.append(node.left)
                nextCount += 1
            else:
                buf.append(None)
            if node and node.right:
                buf.append(node.right)
                nextCount += 1
            else:
                buf.append(None)
            if count == 0:
                print output
                output = []
                count = nextCount
                nextCount = 0
        # print the remaining all empty leaf node part
        for i in range(len(buf)):
            output.append('$')
        print output

if __name__ == "__main__":
    root = Node()
    root.value = 1
    leftNode = Node()
    leftNode.value = 2
    root.left = leftNode
    rightNode = Node()
    rightNode.value = 3
    root.right = rightNode
    leftleftNode = Node()
    leftleftNode.value = 4
    leftNode.left = leftleftNode
    rightleftNode = Node()
    rightleftNode.value = 5
    rightNode.left = rightleftNode
    rightrightNode = Node()
    rightrightNode.value = 6
    rightNode.right = rightrightNode

    printTree(newRoot)


texts: Trait class for a serialization framework

texts:
In a current project I have implemented a small non-intrusive serialization framework based on type traits. The generic trait template looks like this:

template<typename T>
class Serializable
{
public:
    static const bool isSerializableToString = false;

    static QString toString(const T &t) {
        (void) Error<T>::Trait_does_not_support_serialization_to_strings();
        return QString();
    }

    static T fromString(const QString &s, const T &defaultValue, bool *ok = 0) {
        (void) Error<T>::Trait_does_not_support_serialization_to_strings();
        return defaultValue;
    }

private:
    template<typename I>
    struct Error { };
};

To implement serialization for a certain type, this trait is specialized for this type, the isSerializableToString constant is defined true and the appropriate methods are implemented.

For types that do not support serialization I intended to raise a compile time error in the generic template.

I came along like 1000 solutions to accomplish this just on Stackoverflow. Among others variations, most solutions use static_asserts or SFINAE to various degrees. Yet, while following these solutions and experimenting, I came up with the above solution which seems to work like a charm.

In contrast to most SFINAE-based solutions, it is quite simple to understand (the (void) could even be removed), it does not rely on static_assert or the workarounds provided by, e.g. boost (unfortunately, static_assert is still not supported everywhere I need it) and it generates an error message as compact as

'Trait_does_not_support_serialization_to_strings' is not a member of 'Serializable<SomeType>::Error<SomeType>'
         (void) Error<T>::Trait_does_not_support_serialization_to_strings();

Now given the (imho) simplicity of this approach I am wondering if I am missing some caveat.

Specialization for types

QDate can easily be turned into a string representation by means of its builtin QDate::toString() and QDate::fromString() methods, so the specialization is merely a wrapper around those:

// Header
template<>
class Serializable<QDate>
{
public:
    static const char *const typeName;
    static QString toString(const QDate &value);
    static QDate fromString(const QString &s, const QDate &defaultValue, bool *ok = 0);
};

// Implementation
const char *const Serializable<QDate>::typeName = "date";

QString Serializable<QDate>::toString(const QDate &value) {
    return value.toString(Qt::ISODate);
}

QDate Serializable<QDate>::fromString(const QString &s, const QDate &defaultValue, bool *ok) {
    const QDate value = QDate::fromString(s, Qt::ISODate);
    if (ok)
        *ok = value.isValid();

    return value.isValid() ? value : defaultValue;
}

Other types may require more elaborate implementations. A specialization for bool could generate the strings true and false and it might be tolerant to accept others like yes/no and on/off. The specialization for QColor might convert hexadecimal color strings as used in HTML (#112233).

Usage

Usage should be straightforward:

QDate d = QDate::currentDate();
qDebug() << Serializable<QDate>::toString(d);


texts: Reading input from file for bridge simulation program

texts:
I am simulating a bridge where only one car can cross at a time. The bridge runs north south. The car arrival times and times taken to cross the bridge are given in an input file. The format is direction|arrival time,time taken to cross. The possible directions are north and south, represented by N/n and S/s respectively. An upper case letter means high priority and a lower case letter means low priority. The arrival times and time to cross are can have a value after the decimal e.g. 10.5
Examples:

N|6.0,10.0
n|4.5,5.5

Here is my function, which is pretty ugly but works:
void getInput(char * inFile)
{
    enum direction_t {NORTH, SOUTH};
    direction_t direction;
    enum priority_t {HIGH, LOW};
    priority_t priority;
    string line;
    ifstream inFile(inFile);
    if(!inFile.good())
    {
        cerr << "can't open input file";
        exit(1);
    }
    while(getline(inFile, line))
    {
        char first = line.at(0);//first letter signifies direction and priority
        if(first == 'n')
        {
            direction = NORTH;
            priority = LOW;
        }
        else if(first == 'N')
        {
            direction = NORTH;
            priority = HIGH;
        }
        else if(first == 's')
        {
            direction = SOUTH;
            priority = LOW;
        }
        else if(first == 'S')
        {
            direction = SOUTH;
            priority = HIGH;
        }
        else
        {
            cerr << "invalid direction given: " << first << endl;
            //exit(1);
        }
        size_t commaIndex = line.find(",", 2);//know first character is letter, second is |
        string firstNumber = line.substr(2, commaIndex-2);
        string secondNumber = line.substr(commaIndex+1, line.length());
        cout << "firstNumber: " << firstNumber << " secondNumber " << secondNumber << endl;
    }

I was wondering if the way I use enum is good. Any tips for making code more readable and more compact are appriaciated.


texts: Templating libraries' intelligibility and their performance (compared to mine)

texts:
I've just started writing my own little templating library in JavaScript, because as I went through others, there is always this voice in head, which says: "Oh, this is a lot of code and functionality. Is that really necessary or would it slow down the performance?"

If you are able to follow conventions, you would probably run into less issues.

So I ended up with this little script with the upper quote in my head.  The convention, here is that data needs an object and its keys must be the same like in template, mentioned between those delimiter-brackets "{{key}}"

function Template(url, data) {

    this.url = url;
    this.data = data;

    this.delimiter = ['{{','}}'];

    this.load = function() {

        var string = new String();

        var http = null;
        if ( window.XMLHttpRequest ) {
            http = new XMLHttpRequest();
        } else {
            http = new ActiveXObject("Microsoft.XMLHTTP");
        }

        http.open('GET', url, false);
        http.onreadystatechange = function() {
            if ( http.readyState === 4 ) {
                string = http.response;
            }
        };
        http.send(null);

        this.template = string;
        return this;

    };

    this.exchange = function() {

        for ( var key in this.data ) {

            var bracketedKey = this.delimiter[0] + key + this.delimiter[1];
            var indexOfKey = this.template.indexOf(bracketedKey);
            var lengthOfKey = bracketedKey.length;

            var exchange = this.template.substring(indexOfKey, indexOfKey+lengthOfKey);

            this.template = this.template.replace(exchange, this.data[key]);

        }

        return this;

    };

    this.build = function(selector) {

        this.load();
        this.exchange();

        var div = document.createElement('div');
        div.innerHTML = this.template;
        div = div.firstChild;

        if ( typeof selector === 'string' ) {
            document.querySelector(selector).appendChild(div);
        } else {
            return div;
        }

    };

}

But now I've started thinking about the fact, that other libraries include more code than mine and there must be a reason for it, mustn't it?

There also a few more things that are coming to my head, like:

Less code = better performance?
Why do so many people relate their projects with this templating library?
(Matter of performance => that would refute my first point)

It'd be cool if someone could explain me a few things about this topic.

Am I right with my mindset?
When I am right, is there something that I could improve, or even when I am wrong?
If you would recommend a library to me, what is your reason?


texts: Raspberry Pi Safe Clean Up - the decorator way

texts:
Yesterday, I've come up with the idea of using python context manager to ensure cleanup available here. This time I am using that context manager to make a decorator.

The context manager

# SafeGPIO.py
# updated, warning silenced

from RPi import GPIO
from exceptions import RuntimeWarning
import warnings

class SafeGPIO(object):

    def __enter__(self):
        return GPIO

    def __exit__(self, *args, **kwargs):
        with warnings.catch_warnings():
            warnings.simplefilter("error") #turn warning into exceptions
            try:
                GPIO.cleanup()
            except RuntimeWarning:
                pass # silence it

The decorator

#decorators.py

from . import SafeGPIO
from RPi import GPIO
from functools import wraps

def safe_gpio(func):
    """
    This decorator ensure GPIO.cleanup() is called when function call ends,
    also it injects GPIO as first argument into your function
    """
    @wraps(func) # using wraps preservses doc string
    def wrapper(*args, **kwargs):
        with SafeGPIO() as GPIO:
            return func(GPIO, *args, **kwargs)
    return wrapper

def gpio(func):
    """
    This decorator injects GPIO as first argument into your function
    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(GPIO, *args, **kwargs)
    return wrapper

Use like this:

# decorator_test.py

from SafeGPIO.decorators import safe_gpio, gpio
from time import sleep
from random import choice, randint

GPIO_PINS = (3,5,7,8,10,11,12,13,15,16,18,19,21,22,23,24,26)
VALUES = (True, False)

@safe_gpio
def do_random_things_with_pins_for_ten_times(GPIO):
    GPIO.setmode(GPIO.BOARD)
    for pin in GPIO_PINS:
        GPIO.setup(pin, GPIO.OUT)
    for _ in xrange(10):
        pin = choice(GPIO_PINS)      # choose one of the GPIO pin
        value = choice(VALUES)       # output either true or false
        sleep_seconds = randint(1,3) # sleep from 1 to 3 seconds
        print "slected pin %d, output %r, sleep for %d seconds" %
                (pin, value, sleep_seconds)
        GPIO.output(pin, value)
        sleep(sleep_seconds)

@safe_gpio
def do_real_work(GPIO):
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(7, GPIO.OUT)
    print "doing real work for 5 seconds"
    GPIO.output(7, True)
    sleep(5)

@safe_gpio # guarantee to clean up on exit
def main(GPIO):
    do_random_things_with_pins_for_ten_times()
    do_real_work()

if __name__ == '__main__':
    main()


texts: Finding the Minimum and Maximum Value in an Image

texts:
Given an image which is padded to support aligning (SSE) I need to find its minimum and maximum value as fast as possible.
Mind you the padded values are not defined and can't be assumed to have certain values.

This is the code I created:

void ExtractMinMax(float* vMinMax, float* mI, int numRows, int numCols, int numColsPad)
{

    int ii, jj, numColsSse;

    __m128 pxI;
    __m128 minVal;
    __m128 maxVal;

    numColsSse = numCols - (numCols % SSE_STRIDE);

    minVal = _mm_loadu_ps(&mI[0]);
    maxVal = _mm_loadu_ps(&mI[0]);

    for (ii = 0; ii < numRows; ii++) {
        for (jj = 0; jj < numColsSse; jj += SSE_STRIDE) {

            pxI     = _mm_loadu_ps(&mI[(ii * numColsPad) + jj]);
            minVal  = _mm_min_ps(minVal, pxI);
            maxVal  = _mm_max_ps(maxVal, pxI);

        }
    }

    vMinMax[0] = HorizontalMinSse(minVal);
    vMinMax[1] = HorizontalMaxSse(maxVal);

    for (ii = 0; ii < numRows; ii++) {
        for (jj = numColsSse + 1; jj < numCols; jj++) {

            if (mI[(ii * numColsPad) + jj] < vMinMax[0]) {
                vMinMax[0] = mI[(ii * numColsPad) + jj];
            }

            if (mI[(ii * numColsPad) + jj] > vMinMax[1]) {
                vMinMax[1] = mI[(ii * numColsPad) + jj];
            }

        }
    }

}

The horizontal min / max are given by (following Peter Cordes' advice):

static inline float HorizontalMaxSse(__m128 x) {
    // Calculates the sum of SSE Register - http://stackoverflow.com/a/35270026/195787
    __m128 shufReg, sumsReg;
    shufReg = _mm_movehdup_ps(x);        // Broadcast elements 3,1 to 2,0
    sumsReg = _mm_max_ps(x, shufReg);
    shufReg = _mm_movehl_ps(shufReg, sumsReg); // High Half -> Low Half
    sumsReg = _mm_max_ss(sumsReg, shufReg);
    return  _mm_cvtss_f32(sumsReg); // Result in the lower part of the SSE Register
}

static inline float HorizontalMinSse(__m128 x) {
    // Calculates the sum of SSE Register - http://stackoverflow.com/a/35270026/195787
    __m128 shufReg, sumsReg;
    shufReg = _mm_movehdup_ps(x);        // Broadcast elements 3,1 to 2,0
    sumsReg = _mm_min_ps(x, shufReg);
    shufReg = _mm_movehl_ps(shufReg, sumsReg); // High Half -> Low Half
    sumsReg = _mm_min_ss(sumsReg, shufReg);
    return  _mm_cvtss_f32(sumsReg); // Result in the lower part of the SSE Register
}

It's a really straightforward implementation using SSE, yet it seems it is not so fast.
For instance, MATLAB's min() and max() running sequencely are 10 times faster.

The code was compiled into DLL using Visual Studio 2017 Update 3.
Timing was done using MATLAB's tic() / toc().

What can be done to make it faster?


texts:
I'm new to Elixir, and in order to learn the syntax, I'm doing a roman numeral kata which converts a decimal number into roman numeral. I would appreciate any feedback you have.

defmodule RomanNumeral do

  @decimal_roman_numerals [[5, 'V'], [4, 'IV'], [1, 'I']]

  def converts(number) do
    converts(number, [], @decimal_roman_numerals)
  end

  def converts(number, roman_value, _) when number < 1 do
    roman_value
  end

  def converts(number, roman_value, [[decimal, roman] | numerals]) when number >= decimal do
    converts(number - decimal, roman_value ++ roman, [[decimal, roman] | numerals])
  end

  def converts(number, roman_value, [_ | numerals]) do
    converts(number, roman_value, numerals)
  end
end


texts:
I'm trying to make a safe "remember me / auto login" function on my site and as I'm just a hobby programmer I would like someone professional to take a look at my code this far. This site will probably never see the light of day I'm just doing this because I find it fun and learning, but I still like to do it correct. I have read this.

Login.php

$query = $db->prepare('SELECT id, username, password FROM users WHERE username = ? OR email = ?');
$query->execute(array($_POST['username'], $_POST['username']));
$row = $query->fetch();

if ($row and password_verify($_POST['password'], $row['password'])) {

    // Remember?
    if (isset($_POST['remember'])) {

        $selector = base64_encode(random_bytes(9));
        $authenticator = random_bytes(33);

        setcookie('remember', $selector.':'.base64_encode($authenticator), time() + 864000);

        $query = $db->prepare('INSERT INTO auth_tokens (selector, token, userid, expires) VALUES (?, ?, ?, ?)');
        $query->execute(array(   $selector, hash('sha256', $authenticator), $row['id'], date('Y-m-d\TH:i:s', time() + 864000)  ));
    }

    $_SESSION['userid'] = $row['id'];
    $_SESSION['username'] = $row['username'];

    exit(header('Location: /'));
}

This is my logout:

session_destroy();

if (!empty($_COOKIE['remember'])) {
    setcookie('remember', '', time() - 1000);
    $db->exec('DELETE FROM auth_tokens WHERE userid = '.$_SESSION['userid']);
}

exit(header('Location: '.SITE_URL));

And this is my code in index.php to check if the user has the cookie and log them in:

if (empty($_SESSION['userid']) && !empty($_COOKIE['remember'])) {

    list($selector, $authenticator) = explode(':', $_COOKIE['remember']);

    $query = $db->prepare('SELECT * FROM auth_tokens WHERE selector = ?');
    $query->execute(array($selector));
    $row = $query->fetch();

    if (hash_equals($row['token'], hash('sha256', base64_decode($authenticator)))) {
        $_SESSION['userid'] = $row['userid'];
    }
}

One thing I need to do is check if the cookie has expired and log them out, but other than that what do you think? Am I missing something?


texts: Edit file name method - run time complexity

texts:
I wrote a function in Java that edit file name, and replace each space char into dash char.
Currently I iterate all the files in a specific directory, iterate in each file name, creating a new file name, and replace the file in the directory.

  I guess that the current complexity is \$O(N*M)\$ with

  \$N\$ being the number of files in directory and
  \$M\$ being the number of chars in each file.

Can the run-time-complexity be improved?

public static void editSpace(String source, String target) {

    // Source directory where all the files are there
    File dir = new File(source);
    File[] directoryListing = dir.listFiles();

    // Iterate in each file in the directory
    for (File file : directoryListing) {

        String childName = file.getName();
        String childNameNew = "";

        // Iterate in each file name and change every space char to dash char
        for (int i = 0; i < childName.length(); i++) {

            if (childName.charAt(i) == ' ') {
                childNameNew += "-";
            } else {
                childNameNew += childName.charAt(i);
            }
        }

        // Update the new directory of the child
        String childDir = target + "\\" + childNameNew;

        // Renaming the file and moving it to a new location
        if (!(childNameNew.equals(""))
                && (file.renameTo(new File(childDir)))) {

            // If file copied successfully then delete the original file .
            file.delete();

            // Print message
            System.out.println(childName + " File moved successfully to "
                    + childDir);
        }

        // Moving failed
        else {
            // Print message
            System.out.println(childName + " Failed to move the file to "
                    + childDir);
        }
    }

}


texts: Reading a line ending with a newline character from a file descriptor

texts:
I'm implementing a function that behaves like getline() which reads a line from file descriptor and returns the results without \n. allowed functions, read(), free() and malloc. Please review my code.

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#ifndef GET_C_BUFF_SIZE
# define GET_C_BUFF_SIZE 1023
#endif
#ifndef BUFF_SIZE
# define BUFF_SIZE 32
#endif

void    *my_memcpy(void *dest, const void *src, size_t n)
{
    unsigned char       *n_dest;
    const unsigned char *n_src;

    n_dest = (unsigned char *)dest;
    n_src = (unsigned char *)src;
    while (n--)
        *n_dest++ = *n_src++;
    *(++n_dest) = '\0';
    return (dest);
}

void    *my_realloc(void *ptr, size_t len)
{
    void    *real;

    real = malloc(len);
    if (real)
        my_memcpy(real, ptr, len);
    free(ptr);
    return (real);
}

int my_getchar(const int fd)
{
    static char buff[GET_C_BUFF_SIZE];
    static char *chr;
    static int  pos = 0;
    static int  ret = 0;

    if (pos >= ret)
    {
        if ((ret = read(fd, buff, GET_C_BUFF_SIZE)) > 0)
        {
            chr = buff;
            pos = 0;
            return (*(chr + pos++));
        }
        else
            return (0);
    }
    else
        return (*(chr + pos++));
}

int read_line(char *text, int buf_size, char **line, const int fd)
{
    int     position;
    int     c;

    position = 0;
    while (1)
    {
        c = my_getchar(fd);
        if (c == 0 || c == '\n')
        {
            text[position] = '\0';
            *line = text;
            return (1);
        }
        else
            text[position] = c;
        position++;
        if (position >= buf_size)
        {
            buf_size += BUFF_SIZE;
            text = my_realloc(text, buf_size);
            if (!text)
                return (-1);
        }
    }
    return (1);
}

int get_line(const int fd, char **line)
{
    char    *text;
    int     buf_size;

    buf_size = BUFF_SIZE;
    text = malloc(sizeof(char) * buf_size);
    if (fd < 0 || !text || !line)
        return (-1);
    return (read_line(text, buf_size, line, fd));
}


texts:
I've built a Palindrome checker in JavaScript. It's fairly simple.

I'm still learning JS and am looking to learn.

So I would love hear ideas on how to improve the JavaScript in this. Like more efficient ways to resolve the task of checking for Palindrome.

Source code is below. Link to CodePen is her: http://codepen.io/MarkBuskbjerg/pen/JWMWwN?editors=1010

HTML:

Palindrome checker

A nut for a jar of tuna

                <textarea class="col-md-12" id="inputPalindrome" rows="5">Borrow or rob?</textarea>

            <button id="checkPalindrome" class="btn btn-default btn-lg btn-block col-sm-6 col-sm-offset-4" type="submit">Check palindrome</button>

Palindrome has not been checked yet

CSS:

.cover {
  height: 100vh;
}

.row-margin {
  margin: 4vh auto;
}

body {
  background: #FF4E50;
  background: -webkit-linear-gradient(135deg, #FF4E50, #F9D423);
  background: linear-gradient(135deg, #FF4E50, #F9D423);
}

.header {
  color: #fff;
}

h1 {
  font-family: "Pacifico";
}

.btn-default {
  background-color: black;
  color: #fff;
  font-weight: bold;
  text-transform: uppercase;
 }

JavaScript:

var checkButton = document.getElementById("checkPalindrome");

function isPalindrome(str) {
    str = str.toLowerCase().replace(/[^a-z0123456789]+/g,"");
    var reversedStr = str.split("").reverse().join("");
    if (str == reversedStr) {
        return true
    }
    return false
}

checkButton.addEventListener("click", function() {
    var palindromeInput = document.getElementById("inputPalindrome").value;
    var palindromeReturn = isPalindrome(palindromeInput);
    if(palindromeReturn === true) {
        document.getElementById("notification").innerHTML = "Yay! You've got yourself a palindrome";
        document.getElementById("notification").className = "alert alert-success";
    } else {
        document.getElementById("notification").innerHTML = "Nay! Ain't no palindrome";
        document.getElementById("notification").className = "alert alert-danger";
    }
});

Link to CodePen with the Palindrome Checker
http://codepen.io/MarkBuskbjerg/pen/JWMWwN


texts:
My code below uses JSON to append images into the DOM. It works properly but I want to optimize my JavaScript to see if I can write it in fewer lines or if there are methods I can use that optimize my code.

Questions

Is a more efficient way to write my code, considering there are many operations happening at once?
Are my functions nested properly?
Can I write this in fewer lines?

I also did up a fiddle.

HTML

JavaScript

function append(v) {
  var grid = $('#columns')[0];
  var item = document.createElement('div');
  var win = $(window, document);
  var allMods = $('.module');
  var h = '
';
      h += '
';
      h += '';
      h += '
';
      h += '
';
      salvattore['append_elements'](grid, [item]);
      item.outerHTML = h;

      // http://codepen.io/chriscoyier/pen/DjmJe
      // slide in feature
      allMods.each(function(i, el) {
        var el = $(el);
        if (el.visible(true)) {
          el.addClass('already-visible');
        }
      });

      win.scroll(function(event) {
        allMods.each(function(i, el) {
          var el = $(el);
          if (el.visible(true)) {
            el.addClass('come-in');
          }
        });
      });

      var insertPrint = $('.carousel-inner');
      insertPrint.append('

');

      var modalClick = $('.module');
      modalClick.on('click', function(){
       var found = $(this).attr("data-src");
       insertPrint.find("[data-src='" + found + "']").parent().addClass("active");
      });
}

var dataJson = 'https://api.myjson.com/bins/1mb96';
$.getJSON(dataJson, function (data) {
 $.each(data.printImages,function (k, v) {
  append(v);
 });
});


texts:
I am new to JavaScript. I've recently completed first 10 Chapters of "JavaScript: The Good Parts".

I've coded this small program to find maximum subarray of an array and would appreciate your feedback on the structure of the program (from JavaScript's point of view). I am basically looking for suggestions in following areas:

Objects being returned
Usage of Infinity
Usage of non-pure functions
Closures

Here is the code:

// Max. subarray from CLRS
var maxsubarr = function (arr) {
    var that  = {};

    var max_cross_subarr = function (low, mid, high) {
        var left_sum = -Infinity;
        var right_sum = -Infinity;
        var max_low;
        var max_high;

        var sum = 0;
        var i;
        for (i=mid; i >=low; i--) {
            sum = sum + arr[i];
            if (sum > left_sum) {
                left_sum = sum;
                max_low = i;
            }
        }
        sum = 0;
        for (i=mid+1; i <=high; i++) {
            sum = sum + arr[i];
            if (sum > right_sum) {
                right_sum = sum;
                max_high = i;
            }
        }

        return {
            low: max_low,
            high: max_high,
            sum: left_sum + right_sum
        };
    }

    var max_sub_arr = function (low, high) {
        var leftarr, rightarr, mid;
        if (low === high) {
            return {
                low: low,
                high: high,
                sum: arr[low]
            };
        }
        else {
            mid = Math.floor((high+low)/2);
            leftarr = max_sub_arr (low, mid);
            rightarr = max_sub_arr (mid+1, high);
            crossarr = max_cross_subarr (low, mid, high);

            if (leftarr.sum >= rightarr.sum && leftarr.sum >= crossarr.sum) {
                return leftarr;
            } else if (rightarr.sum >= leftarr.sum && rightarr.sum >= crossarr.sum) {
                return rightarr;
            } else {
                return crossarr;
            }
        }
    }

    that.find = function () {
        return max_sub_arr (0, arr.length - 1);
    }

    return that;
}

var mb = maxsubarr ([13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]);
console.log(mb.find());


texts: OpenSSL PBKDF2-HMAC-SHAx proof of concept

texts:
I have regrettably been away from C programming for a very long time, so I'd like to get a quick code review of a first proof of concept, before I get too far into adding capabilities, using the getopt library for arguments, alternate output and input character sets, a PolarSSL implementation, and so on and so forth.

Target platforms: gcc 4.5+ for MinGW for Windows, gcc 4.7+ for Linux.

My ranking of concerns:

Security holes
Incorrect use of OpenSSL
Memory leaks
Performance
Suboptimal or incorrect compilation commands
Inefficient code
deviations from ANSI C/portability
Unclean code
Suggestions for improvement
other

As a purely secondary interest, if anyone has advice on the getopt library, C code for Base32/Base64/etc output formats, or PolarSSL use, I'd appreciate it.

Linux compilation:

gcc -O3 -lssl pbkdf2.c -o pbkdf2

Windows compilation:

gcc -O3 -I OpenSSLLibraryPath\include -L OpenSSLBinariesPath -leay32 pbkdf2.c -o pbkdf2

The code:

#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <openssl/evp.h>
#include <openssl/sha.h>

// Originally from http://stackoverflow.com/questions/10067729/fast-sha-2-authentication-with-apache-is-it-even-possible

void PBKDF2_HMAC_SHA_256(const char* pass, const unsigned char* salt, int32_t iterations, uint32_t outputbytes, char* HexResult)
{
    unsigned int i;
    unsigned char digest[outputbytes];
    PKCS5_PBKDF2_HMAC(pass, strlen(pass), salt, strlen(salt), iterations, EVP_sha256(), outputbytes, digest);
    for (i = 0; i < sizeof(digest); i++)
        sprintf(HexResult + (i * 2), "%02x", 255 & digest[i]);
}

void PBKDF2_HMAC_SHA_512(const char* pass, const unsigned char* salt, int32_t iterations, uint32_t outputbytes, char* HexResult)
{
    unsigned int i;
    unsigned char digest[outputbytes];
    PKCS5_PBKDF2_HMAC(pass, strlen(pass), salt, strlen(salt), iterations, EVP_sha512(), outputbytes, digest);
    for (i = 0; i < sizeof(digest); i++)
        sprintf(HexResult + (i * 2), "%02x", 255 & digest[i]);
}

int main(int argc, char *argv[])
{
  printf("Usage: %s SHA-512|SHA-256 password salt iterations outputlengthinbytes\nSHA-512 is recommended (for password hashing, outputlengthinbytes <= 64)\nSHA-256 is not as good, (for password hashing, outputlengthinbytes <= 32)\n",argv[0]);
  if(argc != 6){printf("Incorrect number of parameters.\n");return 2;};
  char pass[strlen(argv[2])];
  unsigned char salt[strlen(argv[3])];
  int32_t iterations;
  uint32_t outputbytes;

  strcpy(pass,argv[2]);
  strcpy(salt,argv[3]);
  iterations = atoi(argv[4]);
  outputbytes = atoi(argv[5]);
  printf("\n%s\n",argv[1]);

  char HexResult[2*outputbytes-1];

//    printf("Computing PBKDF2(HMAC-SHA512, '%s', '%s', %d, %d) ...\n", pass, salt, iterations, outputbytes);
  memset(HexResult, 0, outputbytes);
  if (strcmp(argv[1],"SHA-512")==0)
    {
    PBKDF2_HMAC_SHA_512(pass, salt, iterations, outputbytes, HexResult);
    }
  else if (strcmp(argv[1],"SHA-256")==0)
    {
    PBKDF2_HMAC_SHA_256(pass, salt, iterations, outputbytes, HexResult);
    }
  else
    {
    printf("Invalid value for hash - choose one of:\nSHA-512\nSHA-256\n");
    return 1;
    }

  printf("Result: in Base16 (hex)\n%s\n", HexResult);
  return 0;
}


texts: Using third party library named "nsetools" for fetching stock data

texts:
I want to make the code shorter.  Is there any way to loop through the stocks and qty dictionaries, access the closing prices of each individual stock and then calculate the current value of the investment preferably in one or two lines?

from nsetools import Nse
nse = Nse()

#stock name and buy price pair, but not used in my method below. I would  like a method that uses it though.
stocks = {
    "ADANIPORTS" : 284.95,
    "HINDALCO"   : 152.30,
    "ONGC"       : 279.70,
    "SBIN"       : 259.70
}

#stock name and quantity of stocks
qty = {
    "ADANIPORTS" : 20,
    "HINDALCO"   : 20,
    "ONGC"       : 20,
    "SBIN"       : 20
}

### Adaniports
#Fetches a dictionary with data such as best buy/sell prices, 'closePrice', etc.
stock1      = nse.get_quote('ADANIPORTS')
#Accessing the 'closePrice' from the above dictionary.
stock1Close = stock1['closePrice']

### Hindalco
stock2      = nse.get_quote('HINDALCO')
stock2Close = stock2['closePrice']

### ONGC
stock3      = nse.get_quote('ONGC')
stock3Close = stock3['closePrice']

### SBIN
stock4      = nse.get_quote('SBIN')
stock4Close = stock4['closePrice']

current_value = (stock1Close * qty['ADANIPORTS']) + (stock2Close * qty['HINDALCO']) + (stock3Close * qty['ONGC']) + (stock4Close * qty['SBIN'])


texts: Determining a salary for buying a house in 36 months

texts:
I did this programming challenge. Part C of the challenge, is to find the salary you have to save every month to be able to buy a house in 36 months.

This is my first time using bisection search so I just want to make sure that I did it correctly. I question the efficiency of my program because in test case 2 for part C, the supposed number of guesses is 9, but my program guesses 13 times.

annual_salary = int(input('Enter your annual salary.'))
total_cost = 1000000
semi_annual_raise = .07
portion_down_payment = total_cost * 0.25
current_savings = 0
r = 0.04
guesses = 1
low = 0
high = 1

while abs(portion_down_payment-current_savings) > 100:
    portion_saved = (low + high) / 2
    salary = annual_salary
    current_savings = 0

    for month in range(1, 37):
        if month % 6 == 1 and month != 1:
            salary += salary*semi_annual_raise
        current_savings += current_savings*r/12
        current_savings += salary/12 * portion_saved

    if current_savings >= portion_down_payment:
        high = portion_saved
    elif current_savings < portion_down_payment:
        low = portion_saved

    portion_saved = (low+high)/2
    guesses += 1

print(portion_saved, guesses)


texts: Extracting the first two initials of a person's name

texts:
I've come up with a hackish approach to get my XSL function to only return the first 2 initials of a person. I think there should be a more efficient way to do this though. The replace specifically is what I think I should be able to get rid of, looking through docs though I can't figure out how to correctly iterate with the split.

So 5 examples of my XML:

<name>
    <surname>Test I</surname>
    <given-names>Chris</given-names>
</name>
<name>
    <surname>Test II</surname>
    <given-names>Chris Chris</given-names>
</name>
<name>
    <surname>Test III</surname>
    <given-names>Chris Eat Meat</given-names>
</name>
<name>
    <surname>Test IV</surname>
    <given-names>Chris-Eat Meat</given-names>
</name>
<name>
    <surname>Test V</surname>
    <given-names>Chris-Eat-Meat</given-names>
</name>

My function call:

<xsl:value-of select="pull_it:get_initials(name/given-names/text())"/> <!-- name/given-names -->

and my inefficient XSL function:

<xsl:function name="pull_it:get_initials">
    <xsl:param name="names"/>
    <xsl:value-of select="
            replace(string-join(
                for $token in tokenize($names,'(-|\s+)')[string-length(.) > 0]
                    return concat(substring($token,1,1),'.'),
                ''), '(\w\.\w?\.?).*', '$1')
                    "/>
</xsl:function>

So with the first two XML blocks the expected output/return is:

C.

and

C. C.

The remaining three should return (as expected, no M. because we only want the first 2 initials)

C. E.

but I thought there would be a way to stop the iteration. For example my PHP just has:

$abbreviated_firstnames = array();
$firstnames = mb_split('(\s+|-)', html_entity_decode($this->firstname,ENT_QUOTES,'UTF-8'));
$intial_count = 0;
foreach ($firstnames as $firstname) {
    $intial_count++;
    $firstinit = mb_substr($firstname,0,1,'UTF-8');
    if ($firstinit) {
        $abbreviated_firstnames[] = $firstinit . '.';
        if($intial_count >= 2) {
            break; // <---- we got 2 matches stop NOW
        }
    }
}
return implode(' ',$abbreviated_firstnames);


texts: Bash script to swap out, edit host files

texts:
This is my first useful bash script. It's meant to make it easy to switch between a "work" hosts file (that blocks sites like reddit.com, youtube.com, etc.) and my normal hosts file, and also to allow me to easily add/remove sites I want to block.

I'm not sure if I'm doing everything right or securely, so please feel free to pick at anything.

#!/bin/bash

usage()
{
cat <<EOF
Usage: wrk [command] [host1 host2 ...]

Commands:
    list                list blocked hosts
    add [host ...]      add a host to be blocked
    rm [host ...]       remove hosts from block
    start               start blocking
    stop                stop blocking
EOF
}

VARDIR="$HOME/abes_commands/var"
# HOST_FILE - actual host file to be swapped around.
# ORIG_FILE - original host file without any of the appended blocked hosts.
# BLCK_FILE - list of blocked hosts.
# BLCK_TEMP - temporary file used when removing hosts.
HOST_FILE="/etc/hosts"
ORIG_FILE="$VARDIR/original_host"
BLCK_FILE="$VARDIR/blocked_host"
BLCK_TEMP=`mktemp -t "blocked_hosts"` || `mktemp /tmp/blocked_hosts.XXXXXXX` || exit 1

# Make sure files exist.
[[ -e $ORIG_FILE ]] || touch "$ORIG_FILE"
[[ -e $BLCK_FILE ]] || touch "$BLCK_FILE"

# Check to see if the block is currently active.
ACTIVE_FLAG="$HOME/.wrk_block.flag"
if [[ -e $ACTIVE_FLAG ]]; then
    IS_ACTIVE=0
else
    IS_ACTIVE=1
fi

add_host()
{
    local hosts=("$@")
    for host in "${hosts[@]:1}"; do
        # append host to blocked hosts list
        echo "127.0.0.1 $host" >> "$BLCK_FILE"
        echo -e "\033[0;32madded\033[0m $host"
    done
}

# todo: remove need for loop; do in one go
rm_host()
{
    local hosts=("$@")
    for host in "${hosts[@]:1}"; do
        # overwrite host list file with a copy removing a certain host
        awk -v host=$host 'NF==2 && $2!=host { print }' "$BLCK_FILE" > "$BLCK_TEMP"
        mv "$BLCK_TEMP" "$BLCK_FILE"
        echo -e "\033[0;31mremoved\033[0m $host"
    done
}

check_root()
{
    if [[ "`whoami`" != "root" ]]; then
        echo "You don't have sufficient priviledges to run this script (try sudo.)"
        exit 1
    else
        [[ -e $HOST_FILE ]] || { echo "Can't find or access host file."; exit 1; }
    fi
}

start_block()
{
    if [[ $IS_ACTIVE -ne 0 ]]; then
        cp "$HOST_FILE" "$ORIG_FILE"
        cat "$BLCK_FILE" >> "$HOST_FILE"
        touch "$ACTIVE_FLAG"
        echo "Block started."
    else
        echo "Already blocking."
    fi
}

stop_block()
{
    if [[ $IS_ACTIVE -eq 0 ]]; then
        cp "$ORIG_FILE" "$HOST_FILE"
        [[ -e $ACTIVE_FLAG ]] && rm "$ACTIVE_FLAG"
        echo "Stopped blocking."
    else
        echo "Not blocking."
    fi
}

case $1 in
    'ls' | 'list')
        awk 'NF == 2 { print $2 }; END { if (!NR) print "Empty" }' "$BLCK_FILE";;
    'add')
        [[ -z $2 ]] && { usage; exit 1; }
        add_host $@;;
    'rm' | 'remove')
        [[ -z $2 ]] && { usage; exit 1; }
        rm_host $@;;
    'start')
        check_root
        start_block;;
    'stop')
        check_root
        stop_block;;
    *)
        usage;;
esac

The blocked_host file is appended to the hosts file when blocking starts, and looks like this:

127.0.0.1 www.reddit.com
127.0.0.1 reddit.com
127.0.0.1 www.news.ycombinator.com
127.0.0.1 news.ycombinator.com


texts: Correct way to assign variables before a try/catch/finally

texts:
using Excel = Microsoft.Office.Interop.Excel

...

Excel.Application app = null;
Excel.Workbooks books = null;
Excel.Workbook book = null;

object[,] data;

try
{
    app = new Excel.Application();
    books = app.Workbooks;
    book = books.Open("C:\...");

    Excel.Worksheet sheet = book.Worksheets[1];
    Excel.Range range = sheet.UsedRange;
    data = range.Value;
}
catch (Exception ex)
{
    throw ex;
    //To Do...
}
finally
{
    book.Close();
    app.Quit();
}

//code that the uses data object from above e.g.
...

In the code above I have to declare the objects app, books and book outside of the try block so that I have access to them in the finally block. However if I do not assign anything to them (i.e. Excel.Application app; instead of Excel.Application app = null;) then the compiler complains about the line app.Quit() saying "Use of unassigned local variable...". So is it correct to assign null to app etc in this case?

Also books doesn't get used in the finally block so is it better to declare it as I have, or should I declare it in the try block?


texts: Counting intersections of wires between towers

texts:
The "Rope Intranet" problem from Google Codejam 2010 asks us to count the number of intersections (black circles) in a planar straight-line graph like this:

That is, with each line segment having one endpoint with \$x=x_0\$ and the other with \$x=x_1\$.

  Input

  The first line of the input gives the number of test cases, \$T\$. \$T\$ test cases follow. Each case begins with a line containing an integer \$N\$, denoting the number of wires you see.

  The next \$N\$ lines each describe one wire with two integers \$A_i\$ and \$B_i\$. These describe the windows that this wire connects: \$A_i\$ is the height of the window on the left building, and \$B_i\$ is the height of the window on the right building.

  Output

  For each test case, output one line containing "Case #\$x\$: \$y\$", where \$x\$ is the case number (starting from 1) and \$y\$ is the number of intersection points you see.

  Sample input

2
3
1 10
5 5
7 7
2
1 1
2 2

  Sample output

Case #1: 2
Case #2: 0

I have a working solution, but the time complexity is awful. Here is my code:

def solve(wire_ints, test_case):
    answer_integer = 0
    for iterI in range(number_wires):
        for iterJ in range(iterI):
            holder = [wire_ints[iterI], wire_ints[iterJ]]
            holder.sort()
            if holder[0][1] > holder[1][1]:
                answer_integer = answer_integer + 1
    return("Case #" + str(test_case) + ":" + " " + str(answer_integer))

for test_case in range(1, int(input()) + 1):
  number_wires = int(input())
  wire_ints = []
  for count1 in range(number_wires):
    left_port,right_port = map(int, input().split())
    wire_ints.append((left_port,right_port))
  answer_string = solve(wire_ints, test_case)
  print(answer_string)

I was wondering if anyone here is able to suggest a way in which I can speed up my algorithm? After 4 hours I really can't see one and I'm losing my miinnnnddd.


texts:
I am creating a utility class to do an HttpURLConnection. I want to make this class generic as in I pass the URL and the POST params. It works with any range of these two values.

public class HttpUrlConnection {

    String url, params;

    public HttpUrlConnection(String url, String params) {
        this.url = url;
        this.params = params;

        try {
            sendPost();
        }catch(Exception e){
            System.out.println("Exception"+e);
        }
    }

    private String sendPost() throws Exception {

        String USER_AGENT = "Mozilla/5.0";
        URL obj = new URL(url);

        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        String urlParameters = params;
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println("rvsp" + response.toString());

        return response.toString();
    }

}

I am unsure if I am following the best practice above.

Should I keep the cosntructor short as:

public HttpUrlConnection(String url, String params) {
        this.url = url;
        this.params = params;
    }

and start the POST using connection.sendPost where in some other class I do:

HttpUrlConnection connection;
connection = new HttpUrlConnection(url,params);
connection.sendPost();


texts: Image-processing filters using decorator pattern in Python 3

texts:
The goal of the following short Python 3 program is to improve my understanding of the decorator design pattern. Therefore, I would be mostly interested about feedback on this aspect, i.e. whether this is a correct usage of mentioned pattern. Also, I would like some comments regarding Python coding best practices, i.e. if there are ways to make my code more "Pythonesque". Of course, any other hints and remarks (e.g., related to the chosen use case, image editing), are welcome too.

#!/usr/bin/python3

import PIL.Image, PIL.ImageFilter, PIL.ImageOps

class IImage:
  def get_img_obj(self):
    raise NotImplementedError("cannot call method of IImage.getImgArr on the interface")

class BaseImage(IImage):
  def __init__(self, img_obj):
    self.img_obj = img_obj

  def get_img_obj(self):
    return self.img_obj

class ImageDecorator(IImage):
  def get_img_obj(self):
    raise NotImplementedError("cannot call method of ImageDecorator.getImgArr on the base class")
  def __init__(self, img):
    self.img = img

class BlurFilter(ImageDecorator):
  def __init__(self, img, radius):
    ImageDecorator.__init__(self, img)
    self.radius = radius
  def get_img_obj(self):
    imageIternal = self.img.get_img_obj()
    return imageIternal.filter(PIL.ImageFilter.GaussianBlur(self.radius))

class ImageFlipper(ImageDecorator):
  def __init__(self, img):
    ImageDecorator.__init__(self, img)
  def get_img_obj(self):
    imageIternal = self.img.get_img_obj()
    return PIL.ImageOps.flip(imageIternal)

im_raw = PIL.Image.open("lena.gif")
im_raw = im_raw.convert('L')
im_obj = BaseImage(im_raw)
im_obj_flipped = ImageFlipper(im_obj)
im_obj_flipped_blurred = BlurFilter(im_obj_flipped, 5)

im_obj.get_img_obj().show("original")
im_obj_flipped.get_img_obj().show("flipped")
im_obj_flipped_blurred.get_img_obj().show("flipped and blurred")


texts: Should I hide or show this implementation?

texts:
An animation is composed of frames. I have the following class:

class Frame
{
private:
    sf::IntRect rect;
    unsigned int duration;

public:
    Frame(sf::IntRect rect, unsigned int duration);

    unsigned int getDuration();
    sf::IntRect& getRect();
};

At the animation class I have the following function:

void Animation::addFrame(sf::IntRect rect, unsigned int duration) // public
{
    frames.push_back(Frame(rect, duration)); // ps: private std::vector<Frame> frames;
}

should it actually be:

void Animation::addFrame(Frame frame) // public
{
    frames.push_back(frame);
}

thus showing how animation is implemented underneath?
I'm also in doubt if the frame class shouldn't simply be a struct with rect and duration. Thanks a lot in advance!


texts: ASP.NET MVC using Repository pattern - code review

texts:
I am just trying to use ASP.NET MVC using repository pattern. Could somebody see If I am doing something wrong here.

Model - Contains the model

public class Contact
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailAddress { get; set; }
    }

Repository interface - Interface

    public interface IContactRepository
        {
            void Create(Contact contact);
            void Delete(int contactId);
            void Save(Contact contact);
            Contact Retrieve(int contactId);
            IEnumerable<Contact> Select();
        }

Repository class

public class ContactRepository : IContactRepository
    {
        private AddressBookDb addressBookdb = new AddressBookDb();

        public void Create(Contact contact)
        {
            addressBookdb.Contacts.Add(contact);
            addressBookdb.SaveChanges();
        }

        public void Save(Contact contact)
        {
            Delete(contact.Id);
            Create(contact);
        }

        public void Delete(int contactId)
        {
            Contact contact = Retrieve(contactId);
            if (contact != null)
            {
                addressBookdb.Contacts.Remove(contact);
                addressBookdb.SaveChanges();
            }
        }

        public Contact Retrieve(int contactId)
        {
            return addressBookdb.Contacts.FirstOrDefault<Contact>(c => c.Id == contactId);
        }

        public IEnumerable<Models.Contact> Select()
        {
            return addressBookdb.Contacts.ToList<Contact>();
        }
    }

Controller class

public class ContactController : Controller
    {
        IContactRepository contactRepository = null;
        public ContactController() : this (new ContactRepository())
        {

        }

        public ContactController(IContactRepository contactRepository)
        {
            this.contactRepository = contactRepository;
        }

        [HttpPost]
        public ActionResult Edit(Contact contact)
        {
            if (ModelState.IsValid)
            {
                contactRepository.Save(contact);
                return RedirectToAction("Index");
            }
            return View(contact);
        }
}


texts:
I'm trying to write a function that returns the number of bits set in a 32-bit integer in VBScript, it's just for practising the language. The function I've written so far looks okay, but I'm wondering if there was a simpler solution.

Function countBits(value)
  Dim n : n = 0
  Dim mask : mask = 1
  Dim i
  For i = 0 to 30
    If (value And mask) > 0 Then
      n = n +1
    End If
  Next
  If (value And &h8000) then
    n = n+1
  End If
  countBits = n
End Function

I found that there are no shift operators in VBScript and an overflow (Err.Number = 6) if I iterate for 0 to 31, that's why I add the explicitly check of the MSB after the look.

Any solutions to improve (maybe generalize) this?

edit: removed the useless error handling part, as it's a remains of starting with 31 as an upper bound in the first (and at that time only) loop


texts:
I'm using two category filters from this demo. I give the filters two different sets of classes so they won't affect each other. Since I'm very new to jQuery, all I can come up with is repeating the same code with a different set of classes. I wonder if there's a shorter way to write this:

$(function(){

    /* filter1 */
    $(".category-menu ul li").click(function(){
        var CategoryID = $(this).data('category');
        $('.category-menu ul li').removeClass('cat-active');
        $(this).addClass('cat-active');

        $('.prod-cnt').each(function(){
            if(($(this).hasClass(CategoryID)) == false){
               $(this).css({'display':'none'});
            };
        });
        $('.'+CategoryID).fadeIn();

    });

    $('.category-menu select').change(function(){
        var CategoryID = $(this).find('option:selected').data('category');
        $('.prod-cnt').each(function(){
            if(($(this).hasClass(CategoryID)) == false){
               $(this).css({'display':'none'});
            };
        });
        $('.'+CategoryID).fadeIn();
    });

    /* filter2 */
    $(".category-menu2 ul li").click(function(){
        var CategoryID = $(this).data('category');
        $('.category-menu2 ul li').removeClass('cat-active2');
        $(this).addClass('cat-active2');

        $('.prod-cnt2').each(function(){
            if(($(this).hasClass(CategoryID)) == false){
               $(this).css({'display':'none'});
            };
        });
        $('.'+CategoryID).fadeIn();

    });

    $('.category-menu2 select').change(function(){
        var CategoryID = $(this).find('option:selected').data('category');
        $('.prod-cnt2').each(function(){
            if(($(this).hasClass(CategoryID)) == false){
               $(this).css({'display':'none'});
            };
        });
        $('.'+CategoryID).fadeIn();
    });

});

Please check out this demo.


texts:
I have this common design in my application:

public class MyListener1{
  MyTask1 task1;
  MyTask2 task2;

  public class MyListener1{

    public MyListener1(){
      task1 = new MyTask1(this);
      task2 = new MyTask2(this);
      task1.execute();
      task2.execute();
    }

    public void onResult1(String result){
      //extract result
    }

    public void onResult2(String result){
      //extract result
    }
}

public class MyTask1 extends AsyncTask{

  MyListener1 myListener1;

  public MyTask1(MyListener1 myListener1){
    this.myListener1 = myListener1;
  }

  @Override
  public void onResult(String result){
    myListener1.onResult1(result);
  }

}

public class MyTask2 extends AsyncTask{

  MyListener1 myListener1;

  public MyTask2(MyListener1 myListener1){
    this.myListener1 = myListener1;
  }

  @Override
  public void onResult(String result){
    myListener1.onResult2(result);
  }

}

The AsyncTask is a library class that execute the code in a method doInBackground() in another thread when calling execute(), and call onResult(String result) when task finished.

Of course, I summarize the code, MyTask1 and MyTask2 have a little bit more code, but I soon realized that they could be factorize on a common task:

public class MyListener1{
  MyTask task1;
  MyTask task2;

  public class MyListener1{

    public MyListener1(){
      task1 = new MyTask(0,this);
      task2 = new MyTask(1,this);
      task1.execute();
      task2.execute();
    }

    public void onResult(int taskId, String result){
       switch(taskId){
         case(0) : //extract result from task 0
         case(1) : //extract result from task 1
    }
}

public class MyTask extends AsyncTask{

  int id;
  MyListener1 myListener1;

  public MyTask(int id, MyListener1 myListener1){
    this.id = id;
    this.myListener1 = myListener1;
  }

  @Override
  public void onResult(String result){
    myListener1.onResult(id, result);
  }

}

I heard some people telling me to avoid "switch case" to identify a source and prefer to use "polyphormism" instead. In that case, I don't know what they mean.

So here is my question:

Is there a better way to identify the source (the object calling) of a callback method than using an identifier for the caller?


texts: Long switch statement to lookup fifty-something commands

texts:
I have a very long switch statement which is expected to have nearly 50-55 cases.

switch (commandType) {
            case COMMAND_LOGIN:
                command = getCommand(commandType, agentId);
                break;

            case COMMAND_MAKE_READY:
                command = getCommand(commandType, agentId);
                break;

            case COMMAND_MAKE_NOT_READY:
                command = getCommand(commandType, agentId);
                break;

            case COMMAND_MAKE_NOT_READY_WITH_REASON:
                command = getCommand(commandType, agentId);
                break;

            case COMMAND_LOGOUT_WITH_REASON:
                command = getCommand(commandType, agentId);
                break;

            case COMMAND_ANSWER_CALL:
                command = getCommand(commandType, agentId);
                break;

            case COMMAND_HOLD_CALL:
                command = getCommand(commandType, agentId);
                break;

            case COMMAND_RETRIEVE_CALL:
                command = getCommand(commandType, agentId);
                break;

            case COMMAND_END_CALL:
                command = getCommand(commandType, agentId);
                break;

            case COMMAND_TRASFER_SST_CALL:
                command = getCommand(commandType, agentId);
                break;

            case COMMAND_CONSULT_CALL:
                command = getCommand(commandType, agentId);
                break;
                 .
                 .
                 .
                 .
                 .
           default :
                command = "";
                break;

        }//end switch

It doesn't seem to be something which should exist in this current form, I have gone through some questions here 'but they doesn't seem to help in this condition' I have seen the "strategy pattern", but that also seems to be suitable for the case where i have to execute different method for every case. Kindly guide me how the size of this code can be reduced.


texts:
I wrote a method that reduces a string like aabcccccaaa to a2b1c5a3

My implementation:

string Compress(string str)
{
    StringBuilder builder = new StringBuilder();
    using(TextReader reader = new StringReader(str))
    {
        while(reader.Peek() != - 1){
            char c = (char)reader.Read();
            int n = 1;
            while(reader.Peek() == c) {
                reader.Read();
                n++;
            }
            builder.AppendFormat("{0}{1}",c,n);
        }
    }
    return builder.ToString();
}

What do you think about this, is there a better way to do this?


texts:
Can someone check my Merge Sort implementation on Java? Is it good/bad and can it be improved further?

public class MyMergeSort {
    private int [] data;

    public MyMergeSort(int[] data){
        this.data = data;
    }

    public int[] sort(int[] data){
        if (data.length < 2){
            return data;
        }
        int mid = data.length/2;
        int first[] = new int[mid];
        int second[] = new int[data.length - mid];
        System.arraycopy(data, 0, first, 0, mid);
        System.arraycopy(data, mid, second, 0, data.length - mid);
        return merge(sort(first), sort(second));
    }

    private int[] merge(int[] arr1, int[] arr2) {
        if(arr1.length == 0){
            return arr2;
        }
        if(arr2.length == 0){
            return arr1;
        }
        int res[] = new int[arr1.length + arr2.length];
        int i;
        int j = 0; // iterate over the first array
        int k  = 0; // iterate over the second array
        for (i = 0; i < res.length; i++) {
            if(j < arr1.length && k < arr2.length){
                if(arr1[j] < arr2[k]){
                    res[i] = arr1[j];
                    j++;
                }
                else{
                    res[i] = arr2[k];
                    k++;
                }
            }
            else{
                if(j < arr1.length){
                    System.arraycopy(arr1, j, res, i, arr1.length-j);
                    break;
                }
                else{
                    System.arraycopy(arr2, k, res, i, arr2.length-k);
                    break;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int d[] = {1, 9, 2, 8, 6, 3, 7, 4, 2};
        MyMergeSort mySort = new MyMergeSort(d);
        int res[] = new int[d.length];
        res =  mySort.sort(d);
        for (int i = 0; i < res.length; i++) {
            System.out.print(res[i] + " ");
        }
    }
}


texts:
I was trying to implement method number 2, from this article.

  Method 2 (Use temporary array) K largest elements from arr[0..n-1]

  Store the first k elements in a temporary array temp[0..k-1].
  Find the smallest element in temp[], let the smallest element be min.
  For each element x in arr[k] to arr[n-1] If x is greater than the
  min then remove min from temp[] and insert x.
  Print final k elements of temp[]

  Time Complexity: O((n-k)*k). If we want the output sorted then
  O((n-k)*k + klogk)

Please comment on the complexity and runtime speed. Can I improve my implementation in that sense? I was trying to get O((n-k)*k).

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace JobInterviewTests
{

    //Design an algorithm to find K biggest numbers in the array.
    [TestClass]
    public class KBiggestNumbers
    {
        [TestMethod]
        public void FindKBiggestNumbersTest()
        {
            int[] testArray = new[] { 7, 2, 4, 4, 3, 6, 1, 8, 9, 10, 11 };
            int k = 5;
            int[] result = FindKBiggestNumbers(testArray, k);
            int[] expectedResult = new[] { 7,8,9,10,11 };
            CollectionAssert.AreEqual(expectedResult, result);
        }

        private int[] FindKBiggestNumbers(int[] testArray, int k)
        {
            int[] result = new int[k];
            for (int i = 0; i < testArray.Length; i++)
            {
                //if bigger than the smallest node
                if (testArray[i] <= result[0])
                {
                    continue;
                }
                else
                {
                    //if bigger than all?
                    if (testArray[i] > result[k - 1])
                    {
                        for (int l = 0; l < k - 1; l++)
                        {
                            result[l] = result[l + 1];
                        }
                        result[k - 1] = testArray[i];
                    }
                    else
                    {

                        //Naive way
                        //for (int j = 0; j < k-1; j++)
                        //{
                        //    if (testArray[i] > result[j] && testArray[i] <= result[j + 1])
                        //    {
                        //        for (int l = 0; l < j; l++)
                        //        {
                        //            result[l] = result[l + 1];
                        //        }
                        //        result[j] = testArray[i];
                        //        break;
                        //    }
                        //}

                        //binary search
                        int indexLeft = 0;
                        int indexRight = k-1;

                        int currIndex = 0;
                        //10 20 30 40 50 - > place 33
                        while (indexRight- indexLeft >1)
                        {
                            currIndex = (indexRight + indexLeft)/2;
                            if (testArray[i] >= result[currIndex])
                            {
                                indexLeft = currIndex;
                            }
                            else
                            {
                                indexRight = currIndex;
                            }

                        }

                        for (int l = 0; l < currIndex; l++)
                        {
                            result[l] = result[l + 1];
                        }
                        result[currIndex] = testArray[i];
                    }
                }
            }
            return result;
        }
    }
}


texts: Apply labels from a stream to a Bitraversable

texts:
Labelling Traversable containers is an ancient and honorable test of skill. My task here is to create a generic labelling mechanism for a Bitraversable, such as a tuple, or a graph with vertex and edge labels.

bilabelWith
    :: Bitraversable t
    => (l ->  indexl -> l') -> (r ->  indexr -> r')
    -> Stream indexl        -> Stream indexr
    -> t l r -> t l' r'
bilabelWith f g xs ys =
  let labelLeft  = fmap (withStateLens fst (\(_, y) x' -> (x', y))) (labelOneWith f)
      labelRight = fmap (withStateLens snd (\(x, _) y' -> (x, y'))) (labelOneWith g)
  in flip evalState (xs, ys) . bitraverse labelLeft labelRight

labelOneWith :: (a -> index -> b) -> a -> State (Stream index) b
labelOneWith f u = do
    (Stream.Cons x xs) <- get
    put xs
    return (f u x)

withStateLens :: (s -> t) -> (s -> t -> s) -> State t a -> State s a
withStateLens thrust merge u = do
    s <- get
    let t = thrust s
    let (r, t') = runState u t
    put (merge s t')
    return r

Here is how it may be applied:

λ bilabelWith (+) (*) (Stream.fromList [2]) (Stream.fromList [3]) (5, 7)
(7,21)

A more complicated example requires us to obtain a Bitraversable graph.

circular :: (DynGraph gr, Bitraversable gr) => gr a b -> gr (V2 Double, a) b
circular gr =
  let n = fromIntegral (Graph.noNodes gr)
      coords =
        let alpha = (pi * 2 / n)
        in Stream.prefix [ 0.8 * V2 (sin (alpha * i)) (cos (alpha * i)) | i <- [1.. n] ]
            $ error "circular: Impossible error: not enough coordinates to label all points."
  in bilabelWith (flip (,)) const coords (Stream.repeat ()) gr

Does this code make sense? Is there anything to make more compact or clarify?