texts: Is my design still a state design pattern, or some abomination?

texts:
I was trying to review state design pattern, and tried to create flexible implementation of it so it could reuse it in future.

So I came out with this:

public interface FsmState<S extends Enum<?>,INPUT> {
    Result<S> action(INPUT input);
}

and this:

public class Result<S extends Enum<?>> {

    public boolean isCompleted() {
        return isCompleted;
    }

    public S getNextState() {
        return nextState;
    }

    public Result(boolean isCompleted, S state) {
        super();
        this.isCompleted = isCompleted;
        this.nextState = state;
    }

    private final boolean isCompleted;

    private final S nextState;
}

and for now this is way how you can use it:

public class Fsm {
    static enum SomeEnum {
        A, B, C
    }

    static class aState implements FsmState<SomeEnum, String> {

        @Override
        public Result<SomeEnum> action(String input) {

            if (input.equals("B")) {
                return new Result<SomeEnum>(false, SomeEnum.B);
            }
            return new Result<SomeEnum>(false, SomeEnum.A);
        }
    }

    static class bState implements FsmState<SomeEnum, String> {

        @Override
        public Result<SomeEnum> action(String input) {
            if (input.equals("B")) {
                return new Result<SomeEnum>(false, SomeEnum.B);
            }
            if (input.equals("C")) {
                return new Result<SomeEnum>(false, SomeEnum.C);
            }
            throw new RuntimeException("Invalit input");
        }
    }

    static class cState implements FsmState<SomeEnum, String> {

        @Override
        public Result<SomeEnum> action(String input) {
            if (input.equals("A")) {
                return new Result<SomeEnum>(true, SomeEnum.C);
            }
            return new Result<SomeEnum>(false, SomeEnum.C);

        }
    }

    private Map<SomeEnum, FsmState<SomeEnum, String>> statesMap = new HashMap<Fsm.SomeEnum, FsmState<SomeEnum, String>>();

    public Fsm() {
        statesMap.put(SomeEnum.A, new aState());
        statesMap.put(SomeEnum.B, new bState());
        statesMap.put(SomeEnum.C, new cState());
    }

    boolean run(String input) {
        FsmState<SomeEnum, String> action = statesMap.get(SomeEnum.A);
        for (char ch : input.toCharArray()) {
             ;
            Result<SomeEnum> state = action.action("" + ch);
            if (state.isCompleted()) {
                return true;
            }
            action = statesMap.get(state.getNextState());

        }
        return false;

    }

    public static void main(String[] args) {
        System.out.println(new Fsm().run("AAABBCA"));
    }
}

For each Enum element you create implementation of FsmState interface, where based on input you do transition to next state.

It is still a bit messy code, and I'm fully aware of that. But I was wondering if it can be called a state pattern?


texts: Converting Arabic numerals to Roman numerals

texts:
These classes are part of a program I am working on to convert Arabic numerals to Roman numerals and vice-versa.  Do these classes look correct for representing objects in Java?

public class ArabicNumeral {
private final int value;

public ArabicNumeral(final int value) {
    if (value < 0) {
        throw new NumberFormatException("Numbers must be positive");
    }
    this.value = value;
}

public int getThousands() {
    return getCardinalValueFor(1000);
}

public int getHundreds() {
    return getCardinalValueFor(100);
}

public int getTens() {
    return getCardinalValueFor(10);
}

public int getOnes() {
    return getCardinalValueFor(1);
}

private int getCardinalValueFor(final int divisor) {
    return value / divisor % 10;
}
}

public enum RomanNumerals {
I("I", 1),
V("V", 5),
X("X", 10),
L("L", 50),
C("C", 100),
D("D", 500),
M("M", 1000);

private final String symbol;
private final int value;

RomanNumerals(final String symbol, final int value) {
    this.symbol = symbol;
    this.value = value;
}

String symbol() {
    return symbol;
}

int value() {
    return value;
}

public RomanNumerals getMultipleOfFive() {
    return this.ordinal() < RomanNumerals.values().length - 1
            ? RomanNumerals.values()[this.ordinal() + 1] : null;
}

public RomanNumerals getMultipleOfTen() {
    return this.ordinal() < RomanNumerals.values().length - 1
            ? RomanNumerals.values()[this.ordinal() + 2] : null;
}
}


texts:
I have made class to setup a random number bases on <random>. It works fine, but I have doubt in std::default_random_engine mEngine{ std::random_device()() }; Did i implement it correctly? What is the best practice for random?

#include <random>
#include <iostream>

// for some compilers that's don't support nested templates with the same parameter
template <typename T>
auto dist() -> typename std::enable_if<std::is_integral<T>::value, std::uniform_int_distribution<T> >::type;

template <typename T>
auto dist() -> typename std::enable_if<std::is_floating_point<T>::value, std::uniform_real_distribution<T> >::type;

template<typename T>
class Random
{
public:
    Random(const T& min, const T& max)
        : mUnifomDistribution(min, max)
    {}
    Random(const Random<T>&) = delete;
    Random(const Random<T>&&) = delete;
    Random<T>& operator = (const Random<T>&) = delete;
    T operator()()
    {
        return mUnifomDistribution(mEngine);
    }

private:
    std::default_random_engine mEngine{ std::random_device()() }; // <-- here the doubt - is it seeding?
    //template <typename T>
    //static auto dist() -> typename std::enable_if<std::is_integral<T>::value, std::uniform_int_distribution<T> >::type;

    //template <typename T>
    //static auto dist() -> typename std::enable_if<std::is_floating_point<T>::value, std::uniform_real_distribution<T> >::type;

    using type = decltype(dist<T>());
    type mUnifomDistribution;
};

int main()
{
    ::Random<int> getRandom(0, 9);
    for (int i = 0; i<9; ++i)
        std::cout << getRandom() << '\n';
}


texts:
In my question to learn F#, I've decided to get one step closer to creating a programming language, and implement this simple Reverse Polish Notation "interpreter" of sorts.

It does not allow for parentheses in input ( ), and only accepts expressions containing the following valid tokens:

0 1 2 3 4 5 6 7 8 9 + - * /

Here's a small list of sample inputs and outputs for reference:

2 2 + -> 4
10 10 + 5 * -> 100
2 2 * 4 + 2 * -> 16

I have a few concerns here:

Is this written in a proper "functional" way?
Is there any way to shorten evaluate_expr?
Are there any glaring issues that I missed?

open System
open System.Collections.Generic
open System.Text.RegularExpressions

/// <summary>
/// Evaluate an expression pair, like '2 2 +'.
/// <summary>
/// <param name="operand">The operand to use.</param>
let evaluate_expr_pair (a: string) (b: string) (operand: string) =
    match operand with
    | "+" -> (Int64.Parse(a) + Int64.Parse(b)).ToString()
    | "-" -> (Int64.Parse(a) - Int64.Parse(b)).ToString()
    | "*" -> (Int64.Parse(a) * Int64.Parse(b)).ToString()
    | "/" -> (Int64.Parse(a) / Int64.Parse(b)).ToString()
    | _ -> ""

/// <summary>
/// Evaluate a tokenized expression, such as '[| "2"; "2"; "+" |]',
/// and return a result, in this case, '2'.
/// </summary>
/// <param name="expr">The expression to evaluate.</param>
let evaluate_expr (expr: string[]) =
    let program_stack = new Stack<string>()

    for token in expr do
        program_stack.Push(token)

        match token with
        | "+" -> let operand = program_stack.Pop()
                 let b = program_stack.Pop()
                 let a = program_stack.Pop()
                 program_stack.Push(evaluate_expr_pair a b operand)

        | "-" -> let operand = program_stack.Pop()
                 let b = program_stack.Pop()
                 let a = program_stack.Pop()
                 program_stack.Push(evaluate_expr_pair a b operand)

        | "*" -> let operand = program_stack.Pop()
                 let b = program_stack.Pop()
                 let a = program_stack.Pop()
                 program_stack.Push(evaluate_expr_pair a b operand)

        | "/" -> let operand = program_stack.Pop()
                 let b = program_stack.Pop()
                 let a = program_stack.Pop()
                 program_stack.Push(evaluate_expr_pair a b operand)

        | _ -> ()

    program_stack.Pop()

/// <summary>
/// Tokenize an input expression, such as '2 2 + 5 *'.
/// </summary>
/// <param name="expr">The expression to tokenize.</param>
let tokenize_expr (expr: string) =
    let split_pattern = "\s*(\+|\-|\*|\/)\s*|\s+"
    let split_regex = new Regex(split_pattern)
    let result = split_regex.Split(expr)
    result.[0..result.Length - 2]

/// <summary>
/// Check all the tokens of an expression to make sure
/// that they are all legal.
/// </summary>
/// <param name="expr">The expression to check.</param>
let check_expr (expr: string) =
    let valid_token_pattern = "[\s0-9\+\-\*\/]"
    let valid_token_regex = new Regex(valid_token_pattern)

    for token in expr do
        if valid_token_regex.Match(token.ToString()).Success then
            ()
        else
            Console.WriteLine(String.Format("Invalid token \"{0}\".", token))

[<EntryPoint>]
let main argv =
    while true do
        Console.Write(": ")
        let input_expr = Console.ReadLine()

        input_expr |> check_expr
        let tokenized_expr = input_expr |> tokenize_expr
        let result = tokenized_expr |> evaluate_expr

        Console.Write("\n ")
        Console.Write(result)
        Console.Write("\n\n")
    0


texts: Deserialize, Copy and Merge Orders from XML to C#

texts:
Here's the flow,

Load XML file
Deserialize to list in c#
Map xml object to c# list
Merge orders but increment order's product count

public Order[] Load(string path)
{
    var element = XElement.Load(path);
    var orders = new List<XElement>();
    orders = element.Elements();

    var _orders = new List<Order>();
    var _alreadyAddedOrders = new List<string>();
    foreach (var order in orders)
    {
        var orderTemp = new Order();
        orderTemp.OrderDate = Convert.ToInt32(order.Attribute("date").ToString());
        orderTemp.Id = Convert.ToInt32(order.Attribute("id").ToString());
        orderTemp.CategoryId = Convert.ToInt32(order.Attribute("categoryId").ToString());
        orderTemp.ProductCount = Convert.ToInt32(order.Attribute("productCount").ToString());

        foreach (var secondOrder in _orders)
        {
            var orderMatches = (orderTemp.OrderDate == secondOrder.OrderDate &&
                                orderTemp.Id == secondOrder.Id &&
                                orderTemp.CategoryId == secondOrder.CategoryId);
            if (orderMatches)
            {
                orderTemp.ProductCount += secondOrder.ProductCount;
                _alreadyAddedOrders.Add(secondOrder.OrderDate.ToString() + secondOrder.Id.ToString() + secondOrder.CategoryId.ToString());
            }
        }

        if(!_alreadyAddedOrders.Contains(orderTemp.OrderDate.ToString() + orderTemp.Id.ToString() + orderTemp.CategoryId.ToString()))
            _orders.Add(orderTemp);
    }

    return _orders.ToArray();
}

public class Order
{
    public int Id;
    public int CategoryId;
    public int OrderDate;
    public int ProductCount;
}

and XML is like this, more then 20,000 rows,

<orders>
    <order date='2000-04-20' Id='1' categoryId='100' productCount='3' />
    <order date='2000-06-21' Id='2' categoryId='101' productCount='14' />
</orders>

Note : Order ID is not unique, date + id + category, is unique altogether


texts: Is this program susceptible to a buffer overflow exploit?

texts:
I use it in a number of embedded devices. It loads the query parameters from an HTTP GET/POST request and prints them to stdout in FORM_key=value format which then get set as an environment variable.

Source:

