texts: Banking: Calculate the Capital Requirement to calculate Risk-Weighted Assets

texts:
I know it's not the perfect code, but it outputs the correct values. Could anyone give me some pointers on how to make the operation more Pythonic?

def capital_requirement(r, lgd, pd, madj, tenor):
    '''Returns the capital requirement.'''
    madjcoeff = 1.5
    tsub = 2.5
    a1 = (stat.norm.ppf(pd) + r**0.5 * stat.norm.ppf(0.999)) / ((1 - r)**0.5)
    b1 = lgd * stat.norm.cdf(a1) - lgd * pd
    return b1 * (1 + ((tenor - tsub) * madj)) / (1- madjcoeff * madj)

See:
https://en.wikipedia.org/wiki/Capital_requirement


texts: Add the first non-null item from one list to another list

texts:
Given these two methods, is it defensible that one is better than the other?
In what terms? Performance? Elegance? Readability?

public static void AddFirstNotNull(List<object> onlyNotNull, List<object> source)
{
  var item = source.FirstOrDefault(v => v != null);
  if (item != null)
  {
    onlyNotNull.Add(item);
  }
}

public static void AddFirstNotNull(List<object> onlyNotNull, List<object> source)
{
  onlyNotNull.AddRange(source.Where(v => v != null).Take(1));
}


texts: Is this usage of the dynamic keyword an indicator of a design fault?

texts:
I feel like I'm likely violating a design principal or two here so I'd appreciate any mistakes or antipatterns being named and pointed out.
I'm attempting to map a system in code which represents a decision tree, so based on the users input would provide them the next choice they can make, then from their input to that the next, and so on.
The response to each choice is either:

Binary Yes/No, so two different possible follow up choices.
1-10 range, so multiple possible follow up choices.

Any choice type can return any other choice type so I've been aiming to have the result for the follow up choice to always be a generic IChoice.
BinaryChoice current = NotifyPersonOrNot();
IChoice next = current.MakeChoice(true); // Binary choice
IChoice next1 = next.MakeChoice(5); // Range choice
IChoice next2 = next1.MakeChoice(3); // Range Choice

An issue I see with my current solution is usage of the dynamic keyword in my IChoice MakeChoice(dynamic answer) function. I used this to avoid having to do a specific cast for the T argument in the Func<T, IChoice> GetNextChoice function that the MakeChoice function calls with it's answer input.
I considered adding a
So the IChoice interface is like so as this is the only function I want to be used.
public interface IChoice
{
    // I feel like having to use dynamic here is a sign of a mistake in the design
    public IChoice MakeChoice(dynamic answer);
}

My base class looks like this
public abstract class Choice<T> : IChoice
{
    public Choice(Func<T, IChoice> getNextChoice)
    {
        GetNextChoice = getNextChoice;
    }

    public Func<T, IChoice> GetNextChoice { get; set; }

    // This seems cleaner than type checking but I'm thinking having to use dynamic indicates a mistake in class design
    public IChoice MakeChoice(dynamic answer)
    {
        return GetNextChoice(answer);
    }
}

And an implementation of the base class is like so, where Choice is given a Type. The RangeChoice version implements Choice<int>
public class BinaryChoice : Choice<bool>
{
    public override ChoiceType ChoiceType => ChoiceType.Binary;

    public BinaryChoice(Func<bool, IChoice> getNextChoice) : base(getNextChoice) { }
}

The idea is that GetNextChoice can be set with the unique logic required to provide correct next choice in the tree.
 private BinaryChoice NotifyPersonOrNot()
    {
        // If we were returning a RangeChoice here we'd have more conditions in the function
        return new BinaryChoice((sendNotification) =>
        {
            if (!sentNotification)
            {
                // This is another BinaryChoice
                return AskAnotherYesNoQuestion();
            }

            // This is a RangeChoice
            return AskRatingQuestion();
        });
    }

I've considered changing the GetNextChoice delegate to Func<object, IChoice> but I would like to avoid the overhead of having to cast from object into the required type when defining each choice. It would preferable to do it once in a single place if it must always happen.
I've looked at adding a abstract ChoiceType enum to the Choice class and handling the type casting in the MakeChoice function but I'm not sure how to do this without explicitly setting a type for the GetNextChoice delegate.


texts: Processing student scores from the stdin

texts:
As part of learning more C, I wrote this extremely trivial C program that takes Student scores from stdin and, upon termination, prints out the minimum score/maximum score and the average score. Can somebody review my code and tell me how I might be able to improve my code?

#include <stdio.h>

int main()
{
        int currentEntry;
        int startValue = 0;
        int counter = 0;
        int currentMax;
        int currentMin;
        double average;

        printf("Enter scores one-by-one, exit by entering -1\n");
        while(currentEntry != -1){
                if((scanf("%d",&currentEntry) == 1) && (currentEntry != -1)){
                        printf("Current score is %d\n",currentEntry);
                        counter++;
                        startValue += currentEntry;
                        average = startValue/counter;
                        if(counter == 1){
                                currentMax = currentEntry;
                                currentMin = currentEntry;
                        }
                        if(currentEntry > currentMax){
                                currentMax = currentEntry;
                        }
                        if(currentEntry < currentMin){
                                currentMin = currentEntry;
                        }
                }
        }
        printf("The average is %lf\n",average);
        printf("The maximum score is %d\n",currentMax);
        printf("The minimum score is %d\n",currentMin);
        return 0;
}


texts: Does checking for the Core.Instance.isLocalPlayer twice in my method constitute a bad design?

texts:
I've been writing some code for my unity project, where I am connecting players to a game and adding them to a dictionary, which is in a Database class.

I have a simple method which is adding them to the database and if successful, it then instantiates the relevant game objects into the game.

The thing that made me wonder if it was a bad design was the way I was checking if the player is the local client or not.

This is my code:

public bool SetConnection(byte connectionID)
{
    Agent agent;
    if (Core.Instance.isLocalPlayer)
        agent = new Agent_Local();
    else
        agent = new Agent_Enemy();

    if (Core.Instance.Database.Add(connectionID, agent)) // fails if room is full
    {
        if (Core.Instance.isLocalPlayer) //Checking this again : maybe bad design?
            Core.Instance.LocalHandler.SetPlayer(agent);
        else
            Core.Instance.SetEnemy(agent);

        return true;
    }
    return false;
}

So you will notice I am checking if the player is local twice, and I feel that I shouldn't need to check if I was smarter about the way I went about setting this up. Is this considered as bad or redundant coding or perhaps someone could suggest a better approach?


texts:
I thought implementing a stack using a linked list was a good option since an array implementation involves reallocation of array size and so on.

I have implemented basic Push, Pop and Print operation: What best practices can I follow?

class StackusingLinkedList
{
    public Node<int> Head;
    int Nodecount = 0;
    public void Push(int data)
    {
        if (Nodecount == 0)
        {
            Head = new Node<int>(data);
            Nodecount++;
            return; ;
        }
        var temp = new Node<int>(data);
        temp.Next = Head;
        Head = temp;
        Nodecount++;
    }
    public void Pop()
    {
        var temp = Head;
        Head = temp.Next;
    }
    public void Print()
    {
        var prtemp = Head;
        StringBuilder sb = new StringBuilder();
        while (true)
        {
            if (prtemp == null)
            {
                break;
            }
            sb.Append("|"+prtemp.Data+"|");
            var temp = prtemp;
            prtemp = temp.Next;
        }
        Console.WriteLine(sb.ToString());
    }
}

class Node<T>
{
    public Node<T> Next { get; set; }

    public T Data { get; set; }

    public Node(T data)
    {
        Data = data;
    }

}


texts: Reduce the number of code if possible when creating a folder

texts:
My code below creates a folder based on the passed data from my client-side(VueJs) and checks if there's already an existing folder and deletes it if there is otherwise it will create a new one.

My problem here is that I think my code is too long and unreadable although it accomplishes the task that I want to happen.

Can someone help me to make this code better?

router.post('/album', (req, res) => {
    let sql = "INSERT INTO GALLERY SET ALBUM = ?, DESCRIPTION = ?";
    let body = [req.body.ALBUM, req.body.DESCRIPTION]
    myDB.query(sql, body, (error, results) => {
        if (error) {
            console.log(error);
        } else {
            let directory = `path\\public\\${req.body.ALBUM}`;
            if (fse.existsSync(directory)) {
                fse.removeSync(directory, err => {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log("Success");
                    }
                })
            } else {
                fse.mkdirpSync(directory, err => {
                    if (err) {
                        console.log(object);
                    } else {
                        console.log("Success");
                    }
                })
            }
        }
    })
})


texts: Separate business logic from Data Access Logic in the repository

texts:
I have a PupilService which is calling the PupilRepository.AttachPupil() method.

I have an N to M relation between SchoolclassCode and Pupil.

Technical logic:

A pupil can be related to many SchoolclassCode like "Math 7 a" or "English 8 c".

Business logic:

A pupil can be related only to SchoolclassCode like "Math 7 a" or "English 7 c". That means it's not possible for a pupil to belong to 2 different class numbers.
A pupil can only be attached to a smaller class number during the year (changes happen in mid-year) thus all higher class relations must be removed.

The business logic from 1) and 2) should be put elsewhere. It just does not fit into the PupilService or another Repository method because by splitting up the tasks in finer grained method It would causes more queries to do the same job. Further more if I split up the business logic the repo.AttachPupil would only work the half if the repository would be called directly. I do not like that either.

public async Task AttachPupil(int pupilId, int targetSchoolclassCodeId)
{
    var pupil = new Pupil { Id = pupilId };
    context.Pupils.Attach(pupil);
    var targetSchoolclassCode = await context.SchoolclassCodes.SingleAsync(s => s.Id == targetSchoolclassCodeId);
    await context.Entry(pupil).Collection(p => p.SchoolclassCodes).LoadAsync();
    var existingLowerSchoolclasses = pupil.SchoolclassCodes.Where( s => s.SchoolclassNumber < targetSchoolclassCode.SchoolclassNumber);
    if (existingLowerSchoolclasses.Any())
    {
        throw new PupilAdvancedNextSchoolclass("A pupil can only downgrade a class within a schoolyear");
    }
    else
    {
        foreach (var schoolclassCodeToDetach in existingLowerSchoolclasses)
        {
            // Detach pupil from higher SchoolclassCode classes e.g. class 9
            pupil.SchoolclassCodes.Remove(schoolclassCodeToDetach);
        }

        // Attach Pupil to a lower class becaue his grades/marks are too bad e.g. in the mid-year to class 8
        targetSchoolclassCode.Pupils.Add(pupil);
        await context.SaveChangesAsync();
    }
}

How would you refactor this AttachPupil method so that the business logic is better separated from the data access logic?


texts: Custom TaskScheduler: Limited concurrency level

texts:
I'm interested in some feedback for a custom TaskScheduler implementation I wrote today for use on a game server - I wanted to be able to have a single-threaded scheduler for tasks since the game is relatively lightweight and its logic doesn't need to be multi-threaded. However, I wanted to handle networking/IO concurrently to avoid blocking the main thread running game logic, and still wanted the ability to easily schedule tasks onto it, jumping back and forth between executors (e.g. game server receives a request, does some logic, then requires something from a database, makes a call on some other thread pool, then executes a callback on the original thread again). Anyway, that's probably too much about why I wanted to do this; Here's how I attempted it:

