texts: Implementation of a new kind of smart pointer in C++

texts:
I'm tempted to write a new kind of smart pointer which, I believe, is less intrusive than boost::intrusive_ptr and has the same memory footprint.

The code for the smart pointer, which I called less_intrusive_ptr, is shown below (the boost version used is 1.57.0):

#include <utility>
#include <boost/intrusive_ptr.hpp>
#include <boost/smart_ptr/intrusive_ref_counter.hpp>

template <class T>
class less_intrusive_ref_counter :
    public boost::intrusive_ref_counter<less_intrusive_ref_counter<T>>, public T
{
    using T::T;
};

template <class T>
class less_intrusive_ptr :
    public boost::intrusive_ptr<less_intrusive_ref_counter<T>>
{
    using boost::intrusive_ptr<less_intrusive_ref_counter<T>>::intrusive_ptr;
};

template <class T, class... Args>
less_intrusive_ptr<T> make_less_intrusive(Args&&... args)
{
    return less_intrusive_ptr<T>(
        new less_intrusive_ref_counter<T>(std::forward<Args>(args)...));
}

The code used to test it is shown below:

#include <iostream>
#include <boost/smart_ptr/shared_ptr.hpp>
#include "less_intrusive_ptr.h"

class MyClass1 {};
class MyClass2 : public boost::intrusive_ref_counter<MyClass2> {};
class MyClass3 {};

int main()
{
    boost::shared_ptr<MyClass1> p1(new MyClass1);
    boost::intrusive_ptr<MyClass2> p2(new MyClass2);
    less_intrusive_ptr<MyClass3> p3(new less_intrusive_ref_counter<MyClass3>);
    // or, more friendly syntax:
    //auto p3 = make_less_intrusive<MyClass3>();

    std::cout << sizeof(p1) << std::endl;   // output: 8
    std::cout << sizeof(p2) << std::endl;   // output: 4
    std::cout << sizeof(p3) << std::endl;   // output: 4
    return 0;
}

The advantages I can see are:

less memory usage (compared to shared_ptr)
ref-counting is used only when necessary
no need to write boilerplate code (compared to intrusive_ptr)
no need for a common base class (as is common when using intrusive_ptr)

The disadvantages I can see are:

we cannot use an existing raw pointer and add ref-counting behavior to it, we must always create an object by means of less_intrusive_ref_counter when we need such behavior
we cannot up-cast the underlying raw pointer (which is of type less_intrusive_ref_counter<T> *) to T * and then try to delete it, unless T's destructor is declared virtual. If it's not, and we try to delete the object trough T's pointer, we get undefined behavior.
we must be able to derive from the passed in T, which excludes built-in and (maybe?) POD types, as well as classes marked as final. [pointed out by Filip Roséen and Morwenn]
we cannot make an assignment such as the following: less_intrusive_ptr<Base> p = make_less_intrusive<Derived>(), because less_intrusive_ref_counter<Derived> does not inherit from less_intrusive_ref_counter<Base>.

My question is: can you spot other disadvantages to this approach? In fact, do you think this design is flawed in some way? I really am not an experienced C++ programmer.


texts: Method to act on parameter or from iterable if not parameters are passed