char *
FP_strdup (char *string)
{
  char *result;

  if (string == NULL)
    return NULL;

  if ((result = (char *) malloc (strlen (string) + 1)) == NULL) {
    fprintf (stderr, "proccgi -- out of memory dupping %d bytes\n",
         (int) strlen (string));
    return NULL;
  }

  strcpy (result, string);
  return result;
}

/*
 * Read CGI input
 */

char *
LoadInput (void)
{
  char *result, *method, *p;
  int length, ts;

  if ((method = getenv ("REQUEST_METHOD")) == NULL) {
    return NULL;
  }

  if (strcmp (method, "GET") == 0) {
    if ((p = getenv ("QUERY_STRING")) == NULL)
      return NULL;
    else
      result = FP_strdup (p);
  }
  else if (strcmp (method, "POST") == 0) {
    if ((length = atoi (getenv ("CONTENT_LENGTH"))) == 0)
      return NULL;

    if ((result = malloc (length + 1)) == NULL) {
      fprintf (stderr, "proccgi -- out of memory allocating %d bytes\n",
           length);
      return NULL;
    }

    if ((ts = fread (result, sizeof (char), length, stdin)) < length) {
      fprintf (stderr, "proccgi -- error reading post data, %d bytes read, %d expedted\n",
           ts, length);
    }
    result[length] = '\0';
  }
  else {
    return NULL;
  }

  return result;
}

/*
 * Parse + and %XX in CGI data
 */

char *
ParseString (char *instring)
{
  char *ptr1=instring, *ptr2=instring;

  if (instring == NULL)
    return instring;

  while (isspace (*ptr1))
    ptr1++;

  while (*ptr1) {
    if (*ptr1 == '+') {
      ptr1++; *ptr2++=' ';
    }
    else if (*ptr1 == '%' && isxdigit (*(ptr1+1)) && isxdigit (*(ptr1+2))) {
      ptr1++;
      *ptr2    = ((*ptr1>='0'&&*ptr1<='9')?(*ptr1-'0'):((char)toupper(*ptr1)-'A'+10)) << 4;
      ptr1++;
      *ptr2++ |= ((*ptr1>='0'&&*ptr1<='9')?(*ptr1-'0'):((char)toupper(*ptr1)-'A'+10));
      ptr1++;
    }
    else
      *ptr2++ = *ptr1++;
  }
  while (ptr2>instring && isspace(*(ptr2-1)))
    ptr2--;

  *ptr2 = '\0';

  return instring;
}

/*
 * break into attribute/value pair. Mustn't use strtok, which is
 * already used one level below. We assume that the attribute doesn't
 * have any special characters.
 */

void
HandleString (char *input)
{
  char *data, *ptr, *p2;

  if (input == NULL) {
    return;
  }

  data = FP_strdup   (input);
  ptr  = ParseString (data);

  /*
   * Security:
   *
   * only accept all-alphanumeric attributes, and don't accept empty
   * values
   */

  if (!isalpha(*ptr) && *ptr != '_') {free (data); return;}
  ptr++;
  while (isalnum(*ptr) || *ptr == '_') ptr++;
  if (*ptr != '=') {free (data); return;}

  *ptr = '\0';
  p2 = ptr+1;

  fprintf (stdout, "FORM_%s=\"", data);

  /*
   * escape value
   */

  while (*p2) {
    switch (*p2) {
    case '"': case '\\': case '`': case '$':
      putc ('\\', stdout);
    default:
      putc (*p2,  stdout);
      break;
    }
    p2++;
  }
  putc ('"',  stdout);
  putc ('\n', stdout);
  *ptr = '=';
  free (data);
}

int
main (int argc, char *argv[])
{
  char *ptr, *data = LoadInput();
  int i;

  /*
   * Handle CGI data
   */

  if (data) {
    ptr = strtok (data, "&");
    while (ptr) {
      HandleString (ptr);
      ptr = strtok (NULL, "&");
    }
    free (data);
  }

  /*
   * Add Path info
   */

  if (getenv ("PATH_INFO") != NULL) {
    data = FP_strdup (getenv ("PATH_INFO"));
    ptr = strtok (data, "/");
    while (ptr) {
      HandleString (ptr);
      ptr = strtok (NULL, "/");
    }
    free (data);
  }

  /*
   * Add args
   */

  for (i=1; i<argc; i++) {
    HandleString (argv[i]);
  }

  /*
   * done
   */

  return 0;
}


texts:
Please give me some feedback to my malloc implementation.  I implemented this design to understand the basic concept.

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

#define HEAP_MEM_SIZE 150
#define MEMORY_AVAILABLE 1
#define MEMORY_USED 0

struct chunk_header {
  struct chunk_header *next; // next pointer on free list
  size_t size;               // the size of this chunk
  bool is_available;         // indicates if this chunk is MEMORY_AVAILABLE or MEMORY_USED
};

typedef struct chunk_header chunk_header;
chunk_header *chunk_header_begin;
static char buffer[HEAP_MEM_SIZE];
unsigned int heap_size;

void init() {
    heap_size = HEAP_MEM_SIZE;
    chunk_header_begin = (chunk_header*)&buffer;
    chunk_header_begin->next = NULL;
    chunk_header_begin->size = heap_size;
    chunk_header_begin->is_available = MEMORY_AVAILABLE;
}

void init_next_chunk(chunk_header *curr, unsigned int bytes) {
    heap_size -= bytes;
    curr->next = NULL;
    curr->size = heap_size;
    curr->is_available = MEMORY_AVAILABLE;
}

void *my_malloc(unsigned int nbytes) {
    static bool init_flag = false;

    if(!init_flag) {
        init();
        init_flag = true;
    }

    int alloc_size = nbytes + sizeof(chunk_header);
    chunk_header *curr = chunk_header_begin;

    while(curr) {
        if(curr->is_available && curr->size >= alloc_size) {
            curr->is_available = MEMORY_USED;
            curr->size = alloc_size;
            curr->next = curr + alloc_size;

            init_next_chunk(curr->next, alloc_size);

            // return memory region
            curr = curr + sizeof(chunk_header);
            return curr;
        }

        curr = curr->next;
    }

    return NULL;
}

void my_free(void *firstbyte) {
    chunk_header *mem = (chunk_header*)firstbyte - sizeof(chunk_header);
    chunk_header *curr = chunk_header_begin;

    while (curr) {
        if (curr == mem) {
            heap_size += curr->size;

            // Mark the block as being available
            curr->is_available = MEMORY_AVAILABLE;
            break;
        }

        curr = curr->next;
    }

    firstbyte = NULL;
}

void print_heap_allocations() {
    chunk_header *curr = chunk_header_begin;

    printf("\n\tSize\tAvailable\tMemory-Ptr");

    while (curr) {
        void *mem_ptr = curr + sizeof(chunk_header);
        printf("\n\t%d\t%d\t\t%x", curr->size, curr->is_available, mem_ptr);
        curr = curr->next;
    }

    printf("\n");
}

int main() {
    char *mem1 = (char*)my_malloc(20);
    if(mem1 == NULL) {
        goto err;
    }
        memset (mem1,'x',19);
        mem1[19] = '\0';

        print_heap_allocations();

        char *mem2 = (char*)my_malloc(20);
        if(mem2 == NULL) {
        goto err;
    }
        memset (mem2,'y',19);
        mem2[19] = '\0';

        print_heap_allocations();

        char *mem3 = (char*)my_malloc(20);
        if(mem3 == NULL) {
            goto err;
        }
        memset (mem3,'z',19);
        mem3[19] = '\0';

        print_heap_allocations();

    my_free(mem2);

    print_heap_allocations();

    char *mem4 = (char*)my_malloc(20);
    if(mem4 == NULL) {
        goto err;
    }
        memset (mem4,'a',20);
    mem4[19] = '\0';

        print_heap_allocations();

        printf("should be 19 x sein: %s\n", mem1);
        printf("should be 19 a sein: %s\n", mem4);
        printf("should be 19 z sein: %s\n", mem3);

    return 0;

err:
        printf("could not allocate mem\n");
        return 0;
}


texts: HTTP scraper efficiency with multiprocessing

texts:
I built this scraper for work that will take a csv list of firewalls from our network management system and scan a given list of HTTPS ports to see if the firewalls are accepting web requests on the management ports. I originally built this in powershell, but decided to rebuild it in python for the learning experience.

I was able to cut down the scan time substantially using multiprocessing, but I'm wondering if I can further optimize my code to get it faster.

Also, I'm very new to python. So if you have any input on better more efficient ways that I could have used to accomplish these steps would be much appreciated.

import urllib.request
import re
import os
import ssl
import multiprocessing

#imports a csv list of firewalls with both private and public IP addresses
f = open(r'\h.csv',"r")
if f.mode =="r":
    cont = f.read()

#regex to remove private ip addresses and then put the remaining public ip addresses in a list
c = re.sub(r"(172)\.(1[6-9]|2[0-9]|3[0-1])(\.(2[0-4][0-9]|25[0-5]|[1][0-9][0-9]|[1-9][0-9]|[0-9])){2}|(192)\.(168)(\.(2[0-4][0-9]|25[0-5]|[1][0-9][0-9]|[1-9][0-9]|[0-9])){2}|(10)(\.(2[0-4][0-4]|25[0-5]|[1][0-9][0-9]|[1-9][0-9]|[0-9])){3}","",cont)
d = re.findall(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}",c)

#uses HTTP requests to check if any of the 8 management ports on the addresses in the list are accepting web requests
def httpScan(list):
    iplen = len(list)
    ports = [443, 4433, 444, 433, 4343, 4444, 4443, 4434]
    portlen = len(ports)
    for k in range(iplen):
        for i in range(portlen):
            context = ssl._create_unverified_context()
            try:
                fp = urllib.request.urlopen("https://" + str(list[k]) + ":" + str(ports[i]), context=context)
                mybytes = fp.read()
                mystr = mybytes.decode("utf8")
                fp.close()
            except:
                continue
            if "SSLVPN" in mystr:
                print(list[k] + " SSLVPN" + ": " + str(ports[i]) + "  " + str(k) + "  " + str(os.getpid()))
            elif "auth1.html" in mystr:
                print(list[k] + " MGMT" + ": " + str(ports[i]) + "  " + str(k))

#splits the list of IP addresses up based on how many CPU there are and adds each segment to a dictionary
cpu = int(multiprocessing.cpu_count())
sliced = int(len(d)/cpu)
mod = int(len(d))%int(cpu)
num = 1
lists = dict()
for i in range(cpu):
    if i != (cpu - 1):
        lists[i] = d[(num*sliced) - sliced:num*sliced]
        num += 1
    else:
        lists[i] = d[(num*sliced) - sliced:(num*sliced) + mod]

#starts a process for each unique segment created
t = dict()
if __name__ == "__main__":
    for i in range(cpu):
        t[i] = multiprocessing.Process(target=httpScan, args=(lists[i],))
        t[i].start()