public class CustomTaskScheduler : TaskScheduler
{
    private readonly int maxThreads;
    private readonly ConcurrentQueue<Task> tasks;
    private readonly bool unbounded;
    private int threadsRunning;

    private CustomTaskScheduler(int concurrencyLevel, bool unboundedThreads)
    {
        maxThreads = concurrencyLevel;
        tasks = new ConcurrentQueue<Task>();
        threadsRunning = 0;
        unbounded = unboundedThreads;
    }

    protected override IEnumerable<Task> GetScheduledTasks()
    {
        return tasks;
    }

    protected override void QueueTask(Task task)
    {
        tasks.Enqueue(task);

        if (unbounded || Interlocked.Increment(ref threadsRunning) <= maxThreads)
        {
            ThreadPool.UnsafeQueueUserWorkItem(_ =>
            {
                try
                {
                    while (tasks.TryDequeue(out Task toRun))
                    {
                        TryExecuteTask(toRun);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    Interlocked.Decrement(ref threadsRunning);
                }
            }, null);
        }
        else
        {
            Interlocked.Decrement(ref threadsRunning);
        }
    }

    protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
    {
        return false;
    }

    public static CustomTaskScheduler MakeSingleThreaded() => new CustomTaskScheduler(1, false);
    public static CustomTaskScheduler MakeMultiThreaded(int threads) => new CustomTaskScheduler(threads, false);
    public static CustomTaskScheduler MakeUnbounded() => new CustomTaskScheduler(0, true);
}

It isn't that complicated, but there are a few things I was wondering about - It is based off of the sample code here, but elects to use a ConcurrentQueue instead of locking on a LinkedList. From what I can see, this causes no issues. Then, I did an interlocked increment on the number of threads running to make sure it was not exceeding the limit, decrementing it immediately if another thread could not be run. This, too, I think is safe and correct, but it still makes me uncomfortable, and I was wondering if there was a more elegant solution to this. I found the Interlocked.CompareExchange function, but what i'm more looking for is being able to compare if something is less than something else.

Finally, I have tried doing some research on TryExecuteTaskInline, and it seems that this allows you to run a task directly from the thread creating the task, which seems like what I don't want. For now I've set it to always return false, but i'm not sure if this is what i'm supposed to do, or if i'm misunderstanding what it is actually doing.


texts: Demonstration of inheritance with some shapes

texts:
I had a job interview take home test where I was asked a series of questions on object inheritance. In addition to answering the questions, I created the following application to demonstrate inheritance among different objects.

The first piece of code are different shape classes. Some inherit from an IShape interface.

The second piece of code is a console application that uses these classes in different inheritance scenarios. The console.write tells the use case.

I would like feedback if my implementation looks correct.

Class definitions

using System;
using OOP.Interfaces;

namespace OOP.Models
{
    public class Circle : IShape
    {
        public void Draw()
        {
            Console.WriteLine("Circle object's draw method\n");
        }
    }

    public class Rectangle : IShape
    {
        public void Draw()
        {
            Console.WriteLine("Rectangle object draw method\n");
        }
    }

    public class Square : Rectangle
    {
        public void Draw()
        {
            Console.WriteLine("Square object draw method\n");
        }
    }

}

Console App

using System;
using OOP.Interfaces;
using OOP.Models;

namespace OOP_Calling_Client
{
  public class Program
  {
    static void Main(string[] args)
    {
        Console.WriteLine("This is a demo console app that shows examples of OOP inheritance through a series of shape classes and interfaces.");
        Console.WriteLine("*********************************\n");

        DrawCircle();
        DrawRectangle();
        DrawSquare();
        AssignDifferentTypesToSameInstanceVariable();
        Console.Read();
    }

    private static void DrawCircle()
    {
        IShape circle = new Circle();
        circle.Draw();
        Console.WriteLine("Object of type circle stored in a variable of type IShape\n");
        Console.WriteLine("*********************************\n");
    }

    private static void DrawRectangle()
    {
        Console.WriteLine("Object of type rectangle stored in a variable of type rectangle\n");
        Rectangle rectangle = new Rectangle();
        rectangle.Draw();
        Console.WriteLine("*********************************\n");
    }

    private static void DrawSquare()
    {
        Console.WriteLine("Object of type square stored in a variable of type rectangle. Rectangle is derived from square\n");
        Rectangle rectangle = new Square();
        rectangle.Draw();
        Console.WriteLine("*********************************\n");
    }

    private static void AssignDifferentTypesToSameInstanceVariable()
    {
        Console.WriteLine("Instance variable holds a type of circle, and then a type of rectangle. The draw methods change\n");
        IShape shape = new Circle();
        Console.WriteLine("The object variable is of type IShape,\nand is holding an instance of a Circle.\n");
        shape.Draw();
        Console.WriteLine("The object variable is of type IShape,\nbut is now holding an instance of a Rectangle.\n");
        shape = new Rectangle();
        shape.Draw();
    }
  }
}


texts:
I am creating a blog using React, MongoDB, Express and Node. I have three components: App, List, and Item. The item is a blog post; the list is a list of the blog posts, and the app includes a place to enter text and submit it. I will eventually add more functionality, but I want to determine if I am adhering to best practices for React (I doubt I am).

So in App, I getInitialState with an array of posts (posts) and a string of text for the input (postbody). I used the componentDidMount to make an AJAX GET request to my database, so the user can see all the posts.

To handle entering text I just made a simple handleChange function which updates the state of postbody.

I also have a handleClick function, which grabs this.state.postbody and then POSTs it database. However the same function also makes a separate GET request of the database to update the state of the posts array. This doesn't seem right! Shouldn't that be handled some other way and updated automatically? * This is the primary question I have. *

Also, please let me know if I need to break the components down further, or if I am violating best practices using React (e.g. changing state in the wrong place, or using props incorrectly).

var React = require('react');

var Item = React.createClass({
  render: function() {
    return (

{this.props.postbody}

    )
  }
})

var List = React.createClass({

  render: function() {
    return (

        {this.props.array.map(function(post) {

          return (
            <Item postbody={post.postbody}></Item>
          )
        })}

    )
  }
})

var App = React.createClass({

  getInitialState: function() {
    return {
       posts: [],
       postbody: ''
    }
  },

  componentDidMount: function() {
    $.ajax({
      type: 'GET',
      url: '/api/blogPosts',
      success: function(data) {
        this.setState({posts: data});
      }.bind(this)
    })
  },

  handleClick: function() {

    event.preventDefault();

    var blogPost = this.state.postbody;

    $.ajax({

      type: 'POST',
      url: '/api/blogPosts',
      data: { postbody: blogPost }
    });

    $.ajax({
      type: 'GET',
      url: '/api/blogPosts',
      success: function(data) {
        this.setState({posts: data});
      }.bind(this)
    })
  },

  handleChange: function(event) {

    this.setState({ postbody: event.target.value})
  },

  render: function() {
    return (

        <form action="/api/blogPosts" method="post">
            <input onChange={this.handleChange} type="text" name="postbody"></input>
            <button type="button" onClick={this.handleClick}>Submit</button>
        </form>
        <List array={this.state.posts} />

    )
  }
})


texts:
This is a simple calculator I created using my Python basic knowledge. I would like to know any coding techniques to simplify and enhance the code to make it efficient. I would also like to know some advanced techniques. Also, please specify where I can reduce duplication to make it DRY.

import math
import cmath
print("""Choose from
        1. Perform basic BODMAS
        2. Find squareroot
        3. Solve quadratic equation
        4. Find Trignometric values
        5. Find logarithms""")
choose = input("enter required number \n")

if choose == '1':

    def bodmas():
        num1 = float(input("Enter number 1 \n"))
        num2 = float(input("Enter number 2 \n"))
        op= input("Enter add,sub,mul,div \n")
        if op == "add":
            res = num1+num2
        elif op == "sub":
            res = num1 - num2
        elif op == "mul":
            res = num1*num2
        elif op == "div":
            res = num1/ num2
        else:
            res = print("Error")
        return res
    print(bodmas())

elif choose == '2':

    def sqrt_n():
        num1 = float(input("Enter number"))
        res = math.sqrt(num1)
        return res
    print(sqrt_n())

elif choose =='3':

    def quad_s():
        print("Standard form of Quadratic equation (Ax^2 + Bx + C)")
        A = int(input("Enter coefficient A: "))
        B = int(input("Enter coefficient B: "))
        C = int(input("Enter coefficient C: "))
        D = (B**2)-(4*A*C)  # Calculate Discriminant

        sol1 = (-B-cmath.sqrt(D))/(2*A)
        sol2 = (-B+cmath.sqrt(D))/(2*A)

        z =print("The solutions are {0} and {1}" .format(sol1 ,sol2))
        return z
    print(quad_s())
elif choose == '4':

    choice = input("Choose sin,cos,tan: ")
    if choice == "sin":
        ang = float(input("Enter angle: "))
        x = math.sin(math.radians(ang))
        print (x)
    elif choice == "cos":
        ang = float(input("Enter angle: "))
        x = math.cos(math.radians(ang))
        print (x)
    elif choice == "tan":
        ang = float(input("Enter angle: "))
        x = math.tan(math.radians(ang))
        print (x)
    else:
        print("Error")

elif choose == "5":
    z = int(input("Enter Value: "))
    res = math.log10(z)
    print (res)
else
    print("Error")

How can I use the functions in a more preferable and efficient way?


texts: Calling different bundles in parallel using ExecutorService

texts:
I am working on a project in which I will be having different Bundles. Let's take an example, Suppose I have 5 Bundles and each of those bundles will have a method name process.

Below are the things, I am supposed to do-

I need to call all those 5 Bundles process method in parallel using multithreaded code and then write to the database. Meaning each bundle will return me back Map of String and String and then I am supposed to write that map into the database. I am not sure what is the right way to do that? Should I have five thread? One thread for each bundle? But what will happen in that scenario, suppose if I have 50 bundles, then I will have 50 threads?
And also, I want to have timeout feature as well. If any bundles is taking lot of time than the threshold setup by us, then it should get timeout and log as an error that this bundle has taken lot of time.

The following attempt that I have done is most probably flawed and error handling is by no means complete. And I am looking for best and efficient way of doing this problem.

Below is the solution I have. And below is my method which will call process method of all the bundles in a multithreaded way.

public void processingEvents(final Map<String, Object> eventData) throws InterruptedException {
    ExecutorService pool = Executors.newFixedThreadPool(5);
    List<ProcessBundleHolderEntry> entries = new ArrayList<ProcessBundleHolderEntry>();

    Map<String, String> outputs = (Map<String, String>)eventData.get(BConstants.EVENT_HOLDER);

    for (BundleRegistration.BundlesHolderEntry entry : BundleRegistration.getInstance()) {
        ProcessBundleHolderEntry processBundleHolderEntry = new ProcessBundleHolderEntry(entry, outputs);
        entries.add(processBundleHolderEntry);
    }

    try {
        List<Future<Map<String, String>>> futures = pool.invokeAll(entries, 30L, TimeUnit.SECONDS);
        for (int i = 0; i < futures.size(); i++) {
            // This works since the list of future objects are in the
            // same sequential order as the list of entries
            Future<Map<String, String>> future = futures.get(i);
            ProcessBundleHolderEntry entry = entries.get(i);
            if (!future.isDone()) {
                // log error for this entry
            }
        }
    } catch (InterruptedException e) {
        pool.shutdownNow(); //cancels the tasks
        //restore interrupted flag and exit
        Thread.currentThread().interrupt();
        //or rethrow the exception
        throw e;
    }
}

Secondly, an implementation of Callable for your threads:

public class ProcessBundleHolderEntry implements Callable<Map<String, String>> {
    private BundleRegistration.BundlesHolderEntry entry;
    private Map<String, String> outputs;