texts:
The scenario is as follows. The API of my program will allow the user to perform some method on a particular element (let's say a tuple from a database). If this parameter is not passed to the function, then the "default" behavior is to look for a list of elements (from a database query, for example) and to act on all of them. Like this:

task(simple_object) # will process simple_object
task() # query the database with some previously defined query

And this is what I did (implementation in Python):

@task(query='SELECT * FROM User WHERE age < 18')
def task_disable_account(user):
    disable_user(user)

This way I can call the task_disable_account with one particular User or I can call it with no arguments and then every tuple from the SQL query will be processed. The definition of task decorator is as follows:

task_registry = []
def task(query):
    Task = namedtuple('Task', ['func', 'query'])
    def decorate(func):
        def queried(*_args):
            if not _args:
                map(func, search(query)) # execute on result from SQL
                return
            return func(*_args) # execute on 1 passed parameter
        task_registry.append(Task(queried, query))
        return queried
    return decorate

And this is how I use it (just an example, actual code is more complicated):

def main(): # lets assume a main() function
    for func, _ in task_registry:
        # I'm getting and ID from sys.argv and returning a User object
        # If not passed via arguments, call function with no parameters
        user = get_from_argv()
        if user:
            func(user)
        else:
            func()

The idea behind all this is:

The tasked method should only take care of the processing of 1 element, centralising the way we search for, and how we iterate over them.
Make it easy to add new task methods to our implementation, not having to repeat the boilerplate code over and over.


texts:
I am looking for improvements for this basic makefile and directory structure. I know this is overkill and could be compiled with one line in a flat directory structure, but I want to use this as a learning exercise.

CC=g++
CFLAGS=-Wl,--no-as-needed -std=c++11
LIBS=-lpthread
SRC=$(PWD)/src
BUILDDIR=$(PWD)/build
OUTDIR=$(BUILDDIR)/bin
TEMPDIR=$(BUILDDIR)/tmp
MKDIR_P = mkdir -p

.PHONY: directories clean run

all: directories $(OUTDIR)/terminal

$(OUTDIR)/terminal: $(TEMPDIR)/main.o $(TEMPDIR)/terminal.o
    $(CC) $(CFLAGS) $(TEMPDIR)/terminal.o $(TEMPDIR)/main.o $(LIBS) -o $(OUTDIR)/terminal

$(TEMPDIR)/main.o: $(SRC)/main.cpp $(SRC)/terminal.hpp
    $(CC) -c $(CFLAGS) $(SRC)/main.cpp -o $(TEMPDIR)/main.o

$(TEMPDIR)/terminal.o: $(SRC)/terminal.cpp $(SRC)/terminal.hpp
    $(CC) -c $(CFLAGS) $(SRC)/terminal.cpp -o $(TEMPDIR)/terminal.o

directories: ${OUTDIR} $(TEMPDIR)

$(OUTDIR):
    ${MKDIR_P} $(OUTDIR)

$(TEMPDIR):
    ${MKDIR_P} $(TEMPDIR)

clean:
    rm -rf $(BUILDDIR)

run:
    $(OUTDIR)/terminal


texts: Sandwich shop interface using the Decorator pattern

texts:
I have implemented a very basic sandwich (sub) shop which a user can add extra toppings at an additional cost. The cost is calculated and the contents of the sandwich is outputted.

I am learning design patterns and the book I am learning from (Head First Design Patterns) is in Java, which I am not too familiar with, so I may be making some errors.

Sub.h

#ifndef SUB_H
#define SUB_H

//Class Sub: Abstract Base class.
//Following the decorator pattern

#include <string>
#include <memory>

class Sub
{
  public:
    virtual double getCost() = 0;
    virtual std::string getToppings() = 0;
    virtual ~Sub() = 0;
};

class Plain: public Sub
{
  public:
    double getCost() override;
    std::string getToppings() override;
};

class ExtraCheese: public Sub
{
  public:
    ExtraCheese(std::shared_ptr<Sub> s) : sub(s) {}
    double getCost() override;
    std::string getToppings() override;
  private:
    std::shared_ptr<Sub> sub;
};

class ExtraMeat: public Sub
{
  public:
    ExtraMeat(std::shared_ptr<Sub> s) : sub(s) {}
    double getCost() override;
    std::string getToppings() override;
  private:
    std::shared_ptr<Sub> sub;
};

class ExtraSauce: public Sub
{
  public:
    ExtraSauce(std::shared_ptr<Sub> s) : sub(s) {}
    double getCost() override;
    std::string getToppings() override;
  private:
    std::shared_ptr<Sub> sub;
};

#endif

Sub.cpp

#include "Sub.h"

inline Sub::~Sub(){}

//class Plain : public Sub
double Plain::getCost()
{
  return 3.75;
}

std::string Plain::getToppings()
{
  return "Basic Sub";
}

//class ExtraCheese : public Sub

double ExtraCheese::getCost()
{
  return sub->getCost() + 0.75;
}

std::string ExtraCheese::getToppings()
{
  return sub->getToppings() + ", Extra Cheese";
}

//class ExtraMeat : public Sub
double ExtraMeat::getCost()
{
  return sub->getCost() + 1.50;
}

std::string ExtraMeat::getToppings()
{
  return sub->getToppings() + ", Extra Meat";
}

//class ExtraSauce : public Sub
double ExtraSauce::getCost()
{
  return sub->getCost() + 0.15;
}

std::string ExtraSauce::getToppings()
{
  return sub->getToppings() + ", Extra Sauce";
}

main.cpp

#include <iostream>
#include <memory>
#include "Sub.h"

int main()
{
  std::shared_ptr<Sub> s(new Plain());

  s = std::make_shared<ExtraCheese>(s);
  s = std::make_shared<ExtraMeat>(s);
  s = std::make_shared<ExtraSauce>(s);

  std::cout<<"COST: "<< s->getCost() <<std::endl;
  std::cout<<"Toppings: " << s->getToppings() <<std::endl;
}


texts: Building tree structure based on flat objects

texts:
You can find here a Follow-up question

Description

A List<UnrelatedObects> is returned by a 3rd party webservice, which will then be transformed to a List<ArchiveDefinition>. These ArchiveDefinition objects are connected by Parent'.ArchiveNodeId == 'Child'.ParentId.

The root objects TypeOfArchive property will always have the value ArchiveType.Archive.

The goal of the given class below is to build a List<ArchiveTreeNode> of these flat object list to fill a treeview control.

The class in question

public class ArchiveBuilder
{
    public static List<ArchiveTreeEntry> Build(List<ArchiveDefinition> entries)
    {
        List<ArchiveTreeEntry> rootArchiveTreeEntries = new List<ArchiveTreeEntry>();

        if (entries != null && entries.Count > 0)
        {
            List<ArchiveDefinition> rootEntries = GetRootEntries(entries);

            foreach (ArchiveDefinition definition in rootEntries)
            {
                rootArchiveTreeEntries.Add(new ArchiveTreeEntry(definition));
                entries.Remove(definition);
            }

            foreach (ArchiveTreeEntry parent in rootArchiveTreeEntries)
            {
                FillChildren(parent, entries);
            }
        }
        return rootArchiveTreeEntries;
    }

    private static void FillChildren(ArchiveTreeEntry parent,
                                     List<ArchiveDefinition> entries)
    {
        if (entries.Count > 0)
        {
            List<ArchiveDefinition> children = GetChildren(entries, parent.Id);

            if (children.Count > 0)
            {
                RemoveChildren(entries, parent.Id);

                foreach (ArchiveDefinition child in children)
                {
                    ArchiveTreeEntry treeEntryChild = new ArchiveTreeEntry(child);
                    parent.AddChild(treeEntryChild);
                    FillChildren(treeEntryChild, entries);
                }
            }
        }
    }

    private static List<ArchiveDefinition> GetRootEntries(List<ArchiveDefinition> entries)
    {
        return entries.FindAll(e => e.TypeOfArchive == ArchiveType.Archive);
    }

    private static List<ArchiveDefinition> GetChildren(List<ArchiveDefinition> entries, string parentID)
    {
        return entries.FindAll(e => e.ParentId == parentID);
    }

    private static void RemoveChildren(List<ArchiveDefinition> entries, string parentID)
    {
        entries.RemoveAll(e => e.ParentId == parentID);
    }
}

Related classes and enums

public class ArchiveDefinition
{
    public string ArchiveNodeId { get; private set; }
    public string ParentId { get; private set; }
    public ArchiveType TypeOfArchive { get; private set; }

    public ArchiveDefinition (String parentId, String archiveNodeId,
                              ArchiveType type)
    {
        ParentId = parentId;
        TypeOfArchive = type;
        ArchiveNodeId = archiveNodeId;
    }
}

public enum ArchiveType
{
    Archive, ArchiveGroup, ArchiveEntry
}

public class ArchiveTreeEntry
{
    public ArchiveType ArchiveEntryType { get; private set; }
    public string Id { get; private set; }
    public ReadOnlyCollection<ArchiveTreeEntry> Children
    {
        get
        {
            return new ReadOnlyCollection<ArchiveTreeEntry>(mChildren);
        }
    }

    private List<ArchiveTreeEntry> mChildren = new List<ArchiveTreeEntry>();
    public ArchiveTreeEntry(ArchiveDefinition archiveDefinition)
    {
        Id = archiveDefinition.ArchiveNodeId;
        ArchiveEntryType = archiveDefinition.TypeOfArchive;
    }

    internal void AddChild(ArchiveTreeEntry child)
    {
        if (child != null)
        {
            mChildren.Add(child);
        }
    }
}

I would like to get a review for the ArchiveBuilder class. If you also want to review the related classes and enums, I won't mind.


texts: Handling HTTP requests and saving user to database

texts:
I am using Play Framework and Slick. In userController.scala I am handling HTTP post requests and sending to personRepository.scala. Is this controller and method written in the correct way?

userController.scala

  def register = Action.async { request =>
    var user = new UserInsert("", "", "", "", "", "")
    request.body match {
      case AnyContentAsText(string) => user = userModel(Json.parse(string))
      case AnyContentAsJson(json) => user = userModel(json)
      case _ => BadRequest {
        "Bad Request: " + play.api.http.Status.BAD_REQUEST
      }
    }
    personRepository.create(user.email, user.provider, user.uid, user.facebook_token, user.display_name, user.photo_url).map(i => {
      Ok(Json.toJson(i))
    })
  }

  def userModel(json: JsValue) = {
    new UserInsert((json \ "email").as[String], (json \ "provider").as[String], (json \ "uid").as[String], (json \ "facebook_token").as[String], (json \ "display_name").as[String], (json \ "photo_url").as[String])
  }

personRepository.scala

  def create(
              email: String,
              provider: String,
              uid: String,
              facebook_token: String,
              display_name: String,
              photo_url: String) = db.run {
    val salt = current.configuration.getString("salt")
    val token = BCrypt.hashpw(email, salt.get)
    (user.map(p => (p.token, p.email, p.provider, p.uid, p.facebook_token, p.display_name, p.photo_url))
      returning user.map(p => p)
      ) +=(token, email, provider, uid, facebook_token, display_name, photo_url)
  }


texts: Combining contents of files by reading them in a human ordering

texts:
This code review is inspired by the this StackOverflow question and written in Java 8.

The code is supposed to:

Order all files, with syntax jobXXX.script, where XXX is a number, by the number.
Write the contents of the files in that ordering to one file.

I am asking for a general code review and there are two things that are bugging me:

I need to wrap Exceptions inside lambda expressions.
The file that is being written to, has an imperfect unnecessary annoying OCD-triggering newline at the end.

package testproject4;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.stream.Stream;

/**
 *
 * @author Beheerder
 */
public class TestProject4 {
    private void init() throws IOException {
        Path directory = Paths.get("C:\\Users\\Frank\\Downloads\\testjob");
        try (BufferedWriter writer = Files.newBufferedWriter(directory.resolve("masterjob.script"))) {
            Files.list(directory)
                    .filter(path -> Files.isRegularFile(path))
                    .filter(path -> path.getFileName().toString().matches("job\\d+.script"))
                    .sorted(Comparator.comparingInt(this::pathToInt))
                    .flatMap(this::wrappedLines)
                    .forEach(string -> wrappedWrite(writer, string));
        }
    }

    private int pathToInt(final Path path) {
        return Integer.parseInt(path.getFileName()
                .toString()
                .replaceAll("job(\\d+).script", "$1")
        );
    }

    private Stream<String> wrappedLines(final Path path) {
        try {
            return Files.lines(path);
        } catch (IOException ex) {
            //swallow
            return null;
        }
    }

    private void wrappedWrite(final BufferedWriter writer, final String string) {
        try {
            writer.write(string);
            writer.newLine();
        } catch (IOException ex) {
            //swallow
        }
    }

    public static void main(String[] args) throws IOException {
        new TestProject4().init();
    }
}


texts: Return a List based on very similar data

texts:
I am rewriting an old VB.NET app in C#. I will not subject you to the old VB.NET code that I am writing (the original method that I have already refactored was over 700 lines long).

The following is what we call On Demand Reports. There is a stored procedure that these objects fill in for us. I don't have a 100% understanding of why most of what I am doing is just static string text but it is.

What I want to do is to find a better way to represent the List<MyObject> (see the embedded comments).

 private IEnumerable<MyObject> GetOnDemandInputsBy(int key)
        {
            var inputs = new List<MyObject>();
            //This is actually called 13 times with different parameter variables (the parameter called parameter) and a different static dictionary
            inputs.Add(AssembleMyObject(key, "@BeginTime", MyObjectPropertyConstants.BeginTime()));
            inputs.Add(AssembleMyObject(key, "@EndTime", MyObjectPropertyConstants.EndTime()));

            return inputs;
        }

        //This method is fine with me. It is just here for context
        private static IEnumerable<MyObjectProperty> AssembleMyObjectProperty(Dictionary<string, string> dictionary)
        {

            return dictionary.Select(item => new MyObjectProperty {PropertyName = item.Key, PropertyValue = item.Value});
        }

        //I feel like I am passing to many things into this method and its doing to much
        private MyObject AssembleMyObject(int key, string parameter, Dictionary<string, string> dictionary)
        {
            //this is set to 0 in the constructor, I am not sure why the original developers chose 10 for every new object
            _displayOrder += 10;
            var MyObject = new MyObject
            {
                DisplayOrder = _displayOrder,
                ParameterName = parameter,
                QueryKey = key,
            };
            MyObject.MyObjectProperties.AddRange(AssembleMyObjectProperty(dictionary));
            return MyObject;
        }

    //This seems like a bad idea as well but all the data is static and I created a separate dictionary for each of the parameter types
    public class MyObjectPropertyConstants
    {
        public static Dictionary<string, string> BeginTime()
        {
            return new Dictionary<string, string>
            {
                {"stuff", "@BeginTime"},
                {"VISIBLE", "TRUE"},
                {"CAPTION", "*beginTime"},
                {"DISPLAYTYPE", "DATEPICKER"},
                {"DATATYPE", "DATE"},
            };
        }

        public static Dictionary<string, string> EndTime()
        {
            return new Dictionary<string, string>
            {
                {"Name", "@EndTime"},
                {"VISIBLE", "TRUE"},
                {"CAPTION", "*EndTime"},
                {"DISPLAYTYPE", "DATEPICKER"},
                {"DATATYPE", "DATE"},
            };
        }
   }

As previously states this is the refactored version so far. The original code to do the above chunk is 180 lines. The method that I am rewriting is over 700 lines long.

Any Suggestions?


texts:
I wanted a buffer like std::vector<uint8_t> which is very fast at resizing, and it does not require byte initialization (it resizes to 16K, then to 2-4 bytes, then goes back to 16K, and repeat, a lot. std::vector zeroes all the bytes every time it grows back to 16K, I thought I could avoid the zeroing-overhead with a custom implementation)

I came up with this:

// buffer which should be faster than std::vector<uint8_t> when resizing a lot because it does not do byte initialization when resizing
class uint8_fast_buffer
{
public:
    uint8_fast_buffer(const size_t initial_size)
    {
        if(initial_size == 0)
        {
            // .. i don't really like the idea of buf being nullptr, this avoids that issue.
            this->internal_reserve(1);
        }
        else
        {
            this->internal_reserve(initial_size);
            this->buf_size=initial_size;
        }
    }
    ~uint8_fast_buffer() noexcept
    {
        free(this->buf);
    }
    size_t size(void) noexcept
    {
        return this->buf_size;
    }
    void reserve(const size_t reserve_size)
    {
        if(reserve_size > this->buf_size_real)
        {
            this->internal_reserve(reserve_size);
        }
    }
    // this function is supposed to be very fast when newlen is smaller than the biggest it has ever been before.
    void resize(const size_t newlen)
    {
        if(__builtin_expect(newlen > this->buf_size_real,0))
        {
            this->internal_reserve(newlen);
        }
        this->buf_size=newlen;
    }
    void append(const uint8_t *data, const size_t len){
        const size_t pos=this->size();
        const size_t new_pos=this->size()+len;
        this->resize(new_pos);
        memcpy(&this->buf[pos],data,len);
    }
    void reset(void) noexcept
    {
        this->buf_size=0;
    }
    bool empty(void) noexcept
    {
        return (this->buf_size==0);
    }
    uint8_t* data(void) noexcept
    {
        return this->buf;
    }
    uint8_t& at(const size_t pos)
    {
        if(__builtin_expect(pos >= this->size(),0))
        {
            throw std::out_of_range(std::to_string(pos)+std::string(" >= ")+std::to_string(this->size()));
        }
        return this->buf[pos];
    }
    uint8_t& operator[](const size_t pos) noexcept
    {
        return this->buf[pos];
    }
private:
    void internal_reserve(const size_t reserve_size)
    {
        uint8_t *newbuf=(uint8_t*)realloc(this->buf,reserve_size);
        if(__builtin_expect(newbuf == nullptr,0))
        {
            throw std::bad_alloc();
        }
        this->buf_size_real=reserve_size;
        this->buf=newbuf;
    }
    size_t buf_size=0;
    size_t buf_size_real=0;
    uint8_t *buf=nullptr;
};


texts:
I just made a generic number class:

From any ordered character list, make number class representing that ordered character list.
create_number_class("01") returns binary number class
create_number_class("0123456789") returns decimal number class
create_number_class("abcdefghij") return decimal number class but representing each digit as a alphabet.

Here is the generic number class definition. I think it is well-made class definition. Is there something needed for improvement in that class definition?

Example:

ABC_Class = create_number_class("abc")
x = ABC_Class("baa")
y = ABC_Class("bbb")
print(x+y)
#output digits: abc, v: cbb, decimal_v: 22

Here is the class definition:

def create_number_class(alphabet):
    class temp(object):
        digits = alphabet
        def __init__(self, v):
            self.v = v
            self.decimal_v = self.to_decimal(self)
        @staticmethod
        def to_decimal(self):
            r = 0
            for i in range(0, len(self.v)):
                r += len(temp.digits)**(len(self.v)-i-1)*(temp.digits.index(self.v[i]))
            return r
        @classmethod
        def from_decimal(cls, decimal_v):
            r = []
            mod = len(temp.digits)
            if decimal_v < mod:
                return cls(temp.digits[decimal_v])
            while True:
                remainder = decimal_v % mod
                r.append(remainder)
                decimal_v = int((decimal_v - remainder)/ mod)
                if decimal_v < mod:
                    r.append(decimal_v)
                    break
            r = "".join(list(reversed([temp.digits[x] for x in r])))
            #r = "".join(list(reversed([str(temp.digits.index(str(x))) for x in r])))
            return cls(r)
        def __add__(self, other):
            return temp.from_decimal(self.decimal_v+other.decimal_v)
        def __sub__(self, other):
            return temp.from_decimal(self.decimal_v-other.decimal_v)
        def __mul__(self, other):
            return temp.from_decimal(self.decimal_v*other.decimal_v)
        def __floordiv__(self, other):
            return temp.from_decimal(self.decimal_v//other.decimal_v)
        def __str__(self):
            return "digits: {}, v: {}, decimal_v: {}".format(temp.digits, self.v, self.decimal_v)
        def convert_to(self, new_class):
            return new_class.from_decimal(self.decimal_v)
    return temp

Here is an example:

BinClass = create_number_class("01")
DecimalClass = create_number_class("0123456789")

x = BinClass("111")
x = BinClass("1000")
y = BinClass("10")

HexClass = create_number_class('0123456789ABCDEF')
x = HexClass('1')
y = HexClass('AA')

print(x+y)
print(x-y)
print(x*y)
print(x//y)
print(x.convert_to(DecimalClass))
isinstance(x, BinClass)


texts:
I have four methods like these (here are only two of them):

  def checkLeft(clickedIndex: Int): Option[Int] = {
    val leftIndex = clickedIndex - 1
    if (leftIndex >= 0 && clickedIndex % field.width != 0 && isEmptyCell(leftIndex))
      Some(leftIndex)
    else
      None
  }

  def checkRight(clickedIndex: Int): Option[Int] = {
    val rightIndex = clickedIndex + 1
    if (rightIndex < field.size && clickedIndex + 1 % field.width != 0 && isEmptyCell(rightIndex))
      Some(rightIndex)
    else
      None
  }

They all have similar structures. How I can reduce code duplication here?


texts:
Here is a Python script I wrote earlier for rapidly requesting a file from a server and timing each transaction. Can I improve this script?

from time import time
from urllib import urlopen

# vars
url = raw_input("Please enter the URL you want to test: ")

for i in range(0,100):
    start_time = time()
    pic = urlopen(url)

    if pic.getcode() == 200:
        delta_time = time() - start_time
        print "%d" % (delta_time * 100)
    else:
        print "error"
print "%d requests made. File size: %d B" % (i, len(pic.read()))

I'm new to Python, though, so I'm not sure if this is the best way to go about it.


texts:
I'm trying to design a binary relation interface in Java and then implement it, but I'm not sure if I'm doing it right. I'd really appreciate a little feedback just so I know if I'm way in the wrong direction or not.

This is what I've got so far:

Interface:

public boolean compare(Object that, Object ths);
// compares relations to see if they are equal.

public Set<Y> getY(X value);
//return set of all Y values with relation X

public Set<X> getX(Y value);
//return set of all X values with relation Y

public void clear();
//clear relation of values

public Set<Relation<X, Y>> delY(X value);
//remove all relations containing given Y

public Set<Relation<X, Y>> delX(Y value);
//remove all relations containing given X

public String write(Object that);
//output Relation in string format

public Y addPair (X valX, Y valY);
//adds the entry (X, Y) to the Relation

public Y delPair (X valX, Y valY);
//deletes entry (X, Y) from the Relation

Implementation:

int size;

String[][] basket = new String[16][2];
String[][] bag = basket;

public String addPair(String X, String Y){

    basket[size][0] = X;
    basket[size][1] = Y;

    String pair = basket[size][0] + basket[size][1];
    size++;
    return pair;

}

public boolean compare(String[][] that, String[][] ths){
    that = basket;
    ths = bag;
    boolean equal;

    if(that.equals(ths))
        equal = true;
    else
        equal = false;
    return equal;
}

public Set<String> getY(String X){

    Set<String> Y = new TreeSet<String>();

    for(int i = 0;i<size;i++)
    {
        if(basket[i][0]==X)
            Y.add(basket[i][1]);
    }

    return Y;

}
public Set<String> getX(String Y){

    Set<String> X = new TreeSet<String>();

    for(int i = 0;i<size;i++)
    {
        if(basket[i][1]==Y)
            X.add(basket[i][0]);
    }

    return X;

}

public String write(Object o){

    o = basket;
    String out = "";
    out += o.toString();
    System.out.println("OUT: " + out);
    return out;

}

public void clear(){
 for(int i = 0;i<size;i++)
    {
        if(basket[i][0]!= null){
            basket[i][0] = null;
            basket[i][1] = null;
        }
    }
}

public Set<String> delY(String X, Relation r){
    Set<String> Y = new TreeSet<String>();

    for(int i = 0;i<size;i++)
    {
        if(basket[i][0]==X){
            Y.add(basket[i][1]);
            basket[i][1]=null;
        }
    }

    return Y;

}

public Set<String> delX(String Y){
   Set<String> X = new TreeSet<String>();

    for(int i = 0;i<size;i++)
    {
        if(basket[i][1]==Y){
            X.add(basket[i][1]);
            basket[i][1]=null;
        }
    }

   return X;
}

public String delPair (String X, String Y){
    X = "Orange";
    Y = "Fruit";
    for(int i = 0;i<size;i++)
    {
        if(basket[i][0]==X && basket[i][1]==Y){
            basket[i][1]=null;
            basket[i][0]=null;
        }
    }

     return (X + Y);

}


texts: Using LINQ to perform a LEFT OUTER JOIN in 2 DataTables (Multiples criteria)

texts:
I know that exists a lot of solutions about how to create an OUTER JOIN between two DataTables.

I created the following code in C#:

DataTable vDT1 = new DataTable();
vDT1.Columns.Add("Key");
vDT1.Columns.Add("Key2");
vDT1.Columns.Add("Data1");
vDT1.Columns.Add("Data2");

vDT1.Rows.Add(new object[] { "01", "ZZ", "DATA1_AAAA", "DATA2_AAAA" });
vDT1.Rows.Add(new object[] { "02", "ZZ", "DATA1_BBBB", "DATA2_BBBB" });

DataTable vDT2 = new DataTable();
vDT2.Columns.Add("Key");
vDT2.Columns.Add("Key2");
vDT2.Columns.Add("Data3");
vDT2.Columns.Add("Data4");

vDT2.Rows.Add(new object[] { "01", "ZZ", "DATA3_AAAA", "DATA4_AAAA" });
vDT2.Rows.Add(new object[] { "01", "ZZ", "DATA3_BBBB", "DATA4_BBBB" });
vDT2.Rows.Add(new object[] { "01", "ZZ", "DATA3_CCCC", "DATA4_CCCC" });
vDT2.Rows.Add(new object[] { "01", "ZZ", "DATA3_DDDD", "DATA4_DDDD" });

DataTable vDT3 = new DataTable();
vDT3.Columns.Add("Key");
vDT3.Columns.Add("Key2");
vDT3.Columns.Add("Data1");
vDT3.Columns.Add("Data2");
vDT3.Columns.Add("KeyTemp1");
vDT3.Columns.Add("KeyTemp2");
vDT3.Columns.Add("Data3");
vDT3.Columns.Add("Data4");

DataRow vDRnull = vDT2.Rows.Add();

var vLINQ = vDT1.AsEnumerable()
    .GroupJoin(vDT2.AsEnumerable(),
        dr1 => new { key1 = dr1["Key"], key2 = dr1["Key2"] },
        dr2 => new { key1 = dr2["Key"], key2 = dr2["Key2"] },
        (dr1, result) => dr1.ItemArray.Koncat(
            ((result.FirstOrDefault<DataRow>() == null)
                ? vDRnull
                : result.FirstOrDefault<DataRow>()).ItemArray));

foreach (var aw in vLINQ)
{
    vDT3.Rows.Add(aw);
}

I implemented this extension:

public static T[] Koncat<T>(this T[] x, T[] y)
{
    if (x == null) throw new ArgumentNullException("x");
    if (y == null) throw new ArgumentNullException("y");
    int oldLen = x.Length;
    Array.Resize<T>(ref x, x.Length + y.Length);
    Array.Copy(y, 0, x, oldLen, y.Length);
    return x;
}

This easy and clean (from my point of view), but I wanted to ask the experts for recommendations, improvements, or if this method have a performance flaw.

Normally I need manage huge amount of data (More than 100K items).


texts: JavaFX Audio Visualizer unsure about MVC / Observer / Listerner design patterns

texts:
I have a MP3Player Class that does the Fast Fourier Transform and puts the values in a float array (called bands). Then every 20ms it notifys the Observer (VisualizerController) which then uses getBands() to get the float array and use it to draw the values on a canvas.

I feel like this is an ugly way to do this but I don't know how to do to it better.

Here is the whole source on github

This is the update function in the VisualizerController handling the drawing:

@Override
public void update(Observable o, Object arg) {
    if (saturation > 0.5) saturation -= 0.02;
    if (brightness > 0.8) brightness -= 0.02;

    bands = player.getBands();

    if (circle) {
        if (bars) drawCircleBars();
        else drawCircleLine();
    } else {
        if (bars) drawStraightBars();
        else drawStraightLine();
    }

    if (player.isBeat()) {
        saturation = 1.0;
        brightness = 1.0;
    }
}

And here is what it looks like in MP3Player where I get the frequencies and notify the Observers:

private class FFTThread extends Thread {

    @Override
    public void run() {

        while (!isInterrupted()) {

            fft.forward(audioPlayer.getMix());
            for (int i = 0; i < bands.length; i++) bands[i] = fft.getBand(i);

            beatDetect.detect(audioPlayer.getMix());
            beat = beatDetect.isOnset();

            progess = audioPlayer.position() * 1.0 / audioPlayer.length();

            setChanged();
            notifyObservers();

            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                interrupt();
            }
        }
    }
}

public float[] getBands() {
    return bands;
}

public boolean isBeat() {
    return beat;
}


texts: Reading contents of a file consisting of strings separated by a null character

texts:
This is my first attempt at reading the contents of a file consisting of strings separated by a null character.

vector<string> CReadFileTest::ReadFile( const char * filename )
{
    ifstream ifs(filename, ifstream::in);
    if (ifs)
    {
        vector<string> list ;

        while (ifs.good())
        {
            string s;
            std::getline(ifs, s,'\0');
            list.push_back(s);
        }

        ifs.close();

        return list;
    }

    return vector<string>();
}

Does this code snippet follows good coding practices?
Is it correct to return a vector type and an empty vector in case of errors?


texts: RXJava operate on exiting List instead of creating new

texts:
I'm dipping my toes in to RXJava for the first time. The function below works just fine but I can't help thinking it can be improved. For instance I'm sure that I'm unnecessarily creating a new List<Dish> sortedDishes when I could be performing operations on the exiting List<Dish> dishes that is passed in, I just don't know how yet.

public void sortDishes(int categoryId, List<Dish> dishes) {
    final List<Dish> sortedDishes = new ArrayList<>();
    final Integer[] subCategories = dbInteractor.getSubCategories(categoryId);
    final ArrayList<Integer> cats = new ArrayList<>();
    cats.add(categoryId);
    if (subCategories != null) {
        cats.addAll(Arrays.asList(subCategories));
    }

    Observable.from(dishes)
            .filter(new Func1<Dish, Boolean>() {
                @Override
                public Boolean call(Dish dish) {
                    Integer[] categories = categoryHelper.getCategorys(dish.getCategories());
                    for (Integer category : categories) {
                        if (cats.contains(category)) {
                            return true;
                        }
                    }
                    return false;
                }
            })
            .subscribe(new Subscriber<Dish>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(Dish dish) {
                    sortedDishes.add(dish);
                }
            });
}


texts: C code to parse out certain characters in a string

texts:
I have the following code

int eval(char* string) {

char* token;

outputString[0] = NULL;

token = strtok(string, " ");

while(token != NULL){

   if(strstr((char *) token, "@") != NULL) {
      strcat(outputString, "@");
      token = calc(token);
   }
   strcat(outputString, token);
   strcat(outputString, " ");
   token = strtok(NULL, " ");
}

 printf("%s\n", outputString);

}

It is called on a string that looks like this

The water has @TREE and @SKY in it.

This code works completely fine. However I want to make it more efficient.

The code is supposed to do the following --

Cut the string up by spaces, however, if an @ is found, it should be sent away to be evaluated by calc();. If none are found, we continue splitting the string by spaces until one is actually found. While we are running through, we concatenate it onto outputString and continue forward.


texts: Function to insert a tag into a database

texts:
I'm developing a MVC structured RESTful API project (thanks to the help of Mārtiņš Tereško for explaining it).

Almost all of my functions look similar to this:

 /**
    * Insert Tag
    */
    public function insertTag(Tag\Tag $tag)
    {
        try{
            //Names
            $name = new Common\Name();

            //Insert into main table
            $sql = "INSERT INTO tag VALUES(null)";
            $statement = $this->connection->prepare($sql);
            $statement->execute();

            //Get main table id
            $tagId = $this->connection->lastInsertId();

            //Insert into audit tag table
            $sql = "INSERT INTO tag_audit(behaviour,action_peformed,state,tag_id) VALUES(:behaviour,'insert','P',:tag_id)";
            $statement = $this->connection->prepare($sql);
            $statement->bindValue(':behaviour',$tag->getBehaviour(),PDO::PARAM_STR);
            $statement->bindValue(':tag_id',$tagId,PDO::PARAM_INT);
            $statement->execute();

            //Insert into names
            $name->setNames($tag->getNames()[0]);
            $values = $name->getBulkValue(
                $name->getValue(),
                ["'insert'","'P'",$tagId]
            );

            $sql = "INSERT INTO tag_name_audit(name,language,action_peformed,state,tag) VALUES".$values;
            $statement = $this->connection->prepare($sql);
            $statement->execute();

            $response = ['status'=>200,'Message'=>'Successfully inserted.'];

        }catch(\Exception $e){

             $sql = "DELETE FROM tag WHERE id_tag = :id_tag";
             $statement = $this->connection->prepare($sql);
             $statement->bindValue(":id_tag",$tagId,PDO::PARAM_INT);
             $statement->execute();

             $sql = "DELETE FROM tag_audit WHERE tag_id = :id_tag";
             $statement = $this->connection->prepare($sql);
             $statement->bindValue(":id_tag",$tagId,PDO::PARAM_INT);
             $statement->execute();

             $response = ['status'=>409,'Message'=>'Error '.$e->getCode()];
        }
        $tag->setResponse($response);
    }

I don't like how much code there is and i tought of having some mapper helper classes which will handle at least a portion of it.But still i don't think that it's the right solution.

Also since i parse the bulk value over an array i know that it's not secure ....how could i solve that part?

So the question is how could i improve it?


texts:
Toggling images in a table. The example would be a user using a checklist program. She can click on a cell next to task to toggle available status images. Like a checkmark, fail, question.

Other design suggestions are welcomed

<!DOCTYPE html>

    <title>Test 123</title>


texts: Efficiently convert 60 GB JSON file to a csv file

texts:
Description
Simply take a JSON file as input and convert the data in it into a CSV file. I won't describe the functionality in too much detail since I have reasonable docstrings for that. As you can see, my solution is not memory efficient since I'm reading all the file into memory.
I'd like to improve the performance of my solution as much as possible. (perhaps not load everything at once into memory -- even if it's gonna be slower).
The JSON file that I'm trying to convert is 60 GB and I have 64GB of RAM.