```


texts:
The following code takes in two params. An array of sentences and an array of queries. Each query has one or more words. The function below prints out index of sentence for each query that has all the words in that sentence.

This is functioning code. However, it is not optimized for large inputs because of how it is written.

How can we make it more runtime optimized? Any ideas would be appreciated.

def textQueries(sentences, queries):
    sentences_sets = [set(s.split(' ')) for s in sentences]
    for i, words in enumerate(queries):
        results = ''
        for j, s in enumerate(sentences_sets):
            exists = True
            for word in words.split(' '):
                if word not in s:
                    exists = False
            if exists:
                results += ' %d' % j if results else '%d' % j
        if results:
            print results
        else: print -1


texts:
I am using Java to parse a JSON file into a hash map so that i can search by typing a date and then get the cost, tax and profit for that date.

So that if i write:

2001-09-18 13:11:01

I get:

7.14, 1.81 and 31.10

Here is part of the JSON file:

{
  "stat":[
    {
      "date":" 2001-09-18 13:11:01 ",
      "cost":" 7.14 ",
      "tax":" 1.81 ",
      "profit":" 31.10 "
    },
    {
      "date":" 2001-09-18 14:15:02 ",
      "cost":" 7.80 ",
      "tax":" 0.99 ",
      "profit":" 30.20 "
    }
  ]
}

And my code using Jackson:

public static void main(String[] args) throws JsonGenerationException {
        try {
            ObjectMapper mapper = new ObjectMapper();
            JSONParser parser = new JSONParser();
            JSONObject jsonobj = (JSONObject) parser.parse(new FileReader("test.json"));
            JSONArray jsons = (JSONArray) jsonobj.get("stat");
            Map<Integer, Map<String, String>> jsonmaps = new HashMap<Integer, Map<String, String>>();
            int i=0;
            for (Object j : jsons) {
                Map<String, String> map = new HashMap<String, String>();
                JSONObject o = (JSONObject) j;
                map = mapper.readValue(j.toString(), new TypeReference<Map<String, String>>() {
                });
                jsonmaps.put(i, map);
                i++;
            }
            System.out.println(jsonmaps.get(0).get("date"));

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


texts:
I have a MySQL table with a very large data.  What I need is to find and separate duplicates from the unique rows

Let's say this is my table:

indx, data_lname, data_fname, data_mname, data_dob, data_mobile

What I'm doing right now is selecting all the rows in one query and then comparing each row with the same table using a different query.  This works ok but slow as hell.

Can this be done with a single query?

private sub poplist()
    DBstrSQL = "SELECT * from tbl_data order by indx asc"
    Dim myCmd As New MySqlCommand
    myCmd.CommandTimeout = 300
    myCmd.CommandText = DBstrSQL
    myCmd.Connection = MySqlConn
    Dim myReader As MySqlDataReader = myCmd.ExecuteReader()
    If myReader.HasRows = True Then
          While myReader.Read()
             if checkifdup(myReader.GetString("indx"),myReader.GetString("data_fname"),myReader.GetString("data_mname"),myReader.GetString("data_lname"),myReader.GetString("data_dob"),myReader.GetString("data_mobile"))=false then
                          With lstUnique.Items.Add(myreader.getstring("data_lname"))
                           .SubItems.Add(myreader.getstring("data_fname"))
                           .SubItems.Add(myreader.getstring("data_mname"))
                           .SubItems.Add(myreader.getstring("data_dob"))
                           .SubItems.Add(myreader.getstring("data_mobile"))
                          End With
             else
                          With lstDup.Items.Add(myreader.getstring("data_lname"))
                           .SubItems.Add(myreader.getstring("data_fname"))
                           .SubItems.Add(myreader.getstring("data_mname"))
                           .SubItems.Add(myreader.getstring("data_dob"))
                           .SubItems.Add(myreader.getstring("data_mobile"))
                          End With
             end if
          End While
    end if
    myReader.Close()
end sub

private function checkifdup(dataindx sa string, data1 as string,data2 as string, data3 as string, data4 as string, data5 as string) as boolean
    myCmd.CommandText = "SELECT * from tbl_data where indx<>@indx and data_lname=@lname and data_mname=@mname and data_fname=@fname and (date_format(data_dob,'%m-%d-%Y')=@dob or data_mobile=@mobile) limit 1"
    myCmd.Prepare()
    myCmd.Parameters.AddWithValue("@lname", data3)
    myCmd.Parameters.AddWithValue("@mname", data2)
    myCmd.Parameters.AddWithValue("@fname", data1)
    myCmd.Parameters.AddWithValue("@dob", data4)
    myCmd.Parameters.AddWithValue("@mobile", data5)
    myCmd.Parameters.AddWithValue("@indx", dataindx)
    Dim myReader As MySqlDataReader = myCmd.ExecuteReader()
    If myReader.HasRows = True Then
          myReader.Close()
          return True
    Else
          myReader.Close()
          return false
    End If
end function


texts: Books Algorithm Dealing with Square Digit Sums

texts:
A little context:

  Book has 411 Pages
  Read a random number of pages on the first day which is unknown
  Number of pages to read next day is the square of the sum of the digits of the page currently on

  I.e. on Page 36: read 81 pages next day
  On day 6 The square answer directly adds to current page number to make 411
  Finish Book

  How many pages did she read on the first day and how many pages did
  she read on the 6 days?

This is what I have so far:

from itertools import accumulate, count

def read_book( start ):
    for i in range( 6 ): yield start; start += sum( int( digit ) for digit in str( start ) ) ** 2

def find_start( pages ):
    for start in count( 1 ):
        for read in read_book( start ): pass
        if read == pages: return start

previous_answer, start = 0, find_start( 411 )
for i, read in enumerate( read_book( start ), 1 ):
    print( "Pages read on day", i ,"was", read-previous_answer ,"\t(Now on page", str(read) + ")\n")
    previous_answer += read-previous_answer

Output:

  Pages read on day 1 was 61 (Now on page 61)

  Pages read on day 2 was 49 (Now on page 110)

  Pages read on day 3 was 4 (Now on page 114)

  Pages read on day 4 was 36 (Now on page 150)

  Pages read on day 5 was 36 (Now on page 186)

  Pages read on day 6 was 225 (Now on page 411)

Is there a more efficient way of writing this using fewer lines of code?


texts:
I've written some script in python following OOP guidelines. I've created two classes in my script in such a way so that both of them are able to make requests and produce flawless results. It can parse names, phone numbers and email addresses from yellowpage. I've already executed my script and found it working as I expected. Now it is able to parse the aforesaid category from any links from that site irrespective of how many pages it traverses. So far, I've used one class for making requests and the other for processing results. However, this time I intend to make a bridge between these two classes so that they can both be able to make requests and can do the same stuff if needed. I've tried my best to make a good class crawler. Any suggestions to make it more dynamic or improved will be highly appreciated.

from lxml import html
import requests

class web_parser:

    page_link = "https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=San%20Francisco%2C%20CA"
    main_url = "https://www.yellowpages.com"

    def __init__(self):
        self.direct_links = [self.page_link]
        self.vault = []

    def parser(self):
        for link in self.direct_links:
            self.get_link(link)
            self.processing_main_link(link)

    def processing_main_link(self, sub_links):
        page = requests.get(sub_links)
        tree = html.fromstring(page.text)
        page_links = tree.cssselect("div.pagination a")
        for page_link in page_links:
            if self.main_url + page_link.attrib["href"] not in self.direct_links:
                self.direct_links.append(self.main_url + page_link.attrib["href"])

    def get_link(self, url):
        page = requests.get(url)
        tree = html.fromstring(page.text)
        item_links = tree.cssselect('h2.n a:not([itemprop="name"]).business-name')
        for item_link in item_links:
            if self.main_url + item_link.attrib["href"] not in self.vault:
                self.vault.append(self.main_url + item_link.attrib["href"])

class get_docs(web_parser):

    def __init__(self):
        web_parser.__init__(self)

    def procuring_links(self):
        for link in self.vault:
            self.using_links(link)

    def using_links(self, newly_created_link):
        page = requests.get(newly_created_link)
        tree = html.fromstring(page.text)
        name = tree.cssselect('div.sales-info h1')[0]
        phone = tree.cssselect('p.phone')[0]
        try:
            email = tree.cssselect('div.business-card-footer a.email-business')[0].attrib["href"].replace("mailto:","")
        except IndexError:
            email = ""
        print(name.text, phone.text, email)

if __name__ == '__main__':

    crawl = get_docs()
    crawl.parser()
    crawl.procuring_links()


texts: I have an encrypted file, how to remove a specific string from that file

texts:
I got a file with lots of ASCII characters. No extension, and has the Type Of file attribute 190000 File.

I have many characters like L¿ö  in the file however I required to remove lines from a word PYGR to another word MCG. It has several lines in between.

I tried the following code. And got everything working. Indexes are 3 and 19001 respectively,

VB:

Dim Load_File = System.IO.File.ReadAllText("C:\Documents and Settings\Fousu.s\Desktop\Files\SYSI091512.190000")
        Dim EditedString = ""
        Dim IndexofPYGR = Load_File.IndexOf("PYGR")
        Dim indexOfMCG = Load_File.LastIndexOf("MCG")
        Dim LengthMCG = "MCG"

        'System.Console.ReadKey()
        If ((IndexofPYGR > -1) And (indexOfMCG > -1)) Then
            EditedString = Load_File.Remove(IndexofPYGR, (indexOfMCG - (LengthMCG.Length + 1)))
            System.IO.File.WriteAllText("C:\Documents and Settings\Fousu.s\Desktop\Files\SYSI091512.190000V1", EditedString)
        End If

c#

//Getting the file as a string.
            string Load_File = System.IO.File.ReadAllText(@"C:\Documents and Settings\Fousu.s\Desktop\Files\SYSI091512.190000");

            string EditedString;
            int IndexofPYGR = Load_File.IndexOf("PYGR");
            int indexOfMCG  = Load_File.IndexOf("MCG");
            string LengthMCG = "MCG";
            //Console.WriteLine("Index of PYGR is : {0}", IndexofPYGR);
            //Console.WriteLine("Index of MCG is : {0}", indexOfMCG);
            //System.Console.ReadKey();
            if ((IndexofPYGR != -1) && (indexOfMCG != -1))
            {
                EditedString = Load_File.Remove(IndexofPYGR, (indexOfMCG - (LengthMCG.Length + 1)));

                System.IO.File.WriteAllText(@"C:\Documents and Settings\Fousu.s\Desktop\Files\SYSI091512.190000V1", EditedString);

Would like to request a review of the above code, or is there a better way to achieve this? and also would like to know how to get the Type Of File attribute to 190000.


texts:
I would like to optimize a snippet of code, which uses a multiple nested if statements. I am looking for a formula to make it as a combination of multiple arrays logical operations. Please, I need just a hint to start. Can you please help me review the loop and vectorize it?

The I is an input image (any):

I = 5*rand(4,4);
A = rand(4,4);
B = [ 1 0 1 0; 0 0 1 1 ; 0 1 1 0; 0 0 1 1];

result = zeros(4,4);
 for i = 1:4
     for j = 1:4
         if A(i,j) > 0.75
             result(i,j) = 1;
         elseif A(i,j) < 0.25
             result(i,j) = 0;
         else
             if B(i,j) == 1
                 result(i,j) = 1;
             elseif B(i,j) == 0
                 result(i,j) = 0;
             end
         end
     end
 end

 figure,
 subplot(2,1,1), imagesc(A),title('I');
 subplot(2,1,2), imagesc(result),title('result');


texts: I want to get rid of unneccessary repetiton of cycles

texts:
I have a code that should read diameters of barrels from a txt file. If a barrel is smaller than the last one, smaller gets put inside bigger one. One package like that is lied on a stack. at the end, code should give out how many stacks we get and how many barrels were in a file. also sum of diameters.
If one number is repeated 3 times, we get 3 stack, if we have 5 repeating nmbers, then 5.
What can I do that I wouldn´t have to write simillar blocks n times.
using System;
using System.Collections.Generic;
using System.IO;

namespace TaaviSimsonTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (TextReader reader = File.OpenText("C:\\temp\\andmed2"))
            {
                int sum = 0;
                string line = string.Empty;
                List<int> numbersList = new List<int>();
                while ((line = reader.ReadLine()) != null)
                {
                    int i = int.Parse(line);
                    sum += i;
                    numbersList.Add(int.Parse(line));
                }
                int[] numbersListArray = numbersList.ToArray();
                int numberOfStacks = numbersListArray.Length;
                //Max number of stacks equals to inital array length

                Array.Sort(numbersListArray);       //Array is ascending orded
                Array.Reverse(numbersListArray);    //Array in descending order

                //Puts smaller barrels inside bigger. Decreases number of stacks.
                List<int> repeatedBrarrelSizes = new List<int>();
                for (int j = 0; j < (numbersListArray.Length - 1); j++)
                {
                    if (numbersListArray[j] > numbersListArray[j + 1])
                    {
                        numberOfStacks--;
                    }
                    else if (numbersListArray[j] == numbersListArray[j + 1])
                    {
                        repeatedBrarrelSizes.Add(numbersListArray[j + 1]);
                    }
                }
                int[] repeatedBarrelSizesArray = repeatedBrarrelSizes.ToArray();

                //Repeats the cycle with repeating numbers
                List<int> repeatedBarrelSizes2 = new List<int>();
                for (int k = 0; k < (repeatedBarrelSizesArray.Length-1); k++)
                {
                    if (repeatedBarrelSizesArray[k] > repeatedBarrelSizesArray[k+1])
                    {
                        numberOfStacks--;
                    }
                    else if (repeatedBarrelSizesArray[k] == repeatedBarrelSizesArray[k + 1])
                    {
                        repeatedBarrelSizes2.Add(repeatedBarrelSizesArray[k + 1]);
                    }
                }
                int[] repeatedBarrelSizes2Array = repeatedBarrelSizes2.ToArray();

                //Repeats the cycle again, until no barrels left
                List<int> repeatedBarrelSizes3 = new List<int>();
                for (int k = 0; k < (repeatedBarrelSizes2Array.Length - 1); k++)
                {
                    if (repeatedBarrelSizes2Array[k] > repeatedBarrelSizes2Array[k + 1])
                    {
                        numberOfStacks--;
                    }
                    else if (repeatedBarrelSizes2Array[k] == repeatedBarrelSizes2Array[k + 1])
                    {
                        repeatedBarrelSizes3.Add(repeatedBarrelSizes2Array[k + 1]);
                    }
                }
                int[] repeatedBarrelSizes3Array = repeatedBarrelSizes3.ToArray();

                foreach (int value in repeatedBarrelSizes3Array)
                {
                    Console.WriteLine(value + " ");
                }

                Console.WriteLine("Sum: " + sum);
                Console.WriteLine("Number of barrels: " + numbersListArray.Length);
                Console.WriteLine("Stacks: " + numberOfStacks);
            }
        }
    }
}


texts: Grouped by First Two Digits of Account_ID of ~240 million rows of Pandas DF

texts:
I have 40 CSV files, each containing ~6 million rows, and 2 columns. The columns are account_id and account_balance.

The objective is getting the sum of all account_balance grouped by first two digits/chars of account_id.

For example:

account_id = 00as3dff01234 is in group 00, and the account id is paired with an account_balance value.

For illustration:

Each CSV file is of the form:

account_id, account_balance
0012228hgs, 123000
01223jj4d, 34000
fb1233999, 1245999
.
.
.
(all about 6 million rows)

The output by using all 40 CSV files would be of the form:

00 : 123000444220
01 : 500000
0a : 30444555120
.
.
.
ff : 45002221222
(all 276 groups)

The right-hand side is the sum of money of all accounts that have account_id with the left-hand side as first two digits/characters.

My code gives the correct result, BUT not efficient enough. On my laptop it consumes around 11-12 minutes. How can I improve the performance such that the time is around 5-6 minutes? Sorry, I can't provide the data, but I think it can be replicated by simulating only 1 replicated CSV file.

import pandas

for i in range(4):

    for j in range(10):

        digits = str(i)+str(j)
        all_data = pandas.read_csv('/home/asus/data/arief_anbiya_{}.csv'.format(digits), chunksize = 100000, iterator = True) #Transform each csv data to DF.
        all_data = pandas.concat(all_data, ignore_index= True)
        all_data['account_group'] = [acc_id[0:2] for acc_id in all_data.account_id] #Adding a now column 'first_two' of each account_id (from current csv).

        dummy = all_data.groupby(by = 'account_group').sum() #Sum of 'account_balance' of current DF grouped by 'first_two' (from current csv).

        if i == 0 and j == 0: #Create the Series for the total 'account_balance' (grouped by 'first_two').

            sum_of_groupby = dummy.account_balance

        else:   #Update the Series of total 'account_balance'.

            for ft in set(all_data['account_group']): # unique_ft is all unique 'first_two' (from current csv).

                try:
                    sum_of_groupby[ft] += dummy.account_balance[ft]
                except:
                    sum_of_groupby[ft] = dummy.account_balance[ft]

        print('Done adding : arief_anbiya_{}.csv'.format(digits))


texts: Subtracting elements of datasets of an HDF5 file

texts:
I am trying to solve the following problem:
Input: Input is two arrays (Nx4, sorted in column-2) stored in datasets-1 and 2 in HDF5 file (input.h5). N is huge (originally belonging to 10 GB of file, hence stored in HDF5 file).
Output: Subtracting each column-2 element of dataset-2 from dataset-1, such that the difference (delta) is between +/-4000. Eventually saving this info in dset of a new HDF5 file. I need to refer to this new file back-and-forth, hence HDF5 not a text file.
Concern: I initially used .append method but that crashed the execution for 10GBs input. So, I am now using dset.resize method (and would like to stick to it preferably). I am also using binary search as I was told in one of my last posts. So now, although the script seems to be working for large (10 GBs) of datasets, it is quite slow! The subtraction (for/while) loop is possibly the culprit! Any suggestions on how I can make this fast? I aim to use the fastest approach (and possibly the simplest, since I am a beginner).
import numpy as np
import time
import h5py
import sys
import csv

f_r = h5py.File('input.h5', 'r+')

dset1 = f_r.get('dataset_1')
dset2 = f_r.get('dataset_2')
r1,c1 = dset1.shape
r2,c2 = dset2.shape

left, right, count = 0,0,0
W = 4000  # Window half-width
n = 1

# **********************************************
#   HDF5 Out Creation
# **********************************************
f_w = h5py.File('data.h5', 'w')
d1 = np.zeros(shape=(0, 4))
dset = f_w.create_dataset('dataset_1', data=d1, maxshape=(None, None), chunks=True)

for j in range(r1):
    e1 = dset1[j,1]

    # move left pointer so that is within -delta of e
    while left < r2 and dset2[left,1] - e1 <= -W:
        left += 1
    # move right pointer so that is outside of +delta
    while right < r2 and dset2[right,1] - e1 <= W:
        right += 1

    for i in range(left, right):
        delta = e1 - dset2[i,1]
        dset.resize(dset.shape[0] + n, axis=0)
        dset[count, 0:4] = [count, dset1[j,1], dset2[i,1], delta]
        count += 1

print("\nFinal shape of dataset created: " + str(dset.shape))

f_w.close()


texts:
I have created a DatabaseConnection class as this:

class DatabaseConnection
{
    public SqlConnection sqlconn { get; set; }
    public DatabaseConnection(string server, string db, string user, string pass)
    {
        sqlconn = new SqlConnection(@"Data Source=" + server + ";Initial Catalog=" + db + ";User ID=" + user + ";Password=" + pass);
        OpenConn();
    }

    public SqlConnection OpenConn()
    {
        try{
            if (sqlconn != null && sqlconn.State == ConnectionState.Closed)
                sqlconn.Open(); // MessageBox.Show("Connection has been successfully established");
        }

        catch(Exception ex){
            MessageBox.Show(ex.Message);
        }

        return sqlconn;
    }
}

Its only purpose is to open the SqlConnection. I am just following the Single Responsibility Principle.

And then, in every class that needs a DatabaseConnection, this is my approach:

class DataViewer
{
    private DatabaseConnection dbCon;
    private SqlConnection sqlconn;
    private SqlDataAdapter sqlDA;

    //Here I am applying constructor injection
    public DataViewer(DatabaseConnection dbCon)
    {
        this.dbCon = dbCon;
        this.sqlconn = dbCon.sqlconn;
    }
    public DataGridView getDataInStoredProc(DataGridView dtgrdView, string storedProcName, params SqlParameter[] parameters)
    {
        try{
            //Some logic here
            sqlconn.Close();
        }

        catch (Exception ex){
            MessageBox.Show(ex.Message);
            sqlconn.Close();
        }
        return dtgrdView;
    }
}

Now, I would like to know if I am doing good or bad approach for this. If not, could you please explain me why and give me some advice on how to do it right?


texts: Displaying an overlay when hovering over photos

texts:
I have some very illogical jQuery code and I want to see if someone finds a better way to do the exact same thing:

jQuery:

$(".col-md-3 img").hover(function() {
  $(this).parent().children(".search").show();
  $(this).parent().children(".photo").css("opacity","0.4");
 }, function(){
  $(this).parent().children(".search").hide();
  $(this).parent().children(".photo").css("opacity","1");
 });
html {
 background-color: #3498db;
}

.photo {
 width:100%;
 height: auto;
 margin: 20px 0px;
}

.search {
 position: absolute;
 margin-left: auto;
 margin-right: auto;
 top:40%;
 left: 0;
 right: 0;
 display: none;
}

.search:hover{
 cursor:pointer;
}

I have multiple similar divs.

I don't like the fact that I am accessing the DOM many times with:

$(this).parent().children();

I'm going back and forth and I think it might be a better solution.

The problem with the siblings() method is that one image is on top of the other image, with position absolute and this causes some tricky hover issues. The live website here: live


texts:
I started a few weeks ago to learn C++ online. I just made a little binary → decimal program. Here is my code:

#include <iostream>

using namespace std;

int main()
{
    int i,j=1;
    long long decimal=0, powerOfTwo=1;
    cin>>i;
    char binary[i];
    i*=2;
    while (i)
    {
        if (i > j)
        {
           cin>>binary[j];
           ++j;
        }
        else
        {
            cout<<binary[i];
            if (i%4 == 1) //adds a space after 4 numbers (eg. 1011 0111 instead of 10110111)
                cout<<" ";
            if (binary[i] == '1')
                decimal += powerOfTwo;
            powerOfTwo *= 2;
        }
        --i;
    }
    cout<<"in ten base is equal to "<<decimal;
    return 0;
}

So I want to know, am I heading in the right direction? Please let me know what I am not doing good or any kind of suggestion.


texts:
I'd like to get feedback on whether my hash table is correct or not. Also, any ideas on performance?

    template<class J,class K>
class List {
private:
    struct Node {
        J key;K data;

        Node * next;
        Node(J _key,K _data):key(_key),data(_data),next(nullptr) {}
    }*head;

public:
    List():head(nullptr){}
    ~List() {
        deleteNode();
    }
    void insert(J _key ,K _data) {
            Node * newNode = new Node(_key, _data);
            newNode->next = head;
            head = newNode;
    }

    void traverse() {
        for(Node * curr = head; curr != nullptr; curr = curr->next) {
            cout<< "( "<<curr->key << ", " << curr->data << " )" << " ";
        }
    }

    K search(J key) {
        if (!empty()){

            for(Node * curr = head;curr != nullptr;curr = curr->next) {
                if (curr->key == key) {
                    return curr->data;
                }
            }
        }

        return K(-1);
    }

    bool empty() { return (head == nullptr); }

    void deleteNode() {
        Node * tmp = nullptr;
        for(Node * curr = head; curr != nullptr;){
            tmp = curr->next;
            delete curr;
            curr = tmp;
        }
    }
};

template<class KEY, class VALUE>
class myHash {
private:

    struct bucket {
        List<KEY,VALUE> list_at_bucket;
    }*Buckets;

    int tableSize;
public:
    myHash(int size) {
        tableSize = size;
        Buckets = new bucket[tableSize];
    }

    ~myHash() {
        for(int i = 0; i < tableSize; i++) {
            Buckets[i].list_at_bucket.deleteNode();
        }
    }

    void put(KEY k, VALUE value) {
        int getCode = hash(k);
         Buckets[getCode].list_at_bucket.insert(k,value);
    }

    VALUE getValue(KEY _key) {
        int getCode = hash(_key);
        return  Buckets[getCode].list_at_bucket.search(_key);
    }

    bool contains(KEY _key) {
        int getCode = hash(_key);
        if (Buckets[getCode].list_at_bucket.search(_key) != -1) {
            return  true;
        }
        return false;
    }

    // need a template hash function
    int hash(KEY key) const {
        int value = 0;
        for (char each: key) {
            value += each;
        }
        return  value % tableSize;
    }

    void traverse() {
        for (int index = 0; index <tableSize; index++){
            cout<< "[" << index << " ]-> ";
            Buckets[index].list_at_bucket.traverse();
        }
    }
};


texts: Speed up sorting algorithm in R: make one column "smaller" than the other

texts:
Consider the following sorting algorithm:

df <- data.frame(food_1 = c("APPLE 1534", "PEAR 2525", "BANANA 3045", "WATERMELON 5000"),
                 food_2 = c("ORANGE 2035", "BROCCOLI 5000", "BLUEBERRY 2000", "TOMATO 3000"),
                 stringsAsFactors = FALSE)

# Sorting
for (i in 1:nrow(df)){
  foods <- sort(c(df$food_1[i], df$food_2[i]))
  df$food_1[i] <- foods[1]
  df$food_2[i] <- foods[2]
}

I have data frames which are of size 250,000+ rows that I've used the code above for, and I'm not sure how to make this more efficient.


texts: Insertion Sort Implementation Using For And While Loop

texts:
Introduction

I'm fairly new to programming (and Java) and I've actually never implemented Insertion Sort.

I know that there's pseudo-code defined in the wikipedia article (linked above), but the goal was to implement the algorithm without looking at the pseudo-code and only using the wiki article's graphic for reference.

Concerns

After I completed my implementation, I looked at a couple implementations on CodeReview.

One uses double for-loops vs. a for-loop and a while-loop. Is the double for-loop more readable?
Method signature should be void and should simply return the modified original array. Again, is this behavior better / more-expected? My argument against this is that maybe it could lead to some unexpected behavior if the user does not expected the original array to be modified? Or unexpected behavior down the road if the user forgets that the returned array has been modified. That being said, with proper documentation, this could be avoided.

Implementation

public class InsertionSorter {
  public static int[] sort(int[] numbers) {
    int[] sorted = numbers.clone();
    for (int i = 1; i < sorted.length; i++) {
      int j = i - 1;
      int numberToInsert = sorted[i];
      while (j >= 0 && numberToInsert < sorted[j]) {
        sorted[j + 1] = sorted[j];
        sorted[j] = numberToInsert;
        j--;
      }
    }
    return sorted;
  }
}


texts:
Could someone tell me if this is a bad idea for coding my validation for a password and it is bad? This is for registration for my site. Could you please tell me why and how you would go about it (I am a beginner and at PHP)?

$username = $_POST['username'];
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];

$password_filter1 = '/(?=.*[a-zA-Z0-9]{6})/m';  //Password contains more then 6 char
$password_filter2 = '/(?=.*[A-Z])/m';           //Capital letter
$password_filter3 = '/(?=.*\d)/m';              //A digit

if (!empty($password & $confirm_password)) {
 if ($password === $confirm_password) {
  if (preg_match($password_filter1, $password)) {
   if (preg_match($password_filter2, $password)) {
    if (preg_match($password_filter3, $password)) {
     //If everything is true do this
    } else {
     $password_error = "Your password must contain at least 1 number";
    }
   } else {
    $password_error = "You're password must have at least 1 capital letter";
   }
  } else {
   $password_error = "You're password must be at least 6 characters long";
  }
 } else {
  $password_error = "The passwords do not match";
 }
} else {
 $password_error = "You must enter a password";
}

The only reason why I am not doing all the filters in 1 preg_match is because I would like specific errors.


texts:
I started a Chess in Python for fun. I learned Python in my free time but I've been doing it for a while. The code works but I just want to know if there's anything non-pythonic in my code. The functions calculate all potentially possible moves (ignoring game state).

from itertools import product
from itertools import chain
from functools import wraps
from math import atan2

_angle_to_direction = {90: "up", -90: "down", 180: "right", 0: "left", -135: "right_down", 135: "right_up",
                       45: "left_up", -45: "left_down"}

def move(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        x, y = args
        moves = f(x, y)
        if (x, y) in moves: moves.remove((x, y))
        return moves

    return wrapper

def check_range(x:tuple) -> bool:
    return x[0] >= 0 and x[1] >= 0 and x[0] < 8 and x[1] < 8

@move
def _knight(x:int, y:int) -> set:
    moves = chain(product([x - 1, x + 1], [y - 2, y + 2]), product([x - 2, x + 2], [y - 1, y + 1]))
    moves = {(x, y) for x, y in moves if check_range((x, y))}
    return moves

@move
def _rook(x:int, y:int) -> set:
    return {(x, i) for i in range(0, 8)}.union({(i, y) for i in range(0, 8)})

@move
def _bishop(x:int, y:int) -> set:
    possible = lambda k: [(x + k, y + k), (x + k, y - k), (x - k, y + k), (x - k, y - k)]
    return {j for i in range(1, 8) for j in possible(i) if check_range(j)}

def direction(start:tuple, end:tuple) -> str:
    delta_a = start[1] - end[1]
    delta_b = start[0] - end[0]
    return _angle_to_direction[int(atan2(delta_a, delta_b) * 180 / 3.14)]


texts: Implementing Binary Tree using Queue in C#

texts:
I am in the process of learning data structures and I am trying to implement Binary Tree using Queue in C#.

Below are my Tree implementation classes.

public class Tree
{
    public char Data { get; set; }
    public Tree LChild { get; set; }
    public Tree RChild { get; set; }
}

public class TreeImplementation
{
    //Initialize tree nodes with data.
    Tree _rootNodeF = new Tree {Data = 'F'};

    Tree _lChildNodeD = new Tree { Data = 'D' };
    Tree _rChildNodeJ = new Tree { Data = 'J' };

    Tree _lChildNodeB = new Tree { Data = 'B' };
    Tree _rChildNodeE = new Tree { Data = 'E' };

    //Initialize an empty queue to use for tree traversal.
    Queue<Tree> _treeQueue = new Queue<Tree>();

    public  TreeImplementation()
    {
        _rootNodeF.LChild = _lChildNodeD;
        _rootNodeF.RChild = _rChildNodeJ;

        _lChildNodeD.LChild = _lChildNodeB;
        _lChildNodeD.RChild = _rChildNodeE;

    }

    public void LevelOrder()
    {
            //Add root node to the queue.
            _treeQueue.Enqueue(_rootNodeF);

            //Create tempNode to add next node to the queue.
            Tree tempNode = new Tree();

            while (_treeQueue.Count != 0)
            {
                tempNode = _treeQueue.Dequeue();

                VisitedTreeNode(tempNode.Data);

                if (tempNode.LChild == null) continue;
                _treeQueue.Enqueue(tempNode.LChild);

                if (tempNode.RChild != null)
                {
                    _treeQueue.Enqueue(tempNode.RChild);
                }
            }
    }

    //Access the data at the node.
    public void VisitedTreeNode(char queueData)
    {
        Console.WriteLine(queueData);
    }

}

I am calling the LevelOrder() method in the main method in another class.

How can I improve my code?


texts:
I am adding two custom metaboxes to the WordPress post page from a plugin. I am currently doing it with two separate instances of add_meta_boxes but this feels very bulky, especially as I go to add more.

Since the plugin is fairly small I dont want to include a framework and was wondering if there was an easier to add more than one metabox. Preferably under one heading, unlike currently if you add this to your functions.php or look at the screenshot below, they are under separate headings.

I was considering posting this on http://wordpress.stackexchange.com, but as it is working fully I posted it here.

function wp_cat_map_add_meta_box() {

$screens = array( 'post' );

foreach ( $screens as $screen ) {
    add_meta_box( 'map_lat', __( 'Add Latitude', 'wp_cat_map' ), 'wp_cat_map_lat_callback', $screen );
    add_meta_box( 'map_long', __( 'Add Longitude', 'wp_cat_map' ), 'wp_cat_map_long_callback', $screen );

}
}
add_action( 'add_meta_boxes', 'wp_cat_map_add_meta_box' );

function wp_cat_map_lat_callback( $post ) {

wp_nonce_field( 'wp_cat_map_lat_data', 'wp_cat_map_lat_nonce' );

$value = get_post_meta( $post->ID, '_wp_cat_map_lat', true );

echo '';
_e( 'Latitude', 'wp_cat_map' );
echo ' ';
echo '<input type="text" id="wp_cat_map_lat" name="wp_cat_map_lat" value="' . esc_attr( $value ) . '"/>';
}

function wp_cat_map_lat_data( $post_id ) {

if ( ! isset( $_POST['wp_cat_map_lat_nonce'] ) ) {
    return;
}

if ( ! wp_verify_nonce( $_POST['wp_cat_map_lat_nonce'], 'wp_cat_map_lat_data' ) ) {
    return;
}

if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
    return;
}

if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {

    if ( ! current_user_can( 'edit_page', $post_id ) ) {
        return;
    }

} else {

    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }
}

if ( ! isset( $_POST['wp_cat_map_lat'] ) ) {
    return;
}

$my_data = sanitize_text_field( $_POST['wp_cat_map_lat'] );

update_post_meta( $post_id, '_wp_cat_map_lat', $my_data );
}

function wp_cat_map_long_callback( $post ) {

wp_nonce_field( 'wp_cat_map_long_data', 'wp_cat_map_long_nonce' );

$value = get_post_meta( $post->ID, '_wp_cat_map_long', true );

echo '';
_e( 'Longitude', 'wp_cat_map' );
echo ' ';
echo '<input type="text" id="wp_cat_map_long" name="wp_cat_map_long" value="' . esc_attr( $value ) . '"/>';
}

function wp_cat_map_long_data( $post_id ) {

if ( ! isset( $_POST['wp_cat_map_long_nonce'] ) ) {
    return;
}

if ( ! wp_verify_nonce( $_POST['wp_cat_map_long_nonce'], 'wp_cat_map_long_data' ) ) {
    return;
}

if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
    return;
}

if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {

    if ( ! current_user_can( 'edit_page', $post_id ) ) {
        return;
    }

} else {

    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }
}

if ( ! isset( $_POST['wp_cat_map_long'] ) ) {
    return;
}

$my_data = sanitize_text_field( $_POST['wp_cat_map_long'] );

update_post_meta( $post_id, '_wp_cat_map_long', $my_data );
}
add_action( 'save_post', 'wp_cat_map_lat_data' );
add_action( 'save_post', 'wp_cat_map_long_data' );


texts: Keep classes anonymous in TicTacToe program

texts:
My console TicTacToe program

This is my first large project attempt and I want to learn how to keep classes as anonymous as reasonable and as protected/secure as reasonable.

The program works as intended and I think it meets the requirements but can you guys share some pointers?

class TicTacToe
    WINNING_SCORES = [7,56,448,73,146,292,84,273]
    SCORE_HASH = {0 => 1, 1 => 2, 2 => 4,
                             3 => 8, 4 => 16, 5 => 32,
                             6 => 64, 7 => 128, 8 => 256}

    class Player
            attr_reader         :mark
            attr_accessor :score
            attr_accessor :turn

            def initialize(player_mark)
                    @mark = player_mark
                    @score = 0
                    @turn = 0
            end
    end

    def initialize(player1_char, player2_char)
            @player1 = Player.new(player1_char)
            @player2 = Player.new(player2_char)
            set_turn()
            setup_board()
            display_board()
            greet_player()
    end

    def go(spot)
            player_mark = get_player()
            if fill_spot?(spot, player_mark)
                    update_score()
                    next_turn()
                    display_board()
                    greet_player()
            end
    end

    private
    # ----------------------------------------------------------------------------

    def setup_board
            @gameboard = []
            9.times { @gameboard << " " }
    end

    def set_turn()
            @player1.turn = rand(2)
            @player2.turn = 1 unless @player1.turn == 1
    end

    def update_score
            @player1.score = calculate_score(@player1.mark)
            @player2.score = calculate_score(@player2.mark)
            congrats(@player1.mark) if winner?(@player1.score)
            congrats(@player2.mark) if winner?(@player2.score)
    end

    def congrats(player)
            display_board()
            puts "\n\n\t CONGRAGULATIONS PLAYER #{player}, YOU WON!\n\n"
            exit()
    end

    def calculate_score(mark)
            score = 0
            @gameboard.each_with_index do |char, i|
                    score += SCORE_HASH[i] if char == mark
            end
            score
    end

    def winner?(player_score)
            WINNING_SCORES.each do |score|
                    return true if player_score & score == score
            end
            false
    end

    def display_board
            puts "\n\n\t TicTacToe \n\n"
            puts "        1|2|3 \t #{@gameboard[0]}|#{@gameboard[1]}|#{@gameboard[2]}"
            puts "        ------ \t ------"
            puts "        4|5|6 \t #{@gameboard[3]}|#{@gameboard[4]}|#{@gameboard[5]}"
            puts "        ------ \t ------"
            puts "        7|8|9 \t #{@gameboard[6]}|#{@gameboard[7]}|#{@gameboard[8]}"
            puts "\n"
    end

    def greet_player
            player_mark = get_player()
            puts "\t#{player_mark}'s turn!"
    end

    def next_turn
            @player1.turn, @player2.turn = @player2.turn, @player1.turn
    end

    def fill_spot?(spot, player_mark)
            if @gameboard[spot-1] == " " then
                    @gameboard[spot-1] = player_mark
                    return true
            else
                    spot_taken()
                    display_board()
                    greet_player()
                    return false
            end
    end

    def spot_taken
            puts "\n\n\t That spot is already taken!"
    end

    def get_player
            return @player1.mark if @player1.turn == 1
            return @player2.mark if @player2.turn == 1
            raise NoPlayerFound "Neither player's turn is set!"
    end
end

game = TicTacToe.new("X","O")

loop do
    print "Choose spot (1..9): "
    choice = gets.chomp.to_i
    game.go(choice) if choice.between?(1,9)
end


texts: Character creator for a role-playing game

texts:
Goal:

  Write a character creator program for a role-playing game. The player
  should be given a pool of 30 points to spend on four attributes:
  strength, health, wisdom, and dexterity. The player should be able to
  spend points from the pool on any attribute and should also be able to
  take points from an attribute and put them back into the pool.

  Python Programming for the Absolute Beginner by Michael Dawson

My attempt:

print "create a character! you have points to assign to strength, health, wisdom, and dexterity."
name=raw_input("what's your character's name? ")
points=30
attributes=("health", "strength", "wisdom", "dexterity")
strength=0
health=0
wisdom=0
dexterity=0
while True:
    print
    print "you have", points, "points left."
    print \
    """
    1-add points
    2-take points
    3-see points per attribute
    4-exit
    """
    choice=raw_input("choice: ")
    if choice=="1":
        attribute=raw_input("which attribute? strength, health, wisdom, or dexterity? ")
        if attribute in attributes:
            add=int(raw_input("how many points? "))
            if add<=points and add>0:
                if attribute=="strength":
                    strength+=add
                    print name, "now has", strength, "strength points."
                elif attribute=="health":
                    health+=add
                    print name, "now has", health, "health points."
                elif attribute=="wisdom":
                    wisdom+=add
                    print name, "now has", wisdom, "wisdom points."
                elif attribute=="dexterity":
                    dexterity+=add
                    print name, "now has", dexterity, "dexterity points."
                points-=add
            else:
                print "invalid number of points."
        else:
            print "invalid attribute."
    elif choice=="2":
        attribute=raw_input("which attribute? strength, health, wisdom, or dexterity? ")
        if attribute in attributes:
            take=int(raw_input("how many points? "))
            if attribute=="strength" and take<=strength and take>0:
                strength-=take
                print name, "now has", strength, "strength points."
                points+=take
            elif attribute=="health" and take<=health and take>0:
                health-=take
                print name, "now has", health, "health points."
                points+=take
            elif attribute=="wisdom" and take<=wisdom and take>0:
                wisdom-=take
                print name, "now has", wisdom, "wisdom points."
                points+=take
            elif attribute=="dexterity" and take<=dexterity and take>0:
                dexterity-=take
                print name, "now has", dexterity, "dexterity points."
                points+=take
            else:
                print "invalid number of points."
        else:
            print "invalid attribute."
    elif choice=="3":
        print "strength -", strength
        print "health -", health
        print "wisdom -", wisdom
        print "dexterity -", dexterity
    elif choice=="4":
        if points==0:
            break
        else:
            print "use all your points!"
    else:
        print "invalid choice."
print "congrats! you're done designing "+name+'.'
print name, "has", strength, "strength points,", health, "health points,", wisdom, "wisdom points, and", dexterity, "dexterity points."

I'm learning my first language, Python, and would really appreciate it if anyone could tell me if I'm writing the most efficient code possible.


texts:
Here's my first significant Haskell program - it presents a count of each word seen on stdin. Any comments are welcome.

import Data.Map

emptyMap = empty :: Map String Integer

countWord m s = alter (\x -> case x of
                               Nothing -> Just 1
                               Just n -> Just (n+1)) s m

mapPairs m = concat [ k ++ ": " ++ (show v) ++ "\n" | (k,v) <- toList m ]

mapTotal = sum . elems

mapOutput m = (mapPairs m) ++ "Total words: " ++ (show (mapTotal m)) ++ "\n"

wc = interact $ mapOutput . (foldl countWord emptyMap) . words

Some of the questions I have are:

Am I using Map efficiently here? (I realize there are other solutions which do not use a Map - the main point of this exercise was to learn how to use Data.Map.)
How can I make sure that emptyMap, countWord and mapTotal all use the same integral type (Int vs. Integer)? For instance, the type of mapTotal is Map a Integer -> Integer, and so I'll get a type error if I change the definition of emptyMap to empty :: Map String Int. Ideally I'd like to make the choice between Int and Integer in one place for all three definitions.


texts: Hotpatching pandas.DataFrame with extended insert method

texts:
pandas.DataFrame.insert can only handle an int for it's loc kwarg this is inconvenient for the user with medium to big data. In an attempt to solve this problem temporarily for my development environment I have come up with the following methods. I'm testing out as hot patches but I plan on implementing them in my fork of pandas and submitting a PR to the pandas master;

import pandas as pd
import numpy as np

@property
def label_pos(self):
    "Return a dict with column labels as keys and their positions as values."
    return dict(i[::-1] for i in enumerate(self.columns))

setattr(pd.DataFrame, 'label_pos', label_pos)

def label_insert(self, label, *args, **kwargs):
    "Insert an array-like into a DataFrame before a column with the given label."
    self.insert(int(self.label_pos[label]), *args, **kwargs)

setattr(pd.DataFrame, 'label_insert', label_insert)

Testing

ex = pd.DataFrame(np.zeros((10,5)),columns=list('ABCEF'))
D = pd.Series(np.zeros(10))

ex.label_insert(label='C', column='D', value=D)

ex.label_insert('E', 'D', D, allow_duplicates=True)


texts:
This code works, and I'm trying to figure out if there's a better way to optimize it. As you can see, I've cut down drastically on time just by using numbers that work for a < b < c. Is there any outstanding thing that can reduce the time? It currently takes ~7 seconds.

Problem:

  A Pythagorean triplet is a set of three natural numbers, \$a < b < c\$, for which

  $$a^2 + b^2 = c^2$$

  For example, \$3^2 + 4^2 = 9 + 16 = 25 = 5^2\$.

  There exists exactly one Pythagorean triplet for which \$a + b + c = 1000\$.  Find the product \$abc\$.

My code:

import time

start = time.time()

def pythag(a, b, c):
    if a ** 2 + b ** 2 == c ** 2:
        return True
    return False

a = [x for x in range(1, 1000)]

for num in a:
    for dig in range(num, 1000 - num):
        for i in range(dig, 1000 - dig):
            if num + dig + i == 1000:
                if pythag(num, dig, i):
                    print(num, dig, i)
                    print("Product: {}".format(num * dig * i))
                    elapsed = time.time() - start
                    print("Time: {:.5f} seconds".format(elapsed))
                    exit(1)

# 200 375 425
# Product: 31875000
# Time: 7.63648 seconds


texts: Bash script to deploy a mongodb cluster on local machine

texts:
I recently wrote a small script to deploy a mongodb cluster on a single machine.
The cluster is composed of :

3 configurations server that holds the same informations (they are replicas )
2 shard server wich will store the data
one mongos which manage connection to the cluster

The script parse a configuration file holding the cluster configuration,
and then starts the different member in a specific order.

Here is the config file:

#config file to store host and port

#config server list, in folowing format:
# config=<host>:<port>
# started with --dbpath /data/configX where
# X is the position of the server in the list
config=localhost:27018
config=localhost:27019
config=localhost:27020

#mongos instance in folowing format:
# mongos=<host>:<port>
mongos=localhost:27017

#shard list in folowinf format:
# shard=<host>:<port>
# started with --dbpath /data/shardX where
# X is the position of the shard in the list
shard=localhost:27021
shard=localhost:27022

and here is the script:

#!/bin/bash

# this script should be launched on the server where you want the
# mongos to run. It should be run like this:
# ./deploy.sh path/to/config.txt

# make sure that mongod, mongos and mongo are linked correctly
# you can achieved this using the following command:
# sudo ln -s /path/to/mongo/bin/mongo /bin/mongo

# host:port for config server
CONFIG=()
# host:port for shards
SHARD=()

# text colors
red=`tput setaf 1`
green=`tput setaf 2`
reset=`tput sgr0`

# clear log file
echo "" > log.txt

# ignore empty or comment line
sed '/^#/d;/^$/d' $1 |
{
while read -r line
do

    IFS='=' read -a array <<< "$line"
    val="${array[1]}"
    key="${array[0]}"

    if [ "$key" == "config" ]; then
        CONFIG+=("$val")
        echo "mongod config server: $val"
    fi
    if [ "$key" == "mongos" ]; then
        MONGOS="$val"
        echo "mongos instance: $val"
    fi
    if [ "$key" == "shard" ]; then
        SHARD+=("$val")
        echo "shard instance: $val"
    fi
done
#start config servers
index=0
for conf in "${CONFIG[@]}"
do
    # ping each host to make sure it's reacheable
    IFS=':' read -a config <<< ${CONFIG[$index]}
        mkdir /data/config$index
        echo "starting config server $index"
    mongod --configsvr --port ${config[1]} --dbpath /data/config$index --replSet conf > log.txt&
    index=$(($index + 1))
    sleep 1
done

sleep 10
echo "${green}config servers deployed${reset}"
# setup the config replica set. Only neccessary on first launch
IFS=':' read -a config0 <<< ${CONFIG[0]}
mongo --host ${config0[0]} --port ${config0[1]} --eval "rs.initiate( { _id: \"conf\", members: [ {_id: 0, host:\"${CONFIG[0]}\"}, {_id: 1, host:\"${CONFIG[1]}\"}, {_id: 2, host:\"${CONFIG[2]}\"} ]})"&

# sleep so a primary shard can be designed among config servers
sleep 15
# get mongos infos
IFS=':' read -a mongos <<< $MONGOS
#start mongos
mongos --port ${mongos[1]} --configdb "conf/${CONFIG[0]},${CONFIG[1]},${CONFIG[2]}" > log.txt&

echo "${green}mongos instance configured${reset}"

sleep 5
# start each shard and add them to the cluster
shardnb=0
for shard in "${SHARD[@]}"
do
        IFS=':' read -a sh <<< ${SHARD[$shardnb]}
        mkdir /data/shard$shardnb
        echo "starting shard $shardnb"
    mongod --shardsvr --port ${sh[1]} --dbpath /data/shard$shardnb > log.txt&
        sleep 5
        mongo --host ${mongos[0]} --port ${mongos[1]} --eval "sh.addShard(\"$shard\");"&
    sleep 5
    shardnb=$(($shardnb + 1))
    echo "${green}shard  $shard added${reset}"
done

# make sure that the sharded cluster has been deployed correctly
mongo --host ${mongos[0]} --port ${mongos[1]} --eval "sh.status();"
}

I use this to quickly deploy a cluster in a docker container in order to run automated integration test.
As this is one of my first bach script, I'm looking for advises on style / readability !


texts: Mocking utility class for database testing

texts:
I have these classes that have a boilerplate way of initialization. So, instead of writing it each time, I wrote a class called MockUtil.java, and I put the boilerplate mocks in there.

MockUtil has static variables and methods which can be called to do the mocking for the test classes. So, when writing a new test class setup, MockUtil's setup, boilerplate expectations, replays, and verifications of mock are being called from the Test class.

I feel like this reduces a lot of boilerplate burden on the test classes. But, I still feel like the code structure/code pattern can be improved. I am not sure if it has to be a util class or something else, because two tests can't run simultaneously because of static variables and methods and I feel like it reduces the scope of enhancements, if any, that has to be done. Could you give me suggestions on what I can improve in my code?

MockUtil.java

public class MockUtil {

    public static JdbcTransactionImpl transaction;
    public static Connection connection;
    public static PreparedStatement statement;
    public static ResultSet resultSet;

    public static Connection getConnection() {
        return connection;
    }

    public static ResultSet getResultSet() {
        return resultSet;
    }

    public static PreparedStatement getStatement() {
        return statement;
    }

    public static void createMocks() {
                //more boilerplate mocks to create services to be used in each Test -- which are ignored here.
                //boilerplate tx mocks
        transaction = createMockBuilder(JdbcTransactionImpl.class)
                .addMockedMethod("getConnection").createMock();

        connection = createMock(Connection.class);
        statement = createMock(PreparedStatement.class);
        resultSet = createMock(ResultSet.class);
    }

    public static void setContextualExpectations(String...sqls) throws Exception {
                //boilerplate tx expectations.
        expect(context.getTransaction()).andReturn(transaction).anyTimes();
        expect(transaction.getConnection()).andReturn(connection).anyTimes();
        for(String sql: sqls) {
            expect(connection.prepareStatement(sql)).andReturn(statement);
        }
        expect(statement.executeQuery()).andReturn(resultSet).anyTimes();
    }

    public static void setReplays() throws SQLException {
        replay(transaction);
        replay(connection);
        replay(statement);
        replay(resultSet);
    }

    public static void closeResources() throws SQLException {
                 //boilerplate resource closing.
        statement.close();
        resultSet.close();
    }

    public static void verifyMocks() {
                 //boilerplate verification of mocks.
        verify(transaction);
        verify(connection);
        verify(statement);
        verify(resultSet);
    }
}

One of the several test classes:

Class1Test

private void setCustomExpectationsForTest1XXX() throws SQLException {
    PreparedStatement stmt = MockUtil.getStatement();
    ResultSet rs = MockUtil.getResultSet();
    checkExp(stmt, rs);
}

private void checkExp(PreparedStatement stmt, ResultSet rs)
        throws SQLException {
    stmt.setString(1, in.getCode());
    expect(rs.next()).andReturn(true);
    expect(rs.getString(1)).andReturn(customVal);
    MockUtil.closeResources();
}

    @Before
public void setUp() throws Exception {
    MockUtil.createMocks();
    createImportExportObj();
}

@After
public void tearDown() throws Exception {
    in = null;
    out = null;
}

@Test
public void test1XXX() throws Exception {
    MockUtil.setContextualExpectations(calcPbValForGldSqls);
    setCustomExpectationsForTest1XXX();
    MockUtil.setReplays();
    program.execute(in, out);
    BigDecimal expected = new BigDecimal("85000").setScale(4);
            BigDecimal actual = out.getAmt();
    assertEquals(expected, actual);
    MockUtil.verifyMocks();
}
}


texts: Early return, unless return value is nil

texts:
I have a lot of code that looks like this:

value = TopicLinkClick.create_from(new_params)
return value unless value.nil?

# do something else

I find this code is not so good because creating a temporary variable is troublesome and disruptive of my workflow, and it takes time to read and understand a large block of code that is meaningless.

Is there a better way for me to do this?


texts: Dynamically create ordered list in outlook from Excel

texts:
I have working code for this project, but I am now in need of some help to create a dynamic ordered list within Outlook from Excel.

I am trying to format comments that a user will enter into a UserForm in Excel and pass those comments into an ordered list via a collection; the issue I run into is that the number of comments can vary and I need to account for that when it comes to setting up the ordered list.  I know I cannot create dynamic variables, so right now I am stuck on how to loop through the collection and adjust the size of the ordered list dynamically.

Below is the code that is working outside of the fact that the ordered list is not dynamic.  Im wondering if maybe passing that Collection into a Class Module would be beneficial, but I am not really proficient with those yet.  Please note that Option Explicit is defined in this module.

Dim strComment As String, commentColl As Collection
Dim arr As Variant

strComment = SheetData.Range("Notes_For_Doc_Reviewer")
arr = Split(strComment, ",")

Set commentColl = New Collection

Dim a

For Each a In arr
    commentColl.Add Trim(a)
Next a

'Dim x As Variant, i As Long

'For Each x In commentColl
'    Debug.Print CStr(x)
'Next x

Count = commentColl.Count

Application.ScreenUpdating = False
Application.DisplayAlerts = False

ZackEmail = "ZackE@nothing.com"
currDir = MLAChecklist.path
hyperlink = "" & currDir & ""

strBody = "Hello Zack," & _
          "
Please complete the closing document review for the following file:" & "&nbsp" & "&nbsp" & hyperlink & "

" & vbCrLf & _
          "Items to make note of in the file." & _
          "
" & _
            "
" & commentColl(1) & "
" & _
            "
" & commentColl(2) & "
" & _
            "
" & commentColl(3) & "
" & _
            "
" & commentColl(4) & "
" & _
            "
" & commentColl(5) & "
" & _
          "
" & _
          "
"

EDIT:  Output of getCheckListHTML per request

Hello Zack,

Please complete the closing document review for the following file:
&nbsp&nbsp
Z:\Projects\Excel Projects\MLA UserForm Checklist

Items to make note of in the file.

Test run

items list

run through things

test number

blah blah

Thank You,


texts:
I was working on a sorting algorithm for my linked list implementation and wanted to get other people's input/comments/critique. What do you think of it in all aspects, including style?

I was told that it is preferred to use a bool type for the changeFlag instead of using an int as it makes it more readable.  Thoughts?

void LinkedList::sort()
{
    if (head != 0)
    {
        Node* current = head;
        Node* prev = 0;
        Node* tempNode = 0;
        bool changeFlag = false;
        for (int i = 0; i < length; i++)
        {
            while (current->next != 0)
            {
                tempNode = current->next;

                if (current->value > tempNode->value)
                {
                    changeFlag = true;
                    current->next = tempNode->next;
                    tempNode->next = current;
                    if (prev != 0)
                        prev->next = tempNode;
                    prev = tempNode;
                    if (head == current)
                        head = tempNode;
                    if (current->next == 0)
                        end = current;
                }
                else
                {
                    prev = current;
                    current = current->next;
                }
            }
            if (changeFlag == false)
                break;
            else
            {
                prev = 0;
                current = head;
                changeFlag = false;
            }
        }
    }
}


texts: The code reads from a specified offset to the specified number of bytes in a file

texts:
The code reads the specified number of bytes from a specified offset in a file, I have handled the partial reads and bytes > buf_size conditions. Could anyone review the code? and say whether the handling strategy is good. The constraint I am  not allowed to use system calls other than open, close, read, write,Thanks a ton.

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<error.h>
#include<errno.h>
#include<fcntl.h>
#define buf_size 5

int main(int argc, char *argv[])
{
    int bytes;
    int offset;
    int fd;
    char *file;
    char buf[buf_size];
    int rlen = 0;
    int len = 0;
    int i = 0;

    if (argc != 4)
        error(1, 0, "Too many or less than the number of arguments");
    file = argv[1];
    offset = atoi(argv[2]);
    bytes = atoi(argv[3]);
    fd = open(file, O_RDONLY);
    printf("The values of the file descriptor is : %d\n", fd);
    if (fd == -1)
        error(1, errno, "Error while opening the file\n");

    while (1) {
        rlen = read(fd, buf, offset);
        if (rlen == -1)
            error(1, errno, "Error in reading the file\n");
        len = len + rlen;
        if(len == offset) {
            len = 0;
            while (1) {
                rlen = read(fd, buf, bytes);
                if (rlen == -1)
                    error(1, errno, "Error in reading the file\n");
                if (rlen == 0)
                    return 0;
                len = len + rlen;
                for (i = 0; i < rlen; i++)
                    putchar(buf[i]);
                if (len == bytes) {
                    printf("\nSuccess\n");
                    return 0;
                }
                bytes = bytes - rlen;
            }
        }
    }
}
```