    public ProcessBundleHolderEntry(BundleRegistration.BundlesHolderEntry entry, Map<String, String> outputs) {
        this.entry = entry;
        this.outputs = outputs;
    }

    public Map<String, String> call() throws Exception {
        final Map<String, String> response = entry.getPlugin().process(outputs);
        // write to the database.
        System.out.println(response);
        return response;
    }
}

Can anyone tell me whether there is any problem with the above approach or is there any better and efficient way of doing the same thing? I am not sure whether there is any thread safety issue as well.

Any help will be appreciated on this.


texts:
I have written two classes, one to represent the tree and a Util class to get the deepest node from the tree. Can you please review the code?

Below is the class for Tree:

package org.vik.ds.tree;

public class BinaryTree<E>{

private E data;
private BinaryTree<E> leftNode;
private BinaryTree<E> rightNode;

public BinaryTree(E data, BinaryTree<E> leftNode, BinaryTree<E> rightNode)
{
    this.data = data;
    this.leftNode = leftNode;
    this.rightNode = rightNode;
}

public E getData()
{
    return data;
}

public void setData(E data)
{
    this.data = data;
}

public BinaryTree<E> getLeftNode()
{
    return leftNode;
}

public void setLeftNode(BinaryTree<E> leftNode)
{
    this.leftNode = leftNode;
}

public BinaryTree<E> getRightNode()
{
    return rightNode;
}

public void setRightNode(BinaryTree<E> rightNode)
{
    this.rightNode = rightNode;
}

public boolean isLeafNode()
{
    return (leftNode == null && rightNode == null);

}

}

Below is algo class, which finds deepest node in tree:

public class DeepestNodeInTree{

public static <T> BinaryTree<T> getDeepestNode(BinaryTree<T> rootNode)
{
    BinaryTree<T> deepestNode = rootNode;
    int maxDeeper = 0;

    Deque<BinaryTree<T>> nodeStack = new LinkedList<BinaryTree<T>>();

    BinaryTree<T> tempNode = rootNode;
    Map<BinaryTree<T>, Boolean> isNodeVisitedMap = new HashMap<>();
    while (tempNode != null)
    {

        if (tempNode.isLeafNode())
        {
            int currentMaxDeeperLen = nodeStack.size() - 1;
            if (currentMaxDeeperLen > maxDeeper)
            {
                deepestNode = tempNode;
                maxDeeper = currentMaxDeeperLen;

            }

            isNodeVisitedMap.put(tempNode, true);
            tempNode = nodeStack.isEmpty() ? nodeStack.pop() : null;
        }
        else
        {

            BinaryTree<T> notVisitedChildNode = getNonVisitedChildNode(tempNode, isNodeVisitedMap);
            if (notVisitedChildNode != null)
            {
                nodeStack.push(tempNode);
                tempNode = notVisitedChildNode;
            }
            else
            {
                isNodeVisitedMap.put(tempNode, true);
                tempNode = nodeStack.isEmpty() ? nodeStack.pop() : null;

            }
        }
    }
    return deepestNode;
}

/**
 * This will get left or right node, if both node is visited it will return
 * null
 *
 * @param tempNode
 * @param isNodeVisitedMap
 * @return
 */
private static <T> BinaryTree<T> getNonVisitedChildNode(BinaryTree<T> tempNode,
        Map<BinaryTree<T>, Boolean> isNodeVisitedMap)
{
    BinaryTree<T> childNode = tempNode.getLeftNode();

    if (isNodeVisited(isNodeVisitedMap, childNode))
    {
        childNode = isNodeVisited(isNodeVisitedMap, tempNode.getRightNode()) ? null : tempNode.getRightNode();
    }
    return childNode;
}

private static <T> boolean isNodeVisited(Map<BinaryTree<T>, Boolean> isNodeVisitedMap, BinaryTree<T> childNode)
{
    return childNode == null || isNodeVisitedMap.containsKey(childNode);
}
}


texts: Automatic Visual Studio Nuget consolidatation

texts:
I'm hoping to automate the 'Manage Nuget Packages for Solution' Consolidate User Interface using Powershell in the 'Package Manager Console'.

The following script should take ONE of the packages in the consolidation list and 'fix it'.

#do just one
get-package | Group-Object Id | foreach { [pscustomobject]@{ packagename=$_.Name; VG=$_.Group ;versions=($_.Group |select -expandproperty versions |select -ExpandProperty Version); versionMAX=($_.Group |select -expandproperty versions |select -ExpandProperty Version |sort -property versions -descending |select -last 1)  } } | foreach { [pscustomobject]@{ packagename=$_.packagename; VG=$_.VG; versions=$_.versions; versionCount= $_.versions.Count; versionMAX=$_.versionMAX }} | where versionCount -gt 1 | foreach { [pscustomobject]@{ packagename=$_.packagename; VG=$_.VG; versions=$_.versions; versionMAX=$_.versionMAX; dversions=($_.versions | select -Unique) }} | foreach { [pscustomobject]@{ packagename=$_.packagename; VG=$_.VG; versionMAX=$_.versionMAX; PN=$_.VG.ProjectName; versions=$_.versions; dversionCount=$_.dversions.Count }} | where dversionCount -gt 1 | select -first 1 | foreach { foreach($v in $_.VG) { update-package -Id $v.Id -Version $_.versionMAX -projectname $v.ProjectName } }


texts: Fetching AJAX results from three endpoints, with error handling

texts:
I have a requirement in which I need to get data by making AJAX calls. First search for data in endPoint1, if not found then in endPoint2, if not found then in endPoint3. But if any of the endPoint returns data, then there is no need to make further REST calls.

I have achieved the functionality, but the code looks spaghetti.

If possible, please suggest a better approach to reduce this call indentation.

function myAjaxFunction(endPoint) {
    // returns promise
}

function checkForData() {
    myAjaxFunction(endPoint1)
        .then(function (data) {
            if (data.d.results.length > 0) { return "Data found"; }
            else {
                myAjaxFunction(endPoint2)
                    .then(function (data) {
                        if (data.d.results.length > 0) { return "Data found"; }
                        else {
                            myAjaxFunction(endPoint3)
                                .then(function (data) {
                                    if (data.d.results.length > 0) { return "Data found"; }
                                    else {
                                        console.info("sorry data not exist");
                                    }
                                }, function (e) {
                                    console.error()
                                });
                        }
                    }, function (e) {
                        console.error()
                    });
            }
        },
        function (data) {
            if (data.d.results.length > 0) { return "Data found"; }
            else {
                return "not found.";
            }
        });
}


texts:
I've made a very simple program that takes integer number arguments either with plus/minus sign or without them, and print the number in binary format.

binary.c

#include <stdio.h>

void printBinary(int);
int toInt(int*, char[]);
int handleProgram(char[]);

int main(int argc, char *argv[])
{
    return handleProgram(argv[1]);
}

int handleProgram(char param[])
{
    int number, state;

    if( toInt( &number, param ) != -1 )
    {
        printBinary(number);

        state = 0;
    }
    else
    {
        printf("\tmain()::Exiting program...\n");

        state = -1;
    }

    return state;
}

void printBinary(int number)
{
    for (int i = 31; i >= 0; i--)
    {
        if (number >> i & 1 == 1)
            putchar('1');
        else
            putchar('0');

        if (i != 0)
        {
            if (i % 4 == 0)
                putchar(' ');

            if (i % 16 == 0)
                printf(": ");
        }
    }

    printf("\n");
}

int toInt(int *num, char param[])
{
    *num = 0;
    int sign = 1;
    int i = 0;

    if(param == NULL)
    {
        printf("\ttoInt()::No parameter, please enter a valid number!\n");

        return -1;
    }

    if(param[i] == '-')
    {
        sign = -1;
        i++;
    }
    else if( param[i] == '+' )
    {
        i++;
    }

    // check that a number exist
    if(param[i] == '\0')
    {
        printf("\ttoInt()::No number detected, please enter a valid number\n");

        return -1;
    }

    for(; param[i] != '\0'; i++)
    {
        if(param[i] >= '0' && param[i] <= '9')
            *num = 10* *num + param[i] - '0';
        else
        {
            printf("\ttoInt()::Invalid parameter, please enter a valid number!\n");

            return -1;
        }
    }

    *num *= sign;

    return 0;
}

Sample output: positive and negative cases

D:\C\chapter2>gcc binary.c -o binary.exe

D:\C\chapter2>binary 3
0000 0000 0000 0000 : 0000 0000 0000 0011

D:\C\chapter2>binary +3
0000 0000 0000 0000 : 0000 0000 0000 0011

D:\C\chapter2>binary -3
1111 1111 1111 1111 : 1111 1111 1111 1101

D:\C\chapter2>binary +3s
        toInt()::Invalid parameter, please enter a valid number!
        main()::Exiting program...

D:\C\chapter2>binary -3s
        toInt()::Invalid parameter, please enter a valid number!
        main()::Exiting program...

D:\C\chapter2>binary s
        toInt()::Invalid parameter, please enter a valid number!
        main()::Exiting program...

D:\C\chapter2>binary +
        toInt()::No number detected, please enter a valid number
        main()::Exiting program...

D:\C\chapter2>binary -
        toInt()::No number detected, please enter a valid number
        main()::Exiting program...

D:\C\chapter2>binary
        toInt()::No parameter, please enter a valid number!
        main()::Exiting program...

Any ideas for a better approach (where to fix, what to do about negative cases, any more functions need)?


texts: Coding adjacency list representing graph

texts:
I want to write some basic code on graph like DFS, BFS but before that I am coding graph representation in adjacency list, and some basic functions like readgraphfrommatrix. (This will initialize graph from adjacency matrix which is easier to supply as input to test the program.)

A vertex can have some info like name (say name of town), an edge can have some info like weight.

Does below code look decent enough or there are more standard recognized code snippets for adjacency list representation of graphs?

struct edge
{
    char *data;
}

struct vertex
{
    char *data;
};

struct node
{
    int vertexnumber;
    struct node *next;
}

struct graph
{
    int nvertex,nedges; //
    struct vertex **V; // in main, I will malloc depending on input to have sth like struct vertex V[nvertex];
    struct edge **E //to have like struct edge E[nedges];
    struct node **list ; // to have like struct node* list[nvertex];
}


texts: Count the number of duplicated chars in a string

texts:
It's an exercise, which I found on Codewars.

Instructions:

Write a function which returns the count of distinct case-insensitive alphabetic characters and numeric digits which occur more then once in a given string. The given string can be assumed to contain only alphabets (lower-, uppercase) and numerics.

Examples:

"abcde" results in 0, because no characters repeats more than once.
"aabbcde" results in 2, because of 'a' and 'b'.
"aabBcde" => 2, because 'a' occurs twice and 'b' occurs twice (b and B).
"indivisibility" => 1, because 'i' occurs six times.
"Indivisibilities" => 2, because 'i' seven times & 's' twice.
"aA11" => 2, because 'a' and '1'.
"ABBA" -> 2, because 'A' and 'B' each twice.

My (valid*) solution:

fun duplicateCount(text: String): Int {
    var count = 0
    var invalid = ArrayList<Char>()
    var i = 0

    while (i < text.length) {
        if (invalid.contains(text[i].toLowerCase())) {
            i++
            continue
        }

        var j = i + 1

        while (j < text.length) {
            if (text[i].toLowerCase() == text[j].toLowerCase()) {
                invalid.add(text[i].toLowerCase())
                count++
                break
            }
            j++
        }

        i++
    }

    return count
}

*It has passed the unit-tests.

What are your thoughts about my implementation?

How could it be improved? What would you have done differently and why?

Looking forward to reading your comments and answers.


texts:
I have built a small script that provides touch screen right click context menu with long touch press in my ELAN touchscreen.
There is no need to remove your finger in order context menu to pop up.

System Specs: Debian 8 Sid, with XFCE and Nautilus as WM.

Some environments handle right clicks differently:

Environments like XFCE and Thunar, right click is correctly injected in free space.
Environments like Nautilus (i.e Caja, Nemo) right click is ignored.

Raising context menu in Nautilus free / user space seems impossible due to the fact that Nautilus does not allow right click menu to pop up while you are pressing left click, and you perform a kind of "drag". Although this is allowed when you select an item (file/folder) inside nautilus. To which I have found a solution to overcome this Nautilus limitation. I inject a right click while I long press the screen inside Nautilus space but it is a little bit ugly, as I temporary disable the screen, then I inject a right click, and then I enable the screen again.

I wonder if there is a better way to overcome this Nautilus limitation.

Below you will find the currently nice working script, which in any case targets to provide context menu without finger release.

Remark : Bellow script works with ELAN TouchScreen and any other touchscreen that emits a BTN_TOUCH (code 330) event.

from evdev import InputDevice
import time
from pymouse import PyMouse
from threading import Timer
import subprocess

def rightclick():
    print "Right Click Timer Starting. Pressed Flag=", pressed
    timestop = time.time()
    endx, endy = m.position()  # Get the coordinates after time has elapsed
    deltatime = timestop - timestart
    if pressed == True and (abs(endx - startx) < 20) and (abs(endy - starty) < 20):
        print 'Timer Finished - Right Click to be injected. Pressed Flag:', pressed, 'Deltatime=', deltatime, ' Delta X:', abs(endx - startx), ' Delta Y:', abs(endy - starty)
    subprocess.check_call(['xinput', '--disable', 'ELAN Touchscreen'])
    m.press(endx, endy, 2)
    m.release(endx, endy, 2)
    subprocess.check_call(['xinput', '--enable', 'ELAN Touchscreen'])

dev = InputDevice('/dev/input/event10')
# Run evtest to verify the correct ELAN event number and modify above line accordingly
print(dev)  # Print device information
m = PyMouse() #Register a pymouse object

# -------- Right Click Injection without finger relase (Code Begin)

pressed = False
for event in dev.read_loop():
    if event.type == 1 and event.code == 330 and event.value == 1:
    #corresponds to BTN_TOUCH (330) event. value 1 means btn pressed down = screen pressed
        startx, starty = m.position()
        # gets mouse current/starting position coordinates
        pressed = True
        timestart = time.time()
        t = Timer(1.0, rightclick) #register a timer of 1 second and call rightclick function when finished.
        t.start() # start the timer