Code
import csv
import json

CSV_PATH = 'file.csv'
JSON_PATH = 'file.json'

def flattenjson(json_data, delim):
    """
    Flatten a simple JSON by prepending a delimiter to nested children.

    Arguments:
        json_data (dict): JSON object
            e.g: {
                    "key1": "n1_value1",
                    "key2": "n1_value2",
                    "parent1": {
                        "child_key1": "n1_child_value1",
                        "child_key2": "n1_child_value2"
                    }
                }
        delim (str): Delimiter for nested children (e.g: '.')

    Returns:
        Flattened JSON object.
            e.g: {
                    'key1': 'n1_value1',
                    'key2': 'n1_value2',
                    'parent1.child_key1': 'n1_child_value1',
                    'parent1.child_key2': 'n1_child_value2'
                }
    """

    flattened_json = {}
    for i in json_data.keys():
        if isinstance(json_data[i], dict):
            get = flattenjson(json_data[i], delim)
            for j in get.keys():
                flattened_json[i + delim + j] = get[j]
        else:
            flattened_json[i] = json_data[i]

    return flattened_json

def write_json_to_csv(flattened_json, csv_path):
    """
    Write flattened json to a csv file. The keys of the json will be the header
    of the csv and the values..well, the values ^_^.

    Arguments:
        flattened_json (dict): Flattened JSON object.
            e.g: {
                    'key1': 'n1_value1',
                    'key2': 'n1_value2',
                    'parent1.child_key1': 'n1_child_value1',
                    'parent1.child_key2': 'n1_child_value2'
                }
        csv_path (str): path of the CSV file

    Returns:
        None
    """

    with open(csv_path, 'w') as out_file:
        w = csv.DictWriter(out_file, flattened_json.keys())
        w.writeheader()
        w.writerow(flattened_json)