texts: Is using the result of cmp() as an index "too cryptic"?

texts:
This is a very subjective question, but I'm curious as to other people's opinions.

Would you find this bit of code distasteful? Is it cryptic and unreadable, or is it using features of the language in an elegant way?

def winning_side(home_goals, away_goals):
    """Takes a home score and an away score, and returns the winner

    Return DRAW, HOME or AWAY depending on the outcome
    """
    return (DRAW, HOME, AWAY)[cmp(home_goals, away_goals)]

The alternative obviously being explicit if-else statements:

def winning_side(home_goals, away_goals):
    """Takes a home score and an away score, and returns the winner

    Return DRAW, HOME or AWAY depending on the outcome
    """
    if home_goals > away_goals:
        return HOME
    elif away_goals > home_goals:
        return AWAY
    else:
        return DRAW

I personally find the verbose if-else logic in the latter solution, and the assumed equality in the 3rd branch, less appealing.


texts:
I am starting to work on a basic 3D renderer for fun, so right now I have made a triangle fill function to be used when I draw faces on models:

public void fillTriangle(Triangle2d t, Color color) {
    // triangle points are already sorted
    Line2d ab = t.getAB(), bc = t.getBC(), ac = t.getAC();
    Line2d leftEdge = ab.getEnd().getX() < ac.getEnd().getX() ? ab : ac;
    Line2d rightEdge = ab.getEnd().getX() > ac.getEnd().getX() ? ab : ac;
    Line2d bottomEdge = bc;

    // horizontal lines
    int startY = (int) t.getA().getY(), endY = (int) t.getC().getY();
    for (int y = startY; y <= endY; y++) {
        int startX, endX = (int) rightEdge.getX(y);
        // we are now below the middle (vertically) point, so to avoid going past the bottom edge,
        // we use it to get the startX
        if (y > leftEdge.getEnd().getY())
            startX = (int) bottomEdge.getX(y);
        else
            startX = (int) leftEdge.getX(y);

        for (int x = startX; x <= endX; x++)
            set(x, y, color);
    }

    set((int) t.getA().getX(), (int) t.getA().getY(), Color.RED);
    set((int) t.getB().getX(), (int) t.getB().getY(), Color.RED);
    set((int) t.getC().getX(), (int) t.getC().getY(), Color.RED);
}