    if event.type == 1 and event.code == 330 and event.value == 0:
    #corresponds to BTN_TOUCH (330) up event. value 0 means btn up = screen not pressed = finger removed
    # Detecting finger release BTN_TOUCH (330); Value becomes 0.
        print "Finger removed ..."
        pressed = False
        t.cancel() #Cancel the timer and cancel right click injection if finger removed before 1 second (short press , equal to left click on touchscreens)

    if event.type == 3 and event.code == 47 and event.value == 1:
    #Event ABS_MT_SLOT . This event gets value 1 when 2 fingers touch the screen.
    # Two fingers tap brings right click menu.
        print "Two Finger tap..."
        x2, y2 = m.position()  # Get the pointer coordinates
        m.click(x2, y2, 2)
        print "Two Finger tap Right Click Injected..."

# --------  Right Click Injection without finger relase (Code End)


texts: Making a datatable, maybe also with column filters

texts:
In case the table has class 'trans' - run dataTable() and columnFilter(); otherwise  just run dataTable().

Is it possible to not repeat the dataTable() part?

$('#dt_a').each(function() {
        if ($(this).hasClass('trans')) {
            $(this).dataTable({
                "sDom": "<'row'<'span6'<'dt_actions'>l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
                "sPaginationType": "bootstrap_alt",
                "oLanguage": {
                    "sLengthMenu": "_MENU_ records per page"
                }
            })
            .columnFilter({
                sPlaceHolder: "head:before",
                aoColumns: [
                    null,
                    { type: "text" },
                    { type: "text" },
                    { type: "date-range" },
                    { type: "text" },
                    { type: "text" },
                    null,
                    null
                ]
            });
        } else {
            $(this).dataTable({
                "sDom": "<'row'<'span6'<'dt_actions'>l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
                "sPaginationType": "bootstrap_alt",
                "oLanguage": {
                    "sLengthMenu": "_MENU_ records per page"
                }
            });
        }
    });

NOTE:

columnFilter is an extension to dataTable.


texts: Handling optimistic concurrency violations

texts:
I'm trying to establish a concurrency violation verification in my SQL updates using C# and raw SQL.

What I'm doing now is storing the TimeStamp value in a byte[] upon selection and before updating I'm checking if the stored value is equal to the current value. here's the code:

static void update()
{
    using (SqlConnection connection = new SqlConnection(""))
    {
        try
        {
            //open connection
            connection.Open();

            //select row for update - for testing purposes it's in the same block
            SqlCommand select = connection.CreateCommand();
            select.CommandText = "SELECT timeStamp FROM Person WHERE ID = 1";
            //store the time stamp in a byte[]
            byte[] ts = (byte[])select.ExecuteScalar();

            //check if the time stamp hasn't changed
            if (ByteArraysEqual(ts, (byte[])select.ExecuteScalar()))
            {
                //Update
                SqlCommand command = connection.CreateCommand();
                command.CommandText = "Update Person SET Age=1111 WHERE ID = 1";
                command.ExecuteNonQuery();
            }
            else
            {
                //cocurrency violation occured
                Console.WriteLine("concurrency error!");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Update error:\n" + ex.Message);
        }
        finally
        {
            connection.Close();
        }
    }
}
static bool ByteArraysEqual(byte[] b1, byte[] b2)
{
    if (b1 == b2) return true;
    if (b1 == null || b2 == null) return false;
    if (b1.Length != b2.Length) return false;
    for (int i = 0; i < b1.Length; i++)
    {
        if (b1[i] != b2[i]) return false;
    }
    return true;
}

I wonder if this is the right approach to verify the Person has not been updated by another user between the selection and the actual update?


texts: SpringData: filtering fields of Entity in Repository

texts:
My entity is Office. In office repository I would like to find all office Addresses:

  default List<Address> findOfficeLocations() {
    Iterable<Office> offices = findAll();
    return StreamSupport.stream(offices.spliterator(), false)
        .map(Office::getOfficeLocation).distinct().collect(Collectors.toList());
  }

Is it good practice or better to do it in the Service?


texts:
private void loadTabsIfGPSAndInternetAvailable()
    {
        final Utils utils = new Utils(this);
        final LocationClient locationClient = new LocationClient(this);
        if (!utils.isConnected())
        {
            utils.generateNoConnectivityAlert();
        }
        else if (!locationClient.hasGPS())
        {
            utils.generateNoGPSAlert();
        }
        else
        {
            if (androidVersion >= Build.VERSION_CODES.M)
            {
                requestAllPermissions();
            }
            else
            {
                loadCameraAndForecastTabs();
            }
        } // ends else block for if internet and GPS are enabled
    }

This is some code that loads tabs if the GPS and internet connectivity are available.  I'm aware that at the moment this is very messy code, with lots of nested if statements, that is hard to read, and am not sure how to structure it better.  Can people help me please?


texts:
This started as a simple exercise in sorting an array. I wanted to make it a bit more complex which is why I made it a 2D array.

I then noticed that each pass that checked and swapped values, it was checking all ten values. This seemed unnecessary because with each pass the highest value gets moved all the way to its final position. So I made it check one less element each pass until it finished.

I did not want to use std::sort, this was an exercise in finding my own solution.

The program was "falling off" the end of the array, and although I managed to work around it, I'm not sure I did it in the right way, or even why it was doing it in the first place.

The program seems to work as intended but would like some feedback on how it can be improved, or any issues etc.

#include "stdafx.h"

#include<iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
    const int ROWS = 10;
    const int COLUMNS = 2;

    int person[ROWS][COLUMNS] =
    {
        { 1,100 },
        { 2,20 },
        { 3,80 },
        { 4,10 },
        { 5,50 },
        { 6,150 },
        { 7,30 },
        { 8,60 },
        { 9,40 },
        { 10,1 }
    };

    for (int i = 0; i < ROWS; ++i)
    {
        cout << "Person " << person[i][0] << " ate: " << person[i][1] << " pancakes";
        {
            cout << endl;
        }
    }

    // Sort lowest to highest

    int loop = 1;
    int count;           // for counting the number of loops
    int limit = ROWS;    // reduced by 1 each loop to skip uneceassary checks

    for (int j = ROWS - 1; j > 0; --j, loop++, limit--)
    {
        cout << "Loop " << loop << endl;
        cout << "Loop limit: " << limit << endl;
        count = 0;

        for (int i = 0; i < ROWS; ++i, ++count )
        {
            if (loop + count == ROWS + 1)   // skips unnecessary checks
            {
                break;
            }
            if (person[i][1] > person[i + 1][1] && i != ROWS - 1)
    // The && condition stopped the  program falling off the end of the array
    // but not sure why it was in the first place
            {
                int temp = person[i][1];
                person[i][1] = person[i + 1][1];
                person[i + 1][1] = temp;
            }
            //cout << person[i][0] << " " << person[i][1] << endl;
            //un-comment ^ to display inner loop passes
        }
        cout << "Number of inner loops: " << count << "\n" << endl;
    }

    // display final order
    for (int i = 0; i < ROWS; ++i)
    {
        cout << person[i][0] << "   " << person[i][1] << endl;
    }

    int pause;
    cin >> pause;

    return 0;
}


texts:
The puzzle is:

  The deck contains 21 unique numbers
  The numbers should be laid up in rows of 7 (3 rows in total)
  ask the player to memorize a number to start the game
  once the game starts, rearrange the numbers in random in all rows.
  ask the player to select the row the number is in.
  once the player selects, rearrange the numbers for a second time

  this time, it is not random but sort the numbers in bundles per row
  stack all the bundles on top of each other, keeping the row selected to be in the centre.
  rearrange it back into rows of 7 such that first number in stack goes to row 1, second to row 2, third to row 3, 4th to row 1 again and so on.

  again ask the player to select the row the number is in.
  repeat step 6
  again ask the player to select the row the number is in.
  point to the middle number of the row selected as the answer.