def main():
    """
    Main entry to our program.
    """

    with open(JSON_PATH) as json_file:
        json_data = json.load(json_file)

    flattened_json = flattenjson(json_data, '.')
    write_json_to_csv(flattened_json, CSV_PATH)

if __name__ == '__main__':
    main()

More about input / output

I don't know where the JSON file comes from so I have to stick with it and process it as is.
I can't change the structure of the JSON file
As far I saw, the JSON data will be at most 7 level-nested so we could have something like:

{
    "a": "1",
    "b": "2",
    "c": {
        "c_1": "3",
        "c_2": "4"
    },
    "d": {
        "d_1": {
            "d_1_1": "5",
            "d_1_2": "6"
        },
        "d_2": {
            "d_2_1": "5",
            "d_2_2": "6"
        }
        ... and so on
    }
}

I have to write the data to the CSV file as described above.
The CSV for the above JSON will look like this:

I'm specifically looking for a review orientated on memory optimizations which probably comes with a cost of a slower running time (that's fine) but any other overall improvements are welcome!
PS: I've done the above in Python 3.8.2 so I'd like you to focus on a version of Python >= 3.6


texts:
I've wrote some simple code to load a JSON file from the Twitter Streaming API, parse the data, and create relationships between users based on who mentions or retweets who.  My ultimate goal is to have a file that I can load into a network analysis program to analyze.

I wrote the code to first look for a retweet, and if present, create a relationship between the author and the user retweeted.  Then look for any mentions, and if present, create a relationship between the author and any users mentioned.  This part can have multiple relationships for a single tweet, as you can mention multiple people in one tweet.  Then if neither a retweet or a mention is present, print the author and the tweet.

End goal of this is to simple parse a JSON file and return a CSV file that I can then analyze.  I will not be loading this into any type of database.

import json
import sys
import time

def main():

    for line in sys.stdin:
        line = line.strip()

        data = []

        try:
            data.append(json.loads(line))
        except ValueError as detail:
            continue

        for tweet in data:
            ## deletes any rate limited data
            if tweet.has_key('limit'):
                pass

            else:
                tweet_time = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y'))

                ## if the key 'retweeted_status' is in the dict, print
                if tweet.has_key('retweeted_status'):
                    print "\t".join([
                    tweet_time,
                    tweet['id_str'],
                    tweet['user']['screen_name'],
                    tweet['retweeted_status']['user']['screen_name'],
                    "RETWEET",
                    tweet['text']
                    ]).encode('utf8')

                ## if there is a mention in the dict, print
                elif 'entities' in tweet and len(tweet['entities']['user_mentions']) > 0:
                    for u2 in tweet['entities']['user_mentions']:
                        print "\t".join([
                        tweet_time,
                        tweet['id_str'],
                        tweet['user']['screen_name'],
                        u2['screen_name'],
                        "MENTION",
                        tweet['text']
                        ]).encode('utf8')

                ## if there is no retweet and no mention, print
                else:
                    print "\t".join([
                    tweet_time,
                    tweet['id_str'],
                    tweet['user']['screen_name'],
                    "\t",
                    "TWEET",
                    tweet['text']
                    ]).encode('utf8')

if __name__ == '__main__':
    main()


texts:
I'd like to render mainly mongoDB data and an array. What I want to do is allow my EJS file to use the components inside the database.

 //Array to store all restaurants
 var restArray = [];

 //Need database restaurant schema
 var databaseArray = [];

 //Find the restaurant in the database,
 //If not there create one.
 var findOrCreate = function() {
     Restaurant.findOne({
             nameOfRest: this.nameOfRest
         })
         .then(exist => {
             if (!exist) {

                 this.save()
                     .then(result => {
                         databaseArray.push(result);
                     })
                     .catch(err => {
                         console.log(err);
                     })
             } else {
                 databaseArray.push(exist);
             }
         })
         .catch(err => {
             debugger;
             console.log(err);
         })
 }
 //Go through each restaurant and put in function.
 restArray.forEach(function(restArr) {

     var tempRest = new Restaurant({
         nameOfRest: restArr.restaurant.name,
         favoriteFoods: [],
     });
     //databaseArray.push(tempRest);

     findOrCreate.call(tempRest);
 });
  //*****************I would use database array here
 res.render('restaurant', {
     restHTML: restArray
 });