set sets a pixel to a specific color
Triangle2d's points are already sorted vertically, so A is above B and B is above C (unless they have equal y-values)
Triangle2d#getAB returns a line going from the first point, A to the second point B
Line2d#getX returns the X-value for a given Y-value (and likewise for Line2d#getY)

The idea is that I draw horizontal lines going from the top to the bottom.


texts:
I have written two different codes for merging (merging with costs) and I want to know if I can make optimizations to run faster.

merge1:

 private static long merge(List<Integer> array, int[] res, int start, int mid, int end) {

        int i = start; // index of left subarray
        int j = mid; // index of right subarray
        int k = start; //index of mid

        long inversions = 0;

        for (int r = start; r <= end; r++) {

            if ((j > end) || (i < mid && array.get(i) <= array.get(j))) {
                res[r] = array.get(i);
                i++;
            } else {

                if (i < mid) {

                    if (array.get(i) - array.get(j) > 1) {

                        inversions += 3 * (mid - i);
                    } else {
                        int s;
                        s = MostRightSmallestElement.search(array, i, mid - 1);
                        inversions += 2 * (s - i + 1);
                        inversions += 3 * (mid - (s + 1));
                    }

                }
                res[r] = array.get(j);
                j++;

            }
        }

       //Copy the remaining elements of left subarray  (if there are any) to res
        while (i <= mid - 1) {
            res[k++] = array.get(i++);
        }

        //Copy the remaining elements of right subarray  (if there are any) to res
        while (j <= end) {
            res[k++] = array.get(j++);
        }

        //Copy back the merged elements to original array
        for (i = start; i <= end; i++) {
            array.set(i, res[i]);
        }

        return inversions;

    }