  You can use any programming language to solve this.

I'd like feedback on this.

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define numRows 3
#define numCols 7
#define TotalNum (numRows*numCols)

void random_rearrange_num(int p[][numCols]) ;
void display(int p[][numCols]) ;
void start();
int row_select(int count);
void stackup(int p[][numCols],int *s,int count);
void back_to_array(int p[][numCols],int *s);

int main()
{
    //for random numbers
    srand(time(NULL));

    //Step 1
    int arr[numRows][numCols] = {{0,1,2,3,4,5,6},{7,8,9,10,11,12,13},{14,15,16,17,18,19,20}};
    int stack[TotalNum] = {0};
    int row = 0;

    //Step 2
    display(arr);

    //Step 3
    start();

    //step 4
    random_rearrange_num(arr);

    //Step 5 (first time)
    display(arr);
    row = row_select(row);

    //Step 6
    stackup(arr,stack,row);
    back_to_array(arr,stack);

    //Step 7 (second time)
    display(arr);
    row = row_select(row);

    //Step 8:repeat step 6
    stackup(arr,stack,row);
    back_to_array(arr,stack);

    //Step 9 (third time)
    display(arr);
    row = row_select(row);

    //Step 10 and Step 11
    printf("The answer is : %i",arr[row][3]);

    return 0;
}
void random_rearrange_num(int p[][numCols])
{
  int temp = 0,k= 0,l = 0;
  for(int i = numRows-1 ; i > 0 ; i--)
  {
    for (int j = numCols-1;j>0; j--)
    {
          k = 0 + rand()/(RAND_MAX/(2-0+1)+1);
          l= 0 + rand()/(RAND_MAX/(6-0+1)+1);
          temp = p[i][j];
          p[i][j] = p[k][l];
          p[k][l] = temp;
    }
  }
}

void display(int p[][numCols])
{
       //printf("\n");
       for (int i = 0; i< numRows;i++)
       {
          for ( int j = 0;j< numCols;j++)
          {
            printf("%8i",p[i][j]);
          }
          printf("\n");
       }
}

void start()
{
        printf("\n");
        printf("Please memorize a number(between 0 to 20) and press enter to continue");
        char c=getchar();
        while (c != '\n')
            c=getchar();
        printf("\n");
}
int row_select(int count)
{
     printf("\n");
     printf("Please select the row the number is in(between 1 to 3):");
     scanf_s("%i",&count);
     return count-1;
}

void stackup(int p[][numCols],int *s,int count)
 {
    int k = 0,t= 0;
    int middle = (numRows-1)/2;
    for (int i = 0; i<numRows; i++)
    {
        t=i;
        if (i==middle || i==count)
            i = (i==count)?middle:count;
        for (int j = 0; j<numCols; j++)
        {
            s[k++] = p[i][j];
        }
        i=t;
    }
}
void back_to_array(int p[][numCols],int *s)
{
  int k = 0;
  for (int i = 0; i< numCols;i++)
       {
          for ( int j = 0;j<numRows;j++)
          {
             p[j][i] = s[k++];
          }

       }
}


texts: Counting the number of distinct words in the input

texts:
Below is a working program I wrote. Please provide comments to help me improve my coding and problem solving skills. I am learning C++ myself by reading Accelerated C++ by Andrew Koenig.

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<string> words;
    cout<<"Please Enter words(Press Ctrl+Z in the end)"<<endl;

    string x; //Word Input
    cin>>x;
    words.push_back(x); //The first word
    int ndw=1; //Number of distinct words

    while(cin>>x) //Input new word
    {
        for(unsigned int counter = 0; counter!=words.size(); ++counter)
        {
            //Check if we already have this word in our list
            if(x!=words[counter])
            {
                if(counter==words.size()-1)//We have reached the end of list
                {
                    words.push_back(x);
                    ndw+=1;
                }
            }
            else
            {
                //If there is a match, leave this word
                break;
            }
        }
    }
    cout<<"number of distinct words are: "<<ndw;
    return 0;
}

Here is a sample output

Another Sample output


texts: leftMerge function to deep overlay saved state

texts:
This code is used to deep overlay saved state (as an object) over a template object, which is the current model, this model can change (e.g have new attributes added), and a simple _.clone call will not cut it since that does a shallow copy, and will copy nested arrays/objects byref. This code works, and I'm curious if you would you fail it on code review or have any suggestions to make it better?  Please don't be kind!

function isObjectPair(a, b) {
    return typeof a == 'object' && typeof b == 'object';
}

function isArrayPair(a, b) {
    return _.isArray(a) && _.isArray(b);
}

function isArrayOrObjectPair(a, b) {
    return isObjectPair || isArrayPair(a, b);
}

function leftMerge(a, b) {
    for (var i in b) {
        if (a.hasOwnProperty(i)) {
            if (isArrayPair(a[i],b[i])) {
                for (var j = 0, jlen = b[i].length; j < jlen; j++) {
                    if (isArrayOrObjectPair(a[i][j], b[i][j])) {
                        leftMerge(a[i][j], b[i][j]);
                    } else {
                        a[i][j] = b[i][j];
                    }
                }
            } else if (isObjectPair(a[i], b[i])) {
                if (a[i] === null) {
                    a[i] = _.clone(b[i]);
                } else {
                    leftMerge(a[i], b[i]);
                }
            } else {
                a[i] = b[i];
            }
        }
    }
}


texts: Efficient date-based lookup function in R

texts:
Right now this function takes an excessively long time to run, please let me know how to make it more efficient.

lunarCal is 144x7 and the dput for it is here.

Here's the code:

if(!require(pacman)) install.packages("pacman")
pacman::p_load(lubridate)
cat("Please make sure that birthday inputs are in YYYY-MM-DD format")

lunarCal             <- readRDS("data/lunarCal.RDS")

eastern.profile <- function(birthday){
    good                 <- is.na.POSIXlt(birthday)
    if(!(good)){birthday <- strptime(birthday, format = "%Y-%m-%d", tz = "Asia/Chongqing")}
    ind                  <- (lunarCal$START_DATE <= birthday) & (lunarCal$END_DATE >= birthday)
    temp                 <- subset(lunarCal, ind)
    return(temp)
}

Here's an example of its non-vectorized usage:

eastern.profile("1975-01-01")
   YEAR START_DATE   END_DATE ANIMAL ELEMENT ASPECT                                   PERSONALITY
75 1974 1974-01-23 1975-02-10  Tiger    Wood      + Imagination, creativity, idealism, compassion

When I run it I'm using sapply but it's still slow. I've got a data set with 250,000 dates I'm applying it to and it took over 15 minutes.
We can simulate the data set to run this function on with

dat <- as.data.frame(seq(as.Date("1900/1/1"), as.Date("2040/1/1"), "days"))
dat <- rbind(dat,dat,dat,dat)


texts:
I've completed the string calculator kata in Ruby (spec from here - http://osherove.com/tdd-kata-1/). All tests currently pass.

Could it be refactored further to improve readability? And could I make my testing better?

string_calculator.rb

class StringCalculator

  def initialize
  end

  def int_add(string_of_numbers)
    raise 'only accepts a string' unless string_of_numbers.is_a?(String)
    string_array = string_of_numbers.split(/[^0-9-]+/)
    integer_array = string_array.map(&:to_i)
    raise "cannot accept negatives - #{check_for_negatives(integer_array)}" if
check_for_negatives(integer_array)
    integer_array.inject(0){|sum,x| x <= 1000? sum + x : sum }
  end

  def check_for_negatives(integer_array)
     negatives_array = integer_array.select{ |i| i<0 }
    if negatives_array.length > 0
      return negatives_string = negatives_array.join(",")
    else
      return false
    end
  end

end

string_calculator_spec.rb

require 'string_calculator'