This is incorrect as it does not push all of it to the database array in time because the code is asynchronous. Is there a better way to access database data to be used in the EJS file or do I have to find a way to push the schema data into the databaseArray and render it alongside restArray data (I need the restArray)?
I would like the mongoDB data to be put here:

<script>
window.onload = function()
{
    var ctx = document.getElementById("myChart").getContext('2d');
    var myChart = new Chart(ctx,
    {
      type: 'bar',
    data: {
        labels: ["Chili dog", "Burger", "Zucchini Fries"], //*****************Put mongodb data inside here *******************
        datasets: [{
            label: 'Best food here:' ,
            data: [12, 19, 3], //********************Put mongodb data inside here. ******************
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
            ],
            borderWidth: 1
        }]
    },
    options: {
        responsive: false,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }

    }
    });
}
</script>


texts: Best way to implement a web MVC application (language agnostic)

texts:
Well, the questions is a little bit broader, so I'll assume that the basics is already defined:

Controller

FrontController
Controllers (plugin hooks, request/response object, view handler)

View

View (template, scripts, partials, helpers)

Model

Domain model objects
Domain model repository
Database abstraction layer

Let me know if I missed something.

Assuming that the above is correct. Now the big question:

Should controllers implement business logic?

// (an example in php)
class UsersController {
   public function create() {
      $user = new User();
      $user->setName($this->getRequest()->getPost('name'));
      // ...
   }
}

The point is, the create action is deciding which information a user need to be created. Therefore, I'm assuming that it's business logic.

// (an example in php just delegating the job to the repository)
class UsersController {
   public function create() {
      $this->userRepository->create($this->getRequest->getPost());
   }
}

If we delegate the job to the repository, then I'm assuming that now the controller is just doing its job, no business logic in there.

Now the second question. Should repositories deal with create, edit and delete operations?

Finally, it will be common for repositories to populate associations and aggregations. So the user repository can also populate the user object with its article associations, for instance. In this case, should the repository call the article repository to do so?

Now about the aspect oriented programming:

We need to deal with ACLs. Whether a domain object or collection is accessible by the current user is determined by the ACLs.

Isn't it part of the model?

Should controller implement ACL's checks as a plugin hooked on the pre-dispatch or, since it's business logic, should our repositories know if its methods are accessible by the current user?

Now what I achieved so far

Well, I ended up with a service layer with protected methods like:

class UsersService extends AbstractService {
   protected function _create($data) {
       $this->validate($data)
       $this->userRepository->create($data);
   }
}

and with a overloading (again in php, but in java for instance, we'd assume a proxy)

class AbstractService {
    public function __call($method, $args) {
       // ACLs checks
       // then call the protected method
    }
}

My service layer is responsible to hold validations and ACLs checks.

So in the end:

class UsersController {
   public function create() {
      $this->userService->create($this->getRequest->getPost());
   }
}


texts:
I'm pretty new to algorithms, and it's my first attempt to implement sentinel linear search in JS. I'm wondering if it can be improved.
const array1 = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit', 'cras', 'eu', 'metus', 'volutpat', 'sagittis', 'nunc', 'in', 'porta', 'quam'];
let i = 0;
let x = 'elit';
let n = array1.length;
let last = array1[n - 1];
array1[n - 1] = x;

(function () {
    while (array1[i] !== x) {
        i++;
        if (array1[i] === x) {
            array1[n - 1] = last;
            if (array1[i] === x) {
                return console.log('FOUND ON INDEX', i);
            } else {
                return console.log('NOT FOUND');
            }
        }
    }
})();


texts: One Time Pad algorithm for encryption and decryption

texts:
I have written my own one time pad algorithm for encryption and decryption, but I would like to listen to your opinions about its correctness and eventually how could I improve it. My idea was to keep it readable, but not so bad in terms of performance. I have also written some tests.

Here's the code:

from random import choice
import string

def convert_to_bits(s):
    """Converts string s to a string containing only 0s or 1s,
    representing the original string."""
    return "".join(format(ord(x), 'b') for x in s)

def gen_random_key(n):
    """Generates a random key of bits (with 0s or 1s) of length n"""
    k = []
    for i in range(n):
        k.append(choice(["0", "1"]))
    return "".join(k)

def xor(m, k):
    """Given strings m and k of characters 0 or 1,
    it returns the string representing the XOR
    between each character in the same position.
    This means that m and k should be of the same length.

    Use this function both for encrypting and decrypting!"""
    r = []
    for i, j in zip(m, k):
        r.append(str(int(i) ^ int(j)))  # xor between bits i and j
    return "".join(r)

if __name__ == "__main__":
    ls = []

    for i in range(100):
        for i in range(100):
            ls.append(choice(string.ascii_letters))

        s = "".join(ls)

        bits = convert_to_bits(s)
        key = gen_random_key(len(bits))
        cipher = xor(bits, key)
        original = xor(key, cipher)

        if original != bits:
            raise Exception("Something wrong with the implementation...")


texts:
I'm trying to cover the following 4 scenarios:

No parameters
DB param
DB param and 1 option
No DB param and 1 option

So far I have the program working for all scenarios. However, I'm not happy with the way it's implemented. Is it possible to change this to a cleaner solution, rather than checking if there's only 1 parameter passed or catching an exception?

def do_work(database=None):
    if database:
        print 'Doing work for {0}'.format(database)
    else:
        print 'Doing work all database'

def do_other_work(database=None):
    if database:
        print 'Doing other work for {0}'.format(database)
    else:
        print 'Doing other work all database'

def create_parser():
    parser = ArgumentParser(description='Parser')
    parser.add_argument('--db', '-d', dest='database',
                        default=None, required=False, help='Database name')

    option_group = parser.add_mutually_exclusive_group(required=False)
    option_group.add_argument('-a', dest='cmd',
                              action='store_const',
                              const=lambda args: do_other_work(args.database)
    return parser

if len(sys.argv) == 1:
    do_work()

parser = create_parser()
parsed_args = parser.parse_args(sys.argv[1:])

try:
    parsed_args.cmd(parsed_args)
except TypeError:
    do_work(parsed_args.database)

No parameters passed: do_work() for all databases
db parameter passed and no option: do_work() for just that database
db parameter and an option: do_other_work() just for that database
No db parameter and an option: do_other_work() for all databases


texts:
I am trying to make an algorithm that will find the index of a given substring (which I have labeled pattern) in a given String (which I have labeled text). This method can be compared to String.indexOf(String str). In addition to general feedback, I'm curious what the time complexity of my method is, and would appreciate if someone can help me figure it out.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

public class SubstringSearch {
    public static void main(String[] args) {
        String text = "This is a test String";
        String pattern = "is a";
        int index = search(pattern, text);
        System.out.println(index);
    }

    private static int search(String pattern, String text) {
        int patternLength = pattern.length();
        int textLength = text.length();

        Set<Integer> set = new HashSet<>(textLength);
        List<Integer> addList = new ArrayList<>(textLength);

        for (int i = 0; i < textLength; i++) {
            set.add(0);

            for (Integer index : set) {
                if (pattern.charAt(index) == text.charAt(i)) {
                    addList.add(index + 1);
                }
            }

            set.clear();
            set.addAll(addList);

            if (set.contains(patternLength)) {
                return i - patternLength + 1;
            }
        }

        throw new NoSuchElementException();
    }
}


texts: Check if an image download from the Internet has already started

texts:
In the method getView() in my implementation of ArrayAdapter I have to download image from Internet using the image's url and set downloaded image to ImageView. I have to check in getView() whether downloading of an image from the given url is already started because of recycling views in TwoWayGridView and because of some bug there (immediately after creating a grid view the adapter's method getView() is called multiple times unnecessarily for the first item in grid view). To check that I use ImageView's tag.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View itemView = (convertView != null) ? convertView : inflateItemView();
    ImageView imageView = (ImageView) itemView.findViewById(R.id.image);
    String url = getItem(position);
    setImageView(imageView, url);
    return itemView;
}

private void setImageView(ImageView imageView, String url) {
    if (url == null) {
        imageView.setImageDrawable(null);
    } else {
        downloadAndSetImage(imageView, url);
    }
}

private final Object LOCK_CHECKING_TAG_AND_URL = new Object();

private void downloadAndSetImage(final ImageView imageView, final String url) {
    synchronized (LOCK_CHECKING_TAG_AND_URL) {
        int tagId = R.id.tag_prevent_unnecessary_image_reset;
        String tag = (String) imageView.getTag(tagId);
        if (tag != null && tag.equals(url)) {
            // Image downloading from the given url for this ImageView is already started.
            // There is no need to start new downloading.
            return;
        }
        imageView.setTag(tagId, url);
    }
    imageView.setImageDrawable(null);
    // ImageManager is my utility class for downloading images in background
    imageManager.getImage(imageView, url, new ImageManager.Listener() {
        @Override
        public void imageReady(Drawable drawable) {
            imageView.setImageDrawable(drawable);
        }
    });
}

Later I changed the downloadAndSetImage() method:

private void downloadAndSetImage(final ImageView imageView, final String url) {
    if (!isNeedToDownload(imageView, url)) {
        return;
    }
    imageView.setImageDrawable(null);
    imageManager.getImage(imageView, url, new ImageManager.Listener() {
        @Override
        public void imageReady(Drawable drawable) {
            imageView.setImageDrawable(drawable);
        }
    });
}

private boolean isNeedToDownload(View imageView, String url) {
    synchronized (LOCK_CHECKING_TAG_AND_URL) {
        int tagId = R.id.tag_prevent_unnecessary_image_reset;
        String tag = (String) imageView.getTag(tagId);
        if (tag != null && tag.equals(url)) {
            return false;
        }
        imageView.setTag(tagId, url);
        return true;
    }
}

But I think that the name isNeedToDownload() is bad (or may be the method itself is bad) because this boolean checking method not only checks some condition but also set a tag to ImageView. I think that the name like a checkDownloadingNecessity() and return type

class CheckingResult {
    public boolean isDownloadingNecessary;
}

would be better, but it is too excessively. What do you think?


texts:
I have the following series of click events in my jQuery code:

$('#morning .up .hour').click(function () {
  morning.hour++
  update_hour(morning);
});

$('#morning .up .min').click(function () {
  morning.min++
  update_min(morning);
});

$('#morning .up .sec').click(function () {
  morning.sec++
  update_sec(morning);
});

$('#morning .down .hour').click(function () {
  morning.hour--
  update_hour(morning);
});

// ...
// morning down min
// morning down sec
//
// evening up hour
// evening up min
// evening up sec
//
// evening down hour
// evening down min
// ...

$('#evening .down .sec').click(function () {
  evening.sec--
  update_sec(evening);
});

Each alarm has an object which contains the values for the hours, minutes and seconds, along with the selector for the values (this is used in the update functions explained below):