merge2:

private static long merge(List<Integer> array, int[] res, int start, int mid, int end) {

        int i = start; // index of left subarray
        int j = mid; // index of right subarray
        int k = start; //index of mid

        long inversions = 0;

        while( ( i <mid) && (j <= end )) {

            if( array.get(i) <=  array.get(j)){
                res[k++] = array.get(i++);
            }
            else {

                if (i != mid) {

                    if (array.get(i) - array.get(j) > 1) {

                        inversions =  inversions + 3 * (mid - i);

                    } else {
                          int s;
                        s = MostRightSmallestElement.search(array, i, mid - 1);
                        inversions =  inversions +  2 * (s - i + 1);
                        inversions =  inversions +  3 * (mid - (s + 1));
                    }
          }
                res[k++] = array.get(j++);

        }
        }

       //Copy the remaining elements of left subarray  (if there are any) to res
        while (i <= mid - 1) {
            res[k++] = array.get(i++);
        }

        //Copy the remaining elements of right subarray  (if there are any) to res
        while (j <= end) {
            res[k++] = array.get(j++);
        }

        //Copy back the merged elements to original array
        for (i = start; i <= end; i++) {
            array.set(i, res[i]);
        }

        return inversions;

    }

Any ideas how I can optimize the code? I count the inversions but the general
idea of merging is the same.