describe StringCalculator do

  subject(:calculator) { described_class.new }

  it 'should accept a string' do
    expect{ calculator.int_add('1,2,3') }.not_to raise_error
  end

  it 'should not accept other data types' do
    expect{ calculator.int_add(123) }.to raise_error('only accepts a string')
    expect{ calculator.int_add(['123']) }.to raise_error('only accepts a
string')
  end

  it 'should return 0 for an empty string' do
    expect(calculator.int_add('')).to eq(0)
  end

  it 'should return a number if the passed string contains no delimiters' do
    expect(calculator.int_add('123')).to eq (123)
  end

  it 'should return the sum of the numbers in the passed string, if the passed
string contains comma delimiters' do
    expect(calculator.int_add('12,34')).to eq(46)
  end

  it 'should return the sum of the numbers in the passed string, if the passed
string contains new line delimiters' do
    expect(calculator.int_add("12\n34\n56")).to eq(102)
  end

  it 'should handle multiple random delimiters' do
    expect(calculator.int_add("//;\n1;2")).to eq(3)
  end

  it 'should not accept negative numbers' do
    expect{ calculator.int_add("123,-2") }.to raise_error("cannot accept
negatives - -2")
  end

  it 'should ignore numbers larger than 1000' do
    expect(calculator.int_add("//;\n1;2:1001")).to eq(3)
  end

end


texts:
I have written code to solve the following Rosalind problem. This is my first time writing in C and I would like a review of my code, particularly in regard to correctness and performance.

#include <stdio.h>
#include <string.h>
int main() {

    /* Input DNA of length at most 1000 nucleotides */
    char dna[1000];
    FILE *input;
    input = fopen("/Users/James/Desktop/rosalind_dna.txt", "r");
    fgets(dna, 1000, input);
    fclose(input);

    /* Count frequency of symbols 'A', 'C', 'G' and 'T' in DNA */
    int i, a, c, g, t;
    for(i=0; i<strlen(dna); i++) {
        if (dna[i] == 'A') {
            a += 1;
        }
        else if (dna[i] == 'C') {
            c += 1;
        }
        else if (dna[i] == 'G') {
            g += 1;
        }
        else if (dna[i] == 'T') {
            t += 1;
        }
    }

    /* Output frequency of DNA nucleotides */
    printf("%i %i %i %i", a, c, g, t);
    return 0;
}

Updated Code

#include <stdio.h>
#include <string.h>
#define READ_BUFFER_SIZE 1000

int main() {

    /* Input DNA of length at most 1000 nucleotides */
    char dna[READ_BUFFER_SIZE];
    FILE *input;
    input = fopen("/Users/James/Desktop/rosalind_dna.txt", "r");
    if (input == NULL) {
        perror("Error");
    }
    fgets(dna, READ_BUFFER_SIZE, input);
    fclose(input);

    /* Count frequency of symbols 'A', 'C', 'G' and 'T' in DNA */
    int aCount, cCount, gCount, tCount;
    char *current;
    for(current = dna; *current; ++current) {
        switch(*current){
            case 'A':
                ++aCount;
                break;
            case 'C':
                ++cCount;
                break;
            case 'G':
                ++gCount;
                break;
            case 'T':
                ++tCount;
                break;
            default:
                printf("Error: Invalid nucleotide\n");
                break;
        }
    }

    /* Output frequency of DNA nucleotides */
    printf("%i %i %i %i", aCount, cCount, gCount, tCount);
    return 0;
}


texts:
I got this data structure and I am checking to see which properties are true, then I am adding the key for all the properties that are true to that object on a new property called combined

const data = [
  {
    keyword: 'banana',
    yellow: true,
    sweet: true
  },
  {
    keyword: 'pineapple',
    yellow: true,
    sweet: false
  },
  {
    keyword: 'apple',
    yellow: false,
    sweet: false
  },
]

const combined = [...data].reduce((acc, { keyword, ...rest}) => {
  const res = Object.entries(rest).reduce((total, [key, value]) => {
    if (value === true) total.push(key)
    return total
  }, [])
  acc.push(res)
  return acc
}, []).map(entry => ({ combined: entry.join(' ') }))

const output = data.map((entry, index) => ({
  ...entry,
  ...combined[index]
}))

console.log(output)
.as-console-wrapper { max-height: 100% !important; top: 0; }

It seems pretty straight forward but somehow this feels a bit convoluted


texts:
Situation
So I have made a list of PictureBoxes on my form that looks as follows:

All images have a panel behind them that is 4px lager (2xp all around the picture box). The images are named x1, x2, xn.. respectively. The panels behind the images are named y1, y2, yn.. respectively.

I want this to happen smoothly when one of the 5 PictureBoxes is clicked:

Before clicked, all pictureboxes are 48x48 and respective panels  52x52
When one gets clicked, resize the picturebox to 62x62 and the respective panels to 66x66
When one gets clicked, the image must hold the same center as previously
When one gets clicked, all other images turn back 'small'
when a 'enlarged' image gets clicked, nothing happens

What I made

When form is created, two lists are initialised:

List<PictureBox> views = new List<PictureBox> { x1, x2, x3, x4, x5 }; and
List<Panel> backviews = new List<Panel> { y1, y2, y3, y4, y5 };

and
PictureBox current which is the name of the current picturebox (x1, x2, etc.)

All PictureBoxes in views have a click event that points to x_Click

private void x_Click(object sender, EventArgs e)
        {
            PictureBox x = sender as PictureBox;

            //Only do something if clicked PictureBox is not large
            if (x.Size != new Size(62, 62))
            {
                // This keeps the PictureBox center constant
                x.Location = new Point(x.Left - 7, x.Top - 7);
                // Resize picturebox
                x.Size = new Size(62, 62);
                // Get the panel corresponding to the PictureBox
                Control y = backviews[int.Parse(x.Name.Replace("x", "")) - 1];
                // This keeps the Panel center constant
                y.Location = new Point(y.Left - 7, y.Top - 7);
                // Resize Panel
                y.Size = new Size(66, 66);

                // Find the current enlarged PictureBox and reverse what is done above
                Control z = views[int.Parse(current.Replace("x", "")) - 1];
                z.Location = new Point(z.Left + 7, z.Top + 7);
                z.Size = new Size(48, 48);
                Control w = backviews[int.Parse(z.Name.Replace("x", "")) - 1];
                w.Location = new Point(w.Left + 7, w.Top + 7);
                w.Size = new Size(52, 52);

                // Set the currently enlarged PictureBox
                current = x.Name;
            }

        }

This works, but not smoothly; I can visually intercept the Panel being enlarged after the PictureBox is being enlarged. I suspect most time is taken by finding the Panels corresponding to the PictureBoxes. Is there any way I can speed this up?


texts:
Problem (Tape Equilibrium):

  A non-empty zero-indexed array A consisting of N integers is given.
  Array A represents numbers on a tape. Any integer P, such that 0 < P < N,
  splits this tape into two non−empty parts:

   A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].

  The difference between the two parts is the value of:

 |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|

  In other words, it is the absolute difference
  between the sum of the first part and the sum of the second part.For
  example, consider array A such that:

  A[0] = 3
  A[1] = 1
  A[2] = 2
  A[3] = 4
  A[4] = 3

  We can split this tape in four places:

P = 1, difference = |3 − 10| = 7
P = 2, difference = |4 − 9| = 5
P = 3, difference = |6 − 7| = 1
P = 4, difference = |10 − 3| = 7

  Write a function: int solution(int A[], int N); that, given a
  non-empty zero-indexed array A of N integers, returns the minimal
  difference that can be achieved.

My solution to it is:

class Solution {
    public int solution(int[] A) {
        long minDiff = Integer.MAX_VALUE;
        long[] leftSums = new long[A.length];
        long totalSum = 0;

        //init
        totalSum += A[0];
        leftSums[0] += 0;  //whatever, don't use leftSums[0] anyway

        for (int i = 1; i < A.length; ++i) {
            totalSum += A[i];
            leftSums[i] += leftSums[i-1] + A[i-1];
        }

        for (int i = 1; i < A.length; ++i) {
            long diff = Math.abs(totalSum - 2 * leftSums[i]);
            if(diff < minDiff){
                minDiff = diff;
            }
        }

        return (int) minDiff;
    }
}


texts:
I was told to create a calculator design on AWT, which is also my first project on AWT.  I wrote the program and submitted it.  I was then told that my program contains around 70 lines of code, and I should try to write less code.  How can I shorten this code?

import java.awt.*;
class Demo{
    Frame f;
    TextField tf;
    Button add,sub,mul,div,find,zero,num1,num2,num3,num4,num5,num6,num7,num8,num9;
    Button num0,decimal,per;
    Demo(String s)
    {
        f=new Frame(s);
        tf=new TextField("0");
        tf.setBounds(20, 40, 205, 40);
        f.add(tf);
        add=new Button("+");
        sub=new Button("-");
        div=new Button("/");
        mul=new Button("x");
        find=new Button("=");
        zero=new Button("C");
        num1=new Button("1");
        num2=new Button("2");
        num3=new Button("3");
        num4=new Button("4");
        num5=new Button("5");
        num6=new Button("6");
        num7=new Button("7");
        num8=new Button("8");
        num9=new Button("9");
        num0=new Button("0");
        per=new Button("%");
        decimal=new Button(".");
        mul.setBounds(125,100,50,40);
        add.setBounds(70,100,50,40);
        sub.setBounds(15, 100, 50, 40);
        div.setBounds(180, 100, 50, 40);
        find.setBounds(180,250,50,88);
        zero.setBounds(180, 150, 50, 40);
        num9.setBounds(15,150,50,40);
        num8.setBounds(70,150,50,40);
        num7.setBounds(125,150,50,40);
        num6.setBounds(15,200,50,40);
        num5.setBounds(70,200,50,40);
        num4.setBounds(125,200,50,40);
        num3.setBounds(15,250,50,40);
        num2.setBounds(70,250,50,40);
        num1.setBounds(125,250,50,40);
        num0.setBounds(15,300,105,40);
        decimal.setBounds(125,300,50,40);
        per.setBounds(180,200,50,40);
        f.add(per);
        f.add(add);
        f.add(mul);
        f.add(div);
        f.add(sub);
        f.add(find);
        f.add(zero);
        f.add(num1);
        f.add(num2);
        f.add(num3);
        f.add(num4);
        f.add(num5);
        f.add(num6);
        f.add(num7);
        f.add(num8);
        f.add(num9);
        f.add(num0);
        f.add(decimal);
        f.setLayout(null);
        f.setSize(250,350);
        f.setVisible(true);
    }
    public static void main(String[] args)
    {
        new Demo("Calculator");
    }

}


texts: Fastest way to determine if a number is perfect square

texts:
I'm looking for the fastest way to determine if a long value is a perfect square (i.e. its square root is another integer). I was asked this in an interview recently.

Here is the very simple and straightforward way I'm doing it now:

  private static boolean isSquare(long n) {
    int i = 1;
    for (;;) {
      if (n < 0)
        return false;
      if (n == 0)
        return true;
      n -= i;
      i += 2;
    }
  }

Is there any better way by which we can do this or optimize this more?


texts: Project Euler 28 - Number Spiral Diagonals

texts:
Project Euler problem 28

  Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

  $$\begin{array}{rrrrr}
\color{red}{21} &22 &23 &24 &\color{red}{25}\\
20 & \color{red}{7} & 8 & \color{red}{9} &10\\
19 & 6 & \color{red}{1} & 2 &11\\
18 & \color{red}{5} & 4 & \color{red}{3} &12\\
\color{red}{17} &16 &15 &14 &\color{red}{13}\\
\end{array}$$

  It can be verified that the sum of the numbers on the diagonals is 101.

  What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?

I realized that the spiral was essentially an arithmetic sequence, so I based my code off of that.

from timeit import default_timer as timer
start = timer()

def spiral_diag_sum(n):
    if n < 1: return None
    elif n == 1: return 1
    elif n % 2 == 0: return None
    else:
        numbers = [1]
        while len(numbers) < (2*n - 1):
            increment = int(len(numbers) * 0.5 + 1.5)
            for p in range(4):
                numbers.append(numbers[-1] + increment)
    return sum(numbers)

ans = spiral_diag_sum(1001)
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)


texts:
I was bored, and I was watching a sci-fi show where people were starting out during a long systems check asking each other whether numbers were prime or not, sort of passing the time as they do their inspections.

The show is irrelevant, but I wondered if I could build a prime number checker in Python 3 that would be very quick.  I know this has been done before, but I was curious whether I could do it on my own.

Now, this works fine for smaller numbers, and is pretty darn quick, a second or two.  But for large numbers, it takes a really long time.

I'm not a coder by profession, though, so I'm pretty sure this could be improved.  Any speed improvements are welcome.

Required imports, and the 'test' function which takes input of a number and spits out the results is below,