var morning = {
  selecthour: "#morning .time .hour",
  selectmin: "#morning .time .min",
  selectsec: "#morning .time .sec",
  hour: 7,
  min: 0,
  sec: 0
};

And finally the HTML code:

Up

Up

Up

            EX:AM:PL

Down

Down

Down

The basic structure of the page is:

There are several alarms, each of which has a unique ID (currently there are two: one named morning, one named evening.)
Each alarm has an hour, minute and second field (see div.time)
Each field, in each alarm, has an up and a down arrow which increases or decreases the time
In the selectors above, the ID is the alarm, the first class is the up or down arrow, and the second class is the field which the arrow is associated with (hour/min/sec)

When a button is clicked, the following should happen:

The hour, min or sec property of the alarm object (morning or evening) is incremented or decremented by 1, based on the arrow pressed
The update_hour, update_min, or update_sec function is called, with the alarm object as its argument (morning or evening)
The update function checks and corrects any invalid input, then updates the appropriate field of the appropriate alarm in the HTML.

It takes 6 functions, each 3 lines long, for every alarm. For just the two alarms that's 36 lines of repetitive code.

Is it possible to simplify this series of jQuery .click() statements? Bonus points if it works with more than the two specified alarms. (I have an array containing all of the alarms if that helps)


texts:
I have some code that draws sprites and and allows new ones to be added. To do this, I use 2 lists: 1 for the sprites that need to be drawn, and one for the new sprites that need to be added to the main list. I have done it this way so that new sprites can still be added in even if the main list is being drawn at that time.

I have the addSprite method synchronized with newSprites. The section for updating the main list with new sprites is also synchronized. These locks are there so that new sprites are not removed from the newSprites list before they are added to the main list.

I also thought of another option:
Remove the newSprites list completely. Instead, just synchronize the main sprites list. This would work, but I am worried it could slow down the program because new sprites could not be added until drawing had completed.

Here is my current code:

List<Sprite> sprites=new ArrayList<Sprite>();
List<Sprite> newSprites=new ArrayList<Sprite>();

public void doDrawing() {

    for(Sprite s:sprites) {
        if(s.isVisible()) {
                s.draw();
        }
    }
    synchronized (newSprites) {
        if(newSprites.size()>0) {
            sprites.addAll(newSprites);
            newSprites.clear();
        }
    }
}

public void addSprite(Sprite s) {
    synchronized (newSprites) {
        newSprites.add(s);
    }

}

Is the newSprites a good idea? Should I replace this with something else? Any other advice or review is welcome as well, of course.

Note: I am not drawing an insane number of sprites, almost always (much) less than 100.


texts:
Given a vector of seller orders (asks) of a certain product (each order having a price) and buyer orders (bids) of the same product, I'm creating a function that resolves the auction by matching the best sellers (lowest asked price) with the best buyers (higher offered price) and then clears the market by selecting a price and 'performing' the transactions between all suitable traders.

I'm experienced as programmer but I'm new to Clojure (or any Lisp), so this question is about the "Clojure way" of doing things so that the resulting code is readable, maintainable and efficient.

(ns trade-routes.core
  (:gen-class))

(defn as-trade-result
  [ask bid]
  (let [bid-price (:price bid) ask-price (:price ask)]
    {:traded (<= ask-price bid-price) :bid bid :ask ask}
    )
)

(defn trade-price-tagger
  [price]
    (fn [trade] (merge trade {:price price}))
  )

(defn bid-price
  [trade]
  (-> trade :bid :price))

(defn average
  [a b]
  (* 0.5 (+ a b)))

(defn resolve-auction
  "Returns a list of trades and unresolved seller asks orders and buyer bids orders.
  The highest asks are matched with the lowest bids until all bids are greater than all asks"
  [asks bids]
  (let [best-asks (sort-by :price asks)
        best-bids (reverse (sort-by :price bids))
        succesful-trades (first (partition-by
            :traded
            (map as-trade-result
                 best-asks
                 best-bids)))
        breakeven-successful-trade (last succesful-trades)
        breakeven-price (average
                          (bid-price breakeven-successful-trade)
                          (bid-price breakeven-successful-trade))]
    (map (trade-price-tagger breakeven-price) succesful-trades)))

(defn random-order
    [min max]
    {:price (+ min (rand (- max min)))}
  )