texts: Symfony2: Extract method from controller, form events, remove conditional

texts:
I have a fairly ugly controller method I would like to refactor / extract. I can only test this in a integration type test which kind of signals a code smell.

The method processes the form and needs to do one of 5 things, depending on which button was pressed

if submitted and valid (button 1) => update some values on the entity and re-render the form
if submitted and valid (button 2) => perform another controller action that shows a pdf print of the entity
if submitted and valid (button 3) => save entity and redirect
if not submitted or not valid => render form (plus errors)

In code it looks kind of like this

protected function processForm(Request $request, MyEntity $entity)
{
    $form = $this->createForm(new MyEntityType, $entity);

    if ($form->handleRequest($request)->isValid()) {

        $alteredEntity = SomeClass:performStuffOnEntity($entity);

        if ($form->get('button1')->isClicked()) {
            $form = $this->createForm(
                new MyEntityType, $alteredEntity
            );
        }
        else if ($form->get('button2')->isClicked()) {
            return $this->pdfPreview($alteredEntity);
        }
        else if ($form->get('button3')->isClicked()) {
            return $this->persistAndRedirectToEntity(
                $alteredEntity
            );
        }
    }

    return $this->render(
        'MyBundle:MyEntity:new.html.twig', array(
            'form' => $form->createView(),
    ));
}