Currently, the results spit out a tuple, the first value either being Boolean or the number '0' (because the number '1' is a unique case that is not prime but you can't just say 'False' for), and a short string description.

from typing import AnyStr, Optional, Union

def is_prime(num: int) -> (Optional[Union[bool, int]], Optional[AnyStr]):
    if num <= 1:
        return 0, "Neither prime nor composite."

    if num <= 3:
        return True, "Prime"

    for i in range(2, num):
        if (num % i) == 0:
            return False, "Not Prime"

    return True, "Prime"

if __name__ == "__main__":
    n = int(input("Value: "))
    print(is_prime(n))

I'm curious how I can improve the performance of this code for larger numbers so that it's a fairly fast function, rather than taking a very long time to iterate over values.  I know that the iterations in the for loop are taking the hugest amount of time, but I'm not a mathematician so I'm not sure the 'best' approach for speeding up this.  Don't yell at me too harshly, this was more a quick 'mind test' to see if I could come up with something that worked.


texts: Using range minimal query for lowest common ancestor (LCA)

texts:
Here is my code to use range minimal query to resolve the LCA problem. Any advice on code bugs, performance improvement in terms of algorithm time complexity, code style are appreciated.

More specifically, my questions are:

I am using in-order traverse to build depth array. Should I use other traverse, like pre-order (dfs), level-order, or post order?
I am using two additional data structures, index_node_map and node_index_map. I'm wondering if there are any ways to remove them, as they make my code seem lengthy.

Major ideas of my idea are:

Build depth array of each node by in-order traverse
Build MRQ index for depth array built in first step
For any two nodes, their LCA are the lowest depth node between them (in depth array)

from collections import defaultdict
class TreeNode:
    def __init__(self, value, left, right):
        self.value = value
        self.left = left
        self.right = right
class Solution:
    def __init__(self):
        self.index_node_map = defaultdict(int)
        self.node_index_map = defaultdict(int)
        self.depth = []
        self.rmp_map = defaultdict(tuple) # key: (index, step), value: (min value, index)
    def in_order(self, root, level):
        if root.left:
            self.in_order(root.left, level+1)
        self.depth.append(level)
        self.index_node_map[len(self.depth)-1]=root.value
        self.node_index_map[root.value] = len(self.depth)-1
        if root.right:
            self.in_order(root.right, level+1)
    def build_depth_index(self, root, level):
        self.in_order(root, level)
        print self.depth
        print self.index_node_map
        print self.node_index_map
        self.build_rmq_map(self.depth)

    def build_rmq_map(self, result):
        step = len(result).bit_length()
        for i in range(len(result)):
            self.rmp_map[(i,0)]=(result[i],i)
        for s in range(1, step+1):
            for i in range(len(result)):
                if i + 2 **(s-1) < len(result):
                    self.rmp_map[(i,s)] = min(self.rmp_map[(i,s-1)],self.rmp_map[(i+2**(s-1),s-1)])
                else:
                    self.rmp_map[(i,s)] = self.rmp_map[(i, s-1)]

    def rmp_query(self, index1, index2):
        step = (index2 - index1).bit_length()-1
        x = self.rmp_map[(index1, step)]
        y = self.rmp_map[(index2+1-2**(step), step)]
        # return index of depth array min value
        if x[0] < y[0]:
            return x[1]
        else:
            return y[1]

    def lca_query(self, node1, node2):
        index1 = self.node_index_map[node1]
        index2 = self.node_index_map[node2]
        min_index = self.rmp_query(index1, index2)
        return self.index_node_map[min_index]

if __name__ == "__main__":
    root = TreeNode(1, TreeNode(2, TreeNode(4, None, None), TreeNode(5, None, None)), TreeNode(3, TreeNode(6, None, None),TreeNode(7,None,None)))
    s = Solution()
    s.build_depth_index(root, 0)
    print s.lca_query(4,5)
    print s.lca_query(4, 7)


texts:
I am currently converting a 2D game to 3D, never having worked with 3D before I am trying to learn as I go. I am wondering what the best way to use vertex/index buffers is.

I am currently looping through a grid and creating a set of buffers for each tile type, which are are then used in the draw method. I'm presuming I shouldn't use multiple sets of vertex buffers, but I don't know of another way to do this, as each tile is a different texture.

Grid loop

for (int i = Convert.ToInt32(xPos / 2) - 30; i < Convert.ToInt32(xPos / 2) + 30; i++)
{
    for (int a = Convert.ToInt32(yPos / 2); a < Convert.ToInt32(yPos / 2) + 50; a++)
    {
        if (mapXtile > 0 && mapYtile > 0 && mapXtile < Globals.mapsizex && mapYtile < Globals.mapsizey)
        {
            int currentTile = Globals.levelArray[level, mapXtile, mapYtile].TyleType;

            if (currentTile == tyleType.grass)
            {
                createCubeVertices(i * 2, a * 2, 1, 0f, count, grassVertices);
                SetUpBufferIndices(count, grassIndices);
                count++;
            }

            if (currentTile == tyleType.water)
            {
                createCubeVertices(i * 2, a * 2, 1, 0f, count, waterVertices);
                SetUpBufferIndices(count, waterIndices);
                waterCount++;
            }
        }
        mapYtile = mapYtile + 1;
        //mapYtile++;
    }
    mapXtile = mapXtile + 1;
    mapYtile = Convert.ToInt32(yPos / 2);
}

CopyToBuffers(grassVertices, grassIndices);
CopyToWaterBuffers(waterVertices, waterIndices);

Draw code

foreach (EffectPass pass in grassEffect.CurrentTechnique.Passes)
{
    pass.Apply();

    device.Indices = myIndexBuffer;
    device.SetVertexBuffer(myVertexBuffer);
    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, grassVertices.Length, 0, grassIndices.Length/3);
}

foreach (EffectPass pass in mouseEffect.CurrentTechnique.Passes)
{
    pass.Apply();

    device.Indices = myWaterIndexBuffer;
    device.SetVertexBuffer(myWaterVertexBuffer);
    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 10000, 0, 10000);
}


texts: Writing a utility class for converting between datetime and timestamp

texts:
I'm writing an Python application that uses frequently datetime and Unix timestamp. I know Python is 'batteries included', however, I found that converting between datetime and timestamp in Python 2.6 is not trivial. That's why I wrote this utility class. This code works as expected, for Python 2.6, 2.7, and 3.4.

I want the code style of my code reviewed. I don't know whether my function names like dttomicrotimestamp and code styles (like @staticmethod) are suitable for pythonic way of coding.

#!usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division

import time
import datetime
import pytz
from tzlocal import get_localzone

class datetimeutil:
    @staticmethod
    def strtodt(text):
        try:
            dt = datetime.datetime.strptime(text, "%Y-%m-%d %H:%M:%S.%f")
        except:
            dt = datetime.datetime.strptime(text, "%Y-%m-%d %H:%M:%S")
        return get_localzone().localize(dt)

    @staticmethod
    def dttotimestamp(dt):
        if dt.tzinfo is None:
            dt = get_localzone().localize(dt)
        return datetimeutil._totalseconds(
            (dt - dt.utcoffset()).replace(tzinfo=None) -
            datetime.datetime(1970, 1, 1))

    @staticmethod
    def dttomicrotimestamp(dt):
        return int(datetimeutil.dttotimestamp(dt) * 1e6)

    @staticmethod
    def timestamptodt(timestamp):
        return get_localzone().localize(datetime.datetime.fromtimestamp(timestamp))

    @staticmethod
    def microtimestamptodt(microtimestamp):
        return datetimeutil.timestamptodt(microtimestamp / 1e6)

    @staticmethod
    def _totalseconds(timedelta):
        return ((timedelta.seconds + timedelta.days * 24 * 3600) * 1e6
                + timedelta.microseconds) / 1e6


texts:
I created a HangPerson game in Haskell and I must admit it feels very imperative. How can I make it more "functional?" Are there more elegant ways of breaking up the task? The getUserLines function seems to be doing a lot of work. Any additional feedback on efficiency or anything of the sort is also appreciated.

import Control.Monad.State
import System.Random
import Data.List
import System.Process
import Data.Char

type GameValue = String
type GameState = (Int, String)

playGame :: String -> String -> State GameState GameValue
playGame [] word = do
    (_, guessed) <- get
    return guessed

playGame (x:xs) word = do
    (missed, guessed) <- get
    put $ check missed x word guessed
    playGame xs word

check n c word guessed
    | not $ isAlpha c || c `elem` guessed = (n, guessed)
    | c `elem` word    = (n, c:guessed)
    | otherwise        = (n + 1, c:guessed)

replace word guess = map replace' word
    where replace' char = if char `elem` guess then char else '_'

gallows n = "\n\n       |||========|||\n" ++
            (if n > 0 then "       |||         |\n" else "       |||          \n") ++
            (if n > 1 then "       |||         O\n" else "       |||          \n") ++
            (if n < 2 then "       |||           \n" else (helper1 n)) ++
            (if n < 5 then "       |||           \n" else (helper2 n)) ++
            "       |||\n" ++ "       |||\n" ++ "     =================\n\n"

helper1 n
    | n <= 3    = "       |||        /  \n"
    | n <= 4    = "       |||        /| \n"
    | otherwise = "       |||        /|\\\n"

helper2 6 = "       |||        / \\\n"
helper2 _ = "       |||        /  \n"

safeHead []     = ' '
safeHead (x:xs) = x

menu = "\x1B[32m\t\t\t\tWelcome to Hangperson.\nThe rules are the same as always except\n\nIf you enter multiple characters only the first will be read.\nPress Ctrl+D to Give up.\nHave fun\x1B[0m"

getUserLines :: String -> IO String
getUserLines word = go (0, "")
      where go contents = do
            system "clear"
            putStrLn menu
            let misses = fst contents
            let guessed = snd contents
            putStrLn $ gallows misses
            putStrLn $ "You've missed " ++ (show $ misses) ++ " out of 7"
            putStrLn $ "You've guessed: " ++ "\x1B[31m" ++ guessed ++ "\x1B[0m"
            putStrLn $ intersperse ' ' $ replace word guessed
            putStrLn "Guess a letter: "
            line <- getLine
            let guess = [safeHead line]
            let result = execState (playGame guess word) contents
            if (((fst result) == 7) || '_' `notElem` (replace word ((snd result))))
            then (if (fst result) < 7 then return ("You won! The word was " ++ word) else return ("You lost! The word was " ++ word))
            else go result

main = do
    system "reset"
    s <- readFile "/usr/share/dict/words"
    num <- randomIO :: IO Int
    let word = (lines s) !! (num `mod` 230000) --(length $ lines s)) efficient way?
    gameResult <- getUserLines (map toLower word)
    putStrLn gameResult
    putStrLn "Play again? :"
    option <- getLine
    if option == "y" then main else return ()


texts:
I started creating a small abstract simulation framework and would be happy if someone could take a look at the code and give me feedback on it.

The code can be found here, and it is currently not in a 100% finished and tested state.

It should be (almost) multi threading ready.

This is some sample code on how you can use the framework:

class Program
    {
        static void Main(string[] args)
        {
            Debug.Listeners.Add(new ConsoleTraceListener());

            var system = new SimulationSystem();

            // Add a thread and a simulation engine to the simulation framework
            system.AddSimulationThread(new SimulationThread(new SimulationEngine[] {new TestSimulationEngine() }.ToList()));

            // Add a new simulation group
            system.World.Objects.Add(new SimulationGroup());

            // Add a new object to the group
            ((SimulationGroup)system.World.Objects[0]).Objects.Add(new SimulationObject());
            system.World.Objects.Add(new SimulationObject());

            DateTime loopStart = DateTime.Now;
            DateTime loopEnd = DateTime.Now;

            // Simulates the update loop
            while (true)
            {
                loopStart = DateTime.Now;
                system.Update(loopStart - loopEnd);
                loopEnd = DateTime.Now;

                // Wait for user to press enter to start the next loop
                //Console.ReadLine();
            }
        }
    }

with this TestSimulationEngine class:

public class TestSimulationEngine : SimulationEngine
{
    public override void UpdateWorld(SimulationContext context, TimeSpan step)
    {
        // Do some stuff to the simulation world

        Console.WriteLine("UpdatingWorld with step {0}", step);

        // Add a new object each loop
        context.World.Objects.Add(new SimulationObject());
    }
}

A short introduction to the architecture behind the framework:

There is the class SimulationSystem which you can use to initialise a new simulated world. You can assign SimulationEngines to defined threads. For example a physicsengine to thread 1, a heatsystem to thread 2, ...

Also it holds the SimulationWorld which is a hierarchical system. Inside the World you can add SimulationObjects and SimulationGroups. A SimulationGroup is the same as a SimulationObject but can also have sub-objects.

For example, inside the world you can add a car as a simulation group. Inside the car you have the engine, driver, etc as simulation sub-objects.

You can also set any property you want on the objects using the code object["Property"].


texts:
I am working on a generic repository. And I wondered if anyone could give some feedback on it.

Interface for DbContext:

public interface IDbContext
{
    IDbSet<T> Set<T>() where T : class;
    DbEntityEntry Entry<T>(T entity) where T : class;
    void SaveChanges();
}

Context class

public class BookContext : DbContext, IDbContext
{
    public BookContext()
        : base("BookDB")
    { }

    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }

    public new DbEntityEntry Entry<T>(T entity) where T : class
    {
        return base.Entry(entity);
    }

    public new void SaveChanges()
    {
        base.SaveChanges();
    }
}