(defn gen-random-orders
    "Create 'total' random orders with price between min and max"
    [total min max]
   (take total (repeatedly #(random-order min max)))
  )

(def test-asks (gen-random-orders 1000 20 100))
(def test-bids (gen-random-orders 1000 0 25))

(defn -main
  "Just tests with test-asks and test-bids."
  [& args]
  (let [succesful-trades (resolve-auction test-asks test-bids)]
   (println (str "There were " (count succesful-trades) " trades"))))


texts: Generating binary sequences without repetition

texts:
I am trying to generate sequences containing only 0's and 1's. I have written the following code, and it works.
import numpy as np

batch = 1000
dim = 32

while 1:
    is_same = False
    seq = np.random.randint(0, 2, [batch, dim])
    for i in range(batch):
        for j in range(i + 1, batch):
            if np.array_equal(seq[i], seq[j]):
                is_same = True
    if is_same:
        continue
    else:
        break

My batch variable is in the thousands. This loop above takes about 30 seconds to complete. This is a data generation part of another for loop that runs for about 500 iterations and is therefore extremely slow. Is there a faster way to generate this list of sequences without repetition? Thanks.
The desired result is a collection of batch_size number of sequences each of length dim containing only 0s and 1s such that no two sequences in the collection are the same.


texts:
Code Review

I've recently (within the last month) started learning Python and am now building a few basic apps. One of the apps I've created is a sort of desktop monitoring tool, that attempts to build a list of all applications used within a specified time period.

Process -

Check whether the current time falls between the monitoring period
Create a record of what is currently being used
Save that record / entry to the log file
Repeat the process until the current time falls outside of the monitoring period
Once outside of monitoring period the Log file is renamed
End

I'd like to know whether some of you could spare a few minutes to review my code - Commenting on it's efficiency (or lack of), thoughts on how it could be improved and more. I do have some additional features to add (currently working on a UI). Right now I'm just looking comments.

Thanks in advance and apologies if I've posted in the wrong area.

from datetime import datetime
import os
import time
import psutil
import win32process

# When to start monitoring
start_time = datetime.now().strftime("%H:%M:%S")
# End Time - When to end monitoring
end_time = "08:55:00"
# Directory - Where to store activity log
directory = r"C:\Users\username\Documents"

def activity_log(s_time, e_time, dir_t):

    # act_app is used to return the active app/window
    act_app = ""

    # entry number/id
    num = 1000

    # monitoring start time
    p_start_time = s_time

    # monitoring end time
    p_end_time = e_time

    # File path / File name
    log_path = dir_t + "\\Log.csv"

    # Look into creating outer look to review current time or use out IF condition
    while p_start_time <= datetime.now().strftime("%H:%M:%S") <= p_end_time:

        # New record will be create IF different from the previous record
        if act_app != GetWindowText(GetForegroundWindow()) and act_app != " ":

            act_app = str.replace(GetWindowText(GetForegroundWindow()), " = ", ", ")
            today = datetime.today()
            num = num + 1
            pid = win32process.GetWindowThreadProcessId(GetForegroundWindow())
            app_name = psutil.Process(pid[-1]).name()

            with open(log_path, "a", encoding="utf-8") as LogFile:
                LogFile.write(f"{num}, {str.replace(act_app, ''''''', ' - ').replace(',', '')}, "
                              f"{app_name}, {today.strftime('''%d/%m/%Y''')}, "
                              f"{today.strftime('''%H:%M:%S''')} \n ")

        time.sleep(2)
        # Sleep/wait two seconds before attempting to create a new entry
    else:
        if os.path.isfile(log_path):
            # need to check if file exists before opening file
            with open(log_path, "a") as LogFile:
                LogFile.write(f"\n\n\n---- Desktop Activity Between {p_start_time} and {p_end_time} ----")
                # rename log file at the end of monitoring period
            os.rename(log_path, f"{dir_t}\\DesktopJ_ActLog_{datetime.now().strftime('''%d%m%Y_%H%M%S''')}.csv")
        else:
            print("No log created.")
            return "No log created"

activity_log(start_time, end_time, directory)


texts: Print an integer and its digits reversed

texts:
This Common Lisp program is an exercise to print an integer and its digits reversed to the screen:

(defun read-number () (format t "Enter a number: ~%") (read))

(defun reverse-string (the-string)
  (if (eq (length the-string) 0)
    ""
    (concatenate 'string (reverse-string (subseq the-string 1)) (subseq the-string 0 1))))

(defun reverse-digits (the-number) (reverse-string (write-to-string the-number)))

(let ((the-number (read-number)))
  (format t "N->: ~a~%<-N: ~a~%" the-number (reverse-digits the-number)))


texts: Optimizing code solution for Palindrome Index-Hackerrank

texts:
I submitted my solution for palindrome Index coding challenge but I get "test cases terminated due to time out error". My code is working and so I don't know what else to do to optimize it. Please help:

function palindromeIndex(s) {
    let palindrome = s === s.split('').reverse().join('')
    if(!palindrome) {
        let i = 0
        let integerIndex = []
        let arr = s.split('')
        while(i < s.length) {
            arr.splice(i,1)
            if(arr.join('') === arr.reverse().join('')) {
               integerIndex.push(i)
            }
            arr = s.split('')
            i++
        }
        return integerIndex.length > 0 ? integerIndex[0] : - 1
    }else {
        return -1
    }
}


texts:
How can I improve or shorten my implementation of the Luhn algorithm?

    int digits;
    cout << "enter the numer of digits" << endl;
    cin >> digits;
    int Acc_num[digits];
    int shuma = 0;

The shuma variable is the sum.

I created an array to store the digits from the string credit_card.

And asked the user how many digits his credit card has, etc. (the digits int).

    string credit_card;
    cout << "enter the identification number" << endl;
    cin >> credit_card;

    // store the digits
    for (int i = 0 ; i < digits ; i ++ ) {
        Acc_num[i] = credit_card[i];
    }

    for (int i = 0 ; i <= (digits - 1) ; i ++ ) {
        Acc_num[i] -= 48;
    }

    // Double every other
    for (int i = 1 ; i <=digits ; i ++) {
        if (i % 2 == 0) {
            Acc_num[i-1] =  2 * Acc_num[i-1];
        } else {
            Acc_num[i-1] = Acc_num [i-1];
        }
    }

    //Sum digits
    for (int i = 1 ; i <= digits ; i ++ ) {
        if (Acc_num[i-1] > 9 && i % 2 == 0) {
            int mod = Acc_num[i-1] % 10 ;
            Acc_num[i-1]  =  1 + mod ;
        } else {
        Acc_num[i-1] = Acc_num[i-1];
        }
    }

    // the sum
    for (int i = 0 ; i <= (digits - 1) ; i ++ ) {
        shuma += Acc_num[i];
    }

    if (shuma % 10 == 0) {
        cout << "\nthis number is valid" << endl;
    } else {
        cout << "\nthis number is invalid" << endl;
    }


texts: Expressing positive integers as the sum of different charming numbers

texts:
In a practice academic interview of mine, we discussed question six, round one, of the United Kingdom Mathematics Trust's 2015 British Mathematical Olympiad. Which states:

  A positive integer is called charming if it is equal to 2 or is of the form
  3i5j where i and j are non-negative integers. Prove that every positive integer can be written as a sum of different charming integers.

Having been able to successfully prove this, afterwards I then went on to implement, in Python, a program which can express any positive integer in terms of the sum of different charming numbers.

To do this I start by converting the integer into base 3 so that it is easier to find a charming number that is more than half the value of the original integer, but less than it. This value is then appended to a list, and the process is then repeated with the difference until left with either 1, 2, or 3. A list of charming numbers is then returned, which all sum to the original number.

I know this method works, simply as I used it somewhat in my proof.

I apologise in advance for the lack of comments.

def to_base_3(base_10: int) -> str:
    working_number = int(base_10)
    output = ''

    while True:
        next_digit = working_number % 3
        output = str(next_digit) + output
        working_number = working_number // 3

        if working_number == 0:
            return output

def to_base_10(base_3: str) -> int:
    output = 0

    for i, char in enumerate(base_3[::-1]):
        output += int(char) * (3 ** i)

    return output

def find_charming_components(number: int, charming_components: list = None) -> list:
    if charming_components is None:
        charming_components = []

    base_3_value = to_base_3(number)
    digit = base_3_value[0]
    component = 0

    if len(base_3_value) == 1:
        if digit != '0':
            charming_components.append(int(digit))

        return charming_components

    if digit == '1':
        component = to_base_10('1' + '0' * (len(base_3_value) - 1))
        # Find the largest power of three that is lower than the current value. I.e: 3**4
        charming_components.append(component)
        # Append this charming number to the list of components

    elif digit == '2':
        component = to_base_10('12' + '0' * (len(base_3_value) - 2))
        # Find the largest power of three times five that is lower than the current value. I.e: 3**4 * 5
        charming_components.append(component)
        # Append this charming number to the list of components

    number -= component
    # Repeat process with the difference
    return find_charming_components(number, charming_components)

print(find_charming_components(int(input('Number: '))))

I just feel like doing a full base 3 conversion and back again isn't the most efficient method of doing this, and would appreciate some help on generally improving the algorithm.


texts:
I am writing a python3 implementation of palindromes checker.

import string

def is_palindrome(text):
    """A string of characters is a palindrome if it reads the same forwards and
    backwards, ignoring punctuation, whitespace, and letter casing"""
    # implement is_palindrome_iterative and is_palindrome_recursive below, then
    # change this to call your implementation to verify it passes all tests
    assert isinstance(text, str)
    return is_palindrome_iterative(text)
    # return is_palindrome_recursive(text)

def is_palindrome_iterative(text):
    word = text

    # if the word[index] is not the same, return False
    # iteration through the index from  the half of the length
    # doing it through
    for index in range(len(word)//2):
        if word[index] != word[-1-index]:
            return False
    return True

def main():
    import sys
    args = sys.argv[1:]  # Ignore script file name
    if len(args) > 0:
        for arg in args:
            is_pal = is_palindrome(arg)
            result = 'PASS' if is_pal else 'FAIL'
            str_not = 'a' if is_pal else 'not a'
            print('{}: {} is {} palindrome'.format(result, repr(arg), str_not))
    else:
        print('Usage: {} string1 string2 ... stringN'.format(sys.argv[0]))
        print('  checks if each argument given is a palindrome')

if __name__ == '__main__':
    main()

I think it works well.

ran python3 palindromes.py 'ABA'
output is
PASS: 'ABA' is a palindrome


texts: Finding time complexity of my solution to the 'longest palindrome' problem in Python

texts:
Here is a short version!

def longestPalindrome(string):

    # Will use this string to record the longest palindrome seen so far
    largestPalindrome = ""

    for index in range(0, len(string)):

        reqcharMatch = string[index]

        # Since a palindrome must have matching start and end characters
        # I will find the index of all occurrences of the current
        # character that I'm looking at in the remaining string.

        # Will accomplish this using regular expression or simply
        # by passing the character I'm looking to find, the remaining
        # string to another function, it will return a list having
        # indices where matching character is present.

        # Let us for example assume that, the character I'm at currently
        # is also present in indices 4, 8, 9.
        # otheroccurList = [4, 8, 9]

        otheroccurList = regexFunctionHere()

        for occurrenceIndex in range(len(otheroccurList)):

            originalString = string[index: otheroccurList[occurrenceIndex] + 1]

            reversedString = originalString[::-1]

            # If the string obtained by slicing from the current
            # character to the next occurence of the same character is
            # a palindrome, and the length of this particular string is
            # more than the largestPalindrome seen so far, then update
            # largestPalindrome to be equal to the current Palindrome
            # we are looking at.

            if((reversedString == originalString) and (len(originalString) >= largestPalindrome)):

                largestPalindrome = originalString

    # If literally no palindrome is found, then simply return the
    # first character in the string
    if largestPalindrome == "":
       return string[0]

    else:
       return largestPalindrome

Here is a longer version, please forgive me if its not refactored. I did my best to ensure good variable names, but you can copy paste this and run it with whatever test cases, it will pass them.

Long version:

class Solution:

    @staticmethod
    def findallOccurrence(findcharIndex, chartoFind, remString):

        """
        Function to find the all other indices where a character
        appears.
        """

        occurrenceList = []

        for i in range(len(remString)):

            if(remString[i] == chartoFind):

                index = findcharIndex + i + 1

                occurrenceList.append(index)
                index = 0

        return occurrenceList

    @staticmethod
    def reverseString(origString):
        """
        Function to reverse a string
        """

        return origString[::-1]

    @staticmethod
    def checkPalindrome(origString, reversedString):

        """
        Function to check if the original string and the reversed
        string is a palindrome.
        """

        if(origString == reversedString):
            return True

        else:
            return False

    def longestPalindrome(self, A):

        """
        This is my main function whose short version I've explained.
        """

        longestPalindrome = ""

        for index in range(len(A)):

            findChar = A[index]

            remainingString = A[index + 1:]

            oList = findallOccurrence(index, findChar, remainingString)

            for j in range(len(oList)):

                origString = A[index: oList[j] + 1]
                revString = reverseString(origString)

                isPalindrome = checkPalindrome(origString, revString)

                if(isPalindrome == True) and (len(origString) >= len(longestPalindrome)):

                    longestPalindrome = origString

        if(longestPalindrome == ""):
            return A[0]

        else:
            return longestPalindrome

sol1 = Solution()
sol1.longestPalindrome("abaaaaaa")

The reason I'm having trouble finding the time complexity of my solution is that there are many interlinked loops, and different function calls within them.. I think its O(n^2), but it looks like its O(n^3).


texts:
I'm currently working on a project that I had to create basically a running queue of items. My thought was to do this by a list, but surprisingly there weren't any methods to remove the first sequence or last sequence of items in a list that I found. I wrote the following class with extension methods for List<T>:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Extensions
{
    public static class ExtensionClass
    {
        public static bool TrimFirst<T>(this List<T> list, int maxCount)
        {
            try
            {
                if (list.Count <= maxCount)
                {
                    throw new InvalidOperationException
                        ("Items in list <= maxCount, unable to trim list.");
                }

                while (list.Count > maxCount)
                {
                    T first = list.First<T>();
                    list.Remove(first);

                }
                return true;
            }

            catch
            {
                return false;
            }

        }

        public static bool TrimLast<T>(this List<T> list, int maxCount)
        {
            try
            {
                if (list.Count <= maxCount)
                {
                    throw new InvalidOperationException
                        ("Items in list <= maxCount, unable to trim list.");
                }

                while (list.Count > maxCount)
                {
                    T last = list.Last<T>();
                    list.Remove(last);

                }
                return true;
            }

            catch
            {
                return false;
            }
        }

        public static bool ItemExists<T>(this List<T> list, T item)
        {
            foreach (T listItem in list)
            {
                if (item.ToString() == listItem.ToString())
                {
                    return true;
                }
            }

            return false;
        }

    }
}

This seems something that I will likely use in the future, so I would like to optimize it and make it as flexible as possible. Does anyone have any suggestions? For reference, the try/catch/exception are in case I need to modify the code to deal with that in the future, although I was not quite sure about the way that I wrote that part of the code. Anyone that needs this function, feel free to use this code!

I have also added the ItemExists() method since I hate the Any() and Exists() methods' use of a predicate. As far as I know, this method processes the items by enumeration, just at the built-in methods do, except they possibly use a Parallel.ForEach loop. Any suggestions for optimizing this method?


texts: Resize image with good quality and less weight

texts:
I want to resize an image with good quality, and the most important thing is having less weight for an image so that webpages will load it faster.

I am using the below method for this. Please check it out, if it is proper or let me know if it needs any modifications. If there is a better method than this, then also please tell me.

public static void ResizeImage(int newWidth, int newHeight, Stream sourcePath, string targetPath)
{
    using (var image = System.Drawing.Image.FromStream(sourcePath))
    {
        Image imgPhoto = Image.FromStream(sourcePath);

        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;

        if (sourceWidth > newWidth || sourceHeight > newHeight)
        {
            //Consider vertical pics
            if (sourceWidth < sourceHeight)
            {
                int buff = newWidth;

                newWidth = newHeight;
                newHeight = buff;
            }

            int destX = 0, destY = 0;
            float nPercent = 0, nPercentW = 0, nPercentH = 0;

            nPercentW = ((float)newWidth / (float)sourceWidth);
            nPercentH = ((float)newHeight / (float)sourceHeight);
            if (nPercentH < nPercentW)
            {
                nPercent = nPercentH;
                destX = System.Convert.ToInt16((newWidth -
                      (sourceWidth * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentW;
                destY = System.Convert.ToInt16((newHeight -
                      (sourceHeight * nPercent)) / 2);
            }
        }

        var thumbnailImg = new Bitmap(newWidth, newHeight);
        var thumbGraph = Graphics.FromImage(thumbnailImg);
        thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
        thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
        thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
        var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
        thumbGraph.DrawImage(image, imageRectangle);
        thumbnailImg.Save(targetPath, image.RawFormat);
    }
}


texts:
Since I had a lot of classes to store inside 1 main class I decided to create a handler system. I was having to create 30 - 50 private readonly fields for private instances of classes, then assigning them all in the constructor, then creating a public method to get them via a return. I decided instead of having up to 150 lines of code that I would try and sort out a more organised system and put it in place.

I start by declaring an empty interface for all my handlers to inherit  that interface. This interface is in a totally seperate .cs file.

namespace Panda.Root.Core.Other
{
    public interface IPandaClass { }
}

Now, I declare a new dictionary in my main class (PandaServer.cs)

private readonly Dictionary<string, IPandaClass> _handlers;

I then assign the dictionary:

public PandaServer()
{
    _handlers = new Dictionary<string, IPandaClass>(StringComparer.InvariantCultureIgnoreCase);
}

I create two methods, one for registering new handlers (or replacing them) and one for returning the handler by name.

private void RegisterHandler(string handlerName, IPandaClass handler)
{
    _handlers[handlerName] = handler;
}

public IPandaClass GetHandler(string handlerName)
{
    return _handlers[handlerName];
}

And then I can register as many hadlers as I can, pretty easily:

RegisterHandler("messages", Utilities.CreateInstanceOf<MessageHandler>());
RegisterHandler("configuration", Utilities.CreateInstanceOf<ConfigurationManager>());
RegisterHandler("console_worker", Utilities.CreateInstanceOf<ConsoleWorker>());
RegisterHandler("base_handler", Utilities.CreateInstanceOf<BaseHandler>());

I then declare them where I need them like this

var panda = Program.GetPandaServer();
var pandaBase = panda.GetHandler("base") as BaseHandler;

if (pandaBase == null)
{
    return;
}

var playerHandler = pandaBase.GetHandler("player") as PlayerHandler;

I was told declaring all your classes there instead of making multiple calls in future was better as you would always have that variable there incase you wanted to make multiple calls to the same method or methods of that method's return type.

The only major bad things I see with this system is you're hardcoding the name of the handlers but I guess there isn't a way around that, its how it works. If anyone can think of any other improvements please let me know.


texts: looking for OO input , is any of this code good OO or am i doing it all wrong?

texts:
Some code im working with for a stock system , i have two ways to do this, looking for review on if any of them are correct and if so which one is better OO than the other

public interface Order {
    public void processed(AllocationResponse response);
}

the two solutions i have in my head are

public class Warehouse {

    public void allocate(Order order){
        AllocationResponse response = calculateAllocation(order.getQuantity());
        order.processed(response)
    }

    private AllocationResponse calculateAllocation(int quantity){
    // code
    }

}

public class AllocationResponse {

    int quantityAllocated = 0;
    int quantityBackOrdered = 0;
}

Order order = // get order
new Warehouse().allocate(order)

or

public class Warehouse {

    public AllocationResponse allocate(int quantity){
        return calculateAllocation(quantity);
    }

    private AllocationResponse calculateAllocation(int quantity){
        // code to generate response object
    }

}

Order order = // get order
AllocationResponse response = new Warehouse().allocate(order.getQuantity());
order.processed(response)


texts:
I was bored, so I wrote a BrainFuck interpreter in Python. It essentially takes input for the amount of cells, then parses the inputted code through a series of if statements.

# Simple BrainFuck interpreter
from sys import exit

# Main interpreter function
def interpreter(cell_amount):
    step = 0
    cell = [0] * cell_amount
    cell_pos = 0
    loop = False
    loop_ret = 0

    code_input = raw_input('Code: ')
    steps = len(code_input)

    while True:

        if code_input[step] == '+':
            cell[cell_pos] += 1

        elif code_input[step] == '-':
            cell[cell_pos] -= 1

        elif code_input[step] == '>':
            cell_pos += 1

        elif code_input[step] == '<':
            cell_pos -= 1

        elif code_input[step] == '[':
            if loop == False:
                loop_ret = step
                loop = True

        elif code_input[step] == ']':
            if cell[cell_pos] != 0:
                step = loop_ret
            elif cell[cell_pos] == 0:
                loop = False

        elif code_input[step] == '.':
            print str(cell[cell_pos])

        elif code_input[step] == ',':
            cell[cell_pos] = int(raw_input())

        step += 1

        if step == steps:
            exit(0)

interpreter(int(raw_input('Cell amount: ')))

Now, it works, with one small issue: loops can't be nested. I'd like a few things to be improved about it.

Read code from a text file instead of stdin.
Better system than a chain of if/elif/else statements.
Be able to nest loops.


texts: A reusable Previous/Next Contact Collection ViewModel class

texts:
I often use a ViewModel class that contains a collection of Contacts and allows me to iterated through the collection with Previous and Next buttons.

I find that I've got duplicate versions of this class all over the place and I'd like to make my code reusable.

How would I go about making the following code reusable (i've been going round in circles for a while now):

public class PartiesViewModel : BaseViewModel
{
    const int MaxParties = 20;

    public ObservableCollection<Party> Parties { get; set; }

    public PartiesViewModel(ObservableCollection<Party> parties)
    {
        Parties = parties;
        Party = Parties.FirstOrCreateIfEmpty();

        Party.PropertyChanged += UpdatePartyShortNamesList;
        Parties.CollectionChanged += Parties_CollectionChanged;

        ClearCommand = new RelayCommand(ClearPressed, CanClear);
        NextCommand = new RelayCommand(NextPressed, CanPressNext);
        PrevCommand = new RelayCommand(PrevPressed, CanPressPrev);
    }

    void UpdatePartyShortNamesList(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "ShortName")
            NotifyPropertyChanged("PartyShortNames");
    }
    void Parties_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        NotifyPropertyChanged("PartyNames");
        NotifyPropertyChanged("PartyShortNames");
        NotifyPropertyChanged("Count");
    }

    Party _Party;
    public Party Party
    {
        get { return _Party; }
        set
        {
            _Party = value;
            NotifyPropertyChanged("Party");
            NotifyPropertyChanged("Count");
        }
    }

    public string Count
    {
        get
        {
            var list = Parties.ToList();
            list.RemoveAll(x => x.IsEmpty());
            int current = list.FindIndex(x => x == Party) + 1;
            int count = list.Count();
            if (current == 0)
                return string.Format("{0} of {0}", count + 1);
            else
                return string.Format("{0} of {1}", current, count);
        }
    }

    public RelayCommand PrevCommand { get; set; }
    public bool CanPressPrev() { return IndexOf(Party) > 0; }
    public void PrevPressed()
    {
        try
        {
            int i = IndexOf(Party);
            Party = Parties[i - 1];
        }
        catch (Exception ex) { Message.ShowError(ex); }
    }

    public RelayCommand NextCommand { get; set; }
    public bool CanPressNext() { return !Party.IsNullOrEmpty() && IndexOf(Party) != MaxParties; }
    public void NextPressed()
    {
        try
        {
            if (IndexOf(Party) + 1 == Parties.Count)
            {
                Party = new Party();
                Parties.Add(Party);
            }
            else
            {
                int i = IndexOf(Party);
                Party = Parties[i + 1];
            }
        }
        catch (Exception ex) { Message.ShowError(ex); }
    }

    public RelayCommand ClearCommand { get; set; }
    public bool CanClear()
    {
        return !Party.IsNullOrEmpty();
    }
    public void ClearPressed()
    {
        try
        {
            int i = IndexOf(Party);
            if (Party == Parties.Last())
                Party.Clear();
            else
            {
                Parties.RemoveAll(x => x == Party);
                Party = Parties[i];
            }
        }
        catch (Exception ex) { Message.ShowError(ex); }
    }

    int IndexOf(Party party) { return Parties.ToList().FindIndex(x => x == party); }

    public static List<string> PartyTypes { get { return new List<string>() { "Individual", "Company", "Partnership" }; } }

    public bool IsCompany { get; set; }
}


texts:
I have a Combobox and I want to edit a boolean value.

        <dxe:ComboBoxEdit ItemsSource="{Binding EnumItemsSource}"
                          DisplayMember="Name"
                          ValueMember="Id"
                          IsTextEditable="False"
                          EditValue="{Binding TargetValue, UpdateSourceTrigger=PropertyChanged}"/>

My ViewModel:

    /// <summary>
    /// Contains the ItemsSource for Enums
    /// </summary>
    public List<EnumItemObject> EnumItemsSource
    {
        get { return _enumItemsSource; }
        set
        {
            _enumItemsSource = value;
            OnPropertyChanged();
        }
    }

public class EnumItemObject
{
   public int Id {get;set;}
   public string Name {get;set;}
}

And I prepare the data for the Combobox ItemsSource that:

    /// <summary>
    /// Sets the value to the properties for the BitTemplate view. (similar with EnumTemplate)
    /// </summary>
    /// <param name="propertyInfo">a boolean property</param>
    private void PrepareDataForBitTemplate(PropertyInfo propertyInfo)
    {
        TargetValue = (int)propertyInfo.GetValue(_firstSelectedItem);
        EnumItemsSource = new List<EnumItemObject>();
        EnumItemsSource.Add(new EnumItemObject() { Id = 0, Name = "Nein" });
        EnumItemsSource.Add(new EnumItemObject() { Id = 1, Name = "Ja" });
    }

Is it the approach correct? Is there any easier solution?

UPDATE:
Extract from my ViewModel code (you remember EnumItemsSource is ItemsSource for Combobox and TargetValue the Combobox selected item):

    private void LookUpViewData()
    {
        var propertyInfo = _firstSelectedItem.GetType().GetProperty(TargetFieldDescription.fdBigViewColumnName);
        if ((propertyInfo != null) && (propertyInfo.GetValue(_firstSelectedItem) != null))
        {
            if ((int) FieldDataType.ENum == TargetFieldDescription.fdDataType)
                PrepareDataForEnumTemplate(propertyInfo);
            if ((int) FieldDataType.Bit == TargetFieldDescription.fdDataType)
                PrepareDataForBitTemplate(propertyInfo); // like EnumTemplate
            else if ((int) FieldDataType.Time == TargetFieldDescription.fdDataType)
                PrepareDataForTimeTemplate(propertyInfo);
            else
                PrepareDataForDefaultTemplate(propertyInfo);
        }
        else
            TargetValue = String.Empty;
    }

    private void PrepareDataForEnumTemplate(PropertyInfo propertyInfo)
    {
        TargetValue = (int)propertyInfo.GetValue(_firstSelectedItem);
        if (_targetFieldDescription.fdEnumSource != null)
        {
            switch (_targetFieldDescription.fdEnumSource)
            {
                case "Station":
                    EnumItemsSource = ConvertListToEnumItemObjectList(_targetFieldDescription.fdEnumSource);
                    break;
                default:
                    EnumItemsSource = EnumUtil.ConvertEnumToEnumItemObjectList(_targetFieldDescription.fdEnumSource);
                    break;
            }

        }
    }

    private void PrepareDataForBitTemplate(PropertyInfo propertyInfo)
    {
        var value = propertyInfo.GetValue(_firstSelectedItem);
        bool bValue;
        if (value == null)
            TargetValue = 0;
        else if (bool.TryParse(value.ToString(), out bValue))
            TargetValue = (bValue) ? 1 : 0;
        else
            TargetValue = 0;
        //TargetValue = (int)propertyInfo.GetValue(_firstSelectedItem);
        var bitItems = new List<EnumItemObject>();
        bitItems.Add(new EnumItemObject { Id = 0, Name = "Nein" });
        bitItems.Add(new EnumItemObject { Id = 1, Name = "Ja" });
        EnumItemsSource = bitItems;
    }

So I want to load three possible kind of data in my Combobox. Enums, List of Objects (with name and id) and booleans (Yes/No List).