Actually there are two buttons like button1, I left one out for brevity of the example.

Idea 1: I have tried to extract this into a EntityFormWizard of some sort but this ended up as a cluttered Object with too many dependencies (Router, Templating, Form) which was also a pain to test.

Idea 2: Using FormEvents I wanted to extract at least the altering of the entity depending on which button was pressed into a FormEventListener, but the only place where I can alter the Entity is the FormEvents::PRE_SET_DATA event, but in there I have problems figuring out which button was clicked.

So the question: Do I have to live with my integration test for this behavior or is there a way to extract it and test it with a unit test?


texts:
I've written an implementation of the "famous" Mars Rover simulation, (another question on this) whose problem statement is this:

The first line of input is the upper-right coordinates of the plateau, the lower-left coordinates are assumed to be 0,0.
The rest of the input is information pertaining to the rovers that have been deployed. Each rover has two lines of input. The first line gives the rover's position, and the second line is a series of instructions telling the rover how to explore the plateau.
The position is made up of two integers and a letter separated by spaces, corresponding to the x and y co-ordinates and the rover's orientation.
Each rover will be finished sequentially, which means that the second rover won't start to move until the first one has finished moving.
Output:
The output for each rover should be its final co-ordinates and heading.
Test Input:
5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM

Expected Output:
1 3 N
5 1 E

This is my working solution:
dirs =: 'NESW'

input =. _4]\ 2 }. '' cut (' ',LF) charsub fread '~/Desktop/marsrover.txt'

NB. State transitions are the directions rotated forward and backwards
st =. 0,."1~ (] ,. 1 |. ] ,.  _2 |. ]) i. # dirs

NB. R = 1, L = 2, anything else = 0
a =. ('R'=a.) + (2 * 'L'=a.)

NB. Run the state machine against the input, initial facing on left
facing =: dirs {~ 4 {"1 ] ;:~ 5 ; st; a; 0 _1 , _1 ,~ dirs i. [

NB. Detect motion in each direction
moves =: ] #~ 1 - 'M' i. [

simulate =: monad define "1
  'x0 y0 dir commands' =. y
  pos =. ". x0, ' ', y0
  f =. dir facing commands
  dest =. pos + (+/ (dirs i. commands moves f) { 4 2 $ 0 1   1 0   0 _1   _1 0)
  (": dest), ' ', {: f
)

echo simulate input
exit ''

My plan for this program was basically this:

Run a state machine with the current facing against the input to figure out what the facing is at the moment of each command. This is what facing calculates.
Get the facing corresponding to each M command
Take the sum of "move" vectors to get the total change in coordinates. N = 0 1, so three moves with facing N will be the sum of 0 1 + 0 1 + 0 1 = 0 3.
The solution is the sum of the total change in coordinates with the initial coordinate, plus the final facing state.

What I'd like review for, is to find out if this code is idiomatic J, if there are more direct ways to do what I'm trying to do here, and especially in the simulate verb, if there are better ways to handle taking apart the input and passing it through the other verbs. I am happy that I figured out how to use sequential machine, but overall this solution feels a bit gassy to me. But I haven't found another implementation to compare to.


texts:
I wrote a script for my Raspberry Pi that keeps checking my external IP. If it changes, the Raspberry Pi will send me the new IP via email.

Any suggestions for improvements?

#!/usr/bin/python3

import os, time

def getIP():
        os.system('dig +short myip.opendns.com @resolver1.opendns.com > raspip.txt')
        with open('raspip.txt', 'r') as f:
                return f.readline().rstrip('\n')

def sendIP(currentIP):
        os.system('sendEmail '                            +
                  '-o tls=yes '                           +
                  '-f \'***@outlook.com\' '               +
                  '-t \'***@outlook.com\' '               +
                  '-s \'smtp.live.com\' '                 +
                  '-xu \'***@outlook.com\' '              +
                  '-xp \'**password**\' '                 +
                  '-u \"raspberry via python\" -m '       +
                  '\"' + currentIP + '\"')

def main():
        lastIP = None
        while (True):
                currentIP = getIP()
                if (lastIP != currentIP):
                        sendIP(currentIP)
                        lastIP = currentIP
                time.sleep(60)

if __name__ == "__main__":
        main()


texts: Reading file and writing to output file with line numbers

texts:
I started learning java relatively recently as my first computer language independently and would like to see if my approach is efficient. An exercise in the book I am studying from tells me to read a file and write it into a seperate file with each line numbered.

Here is my solution

public class FileStuff
{
    public static void main (String [] args)
    {
        System.out.println("Which file do you want to read");
        Scanner in = new Scanner(System.in);
        String fileInput = in.next();
        System.out.println("Which file do you want to write to?");
        String fileOutput = in.next();
        Scanner goThrough = null;
        PrintWriter print = null;
        String content ="";
        try
        {
            print = new PrintWriter(fileOutput);
            goThrough = new Scanner(new File(fileInput));
            while(goThrough.hasNextLine())
            {

                content = goThrough.nextLine();
                writeToLine(content, print);

            }
        } catch(FileNotFoundException e)
        {
            e.getMessage();
        }finally
        {
            goThrough.close();
            print.close();
        }

    }
static int lineNumber = 1;
    static void writeToLine(String line, PrintWriter out) throws FileNotFoundException
    {
        try
        {
        out.println(String.format("/* %d */ %s ",lineNumber,line));
        lineNumber+=1;
        }
        catch(Exception e)
        {
            e.getMessage();
        }
    }

}

Concerns

I have several inquiries about my code as I cannot understand my book clearly, and coding practicing questions.

Firstly, is it ok to initialize goThrough and print outside the try block as null? I did this because I wanted to close the Scanner and PrintWriter inside the finally block, but did not want to define something inside the try block since it is a different scope from the finally block

Secondly: Is it fine to throw FileNotFoundException at my method writeToLine? Or should I be throwing it after public static void main(String [] args), I have seen it done both ways in my book.


texts: Find if cookie name exists in the cookie string

texts:
I need to determine whether a cookie name is available or not in the cookie string. I have achieved this. We could use the cookie-parser package but I don't want to use that package so I have written the below code. Can I reduce the code in a better way that is more optimised?

    function checkCookie(cookie, cookieToBeSearched){
                if(cookie === "" || cookie === undefined){
                    return false
                }
                let res = cookie.split(";").some(cookie => {
                    let eachCookie = cookie.split("=");
                    return eachCookie[0].trim() === cookieToBeSearched
                });
                return res;
            }

    let cookie = "_ga=GA1.2.2091695351.1539084164; __qca=P0-338702612-1539084164095; __gads=ID=770d92bcdac8de40:T=1539084164:S=ALNI_MbsRKpoSJdn8tsdShMHMZUAR17uZA; _gid=GA1.2.798724103.1539582973";

    console.log("Cookie is available - ", checkCookie(cookie, "_gid"))

    console.log("Cookie is available - ", checkCookie(cookie, "_giddd"))