texts:
I have written a water cooler example in which the consumer drinks from the water cooler until it's empty and when it gets empty the producer fills it up. The consumers wait until it's filled up and then start drinking again. Can you please review?

Producer

package com.par.consumer.producer;

import java.util.List;

public class Producer implements Runnable {
    private List<Integer> mySharedList;
    int size;

    public Producer(List<Integer> sharedList,int size) {
        this.mySharedList=sharedList;
        this.size=size;
    }

    @Override
    public void run() {
        while(true)
        {
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }

            synchronized (mySharedList) {
                System.out.println("Size is "+mySharedList.size());

                if(mySharedList.isEmpty()) // Water cooler is empty fill it up
                {
                    for(int i=1;i<=size;i++){
                        System.out.println("Adding water "+i);
                        mySharedList.add(i);
                    }
                    mySharedList.notify();
                }

                try {
                    System.out.println("Producer waiting");
                    mySharedList.wait();
                    System.out.println("Producer waiting exit");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Consumer

package com.par.consumer.producer;

import java.util.List;

public class Consumer implements Runnable{
    private List<Integer> mySharedList;

    public Consumer(List<Integer> sharedList) {
        this.mySharedList=sharedList;
    }
    @Override
    public void run() {
        while(true)
        {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            synchronized (mySharedList) {
                if(mySharedList.isEmpty())
                {
                    System.out.println("IS EMPTY");

                    try {
                        mySharedList.notify();
                        System.out.println("Consumer waiting");
                        mySharedList.wait();
                        System.out.println("Consumer waiting exit");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                System.out.println("Drinking "+mySharedList.remove(0));
            }
        }
    }
}

WaterCooler (Driver)

package com.par.consumer.producer;

import java.util.ArrayList;
import java.util.List;

public class WaterCooler {
    volatile List<Integer> list=new ArrayList<Integer>();

    public static void main(String[] args) {
        new WaterCooler().run();
    }

    void run()
    {
        new Thread(new Producer(list, 4)).start();
        new Thread(new Consumer(list)).start();
    }
}


texts: Basic User Interaction in Python - syntax, docstrings, performance

texts:
Hoping for input on the clarity of the docstrings, syntax and performance of these two functions both of which should be self-explanatory:

def tell(paragraph, duration=.1):
    """Print paragraph line by line with pause between each line."""
    lines = paragraph.splitlines()
    for line in lines:
        print line.lstrip()
        time.sleep(duration)

def yinyang(yes, no, prompt = "y/n: ", tries = 3):
    """Return result based on parsed user input with specified number of tries."""
    input = raw_input(prompt)
    word_list = scan(input)
    repeat_prompt = """Does not compute.
                    Please try again to express yes or no."""
    player_decision = parse_sentence(word_list).decision
    try:
        assert(input and tries > 0)
        input = None
        if player_decision == "affirmative":
            return yes
        elif player_decision == "negative":
            return no
        else:
            tries += 1
            tell(repeat_prompt)
            return yinyang(yes, no, prompt, tries)
    except AssertionError:
        return no

The functions, scan() and parse_sentence() are from a module so their docstring (within the module code) should suffice for any needed explanation, right?

Will include them, too:

"""Accept a word string and return a yes, no or error"""

WORD_TYPES = {'affirmative': ['yes', 'y', 'do', 'will', 'sure', 'will', 'ok', 'can', 'would'],
              'negative': ['no', 'n', 'won\'t', 'not', 'nyet', 'can\'t']}

type_words = {word : label for label, words in WORD_TYPES.items() for word in words}

PUNCTUATION = ['.', '?', '!', ',', ':', ';']

def scan(sentence):
    """Strip punctuation and return list containing word and type"""
    sentence_list = sentence.split()
    for idx, word in enumerate(sentence_list):
        for p in PUNCTUATION:
            if p in word:
                word = word.strip(p)
        try:
            lc_word = word.lower()
            word_type = type_words.get(lc_word, None)
            assert word_type is not None
            sentence_list[idx] = (word_type, lc_word)
        except AssertionError:
            lc_word = word.lower()
            sentence_list[idx] = ('error', lc_word)
    return sentence_list

and parse_sentence is here:

class Sentence(object):

    def __init__(self, decision):
        # remember we take ('noun','princess') tuples and convert them
        self.decision = decision[0]

def peek(word_list):
    if word_list:
        word = word_list[0]
        print word[0]
        print word[1]
        return word[0]
    else:
        return None

def match(word_list, expecting):
    if word_list:
        word = word_list.pop(0)

        if word[0] == expecting:
            return word
        else:
            return None
    else:
        return None

def skip(word_list, word_type):
    while peek(word_list) == word_type:
        match(word_list, word_type)

def parse_decision(word_list):
    next_word = peek(word_list)

    if next_word == 'affirmative':
        return match(word_list, 'affirmative')
    elif next_word == 'negative':
        return match(word_list, 'negative')
    else:
        return ('error', 0)

def parse_sentence(word_list):
    decision = parse_decision(word_list)

    return Sentence(decision)


texts:
I created this module, and I'm wondering if I did a good job. How would an experienced JavaScript developer improve this simple slider module further? Like, let's say that you want to use this module on 3 sliders on the same page.

Here is a jsFiddle.

Module

var sliderTest = (function(){
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ✚   private variables
    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    var expoElement = document.querySelector(".test")
    var expoCanvas = expoElement.querySelector(".canvas")
    var expoSlides = expoCanvas.querySelectorAll(".slide")
    var controlPrev = expoElement.querySelector(".control.prev")
    var controlNext = expoElement.querySelector(".control.next")
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ✚   private functions
    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    function whereIsActive(){
       var y = {}
       for(var i = 0; i < expoSlides.length; i++){
          if(expoSlides[i].classList.contains("active")){
              y.current = i;
              if(expoSlides[i+1]){
                  y.next = i+1;
              } else {
                  y.next = 0;
              }

              if(expoSlides[i-1]){
                  y.prev = i-1;
              } else {
                  y.prev = expoSlides.length-1;
              }
          }
      }
      return y
   }

   function removeActiveClasses(){
       for(var i = 0; i < expoSlides.length; i++){
           expoSlides[i].classList.remove("active")
       }
   }
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ✚   public methodes
    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/

        var publicMethod = {
            nextSlide:function(ev){
               ev.preventDefault();
               var nextIndex = whereIsActive().next;
               removeActiveClasses();
               expoSlides[nextIndex].classList.add("active");
       },

       prevSlide:function(ev){
           ev.preventDefault();
           var prevIndex = whereIsActive().prev;

           removeActiveClasses();
           expoSlides[prevIndex].classList.add("active")
      },
      sendInTheClone:function(){alert(whereIsActive().current)}
  }
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ✚   event listners
    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/

            controlNext.addEventListener("click", publicMethod.nextSlide)
            controlPrev.addEventListener("click", publicMethod.prevSlide)
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ✚   return
    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/

        return publicMethod;
})();

HTML

1

2

3

4

    prev next


texts: CommandBinding refresh on parameter changed

texts:
I need the command I am executing on a datagrids context menu to know which column was clicked on.

XAML

<DataGrid x:Name="dataGrid" ItemsSource="{Binding Table}" ContextMenuOpening="DataGrid_ContextMenuOpening">
    <DataGrid.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Add Column" Command="{Binding AddColumn}"/>
            <MenuItem Header="Remove Column" Command="{Binding RemoveColumn}"/>
        </ContextMenu>
    </DataGrid.ContextMenu>

</DataGrid>

Code behind:

private void DataGrid_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
    var current = e.OriginalSource as DependencyObject;
    while(current != null && !(current is DataGridCell))
    {
        current = VisualTreeHelper.GetParent(current);
    }
    var cell = current as DataGridCell;
    foreach (var item in dataGrid.ContextMenu.Items.OfType<MenuItem>())
    {
        item.CommandParameter = cell.Column.DisplayIndex;
        (item.Command as DelegateCommand<object>)?.RaiseCanExecuteChanged();
    }
}

I'm having to break MVVM by having the view tell the VM command that its execution has changed because the command binding doesn't seem to refresh on the parameter changing. Is there a better way to do this?


texts:
I have to do a pairwise compare of a couple of text files. They have the following format:

id_1|errorcode_1|m|data_1_1|data_1_2|...|data_1_m
id_2|errorcode_2|m|data_2_1|data_2_2|...|data_2_m
  .
  .
  .
id_n|errorcode_n|m|data_n_1|data_n_2|...|data_n_m

The columns are ordered, but the rows can be in an arbitrary order. And there are always a couple of data-fields that have to be ignored.

This is my method that I call twice (switching the target and source array). It takes around 20 minutes to execute with two files where n = 16000 and m = 100.

private static string[] GetDifferences( IEnumerable<string> source
                                      , IEnumerable<string> target
                                      , IEnumerable<int> ignoredIndices)
{
    var uniqueInSource = new List<string>();

    foreach (var sourceLine in source)
    {
        var found = false;
        var sourceSplit = sourceLine.Split('|').ToList();

        // filter out malformed lines
        if (sourceSplit.Count > 2 && !int.TryParse(sourceSplit[2], out _))
        {
            continue;
        }

        foreach (var index in ignoredIndices)
        {
            sourceSplit.RemoveAt(index + 3);
        }

        foreach (var targetLine in source)
        {
            var targetSplit = targetLine.Split('|').ToList();

            if (targetSplit.Count > 2 && !int.TryParse(targetSplit[2], out _))
            {
                continue;
            }

            foreach (var index in ignoredIndices)
            {
                targetSplit.RemoveAt(index + 3);
            }

            if (targetSplit.SequenceEqual(sourceSplit))
            {
                found = true;
                break;
            }
        }

        if (!found)
        {
            uniqueInSource.Add(string.Join("|", sourceLine));
        }
    }

    return uniqueInSource.ToArray();
}

I feel that my approach might be too naive since I think it's somewhere around O(m*n2).


texts:
I'm writing a function to reverse a number in Ruby. IE, 314159.reverse should return 951413.

Here's what I have, which works:

class Numeric
  def reverse
    str = self.to_s.reverse

    if self.is_a?(Float)
      return str.to_f
    elsif self.is_a?(Integer)
      return str.to_i
    end
  end
end

I don't like the enumeration of different number types. Is there a way to dynamically pass in the type?

Something like:

return str.to_type(self.type)

Any other thoughts on simplifying this?

See also: My related Stack Overflow question on some other approaches I tried.


texts:
I have written a program that takes the original file (the script of 'the bee movie') and does a word count, a unique word count and replaces some of the words. This is really just a rushed version, so if there are any errors or ways of fixing/making the code more efficient, please let me know.
Link to the script: https://github.com/esker-luminous/Bee-Movie-Knock-off/blob/main/script.py - it is a very large file.
Code:
file = open('script.py', 'r')

words = []
punctuation = '1234567890!@#$%^&*()_-+=-/*{}[];:\'"\<>~`|?'

for line in file:
    line = line.lower()
    for char in punctuation:
        line = line.replace(char, '')

    words += line.split()

print(len(words))
print(len(set(words)))
file.seek(0)

text = file.read()
print(text)
file.close()

word_replacement ={'bee': 'turtle', 'hive': 'cow', 'flower': 'algae', 'bees': 'turtle', 'flowers' : 'algae'}
for wor_repl in word_replacement.keys():
    text = text.replace(wor_repl, word_replacement[wor_repl])
file = open('knock off.py', 'w')
file.write(text)
file.close()


texts:
This portion is for a button style. I set the style depending on if it is pressed or not. I was wondering if I could write this better or more efficient. Mainly the way I use new.

bool Draw::CustomButton(LPDRAWITEMSTRUCT pDIS) {

using namespace Gdiplus;

// Control info
int ctlResID = pDIS->CtlID;
Status lastCall = (Status)0;

// The bounding box of the button
Rect rect(0.0f,0.0f,pDIS->rcItem.right, pDIS->rcItem.bottom);

// Prepare the text
const int buffer_size_ = 16;
char textCharArray[buffer_size_];
GetWindowTextA(pDIS->hwndItem, textCharArray, buffer_size_);
std::string buttonText = std::string(textCharArray);

// Button state, down or up
bool button_down = false;
if (pDIS->itemState & ODS_SELECTED) button_down = true;

/* Pens, Brushes, Fonts, etc, depending on state *********/
// Center Align
StringFormat format;
format.SetLineAlignment(StringAlignmentCenter);
format.SetAlignment(StringAlignmentCenter);
format.SetFormatFlags(0);

/* This only works with pointers to removed redundent code and making it eaiser to update */
LinearGradientBrush* lgBrushBackgroundPtr = new LinearGradientBrush(  rect, Color(255, 0, 120, 165), Color(255, 0, 90, 190), LinearGradientModeVertical);
int borderSize = 0;
static Pen* penBorderPtr = NULL;
static Font* fontPtr = NULL;
static SolidBrush* fontColorPtr = NULL;

// Button Down
if (button_down) {
    borderSize = 4;
    penBorderPtr       = new Pen ( Color ( 125, 0, 0, 0 ), borderSize );
    fontPtr            = new Font ( L"Arial", 18, FontStyleRegular, UnitPixel );
    fontColorPtr       = new SolidBrush ( Color ( 255, 255, 255, 255 ) );
}
// Button Up
else {
    borderSize = 4;
    penBorderPtr       = new Pen ( Color ( 125, 20, 20, 20 ), borderSize );
    fontPtr            = new Font ( L"Arial", 20, FontStyleRegular, UnitPixel );
    fontColorPtr       = new SolidBrush ( Color ( 255, 255, 255, 255 ) );
}

 // Draw
Graphics g (pDIS->hDC);
lastCall = g.FillRectangle(lgBrushBackgroundPtr, rect);
lastCall = g.DrawRectangle(penBorderPtr, rect);

StringEx(&g, buttonText, fontPtr, rect, ALIGN_CENTER, ALIGN_CENTER, fontColorPtr);

// Clean
g.Flush();
delete penBorderPtr;
delete fontPtr;
delete fontColorPtr;
delete lgBrushBackgroundPtr;

return true;

}

The main thing I am looking at is how I draw the button with new/ delete


texts: Jasmine unit tests for a function to set attributes on an HTML element

texts:
I'm new to unit testing so maybe I have this all wrong, but it seems kind of useless. I want to reduce bugs and integrate some tests with a build process however I'm not seeing the benefit at the moment. How can I improve the quality of tests, like the one below?

/* script */
SetAttributes = function(el, attrs) {
  /**
   * @method simple for in loop to help with creating elements programmatically
   * @param {object} el - HTMLElement attributes are getting added to
   * @param {object} attrs - object literal with key/values for desired attributes
   * @example SetAttributes(info,{
   *    'id' : 'utswFormInfo'
   *    'class' : 'my-class-name'
   * });
   */

  for (let key in attrs) {
    if (attrs.hasOwnProperty(key)) {
      el.setAttribute(key, attrs[key]);
    }
  }

  return el;
};

/** \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ **/

/* unit test */
describe("SetAttributes is for setting multiple attributes at a single time.", function() {

  /** SetAttributes */
  it("should not be null because it returns an HTMLElement with newly added attributes.", function() {
    expect(SetAttributes(document.createElement('div'), {
      defer: true,
      src: null,
      type: 'text/javascript'
    })).not.toBe(null);
  });
  it("should not be a number because it returns an HTMLElement with newly added attributes.", function() {
    expect(SetAttributes(document.createElement('div'), {
      defer: true,
      src: null,
      type: 'text/javascript'
    })).not.toBe(0);
  });
  it("should not be a string because it returns an HTMLElement with newly added attributes.", function() {
    expect(SetAttributes(document.createElement('div'), {
      defer: true,
      src: null,
      type: 'text/javascript'
    })).not.toBe('div');
  });
  it("should not be undefined because it returns an HTMLElement with newly added attributes.", function() {
    expect(SetAttributes(document.createElement('div'), {
      defer: true,
      src: null,
      type: 'text/javascript'
    })).not.toBe(undefined);
  });
  it("should not be a false value because it returns an HTMLElement with newly added attributes.", function() {
    expect(SetAttributes(document.createElement('div'), {
      defer: true,
      src: null,
      type: 'text/javascript'
    })).not.toBeFalsy();
  });
});


texts: Appending messages to hidden input fields

texts:
This code contains an array of objects that I loop over and append to hidden input fields in the DOM. As these inputs have no ID, I first select them by name using $.each and then check the value by looping over the array using another $.each. If there is a match, I then append some HTML to the DOM.

It works fine, but I have doubts about the code, especially where I am using two $.each. Is there a better way of doing this?

var messages = [
            {
                "code":"203294641",
                "message":"A night costs 332 miles"
            },
            {
                "code":"203294642",
                "message":"The night is dark and full of terrors. Costs 32 miles."
            },
            {
                "code":"203294643",
                "message":"The night is dark and full of terrors. Costs 67 miles."
            },
            {
                "code":"203294644",
                "message":"The night is dark and full of terrors. Costs 423 miles."
            },
            {
                "code":"203294645",
                "message":"The night is dark and full of terrors. Costs 431 miles."
            },
            {
                "code":"203294646",
                "message":"The night is dark and full of terrors. Costs 76 miles."
            }
        ];

    $('input[name="code"]').each(function(){
        var inp = $(this);
        $.each(messages, function(i) {
            if (inp.val() == messages[i].code){
                inp.closest('.plan').find('.loyalty').append('
' + messages[i].message + '
');
            }
        });
    });


texts:
I'm new to PyTorch and I'm writing a unit test for an activation function I'm making.

I plan to test against a reference implementation for this function. I want to approach this in a test-driven way, so I learned to write a test using a known-good function: the ReLU implementation "MyReLU" from  this beginner tutorial.

The tests passed, but is there any way I can improve the code below? I worry I might not be taking full advantage of PyTorch's libraries and capabilities.

import unittest
import numpy as np
import torch
from torch.autograd import gradcheck
from my_activation_functions import MyReLU

class ReluTest(unittest.TestCase):
    def setUp(self):
        self.relu = MyReLU.apply

    def test_relu_values_x_leqz(self):
        tin_leqz = torch.tensor(np.linspace(-10,0,300))
        tout_leqz = list(self.relu(tin_leqz))
        for x in tout_leqz:
            self.assertEqual(x,0)

    def test_relu_values_x0(self):
        tin_eqz = torch.tensor([0,0,0,0,0])
        tout_eqz = list(self.relu(tin_eqz))
        for x in tout_eqz:
            self.assertEqual(x,0)

    def test_relu_values_x_geqz(self):
        tin_geqz = torch.tensor(np.linspace(0.001,10,300))
        tout_geqz = list(self.relu(tin_geqz))
        test_geqz = list(tin_geqz)
        for ii in range(len(tout_geqz)):
            self.assertEqual(tout_geqz[ii], test_geqz[ii])

    def test_drelu_values(self):
        tin = (torch.randn(20,20,dtype=torch.double,requires_grad=True))
        self.assertTrue(gradcheck(self.relu, tin, eps=1e-6, atol=1e-4))

if __name__ == '__main__':
    unittest.main(verbosity=2)


texts:
Please review this code.

  import java.awt.*;

 import javax.swing.*;
 public class Snake_Ladder  {
public static void main(String[] args) {
new Snake_Ladder();
}

public Snake_Ladder(){
int i;
JFrame frame = new JFrame();
JPanel pane = new JPanel();
GridLayout experimentLayout = new GridLayout(11,0);
        pane.setLayout(experimentLayout);
        for(i=100;i>=91;i--){
        pane.add(new JButton(" " +i));
        }
        for(i=81;i<=90;i++){
        pane.add(new JButton(" " +i));
       }
        for(i=80;i>=71;i--){
        pane.add(new JButton(" " +i));
        }
        for(i=61;i<=70;i++){
        pane.add(new JButton(" " +i));
        }
        for(i=60;i>=51;i--){
        pane.add(new JButton(" " +i));
        }
        for(i=41;i<=50;i++){
        pane.add(new JButton(" " +i));
        }
        for(i=40;i>=31;i--){
        pane.add(new JButton(" " +i));
        }
        for(i=21;i<=30;i++){
        pane.add(new JButton(" " +i));
        }
        for(i=20;i>=11;i--){
        pane.add(new JButton(" " +i));
        }
        for(i=1;i<=10;i++){
        pane.add(new JButton(" " +i));
        }
frame.add(pane);
frame.setSize(1200,1400);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

}

 }


texts:
I'd like to see if there are any suggestions on how to improve a simple conditional test at the beginning of a backup script that verifies a ZFS volume is "online" and has the name "tank".

For example:

% zpool list
NAME      SIZE  ALLOC   FREE  EXPANDSZ   FRAG    CAP  DEDUP  HEALTH  ALTROOT
tank  54.5T  36.0T  18.5T         -    35%    66%  1.00x  ONLINE  -

The following simple script works, but I suspect there may be a more elegant way to do this. ShellCheck notes $STATUS is unused...

#!/bin/sh
#
STATUS=$(/sbin/zpool list | grep tank | grep ONLINE)
if [ $? -gt 0 ]; then
        echo "Problems"
        exit 1
else

echo all system go!
exit 0

fi


texts: Bush Wanderer - code intended for teaching

texts:
I am teaching computing to an AS class and this was their assignment:

  Bush Wanderer

  Task 1

  Create a 5x5 grid of hashes(#) where the player is an x on the
  board

  Prompt the player to move in either N, E, S or W direction and then
  reprint the board to show the new position.

  Example:

  x # # # #
# # # # #
# # # # #
# # # # #
# # # # #
Which way would you like to move?(N,E,S or W)

  Task 2

  Ensure the player does not move off of the board
  Place a hidden chest somewhere on the board at random
  End the game when the chest is found
  Tell the player how many moves it took to find the chest
  Add a visible (but blind) dragon that can teleport around the board    at random and will eat you and end your game if it gets you before
  you get the chest

This was my exemplar solution at the end and I wanted to get some feedback on what the professional community thought of it. How could this be improved?

import random

grid = 5

moves = 0

x = 0
y = 0

cx = random.randint(0,(grid-1))
cy = random.randint(0,(grid-1))

while(True):

  dx = random.randint(0,(grid-1))
  dy = random.randint(0,(grid-1))

  for i in range(grid):
      if i == dy and i == y:
        for u in range(grid):
          if u == dx:
            print('@ ', end='')
          elif u == x:
            print('x ', end='')
          else:
            print('# ', end='')
        print()
      elif i == y:
          print('# '*x, end="")
          print('x ', end="")
          print('# '*((grid-x)-1))
      elif i == dy:
          print('# '*dx, end="")
          print('@ ', end="")
          print('# '*((grid-dx)-1))
      else:
        for i in range(grid):
          print('# ', end="")
        print()

  if dx == x and dy == y:
    if moves == 1:
      print('You died in', moves,'move!')
    elif moves > 1 or moves == 0:
      print('You died in', moves,'moves!')
    break
  elif cx == x and cy == y:
    if moves == 1:
      print('You won in', moves,'move!')
    elif moves > 1 or moves == 0:
      print('You won in', moves,'moves!')
    break

  m = input('Which way would you like to move?(N,E,S or W)').lower()

  if m == 'n' and y > 0:
      y = y-1
  elif m == 'e' and x < (grid-1):
      x = x+1
  elif m == 's' and y < (grid-1):
      y = y+1
  elif m == 'w' and x >0:
      x = x-1
  else:
      print('Invalid move')

  moves = moves + 1


texts:
I don't really have a problem, but my code bothers me, because I know it could be done in a much better way.

I have an enum of 4 directions: north west, north east, south east and south west. And I have a method that converts a vector to one of those directions. The method prefers North and East, so values of 0 would return those.

public enum Direction {
    NORTH_WEST, NORTH_EAST, SOUTH_EAST, SOUTH_WEST;

    public static Direction vectorToDirection(Vector2 vector) {
        if (vector.y >= 0) {
            if (vector.x >= 0) return NORTH_EAST;
            else return NORTH_WEST;
        } else {
            if (vector.x >= 0) return SOUTH_EAST;
            else return SOUTH_WEST;
        }
    }
}

If anyone can figure out a cleaner or more efficient method, I'd love to know!


texts:
This checks if a given username is valid, before doing any database lookups.
(I know it's possibly better to use regular expressions, but I wanted to be able to give specific errors.)
I'm curious if there is a cleaner way to represent the set of valid characters.
bool check_username_valid(const string& str, string &out_error) {
    static const struct LUT {
        bool a[256]{};
        LUT() {
            for (int x = 'a'; x <= 'Z'; x++) a[x] = true;
            for (int x = 'A'; x <= 'Z'; x++) a[x] = true;
            for (int x = '0'; x <= '9'; x++) a[x] = true;
            a['_'] = true;
        }
        inline bool operator [] (char x) const { return a[int(((unsigned char)(x)))]; }
    } allow;

    if (str.length() < MinUsernameLen) { out_error = "Username Too Short"; return false; }
    if (str.length() > MaxUsernameLen) { out_error = "Username Too Long"; return false; }
    for (char c : str)
        if (!allow[c]) {
            out_error = "Invalid Character in Username";
            return false;
        }
    return true;
}


texts: Optimizing Java Anagram checker (compare 2 strings)

texts:
An anagram is like a mix-up of the letters in a string:

  pots is an anagram of stop

  Wilma is an anagram of ilWma

I am going through the book Cracking the Coding Interview and in the basic string manipulation there's the problem:

  write a method to check if two strings are anagrams of each other.

My method uses StringBuffer instead of String because you can .deleteCharAt(index) with StringBuffer/StringBuilder.

public boolean areAnagrams(StringBuffer s1b, StringBuffer s2b) {

    for (int i=0; i<s1b.length(); ++i) {
        for (int j=0; j<s2b.length(); ++j) {

            if (s1b.charAt(i) == s2b.charAt(j)) {

                s1b.deleteCharAt(i);
                s2b.deleteCharAt(j);

                i=0;
                j=0;
            }
        }
    }

    if (s1b.equals(s2b)) {
        return true;
    } else
        return false;

}

I iterate over every character in s1b and if I find a matching char in s2b I delete them both from each string and restart the loop (set i and j to zero) because the length of the StringBuffer objects changes when you .deleteCharAt(index).

I have two questions:

Should I use StringBuilder over StringBuffer (in Java)?
How can I make this faster?

In regards to fasterness:

This method is good in that it doesn't require any additional space, but it sorta destroys the data as you're working on it.  Are there any alternatives that I have overlooked that could potentially preserve the strings but still see if they are anagrams without using too much external storage (i.e. copies of the strings are not allowed -- as a challenge)?

And, if you can use any sort of storage space in addition to this, can one lower the time complexity to \$O(n)\$ (technically \$O(2n)\$) instead of \$O(n^2)\$?

Also, the above code might not compile because I just wrote it from scratch in here; sorry if it's bugg'd.


texts: Color string from object (random if empty, deterministic else)

texts:
from random import random

def to_color(obj=None):
    """Determine a color (string 000000-ffffff) from the hash of any object

    If no argument is passed, a random color is returned.

    Args:
        obj: any hashable object; string, tuple, ...

    Returns:
        a color string in range '000000' to 'ffffff'
    """
    obj = obj if obj else random()
    return "{0:06x}".format(abs(hash(obj)))

My questions:

Is the line obj = obj if obj else random() idiomatic?
Is hash(obj) the "proper" way to get a deterministic yet scrambled string for my purpose?
The abs takes care of negative hash values (e.g. from hashing negative integers). Is there a better way which doesn't collide so easily for small (absolute) integer values? (Right now, to_color(500) is equal to to_color(-500).)


texts: SQL to find table containing all specified columns

texts:
I have the below code to list all tables which have columns DataAreaId and CountryRegionId.
This works, but requires me to change the code in two places if I amend the column list (i.e. both the name in ('DataAreaId','CountryRegionId') code to list the required column names, and also the having COUNT(1) = 2 to match the number of specified columns.

select *
from sys.tables t
where object_id in
(
    select object_id
    from sys.columns c
    where name in ('DataAreaId','CountryRegionId')
    group by object_id
    having COUNT(1) = 2
)
order by Name

I can tweak it to make things more dynamic (i.e. so I only have to define the list of columns; and not have to remember to amend count(1) = 2 to match the number of values as so:

declare @cols table(name sysname)
insert @cols values('DataAreaId'),('CountryRegionId')
select *
from sys.tables t
where object_id in
(
    select object_id
    from sys.columns c
    where name in (select name from @cols)
    group by object_id
    having COUNT(1) = (select COUNT(distinct name) from @cols)
)
order by Name

But that has a bad smell to it / doesn't look elegant.

Any thoughts on how this could be improved, or is this just one of those scenarios where elegance isn't possible?
I'm thinking the seldom used ALL keyword may help somehow; though not sure how.


texts: Take input of delimited file of integers and output result

texts:
I wanted to learn some new language so I developed a really simple vb.net "console application" (was that the right type?) that takes text input, looks at it and multiplies it if it's even and then reads each result into a msgbox.

test.txt = 1 2 3 4 5 6 7 8 9
result should be an array {1 4 3 8 5 12 7 16 9}

This would be my first vb.net programming attempt

Module MyFirstModule
    Sub Main()
        HelloNumbers()
    End Sub

    Private Sub HelloNumbers()
        Dim inputFile As String
        inputFile = "c:\temp\test.txt"
        Dim i As Integer
        Dim readResult As String() = Split(System.IO.File.ReadAllText(inputFile))
        Dim multipliedResult As Integer()
        Dim lower As Integer = LBound(readResult)
        Dim upper As Integer = UBound(readResult)
        ReDim multipliedResult(0 To upper)
        For i = lower To upper
            multipliedResult(i) = MultiplyEvenNumbers(CInt(readResult(i)))
        Next

        For i = lower To upper
            If multipliedResult(i) Mod 2 = 0 Then
                MsgBox(readResult(i) & " was multiplied by two for " & multipliedResult(i))
            Else : MsgBox(readResult(i) & " is original")
            End If
        Next
    End Sub

    Private Function MultiplyEvenNumbers(ByVal inputNumber As Integer) As Integer
        If inputNumber Mod 2 = 0 Then inputNumber = inputNumber * 2
        MultiplyEvenNumbers = inputNumber
    End Function
End Module


texts: Java Slick StateBasedGame managing resources across states

texts:
I was wondering if it's normal/efficient to have this many static collections in my state based game?
I started doing it for ease of access but it looks sloppy to me and I was just wondering what conventions other people use to maintain references to game objects?

public class DungeonDigger extends StateBasedGame {
    public static NetworkPlayer myCharacter;
    public static Server SERVER = new Server();
    public static Client CLIENT = new Client();
    public static int CHOSEN_GAME_STATE;
    public static final int MAINMENU = 0;
    public static final int LOBBY = 3;
    public static final int SINGLEPLAYERDUNGEON = 1;
    public static final int MULTIPLAYERDUNGEON = 2;
    public static String ACCOUNT_NAME;
    public static String IP_CONNECT;
    public static int MAX_MESSAGE_LENGTH = 50;
    public static ConnectionState STATE;
    public static HashMap<String, Image> IMAGES = new HashMap<String, Image>();
    public static ArrayList<TextPacket> TEXTS = new ArrayList<TextPacket>();
    public static LinkedList<ChatPacket> CHATS = new LinkedList<ChatPacket>();
    public static HashMap<String, NetworkPlayer> CHARACTERBANK = new HashMap<String, NetworkPlayer>();
    public static HashSet<String> ACTIVESESSIONNAMES = new HashSet<String>();
    public static HashMap<Integer, String> KEY_BINDINGS = new HashMap<Integer, String>();
    public static HashMap<String, String> SLOT_BINDINGS = new HashMap<String, String>();
    public static HashMap<String, Ability> ABILITY_TEMPLATES = new HashMap<String, Ability>();
    public static HashMap<String, Mob> MOB_TEMPLATES = new HashMap<String, Mob>();
    public static Vector<Ability> ACTIVE_ABILITIES = new Vector<>();
    public static AbilityFactory ABILITY_FACTORY = new AbilityFactory();
    public static MobFactory MOB_FACTORY = new MobFactory();

    public DungeonDigger(String title) {
        super(title);
    }

    // Start game
    public static void main(String[] args) {
        try {
            System.setProperty("org.lwjgl.librarypath", new File(System.getProperty("user.dir"), "natives").getAbsolutePath());
            System.setProperty("net.java.games.input.librarypath", System.getProperty("org.lwjgl.librarypath"));
            AppGameContainer app = new AppGameContainer(new DungeonDigger("Dungeon Digger"));
            app.setDisplayMode(640, 640, false);
            app.setTargetFrameRate(40);
            app.setUpdateOnlyWhenVisible(false);
            app.setAlwaysRender(true);
            app.start();
        } catch (SlickException e) {
            e.printStackTrace();
        }
    }


texts:
I am trying to make an additional option in my beginning calculator program, which is based on the BigDecimal class: the simultaneous solution for the entire operation by order of operations. I want to create methods by myself, however it took me a long time just to create a sketch, and for a moment I wonder if I chose a right way.

Right now, my only concern is the logic of this task, which I will implement in my program later. Does it make any sense to base such options, which will use a variety of number types, on a simple "looking for brackets" and operations on Strings? Does anyone see any flaws in that method?

import java.util.*;

public class OrderOfOperations {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        String w  = result(s);
        System.out.println("Result: "+w);
    }
    public static String before(String s, int i){       //number before operation mark
        String str = s.substring(0,i);
        String num = "";
        for(int b=str.length()-1;b>=0;b--){
            if(b==0 || !Character.isDigit(str.charAt(b-1))&&str.charAt(b-1)!='.'){
                num=str.substring(b);
                break;
            }
        }
        return num;
    }

    public static String after(String s, int i){          //number after operation mark
        String str = s.substring(i+1);
        String num = "";
        for(int a=0;a<=str.length();a++){
            if(a==str.length() || !Character.isDigit(str.charAt(a))&&str.charAt(a)!='.'){
                num=str.substring(0,a);
                break;
            }
        }
        return num;
    }
    public static String result(String s){
        char o = '(';
        char c = ')';
        while(s.contains(Character.toString(o))||s.contains(Character.toString(c))){
            String in;
            if(s.contains(Character.toString(o))){
                System.out.println(s);
                in = s.substring(s.indexOf(o)+1);
                System.out.println("ino: "+in);
                s = s.substring(0, s.indexOf(o))+ result(in);
            }else if(s.contains(Character.toString(c))){
                in = s.substring(0, s.indexOf(c));
                System.out.println("inc: "+in);
                return count(in)+s.substring(s.indexOf(c)+1);
            }
        }
        return count(s);
    }
    public static String count(String s){
        String num1;
        double n1;
        String num2;
        double n2;

        for(int i=0; i<s.length();i++){
            if(s.charAt(i)=='*'||s.charAt(i)=='/'){
                num1 = before(s,i);
                System.out.println("nu1:" +num1);
                num2 = after(s,i);
                System.out.println("nu2:" +num2);
                n1 = Double.parseDouble(num1);
                n2 = Double.parseDouble(num2);
                double res = (s.charAt(i))=='*' ? n1*n2: n1/n2;
                s = s.substring(0,i-num1.length())+res+s.substring(i+num2.length()+1);

                i = 0;
            }
        }
        for(int i=0; i<s.length();i++){
            if(s.charAt(i)=='+'||s.charAt(i)=='-'){
                num1 = before(s,i);
                num2 = after(s,i);
                n1 = Double.parseDouble(num1);
                n2 = Double.parseDouble(num2);
                double res = (s.charAt(i))=='+' ? n1+n2: n1-n2;
                s = s.substring(0,i-num1.length())+res+s.substring(i+num2.length()+1);
                System.out.println("+:" + s);
                i=0;
            }
        }
        return s;
    }
}


texts: Print file out 1 character at a time in the terminal - Python

texts:
This program opens a file and prints the text out to the terminal 1 character at a time and at a predetermined speed using time.sleep()

Simple and maybe, if you think like me, pretty cool..

GitHub

from time import sleep
import sys

BLINK = 0.2
chars_in_line = 50

def open_file(fn):
    with open(fn, "r") as f:
        for line in f:
            if line:
                yield line

def type_out_text_to_line(text, end="", sep="", line_chars=None, blink=0.2):
    if not text:
        return ""

    c = line_chars
    for i, j in enumerate(text):
        sys.stdout.flush()
        sleep(blink)
        print(j, end=end, sep=sep)
        if line_chars:
            if i + 1 == c:
                print()
                c += line_chars
    return ""

print("\n\tSTART PRINTING\n")

for text in open_file('example.txt'):
    if len(text) > 1:
        print(type_out_text_to_line(text, line_chars=chars_in_line, blink=BLINK, sep=""))

print("\n\tEND PRINTING\n")


texts: Mergesort implementation, eliminating slice()

texts:
I am having trouble coming up an alternate solution to my mergesort. I think using slice is an expensive operation. I have two implementations, recursive and iterative.

function mergeSortRecursive(arr) {
// base case
if (arr.length <= 1) {
 return arr;
}

var leftArr =  arr.slice(0, arr.length/2);
var rightArr = arr.slice(arr.length/2);
var leftSorted = mergeSortRecursive(leftArr);
var rightSorted = mergeSortRecursive(rightArr);
// merge subarrays
return merge(leftSorted, rightSorted);
}

mergeSortRecursive([1,4,5,245,7, 3,3,6,31]);

function merge(left, right) {
var result = [];
var indexLeft = 0;
var indexRight = 0;
// while result is not fully populated
while(result.length < (left.length + right.length)) {
  // if all elements in left have been added, then add remaining
right elements
  if (indexLeft === left.length) {
    result = result.concat(right.slice(indexRight));
  }
  // if all elements in right have been added, then add remaining left elements
  else if (indexRight === right.length) {
   result = result.concat(left.slice(indexLeft));
  }
  // compare elements in subarrays and add lower of the two to result
  else if (left[indexLeft] <= right[indexRight]) {
  result.push(left[indexLeft++]);
  } else {
    result.push(right[indexRight++]);
  }
 }
return result;
}

function mergeSortIterative(arr) {
// create an array of subarrays with each element
var splitArr = arr.map(function(element) {
  return [element];
});
// while there is more than one subarray
while (splitArr.length > 1) {
  var result = [];
  // merge adjacent;
  for (var i = 0; i < splitArr.length; i+=2) {
    // for pairs merge
    if (splitArr[i + 1]) result.push(merge(splitArr[i],
 splitArr[i+1]));
    // for last odd element, just add to results
    else result.push(splitArr[i]);
  }
  // overwrite old splitArr
  splitArr = result;
  }
  return splitArr[0];
}


texts: Vector of numbers where merge sort is slow

texts:
I'm starting to study sorting algorithms in Python.
Merge Sort has a complexity at best and worst cases \$\mathcal{O}(n\log{}n)\$, I want generation a list where Merge Sort is slow but I would some complication.
Could you help me with this problem?

This is the code:

def mergeSort(l):

    #print("Splitting ",l)
    if len(l)>1:
        mid = len(l)//2
        lefthalf = l[:mid]
        righthalf = l[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

        i=0
        j=0
        k=0
        while i<len(lefthalf) and j<len(righthalf):
            if lefthalf[i]<righthalf[j]:
                l[k]=lefthalf[i]
                i=i+1
            else:
                l[k]=righthalf[j]
                j=j+1
            k=k+1

        while i<len(lefthalf):
            l[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j<len(righthalf):
            l[k]=righthalf[j]
            j=j+1
            k=k+1
    #print("Merging ",l)
    return


texts: Dictionary Key look up with variable length inputs

texts:
I am decoding GS1 barcodes and need to match up application identifiers with relevant data about them.

00    SSCC (Serial Shipping Container Code)   N2+N18  FALSE   SSCC
01    Global Trade Item Number (GTIN)         N2+N14  FALSE   GTIN
02    GTIN of Contained Trade Items           N2+N14  FALSE   CONTENT
10    Batch or Lot Number                     N2+X.20 TRUE    BATCH/LOT
11    Production Date (YYMMDD)                N2+N6   FALSE   PROD DATE
12    Due Date (YYMMDD)                       N2+N6   FALSE   DUE DATE
13    Packaging Date (YYMMDD)                 N2+N6   FALSE   PACK DATE
15    Best Before Date (YYMMDD)               N2+N6   FALSE   BEST BEFORE or BEST BY
16    Sell By Date (YYMMDD)                   N2+N6   FALSE   SELL BY
17    Expiration Date (YYMMDD)                N2+N6   FALSE   USE BY OR EXPIRY
20    Variant Number                          N2+N2   FALSE   VARIANT
21    Serial Number                           N2+X.20 TRUE    SERIAL
240   Additional Item Identification          N3+X.30 TRUE    ADDITIONAL ID
241   Customer Part Number                    N3+X.30 TRUE    CUST. PART NO.
242   Made-to-Order Variation Number          N3+N.6  TRUE    MTO VARIANT
243   Packaging Component Number              N3+X.20 TRUE    PCN
250   Secondary Serial Number                 N3+X.30 TRUE    SECONDARY SERIAL
251   Reference to Source Entity              N3+X.30 TRUE    REF. TO SOURCE
253   Global Document Type Identifier (GDTI)  N3+N13+XTRUE    GDTI
254   GLN Extension Component                 N3+X.20 TRUE    GLN EXTENSION COMPONENT
255   Global Coupon Number (GCN)              N3+N13+NTRUE    GCN
30    Count of Items (Variable Measu ...      N2+N..8 TRUE    VAR. COUNT
3100  Net weight  kilograms (Var... )     N4+N6   FALSE   NET WEIGHT (kg)
...

Full list here.

This is how I identify them:

public Dictionary<int, Tuple<string, string, bool, string>> gs1AiDict { get; private set; }

var aiDataOut = new Tuple<string, string, bool, string>("","",false,"");

//Get first 4 digits (max identifier length)
//the string input pi might look like this: ~10000123
int applicationIdentifier = Convert.ToInt16(pi.Substring(1,4));
//Try to find an identifier with 2 digits.
if (gs1AiDict.TryGetValue(applicationIdentifier / 100, out aiDataOut))
{
    //assign found data to tuple
    id = aiDataOut.Item1;
    format = aiDataOut.Item2;
    func = aiDataOut.Item3;
    abrv = aiDataOut.Item4;
}
//look up the first 3 digits
else
{
    if (gs1AiDict.TryGetValue(applicationIdentifier / 10, out aiDataOut))
    {
        id = aiDataOut.Item1;
        format = aiDataOut.Item2;
        func = aiDataOut.Item3;
        abrv = aiDataOut.Item4;
    }
    //look up first 4 digits
    else
    {
        if (gs1AiDict.TryGetValue(applicationIdentifier, out aiDataOut))
        {
            id = aiDataOut.Item1;
            format = aiDataOut.Item2;
            func = aiDataOut.Item3;
            abrv = aiDataOut.Item4;
        }
        //no identifiers are 5 digits
        else
        {
         console.log("No Application Identifier found!");
        }
    }
}

My tests have worked wonderfully, but my issue is the readability and efficiency of this solution. Are 3 dictionary key look ups for about 140 keys too much?


texts: Functional tests for a web app repeating the same code

texts:
My problem/concern is that I am trying to remove duplicate code from my functional tests without breaking the Page Object Pattern that I am following.

If you look at the code below, you will notice that 4 lines are constantly repeated in my tests, breaking the DRY principle - they are marked with a "todo" comment. But the problem is that the methods belong to 2 different Page Objects/classes. Therefore, I don't know how to condense this code because it doesn't belong in either page since it uses 2 different pages.

I'm following the Single Responsibility Principle that the Page Object class actually represents a single web page through my code, essentially doing 1 thing. I don't want to break this principle in order to condense my code. But I also don't want to maintain this duplicate code throughout a bunch of my tests.

The problem my code solves is that they are tests written against a GUI to exercise the functionality under test.

using Automation.Pages;
using NUnit.Framework;

namespace Automation.Tests
{
[TestFixture, Author("nikolay"), Category("LL"), Property("FunctionalityTested","ShortTextPopUp")]
class ShortTextPopupTests : BaseTest
{
    [Test]
    [Retry(2)]
    [Description("Validate that the pop up can open and close when it is clicked.")]
    public void GivenCorrectItemIsOpened_WhenTogglingPopup_ThenPopupOpensAndCloses()
    {
        //todo these 4 lines are repeated everywhere for the setup of this test
        var adminLoginPage = new ENAEPAdminLoginPage(Driver);
        adminLoginPage.GoToAndLoginWithOperationalBookletSupervisor();
        var adminResetPage = new AdminResetPage(Driver);
        var studentAssessmentPage = adminResetPage.GoToSpecificBookletLocation(BookletLocations.ShortTextPopup);

        studentAssessmentPage.ShortTextPopup.OpenPopUp();
        studentAssessmentPage.ShortTextPopup.ClosePopUp();
        Assert.IsFalse(studentAssessmentPage.ShortTextPopup.IsPopUpOpen(), "The pop up did not close after trying to close the pop up");
    }

    [Test]
    [Retry(2)]
    [Description("Validate that opening a pop up, clicking next, coming back to a page, closes that opened pop up")]
    public void NavigationToDifferentPageClosesPopup()
    {
        //todo these 4 lines are repeated everywhere for the setup of this test
        var adminLoginPage = new ENAEPAdminLoginPage(Driver);
        adminLoginPage.GoToAndLoginWithOperationalBookletSupervisor();
        var adminResetPage = new AdminResetPage(Driver);
        var studentAssessmentPage = adminResetPage.GoToSpecificBookletLocation(BookletLocations.ShortTextPopup);

        studentAssessmentPage.ShortTextPopup.OpenPopUp();

        studentAssessmentPage.ENAEPToolBar.ClickNextButton();
        studentAssessmentPage.ENAEPToolBar.ClickBackButton();
        Assert.IsFalse(studentAssessmentPage.ShortTextPopup.IsPopUpOpen(), "The pop up did not close after leaving and coming back to the page.");
    }

    [Test]
    [Retry(2)]
    [Description("Opening a short text pop up and then clicking on other things on the page should not close the pop up.")]
    [Property("TCID", "35458")]
    public void ClickingItemsOnScreenShouldNotClosePopUps()
    {
        //todo these 4 lines are repeated everywhere for the setup of this test
        var adminLoginPage = new ENAEPAdminLoginPage(Driver);
        adminLoginPage.GoToAndLoginWithOperationalBookletSupervisor();
        var adminResetPage = new AdminResetPage(Driver);
        var studentAssessmentPage = adminResetPage.GoToSpecificBookletLocation(BookletLocations.ShortTextPopup);

        studentAssessmentPage.ShortTextPopup.OpenPopUp();
        studentAssessmentPage.ClickRandomPlacesOnPage();
        Assert.IsTrue(studentAssessmentPage.ShortTextPopup.IsPopUpOpen(), "The popup did not stay open after clicking in random places in the assessment.");
    }
}

}


texts:
I've been working on a simple login script. The registration part is still to be coded, but I'm done the login part. Are there any security holes in my code? I'm using SHA-512 right now but I think I'll change it to mcrypt later.

Class User
{
    private $db;

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

    public function Login($user_email, $user_pass, $remember = false)
    {
        $user_pass = sha1($user_pass);
        $query = $this->db->prepare("SELECT id, password FROM users WHERE email = :email");
        $query->bindValue(':email', $user_email);
        $query->execute();

        if($query->rowCount() > 0) {
            $user = $query->Fetch(PDO::FETCH_OBJ);
            if($user->password == $user_pass) {
                $_SESSION['loggd_id'] = $user->id;
                if($remember == true) {
                    setcookie('lggd_sess', hash('sha512', uniqid()), 84600);
                    return true;
                }
                return true;
            } else {
                return 'Incorrect Email/Password Combination.';
            }
        } else {
            return 'Incorrect Email/Password.';
        }

    }
}


texts:
I'm very new to coding and decided to try a mini-project in python to create a 'guess the number game'. I was just hoping for some feedback on my code-writing to prevent bad habits before they develop. This program runs smoothly but I would like to know if there are improvements I could make.
In particular:

How can I improve the efficiency and readability?
Is it okay to call a function within its own body?
Is there any ugly implementation that I should avoid?

import random

number = 0
counter = 0

def start_game():
    print("I'm thinking of a number between 1 and 10.")
    print("Can you guess it?")
    global number
    number = random.randint(1,10)
    global counter
    counter = 0
    check_valid()

def check_valid():
    global counter
    counter += 1
    guess = input()
    try:
        val = int(guess)
        if int(guess) not in range(0,11):
            print("Hmmm.. that number is not between 1 and 10! Try again!")
            check_valid()
        elif int(guess) > number:
            print("Too high, try a smaller number")
            check_valid()
        elif int(guess) < number:
            print("Too low, try a bigger number")
            check_valid()
        elif int(guess) == number:
            print("Congratulations, you guessed it! The number was " +
                  str(number) + ".\nIt took you " + str(counter) + " tries!")
            print("Do you want to play again?")
            check_replay()
    except ValueError:
        print("That's not a number, try again!")
        check_valid()

def check_replay():
    answer = input()
    valid_yes = ["yes", "ye", "y"]
    valid_no = ["no", "n"]
    if answer.lower() in valid_yes:
        start_game()
    elif answer.lower() in valid_no:
        print("Thanks for playing!")
    else:
        print("Please enter yes or no")
        check_replay()

start_game()


texts:
I have a method which I use on occasion to convert strings (like enum and property names) to PascalCase for display.

It's fairly simple, so there's probably not much to comment on, but as usual I appreciate any advice on improving it.

/// <summary>
/// Converts a string of dash-separated, or underscore-separated words to a PascalCase string.
/// </summary>
/// <param name="s">The string to convert.</param>
/// <returns>The resulting PascalCase string.</returns>
public static string ToPascalCase(this string s)
{
    string[] words = s.Split(new char[2] { '-', '_' }, StringSplitOptions.RemoveEmptyEntries);

    StringBuilder sb = new StringBuilder(words.Sum(x => x.Length));

    foreach (string word in words)
    {
        sb.Append(word[0].ToString().ToUpper() + word.Substring(1));
    }

    return sb.ToString();
}

Feel free to use it if you like, as per my usual regards.


texts:
I am just starting to get my feet wet with C; and am rather enjoying myself in doing so. This is sort of a follow up to my last question here. I am posting this ordinate to hopefully getting some feedback on the logic itself, and possibly also some feedback on coding style. I do, however insist on making everything explicit. I'm not a huge fan of implicit anything... Maybe that's something I need to get over?

#include <stdio.h>

typedef enum {
    false = (int) 0, true = (int) 1
} bool;

inline void set_bit(register unsigned int *x,
        register const unsigned short int offset, register const bool value) {
    if (value)
        *x |= (1 << offset);
    else
        *x &= ~(1 << offset);
}

inline bool get_bit(register const unsigned int x,
        register const unsigned short int offset) {
    return (x & (1 << offset)) != 0;
}

int main(void) {
    unsigned int x = 0;
    int count;
    for (count = 0; count < 8; count += 2)
        set_bit(&x, count, true);
    for (count = 7; count >= 0; count--)
        printf("%d ", (int) get_bit(x, count));
    printf("\n");
    return 0;
}


texts: Find the square root of the number without using any built-in function?

texts:
I am working on below problem:

  Given an integer, how do you find the square root of the number
  without using any built-in function?

  private static double computeSquareRootBinarySearch(double x, double precision) {
    double start = 0;
    double end = x / 2 + 1;
    double mid = (start + ((end - start) / 2));
    double prevMid = 0;
    double diff = Math.abs(mid - prevMid);

    while ((mid * mid != x) && (diff > precision)) {
      if (mid * mid > x) {
        end = mid;
      } else {
        start = mid;
      }
      prevMid = mid;
      mid = (start + end) / 2;
      diff = Math.abs(mid - prevMid);
    }
    return mid;
  }

I came up with above binary search algo but wanted to see if there is any optimization I can do in above algorithm?


texts: My first RSpec test - Rock Paper Scissors

texts:
I'm relatively familiar to Ruby, but I'm brand-new to testing code. I've decided to use RSpec because as it seems like a popular option.

The game works perfectly, but the spec has a lot of repetition and I have a feeling it can be improved.

The Spec

require 'rock_paper_scissors'

# game = RockPaperScissors.new('rock')
# game.result => ['win!', 'lose!', 'tie!']
#
# 1 == rock
# 2 == paper
# 3 == scissors

describe "Rock Paper Scissors" do
  let(:answers_snippet) { /valid answers/ }

  context "when a number is passed" do

    it "fails when invalid" do
      game = RockPaperScissors.new(0)
      game.result.should match(answers_snippet)
    end

    it "passes when valid and convert to string value" do
      game = RockPaperScissors.new(1)

      game.result.should_not match(answers_snippet)
      game.choice.should == "rock"
    end
  end

  context "when a string is passed" do

    it "fails when invalid" do
      game = RockPaperScissors.new('cheese')
      game.result.should match(answers_snippet)
    end

    it "passes when valid" do
      game = RockPaperScissors.new('rock')
      game.result.should_not match(answers_snippet)
    end
  end

  it "should tie when rock vs rock" do
    RockPaperScissors.any_instance.stub(:random_choice).and_return('rock')

    game = RockPaperScissors.new('rock')
    game.result.should == "tie!"
  end

  it "rock should beat scissors" do
    RockPaperScissors.any_instance.stub(:random_choice).and_return('scissors')

    game = RockPaperScissors.new('rock')
    game.result.should == "won!"
  end

  it "paper should beat rock" do
    RockPaperScissors.any_instance.stub(:random_choice).and_return('rock')

    game = RockPaperScissors.new('paper')
    game.result.should == "won!"
  end

  it "scissors should beat paper" do
    RockPaperScissors.any_instance.stub(:random_choice).and_return('paper')

    game = RockPaperScissors.new('scissors')
    game.result.should == "won!"
  end

end

I've created a gist that has both the Rock Paper Scissors class and RSpec tests.


texts:
I needed to implement a stop watch like class that will be used to measure running time of different functions by others. The final running time needs to be printed in 9h 3min 2s 23s 32ms 87us 78ns format. If the larger units are zero then they must be omitted. Time duration in a particular time-unit like seconds or milliseconds can be obtained from functions similar to hours. I need better ideas to improve the implementation.

#ifndef _STOP_WATCH_HPP_
#define _STOP_WATCH_HPP_

#include <chrono>
#include <utility>
#include <iostream>

class stop_watch {
    std::chrono::high_resolution_clock::time_point last_time_point;
    std::chrono::duration<double> time_duration;
    bool is_running;
  public:
    stop_watch() :
      last_time_point {std::chrono::high_resolution_clock::now()},
      time_duration {std::chrono::duration<double>::zero()},
      is_running {false}
      {}
    void start() {
      assert(!is_running); // stop watch is already running
      last_time_point = std::chrono::high_resolution_clock::now();
      time_duration = std::chrono::duration<double>::zero();
      is_running = true;
    }
    void stop() {
      assert(is_running); // stop watch is not running
      auto n = std::chrono::high_resolution_clock::now();
      time_duration = n - last_time_point;
      last_time_point = n;
      is_running = false;
    }
    double hours() {
      return std::chrono::duration_cast<std::chrono::hours>(
          time_duration).count();
    }
    friend std::ostream& operator<<(std::ostream& out, stop_watch sw) {
      std::chrono::hours h = std::chrono::duration_cast<
          std::chrono::hours>(sw.time_duration);
      if (h.count()) {out << h.count() << "h "; sw.time_duration -= h;}
      std::chrono::minutes m = std::chrono::duration_cast<
          std::chrono::minutes>(sw.time_duration);
      if (m.count()) {out << m.count() << "min "; sw.time_duration -= m;}
      std::chrono::seconds s = std::chrono::duration_cast<
          std::chrono::seconds>(sw.time_duration);
      if (s.count()) {out << s.count() << "s "; sw.time_duration -= s;}
      std::chrono::milliseconds ms = std::chrono::duration_cast<
          std::chrono::milliseconds>(sw.time_duration);
      if (ms.count()) {out << ms.count() << "ms "; sw.time_duration -= ms;}
      std::chrono::microseconds us = std::chrono::duration_cast<
          std::chrono::microseconds>(sw.time_duration);
      if (us.count()) {out << us.count() << "us "; sw.time_duration -= us;}
      std::chrono::nanoseconds ns = std::chrono::duration_cast<
          std::chrono::nanoseconds>(sw.time_duration);
      if (ns.count()) {out << ns.count() << "ns "; sw.time_duration -= ns;}
      return out;
    }
};

#endif

Sample usage

stop_watch sw;
sw.start();
// function(s) to measure time
sw.stop();
cout << "It took " << sw << endl;

I need some guideline on how to do this more efficiently, as my code is already too messy :(. I also have the following questions:

Is there a way to generate the functions for hours, seconds, etc. dynamically?
How can I improve the operator<< function? Is there a way to have a list of time units that I can iterate?


texts:
I'm in the process of cross-training myself from CFML to PHP as part of a learning exercise. I'm learning from the docs and online tutorials and googling.

As an initial exercise, I've knocked together the following PHP facsimile of some CFML code I have. I have a blog article explaining the requirement for the code. This is basically a work-around for the fact that the inbuilt PHP web server does not do directory browsing.

I'm just posting the PHP here in case anyone can make observations about how I might improve it. I'm more after PHP-specific info than coding structure "advice", but any observations one might make will be taken on board.

<?php
    // directory to create listing for, defaulting to the current one
    if (array_key_exists("dir", $_GET)){
        $dirCurrent = $_GET["dir"];
    }else{
        $dirCurrent = getcwd();
    }

    // sort out some baseline dirs / URLs
    $dirCurrent = realpath($dirCurrent);
    $dirBase    = realpath($_SERVER["DOCUMENT_ROOT"]);
    $urlBase    = "http://" . $_SERVER["HTTP_HOST"];

    if (strpos($dirCurrent, $dirBase) !== false && file_exists($dirCurrent)){
        // Used for building links to files
        $relativePath = str_replace($dirBase, "", $dirCurrent);
        $urlPath = str_replace("\\", "/", $relativePath);

        // provide a link to go up a level
        $parentDir = preg_replace("#[\\\/][^\\\/]+$#", "", $dirCurrent);
        $parentLinkUrl = $_SERVER["SCRIPT_NAME"] . "?dir=" . $parentDir;
        echo "[Parent Directory]
";

        echo "
";
        opendir($dirCurrent);
        while ($entry = readdir()) {
            if (in_array($entry, [".", ".."])){    // skip these two
                continue;
            }
            $linkText = $entry;
            $wholePathToFile = $dirCurrent . DIRECTORY_SEPARATOR . $entry;
            if (is_dir($wholePathToFile)){
                // we just want to link back to this file, passing the dir
                $linkUrl = $_SERVER["SCRIPT_NAME"] . "?dir=" . $wholePathToFile;
                $linkText .= "/"; // just to make it more clear it's a dir
            }else{
                // we want a link to the actual file
                $linkUrl = $urlPath . "/" . $entry;
            }
            echo "
$linkText
";
        }
        closedir();
        echo "
";
    }else{
        header("HTTP/1.0 404 Not Found");
    }
?>


texts:
I'm new to programming and just made a basic calculator on my own.

Can anyone see if there is any room for improvement in the code, like stuff i should do different.

package calculator;

import java.util.Scanner;

public class Main {

static Scanner userInput = new Scanner(System.in);

public static void main(String[] args) {
    float numOne;
    float numTwo;
    float answer = 0;
    String option;
    boolean loop = true;

    while(loop==true){
    System.out.print("Addition, Subtraction, Multiplication or Division? (WRITE ONLY IN LOWERCASE!) \n Type:");
    option = userInput.next();
    if(option.equals("addition")){
        System.out.print("Enter your first number: ");
        numOne = userInput.nextFloat();
        System.out.print("Enter your second number: ");
        numTwo = userInput.nextFloat();
        answer = addition(numOne, numTwo);
        getAnswer(answer);
    }else if(option.equals("subtraction")){
        System.out.print("Enter your first number: ");
        numOne = userInput.nextFloat();
        System.out.print("Enter your second number: ");
        numTwo = userInput.nextFloat();
        answer = subtraction(numOne, numTwo);
        getAnswer(answer);
    }else if(option.equals("multiplication")){
        System.out.print("Enter your first number: ");
        numOne = userInput.nextFloat();
        System.out.print("Enter your second number: ");
        numTwo = userInput.nextFloat();
        answer = multiplication(numOne, numTwo);
        getAnswer(answer);
    }else if(option.equals("division")){
        System.out.print("Enter your first number: ");
        numOne = userInput.nextFloat();
        System.out.print("Enter your second number: ");
        numTwo = userInput.nextFloat();
        answer = division(numOne, numTwo);
        getAnswer(answer);
    }else{
        System.out.println("Error! unvalid option chosen!");
    }
    System.out.println("Do you whish to quit? (if so, do /quit but if not, type /continue)\ntype: ");
    option = userInput.next();

    if(option.equals("/quit")){
        loop = false;
    }

    }

    }

static float addition(float numX, float numY){
    float finalNum;
    finalNum = numX + numY;
    return finalNum;
}

static float subtraction(float numOne, float numTwo){
    float finalNum;
    finalNum = numOne - numTwo;
    return finalNum;
}

static float multiplication(float numOne, float numTwo){
    float finalNum;
    finalNum = numOne * numTwo;
    return finalNum;
}

static float division(float numOne, float numTwo){
    float finalNum;
    finalNum = numOne / numTwo;
    return finalNum;
}

static void getAnswer(float finalAnswer){
    System.out.println("The answer is " + finalAnswer);
}

}


texts: Converts Pandas and Numpy into Dictionary and Converts back to original format for data split

texts:
I'm trying to refactor some code so that it does not have so much repetition to it. What I'm trying to do is create an input for a multiple channel/input neural network. The features that are being considered come from two different sources completely and the inputA here is a 2D array and has to be kept in this format.
I have the following code:
'Create Input Values'
inputA= word_embeddings.numpy()
inputB = df['Features'].values
y = df['Target'].values

full_model_inputs = [inputA, inputB]

#Create Dictionary
original_model_inputs = dict(inputA= inputA, inputB= inputB)

'Create Train and Validation Data from Inputs'
#Preserve data dimensionality for data split
df = pd.DataFrame({"inputA":original_model_inputs["inputA"],
                   "inputB":list(original_model_inputs["inputB"])})

#Data Split
x_train, x_valid, y_train, y_valid = train_test_split(df, y, test_size = 0.25)

#Convert back to original format
x_train = x_train.to_dict("list")
x_valid = x_valid.to_dict("list")

#Format dictionary items as arrays to be functional for model
x_train = {k:np.array(v) for k,v in x_train.items()}
x_valid = {k:np.array(v) for k,v in x_valid.items()}

Are there any suggestions to improve this code? Just want some insight from the community.
what the dictionary looks like:
{'inputA': array([40., 68., 46., ..., 60., 42., 50.]),
 'inputB': array([[-1.915694  , -2.39863253, -1.75456583, ...,  2.11158562,
          2.42145038,  1.0996474 ],
        [-1.99583805, -2.38059568, -1.94454968, ...,  2.14585209,
          2.56227231,  1.2808286 ],
        [-2.1607585 , -2.29914975, -1.85722673, ...,  2.04741383,
          2.34712863,  1.77104282],
        ...,
        [-2.1576829 , -2.28505015, -1.71492636, ...,  2.05909061,
          2.43704724,  1.90647388],
        [-1.81904769, -2.74457788, -2.15936947, ...,  2.31333733,
          2.50243115,  1.75907826],
        [-2.01300311, -2.32310271, -2.00470185, ...,  2.09641671,
          2.53372359,  1.22000134]])}


texts: Using Models and Entities in MVP pattern

texts:
I'm a beginner in MVP design pattern and In a MVP triad, I have

Model - AdvanceInfo

View - AdvanceForm

Presenter - AdvancePresneter

and Entity class Advance as follows.

 public class Advance
{
    public int AdvanceID { get; set; }
    public decimal AdvanceAmount { get; set; }
    public DateTime AdvanceEnteredDate { get; set; }
    public DateTime AdvanceProcessDate { get; set; }
}

So Should my model be as follows...

class AdvanceInfo
{
    public int AdvanceID  { get { return Advance.AdvanceID; } }
    public decimal AdvanceAmount { get { return Advance.AdvanceAmount; } set { Advance.AdvanceAmount = value; } }
    public DateTime AdvanceEnteredDate  { get { return Advance.AdvanceEnteredDate; } set { Advance.AdvanceEnteredDate = value; } }

    public int EmployeeID { get; set; }
    public string NameWithInitials { get; set; }
    public string BankAccountName { get; set; }
    public string BankAccountNumber { get; set; }

    public Advance Advance = new Advance();
}

or else...

class AdvanceInfo
{
    public int AdvanceID { get; set; }
    public decimal AdvanceAmount { get; set; }
    public int EmployeeID { get; set; }
    public string NameWithInitials { get; set; }
    public string BankAccountName { get; set; }
    public string BankAccountNumber { get; set; }
    public DateTime AdvanceEnteredDate { get; set; }
    public DateTime AdvanceProcessDate { get; set; }

}

Note:
* I'm using entity class Advance as an aggregate class in DeductionInfo class as well.
* I'm not using any frameworks like EF. Only VS. (Since this is academic purpose project)

I hope my question is clear; actually what I want to know is how entity classes are used to build model? or else can we use Model classes alone?


texts:
I am a beginner in PHP-OOP and design patterns. I have got this basic piece of code in Singleton Pattern and I changed it in order to understand its behavior. I can see that it works as expected.

However, it is not clear for me exactly how it works. Can anyone explain me? So it is working! My doubt is "Whis $inst is not always null in the if since I am defining it null before entering the if"?

<?php

final class UserFactory // "final" prevents child classes from overriding a method by prefixing the definition
{
    private $state=1;

    /**
     * Call this method to get singleton
     *
     * @return UserFactory
     */
    public static function Instance()
    {
        static $inst = null;
        if ($inst === null) {
            $inst = new UserFactory();
        }
        return $inst;
    }

    private function __construct()
    {

    }

    public function addToState(){
        $this->state=$this->state+1;
    }
    public function getState(){
        return $this->state;
    }
}

// $myFactory=new UserFactory(); //Throws an error

$myFactory=UserFactory::Instance();
print_r($myFactory);

echo "
";
echo 'myState: '.$myFactory->getState()."
";

$myFactory->addToState();

echo 'myState: '.$myFactory->getState()."
";

$myFactory2=UserFactory::Instance();
print_r($myFactory2);

?>

The output is:

UserFactory Object ( [state:UserFactory:private] => 1 )
myState: 1
myState: 2
UserFactory Object ( [state:UserFactory:private] => 2 ) UserFactory Object ( [state:UserFactory:private] => 2 )


texts:
I am working on the following script for python2.7 which "works" on small files.

I ran a sample on an input file of 188kB and it took approx. 1.15 min to complete. However, I need to process a 5GB file using this script and I did the math, it will take 11.48 years to finish it the way it is now.

sample input1

aba_transit_number  com
abaca   plt|sub|sub|sub
abacus  art|art
abalone anm
abamp   qud

sample input2

zoonosis-n  of+n-j+n-the-development-n
zoonosis-n  of+n-j+n-the-j-collection-n 1
zoonosis-n  of+n-j+n-the-j-success-n    1

Can someone provide me insight on how to optimize my script for computation speed??

    #!/usr/bin/python
    # -*- coding: utf-8 -*-

    from __future__ import division
    from collections import defaultdict, Counter
    import codecs
    import random

    mapping = dict()

#### takes as input a file with the following input1:

    with codecs.open ("input1", "rb", "utf-8") as oSenseFile:
        for line in oSenseFile:
            concept, conceptClass = line.split()
            mapping[concept + '-n'] = conceptClass

    lemmas = set()

#### takes as input2 a file with the following format

    with codecs.open('input2', "rb", "utf-8") as oIndexFile:
        for line in oIndexFile:
            lemma = line.split()[0]
            if lemma in mapping.keys():
                lemmas.add(lemma)

### randomly splits input2 into 2 files -- 80% and 20%
# -- and prints the 20% directly  into out 2 for the other 80%
# --- it matches each 1st column in input2 with the first column in input 1
# -- if it is a match - it replaces it with the corresponding value in Col2 of  Input1
# --- if there is more than one volume in Col2 of Input 1
# -- it prints all of the possible combinations and divides the freq (Col4 in Input2)
# by the number of values present

        training_lemmas = random.sample(lemmas, int(len(lemmas) * 0.8))

    classFreqs = defaultdict(lambda: Counter())

    with codecs.open('out1', 'wb', 'utf-8') as testOutfile:
        with codecs.open('input2', "rb", "utf-8") as oIndexFile:
            for line in oIndexFile:
                lemmaTAR, slot, filler, freq = line.split()
                if lemmaTAR in training_lemmas:
                    senses = mapping[lemmaTAR].split(u'|')
                    for sense in senses:
                        classFreqs[sense][tuple([slot, filler])] += int(freq) / len(senses)
                elif lemmaTAR in lemmas:
                    testOutfile.write(line)

    with codecs.open('out2', 'wb', 'utf-8') as oOutFile:
        for sense in sorted(classFreqs.keys()):
            for slotfill in classFreqs[sense].keys():
                 string_slotfill = '\t'.join(list(slotfill))
                 outstring = '\t'.join([sense, string_slotfill, str(classFreqs[sense][slotfill])])
                 oOutFile.write(outstring + '\n')


texts: Function to return the closest Date to Today (inclusive) from Ordered list

texts:
The way I've written this feels clunky. Particularly, it feels like I shouldn't need to have both a 'dateToCheck' and 'selectedDate' variables.

The objective is to find the Date in a list that is the closest to today (inclusive), with a preference for dates in the future.

The list is guaranteed to be passed in, in descending order.

The list can contain dates in the future...all the way to anytime in the past. Or just dates in the future. Or just today. Or just dates in the past. Anything...

Here is my working version:

Public Shared Function GetClosetDateToToday(lstOrderedDates As List(Of Date)) As Date

    ' Select the closest Delivery date to TODAY (inclusive) from the list of Ordered dates
    If lstOrderedDates.Count > 1 Then
        Dim dateToCheck = lstOrderedDates.ElementAt(1)
        Dim selectedDate = lstOrderedDates.ElementAt(0)
        For i = 1 To lstOrderedDates.Count - 1

            If dateToCheck < Date.Now.Date Then
                Exit For
            End If

            If dateToCheck >= Date.Now.Date Then
                selectedDate = dateToCheck
            End If

            If i + 1 < lstOrderedDates.Count Then
                dateToCheck = lstOrderedDates.ElementAt(i + 1)
            End If
        Next i
        Return selectedDate
    ElseIf lstOrderedDates.Count = 1 Then
        Return lstOrderedDates.First()
    End If

    Return Nothing
End Function

Is there a better way?


texts: Functional, but not recursive, tree traversal

texts:
To learn tree traversal i implemented os.walk, tail-recursive and stack-based. Unfortunately Python doesn't support tail call optimization. How do i rewrite my function so that it is maximally functional paradigm compliant? I want to keep side-effects to minimum yet not dive into deep recursions.

def walk_rec(path):
    def i(result, stack):
        if not stack:
            return result
        else:
            path = stack.pop()
            with cd(path):
                ds, fs = partition(isdir, listdir(path))
            stack.extend(join(path, d) for d in ds)
            result.append((path, ds, fs))
            return i(result, stack)
    return i([], [expanduser(path)])

def walk_iter(path):
    stack = [expanduser(path)]
    result = []
    while stack:
        path = stack.pop()
        with cd(path):
            ds, fs = partition(isdir, listdir(path))
        stack.extend(join(path, d) for d in ds)
        result.append((path, ds, fs))
    return result

See: cd, partition.

I could get rid of cd, but this is not critical.

with cd(path):
    ds, fs = partition(isdir, listdir(path))
# can be replaced with
ds, fs = partition(lambda d: isdir(join(path, d)),
                   listdir(path))


texts:
My external sort function works but it is way too slow. I think the bottleneck is the merge function. How can I make it faster. Is there a better merge function I can use for merging into a file using random access file objects and buffers?

private static void merge(String a, String b,
int l, int m, int r)throws FileNotFoundException, IOException
{
    RandomAccessFile a1f = new RandomAccessFile(a,"rw");
    RandomAccessFile b1f = new RandomAccessFile(b,"rw");
    a1f.seek(l*4);
    b1f.seek(l*4);

    for(int i = l; i<m;i++){
        a1f.seek(i*4);
        b1f.seek(i*4);
        int num = a1f.readInt();
        b1f.writeInt(num);
    }

    for(int j=m; j<r; j++){
        a1f.seek((m + r - j - 1)*4);
        b1f.seek(j*4);
        int num = a1f.readInt();
        b1f.writeInt(num);
    }
    int i = l;
    int j = r - 1;

    //for (int i = l; i < m; i++) b[i] = a[i];
    //for (int j = m; j < r; j++) b[j] = a[m + r - j - 1];
    //if (b[j] < b[i]) a[k] = b[j--];
    //else a[k] = b[i++];

    for (int k = l; k < r; k++){
        b1f.seek(j*4);
        int b_j = b1f.readInt();
        b1f.seek(i*4);
        int b_i = b1f.readInt();
        if(b_j<b_i){
            b1f.seek((j--)*4);
            a1f.seek(k*4);
            a1f.writeInt(b1f.readInt());
        }
        else{
            b1f.seek((i++)*4);
            a1f.seek(k*4);
            a1f.writeInt(b1f.readInt());
        }

    }

    a1f.close();
    b1f.close();
}


texts:
Can this be simplified in any way?

if ($('.content').length && (document.referrer.search('page1.html') > 0) ||
    $('.content').length && (document.referrer.search('page2.html') > 0) ||
    $('.content').length && (document.referrer.search('page3.html') > 0) ||
    $('.content').length && (document.referrer.search('page4.html') > 0) ||
    $('.content').length && (document.referrer.search('page5.html') > 0) ||
    $('.content').length && (document.referrer.search('page6.html') > 0) ||
    $('.content').length && (document.referrer.search('page7.html') > 0) ||
    $('.content').length && (document.referrer.search('search/?') > 0)) {
        window.location.href = document.referrer;
};


texts: F# Operation Framework (Railway-Oriented Programming + Task/Async/Lazy)

texts:
I recently published the initial version of what is effectively my first open-source software package, a Railway-Oriented Programming Framework for F# that encapsulates Tasks, Async Workflows, and Lazy Computations (as well as any code written inside an operation {} computation as "Operations" and provides a library for working with Operations and their Results.

I have published the source for the project on GitHub, and I am looking for feedback on the design of the framework, the implementation of the OperationBuilder (effectively using Tasks behind the scenes) and any possible use-cases I have missed that could also be encapsulated as Operations.  The github project has some documentation and examples in the readme, but the basic way the framework is used is as follows:

let readFile (fileName: string) =
    operation {
        use fileStream = new StreamReader(fileName)
        return! fileStream.ReadToEndAsync()
    }

This returns an Operation<string,exn>.  An Operation is a type representing a computation, which can be either Completed, InProcess, Deferred, or Cancelled.

type Operation<'result,'event> =
| Completed of OperationResult<'result,'event>
| InProcess of InProcessOperation<'result,'event>
| Deferred of EventingLazy<Operation<'result,'event>>
| Cancelled of 'event list

Operations that are not completed or cancelled can be completed by calling Operation.wait or Operation.waitAsync.  Multiple Operations can be executed concurrently by calling Operation.Parallel.  Operation Results are either Success or Failure, and the Failure event type is assumed to be System.Exception unless a domain event is explicitly used in the Operation computation or in another Operation called by the computation.

type OperationResult<'result,'event> =
| Success of SuccessfulResult<'result,'event>
| Failure of 'event list

Operations and their Results can be used in other Operation computations, or acted upon by a set of functions provided in the framework, such as Operation.ok to test if an Operation was successful or Result.either which maps an OperationResult with one function if it was successful or another function if it failed.

Domain events are propagated from one Operation to another, such as in the following example:

type FileAccessEvents =
| FileOpenedSuccessfully
| FileReadSuccessfully
| FileNotFound of string
| UnhandledException of exn // This is returned automatically if an unhandled exception is thrown by an Operation

let getFile (fileName: string) =
    operation {
        let file = FileInfo fileName
        return! if not file.Exists
                then Result.failure [FileNotFound file.FullName]
                else Result.success file
    }

let openFile fileName =
    operation {
        let! file = getFile fileName
        return! file.OpenText() |> Result.successWithEvents <| [FileOpenedSuccessfully]
    }

let readFile fileName =
    operation {
        use! fileStream = openFile fileName
        let! fileText = fileStream.ReadToEndAsync()
        return! Result.successWithEvents fileText [FileReadSuccessfully]
    }

Calling readFile with a valid file path returns an Operation that, when completed, contains the text from the file and the events [FileOpenedSuccessfully; FileReadSuccessfully].

When returning to a user interface or a non-ROP caller, the Operation can be passed to Operation.returnOrFail to either return the successful result or raise an exception based on the failure.


texts:
There are a several articles about true data access in MVC. I tried to make the best one according to the architecture flexibility. My way is following:

ADO .NET Entity Data Model (*.edmx from Entity Framework) with default code generation.
Common repository interface

 public interface IGenericRepository<T> where T : class
 {
     T Get(int id);
     void Create(T entityToCreate);
     void Edit(T entityToEdit);
     void Delete(T entityToDelete);
 }

Interface (with particular methods of the current class), class with real implementation of methods. For example

public interface ITestingRepository: IGenericRepository<Testing>
{
    List<dynamic> GetTestingUser(int id);
    List<dynamic> GetNotTestingUser(int idTesting, Guid idCompany);
    List<Testing> List(Guid CompanyId);
}

public class TestingRepository : ITestingRepository
{
   private TestEverybody _entities = new TestEverybody();

   public List<Testing> List(Guid CompanyId)
   {
       return _entities.Testing.Where(t => t.idCompany == CompanyId).ToList();
   }
   public void Edit(Testing productToEdit)
   {
       var originalProduct = Get(productToEdit.id);
       _entities.ApplyCurrentValues(originalProduct.EntityKey.EntitySetName, productToEdit);
       _entities.SaveChanges();
   }
   public void Create(Testing productToCreate)
   {
       _entities.Testing.AddObject(productToCreate);
       _entities.SaveChanges();
   }
   //other methods
}

The following data access method in the controller

 public class TestingController : Controller
 {
   //
   // GET: /Testing/
   private ITestingRepository _repository;
   public TestingController() : this(new TestingRepository()) { }

   public TestingController(ITestingRepository repository)
   {
      _repository = repository;
   }
   [HttpPost]
   public ActionResult Create(Testing newobject)
   {
       _repository.Create(newobject);
       return RedirectToAction("Index");
   }
   [HttpPost]
   public ActionResult Edit(Testing item)
   {
      _repository.Edit(item);
      return RedirectToAction("Index");
   }
 }

Is it a good one? Have I any mistakes there?


texts: Reducing a list of points into a list of pairs of points

texts:
I have some data…

let points = [(718, 620), (4596, 1280), (410, 333), (4597, 993),
(410, 337), (4597, 996), (428, 337), (4597, 1000), (431, 335), (4599, 1044)]

… that follows the pattern

[(pointStartOne.x, pointStartOne.y), (pointEndOne.x, pointEndOne.y),
(pointStartTwo.x, pointStartTwo.x) // ...

I need to structure it to

typealias PointPair = [(start: Point, end: Point)]
struct Point {
    let x: Int
    let y: Int
}

Here is my code:

var result: PointPair = []
while i < points.count{
    result.append((Point(x: points[i].0, y: points[i].1), Point(x: points[i+1].0, y: points[i+1].1)))
    i+=2
}

I think maybe it is nice situation to use functional programming reduce

Here is code ituitive:

let result = zip((points.enumerated().filter({ (offset: Int, element: (Int, Int)) -> Bool in
        return offset%2==0
    })), (points.enumerated().filter({ (offset: Int, element: (Int, Int)) -> Bool in
        return offset%2==1
    }))).reduce(PointPair(), { (result: PointPair, arg) -> PointPair in
        let (one, other) = arg
        let (offset, point) = one
        let (offsetTwo, otherPoint) = other
        return result + [(Point(x: point.0,y: point.1), Point(x: otherPoint.0,y: otherPoint.1))]
    })

It is messy. Trying to use functional programming conveniently and elegantly.

Here is the improved code:

result = points.enumerated().reduce(into: PointPair(), {(temp, arg) in
        let (offset, point) = arg
        if offset % 2 == 0{
            temp += [(Point(x: point.0, y: point.1), Point(x: 0, y: 0) )]
        }
        else if let last = temp.last {
           temp[temp.count - 1] = (last.0, Point(x: point.0, y: point.1))
        }
    })


texts: Rearranging array - with empty strings in front and non-empty strings at back

texts:
Given a string array that either contains empty strings or non-empty
  strings, arrange the contents such that all the empty strings are at
  front and non-empty strings at back, retaining their order from
  original array.

  For example, input:

  {"","a","","d","","o","","g",""}
{"d","o","g"}
{"","","",""}

  Output:

  [, , , , , a, d, o, g]
[d, o, g]
[, , , ]

I wrote two implementations below:

In-place re-arrangement

//in-place arrangement with two pointers running towards starting index from back
public static void arrangeString(String...arr) {
    for (int i=arr.length-1, j=i; i>=0 && j >=0; ) {
        boolean needSwap  =false;
        boolean exit = false;
        while (!exit && arr[i].equals("")) {
            i--; needSwap = true;
            if (i==-1) exit = true;
        }
        while (!exit && !arr[j].equals("")) {
            j--; needSwap = true;
            if (j==-1) exit = true;
        }
        if (exit) break;
        if (needSwap) {
            String temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        i--; j--;
    }
}

Re-arranging using a temp array

public static String[] arrangeString(String...arr) {
    int len = arr.length;
    String[] temp = new String[len];
    for (int i=0, t1=0, j=len-1, t2=len-1; i<len && j>=0; i++, j--) {
        if(arr[i].equals(""))
            temp[t1++] = arr[i];
        else if(!arr[j].equals(""))
            temp[t2--] = arr[j];
    }
    return temp;
}

Please give me suggestions on how to improve them. It'll be great if you can provide an alternative code snippet replacing my code.


texts:
Can someone improve this code? I need to eliminate the for loop.

public bool CheckMobileSim(List<Mobile_Range> numberRange, string MobileNumber)
{
    bool SimType = new bool();
    string NineDigits = MobileNumber.Substring(0, 9).ToString();
    long Number = Convert.ToInt64(NineDigits);
    if (numberRange != null)
    {
        if (numberRange.Count > 0)
        {
            for (int i = 0; i < numberRange.Count; i++)
            {
                if ((Number >= numberRange[i].RangeStart && Number < numberRange[i].RangeEnd))
                {
                    SimType = true;
                    break;
                }

            }
        }
    }

    return SimType;
}


texts: Extract contiguous elements from an array in JavaScript

texts:
I'm trying to extract contiguous elements from an outcome array and print their equivalent elements in a reference array. This is my test case:

it('should split into fragments', function() {
  let ranges = getRanges({
    reference: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
    outcome: [true, true, false, false, true, false, false, true]
  })
  expect(ranges).to.eql([
    ['a b', true],
    ['c d', false],
    ['e', true],
    ['f g', false],
    ['h', true]
  ])
})

This works, but I'm wondering if there is a more elegant way of doing this:

function getRanges({reference, outcome}) {
  function withinBoundsAndSameOutcome(i, currentOutcome) {
    return i < outcome.length && outcome[i] == currentOutcome
  }
  let ranges = []
  for (let i = 0; i < outcome.length; i++) {
    let range = [reference[i]]
    let currentOutcome = outcome[i]
    while (withinBoundsAndSameOutcome(i + 1, currentOutcome)) {
      i += 1
      range.push(reference[i])
    }
    ranges.push([range.join(' '), currentOutcome])
  }
  return ranges
}


texts:
I create python dictionary based on the parsed data:

user_details['city'] = None
if api_result.get('response')[1] and api_result.get('response')[1][0]:
    api_result_response = api_result.get('response')[1][0] # city details
    if api_result_response:
        user_details['city'] = int(api_result_response.get('cid'))
        city_name = api_result_response.get('name')
if user_details['city'] and city_name:
    # do something

So, I do a lot of verifications if passed data exists, if user_details['city'] assigned etc. Is there any way to simplify that?


texts:
I have an Android service which must offload a task to a different thread but schedule the response callback unto the calling thread. After much thinking I came up with this code:

public void testRequestingAScheduleUpdateShouldNotBlockAndDeliverItOnTheCallingThread() throws Exception {
    final StreamSchedule mockSchedule = new StreamSchedule(
        new StreamMetadata("TyPhone", "Tidal Waves 028"),
        new StreamMetadata[] { new StreamMetadata(null, "The Progmatic Radio Show 002 with Ashley Bonsall") },
        new StreamMetadata[] { new StreamMetadata("TEKNO", "Sound Escalation 065 with Xabi") }
    );

    final boolean[] threadBlocked = {true};
    LooperThread looperThread = new LooperThread();
    looperThread.start();

    StreamScheduleProvider mockScheduleProvider = mock(StreamScheduleProvider.class);
    when(mockScheduleProvider.getCurrentStreamSchedule()).then(invocation -> {
        threadBlocked[0] = Thread.currentThread().getId() == looperThread.getId();
        return mockSchedule;
    });
    DataAccessModule.scheduleProviderOverride = mockScheduleProvider;

    final long[] callingThreadId = {-1};

    ScheduleUpdateListener updateListener = mock(ScheduleUpdateListener.class);
    doAnswer(invocation -> {
        callingThreadId[0] = Thread.currentThread().getId();
        looperThread.stopLooper();
        return null;
    }).when(updateListener).onScheduleChanged(any(StreamSchedule.class));

    PlaybackServiceBinder serviceBinder = (PlaybackServiceBinder) bindService(getServiceIntent());
    serviceBinder.subscribeScheduleUpdates(updateListener);
    looperThread.getHandler().post(serviceBinder::updateSchedule);
    looperThread.join();

    verify(updateListener).onScheduleChanged(mockSchedule);
    assertFalse("The thread was blocked, this is unacceptable", threadBlocked[0]);
    assertEquals("The update callback was not called on the requesting thread", callingThreadId[0], looperThread.getId());
}

class LooperThread extends Thread {
    private Handler handler;

    @Override
    public void run() {
        Looper.prepare();
        handler = new Handler(Looper.myLooper());
        Looper.loop();
    }

    public Handler getHandler() {
        return handler;
    }

    public void stopLooper() {
        handler.getLooper().quit();
    }
}

It does work (the test fails if I simply execute the callback on the background thread or if I use no background thread at all) but I have this that intense itch I overlooked something that could make this more readable/elegant. Any ideas?


texts:
I wanted to step up my JS game, and move on from mostly closure based scripting, so I decided to write an application in node. I don't have much experience with prototype based programming, and I guess it's a little too early for ES6 (well, maybe with traceur).

During planning of my app I saw that often I'll need container behaviour. So, I know I could implement it with a class, but I thought: why not use trait-like thingy instead?

Gamemode.js, concrete class

'use strict';

var Script = require('../Script');

var Gamemode = module.exports = function () {
    Script.apply(this, arguments);
};

Gamemode.prototype = Object.create(Script.prototype);
Gamemode.prototype.constructor = Gamemode;

Script.js, abstract class

'use strict';

var helper = require("./helper");
var _ = require("lodash");

var Script = module.exports = function () {
    if (this.constructor === Script) {
        throw new Error("Can't initialize abstract class!");
    }

    var defaultDefinitions = {
        MAX_PLAYERS: '(500)'
    };

    _.merge(this, helper.collection("definition", defaultDefinitions));
};

Script.prototype.build = function () {
    return this.definitions;
};

helper.js

'use strict';

var _ = require("lodash");

var capitalize = function (string) {
    return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
};

var container = function (singular, mutable) {
    if (undefined === mutable) {
        mutable = false;
    }

    var accessors = {},
        methodSingular = capitalize(singular),
        plural = singular + 's',
        methodPlural = capitalize(plural);

    accessors['get' + methodPlural] = function () {
        return this[plural];
    };

    accessors['set' + methodPlural] = function (value) {
        if (undefined === value) {
            delete this[plural];
        }

        this[plural] = value;

        return this;
    };

    if (mutable) {
        accessors['add' + methodSingular] = function (item) {
            _.assign(this[plural], item);
        };

        accessors['remove' + methodSingular] = function (item) {
            delete this[plural][item];
        };
    }

    return accessors;
};

var collection = function (name, defaults) {
    if (undefined === defaults) {
        defaults = {};
    };

    var all = {};
    all[name + 's'] = _.defaults({}, defaults);

    return _.merge(all, container(name, true));
};

var helper = module.exports = {
    capitalize: capitalize,
    container: container,
    collection: collection
};

It works properly, now every instance of Gamemode has its own "definitions" property, with getDefinitions, setDefinitions, addDefinition and removeDefinition methods.

Am I violating any rules, like encapsulation?
Am I adding property somewhere else than in the constructor?
Would creating a "container" object instead be better?