Repository interface

public interface IRepository<T>
{
    IQueryable<T> FindAll();
    IQueryable<T> Find(Expression<Func<T, bool>> predicate);
    T FindById(int id);
    void AddOrUpdate(T entity);
    void Remove(T entity);
}

Repository implementation

public class Repository<T> : IRepository<T>
    where T : class, IEntity
{
    protected readonly IDbContext Context;

    public Repository(IDbContext context)
    {
        Context = context;
    }

    public IQueryable<T> FindAll()
    {
        return Context.Set<T>();
    }

    public IQueryable<T> Find(Expression<Func<T, bool>> predicate)
    {
        return Context.Set<T>().Where(predicate);
    }

    public T FindById(int id)
    {
        return Context.Set<T>().SingleOrDefault(o => o.Id == id);
    }

    public void AddOrUpdate(T entity)
    {
        if (entity == null)
            throw new ArgumentNullException("entity");

        if (entity.Id == 0)
        {
            Context.Set<T>().Add(entity);
        }
        else
        {
            Context.Entry(entity).State = EntityState.Modified;
        }

        Context.SaveChanges();
    }

    public void Remove(T entity)
    {
        if (entity == null)
            throw new ArgumentNullException("entity");

        Context.Set<T>().Remove(entity);
        Context.SaveChanges();
    }
}

Additional repository

public interface IBookRepository
{
    Book FindByIsbn(string isbn);
    IQueryable<Book> FindByAuthor(Author author);
}

Book repo implementaion

public class BookRepository : Repository<Book>, IBookRepository
{
    public BookRepository(IDbContext context) : base(context)
    {
    }

    public Book FindByIsbn(string isbn)
    {
        return Context.Set<Book>().SingleOrDefault(b => b.Isbn.Equals(isbn));
    }

    public IQueryable<Book> FindByAuthor(Author author)
    {
        return Context.Set<Book>().Where(b => b.Author.Id == author.Id);
    }
}

I am planning to use this repo with autofac IoC. I am not sure If I should use Unit of work pattern and should I make my repos disposable. Any feedback would be appreciated.


texts:
Same exact story as Verbose Word/Phrase Reverse in Node.js, but in C++.

If you don't want to follow the link:

  The assignment is to:

  If input is a word, reverse the word. (e.g. "hello" becomes "olleh")
  If input is a phrase, reverse the order of the phrase but not the actual words. (e.g. "united states of america" becomes "america of states united")

  The other restriction is I am only allowed to use the C++ equivalent of Java String's length, substring, charAt, concatenation and indexOf methods.

Code:

#include <iostream>

std::string ReverseWord(const std::string& word) {
    std::string reverse;
    for (unsigned long i = word.length() - 1; i <= word.length(); --i) reverse += word[i];
    return reverse;
}

std::string ReversePhrase(const std::string& phrase) {
    unsigned long last_space = phrase.length();
    std::string out;
    for (unsigned long i = phrase.length() - 1; i <= phrase.length(); --i) {
        if (phrase[i] == ' ') {
            out += phrase.substr(i + 1, last_space - i - 1) + " ";
            last_space = i;
        }
    }

    out += phrase.substr(0, last_space);
    return out;
}

int pa12() {
    std::string in;
    std::cout << "Enter a word or phrase: ";
    getline(std::cin, in);

    if (std::find(in.begin(), in.end(), ' ') == in.end()) {
        std::cout << "The reversed word is: " << ReverseWord(in) << std::endl;
    } else {
        std::cout << "The reversed phrase is: " << ReversePhrase(in) << std::endl;
    }

    return 0;
}


texts: Sorting an array in different ways with efficient output

texts:
I am going through some PHP array exercises on w3resource because I want to get to grips with all the different functions PHP offers for arrays. I have just done this one:

  Write a PHP script to sort the following associative array : array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40") in

  a) ascending order sort by value

  b) ascending order sort by Key

  c) descending order sorting by Value

  d) descending order sorting by Key

And here is my code:

<?php
    echo "
";

    $people = array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40");

    function display($array)
    {
        foreach($array as $p => $a)
        {
        echo "$p\t $a
";
        }
    }

    //sorted by value, ascending
    asort($people);
    display($people);
    echo"
";

    //sorted by key, ascending
    ksort($people);
    display($people);
    echo"
";

    //sorted by value, descending
    arsort($people);
    display($people);
    echo"
";

    //sorted by key, descending
    krsort($people);
    display($people);

    echo "
";
?>

I was pretty content with how I solved this, using the display() helper method to cut down on typing.

However, the example on the website is as follows:

<?php
echo "
Associative array : Ascending order sort by value
";
$array2=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); asort($array2);
foreach($array2 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Ascending order sort by Key
";
$array3=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); ksort($array3);
foreach($array3 as $y=>$y_value)
{
echo
"Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Descending order sorting by Value
";
$age=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40");
arsort($age);
foreach($age as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Descending order sorting by Key
";
$array4=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); krsort($array4);
foreach($array4 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
?>

This came across, to me, as flawed code in some ways, because I wondered why the same array was declared multiple times when it seems unnecessary.

Am I missing something with this example code? Is there a reason I should not use a display() helper method?
Is readability improved by following echo immediately with a line, as is done in the example?
Is it good practise to use the . concatenation operator alongside ' ' (single quotation marks), as opposed to simply putting everything inside " " (doubles)? (I find the latter more readable and easier to work with.)
Is it acceptable to place more than one statement per line, as is done in the example

$array2=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); asort($array2);


texts:
This is a simple script to make ls output first folders, then files, then other stuff (symlink). I think this is really neat and would like to share the script in exchange for comments.

It should be noted that I'm working with GNU findutils and coreutils.

Some basic criteria that I'm aiming for include:

lssort must accept the same arguments as ls
lssort should depend on bash, find, ls and xargs
the output must not be prefixed with "./"

Problems:

arguments can not be augmented (-CFXtrs does not work)

Script

#! /bin/bash
#source $HOME/.scripts/string_manipulation.mergeme
function trim {
    local var="$@"
    #$ var="  hello space    "
    #$ echo ">"
    #$ >
    var="${var#"${var%%[![:space:]]*}"}" # rm leading whitespace characters
    var="${var%"${var##*[![:space:]]}"}" # rm trailing whitespace characters
    echo -n "$var"
}

function arrayContains {
    # remove the shortest needle from array and compare lengths
    # needs more testing...
    declare -a array
    declare -a arrayLess
    declare needle
    array=( "${!1}" ); shift        # expand the passed array name
    needle="$@"                     # try to match the rest as a string
    arrayLess=( `trim "${array[@]#${needle}}"` )    # remove value $needle
    if [ ${#array[@]} -eq 0 ];then                  return 1 ;fi
    if [ ${#array[@]} -eq ${#arrayLess[@]} ];then   return 1 ;fi
    if [ ${#array[@]} -lt ${#arrayLess[@]} ];then   return 1 ;fi
    return 0
}

# d dir f file p named pipe (FIFO) l sylink s socket D door (Solaris)
# c character (unbuffered) special b block (buffered) special

function finddirs {
    find "$@" \
        -maxdepth 1 -depth -type d \
        -regextype gnu-awk -regex "$REGEX" \
        -printf '%f\0'
}
function findfiles {
    find "$@" \
        -maxdepth 1 -depth -type f \
        -regextype gnu-awk -regex "$REGEX" \
        -printf "%f\0"
}
function findspecials {
    find "$@" \
        -maxdepth 1 -depth \( -type l   -o -type p   -o -type s \) \
        -regextype gnu-awk -regex "$REGEX" \
        -printf "%f\0"
}
##
## vars and such
##
validswitches=(-X -l -r -t -C -F -1 -a -A -d -s)
PATHS=()
FPATHS=""
LSSWITCHES=""
ORIGIN_DIR="`pwd`"
LSHIDDEN="^\./.+"       # gnu-awk regex for find, single dot does not match
LSNORMAL="^\./[^\.]+.+" # exclude files starting with .
LS=ls\ --color=auto

ARG=$1
ARGC=0
while [ "$ARG" != "" ];
do
    if [ `arrayContains validswitches[@] $ARG ;echo $?` -eq 0 ];then
        LSSWITCHES="${LSSWITCHES} $ARG"
        unset ARG
    fi

    if [ -d "$ARG" ];then
        #PATHS="${PATHS} $ARG"
        PATHS[${ARGC}]=$ARG
        let ARGC=ARGC+1
    else
        FPATHS="${FPATHS} $ARG"
    fi
    shift
    ARG=$1
done

# FIX only -A excludes . and ..
if [[ "$LSSWITCHES" =~ '-a' || "$LSSWITCHES" =~ '-A' ]]; then
    REGEX=$LSHIDDEN
else
    REGEX=$LSNORMAL
fi

#PATHS=`trim $PATHS`
FPATHS=`trim $FPATHS`

if [ ${#FPATHS} -eq 0 ]; then
    if [ ${#PATHS[@]} -eq 0 ]; then
        PATHS=(".")
    fi
fi
for arg in "${PATHS[@]}";
do
    if [[ ${#arg} -eq 1 && "$arg" == "/" ]];then
        p=/
    else
        #p=${arg%%/}
        p=$arg
    fi

    cd "$p"
    if [[ "$p" != "." && "$p" != "./" ]];then echo "$p": ;fi
    finddirs | xargs -r0 $LS $LSSWITCHES -d
    findfiles | xargs -r0 $LS $LSSWITCHES
    findspecials | xargs -r0 $LS $LSSWITCHES -d
    [ ${#PATHS[@]} -gt 1 ] && echo
    cd $ORIGIN_DIR
done

echo $FPATHS |xargs -r $LS $LSSWITCHES
#echo paths.:\ size: ${#PATHS[@]}
#echo fpaths:\

lssort


texts: Limiting the number of text fields created

texts:
It's a script that I've ripped off elsewhere, and have modified it via help from Stack Overflow on a couple of other questions, so that it tops out at 10 fields.

My knowledge of JS/jQuery is barely there.  I'm terrified that I did it badly or wrongly. Could you please let me know if this is the correct way of doing it, or if there's another way that I should have done it differently?

I need to make sure that the max number of text fields created is limited to 10 at most.

Here's a demo and a JSFiddle.

jQuery(document).ready(function($) {
    var max_fields = 10;
    var x = 1;

    $('.my-form .add-box').click(function() {
        var n = $('.text-box').length + 1;

        if(x < max_fields) {
            var box_html = $('
Name ' + n + ' <input type="text" name="on' + (n - 1) + '" value="" id="box' + n + '" /> Remove
');
            box_html.hide();
            $('.my-form p.text-box:last').after(box_html);
            box_html.fadeIn('slow');
            x++;
        }
    });

    $('.my-form').on('click', '.remove-box', function() {
        $(this).parent().css('background-color', '#FF6C6C').fadeOut("slow", function() {
            $(this).remove();
            $('.text-box').each(function(index) {
                var label = $(this).children('label');
                label.attr('for', 'box' + (index + 1));
                label.children('.box-number').text(index + 1);
                $(this).children('input').attr({
                    name: 'on' + index,
                    id: 'box' + (index + 1)
                });
            });
        });
        return false;
    });
});

        Name 1
        <input type="text" name="on0" value="" id="box1" />
        Add More Names