texts:
I've a application which runs with two threads.  The main thread runs in one infinity-while-loop:

while (true) {
   try {
      ArrayList<Info> infoList = zabbixHandler.APIRequest();
      handleInfo.handleInformation(infoList);
      Thread.sleep(5000);
   }
}

The second thread, which uses more than 50% of my CPU, must be able to stop and run again, which I asked already with this question on Stack Overflow.

The solution works perfectly, but as I already said, it uses >50% of the CPU.  Here are the two loops of the solution:

private volatile boolean finished = true;
public void run() {
   Process p;

   while (true) {
        // loop until the thread is finished
        while (!finished) {
            try {

                // let every lamp shine...
                p = Runtime.getRuntime().exec(onCommand + "-green");
                p.waitFor();

                // ... for 0.5 seconds ...
                Thread.sleep(500);

                // ... then turn it off again ...
                p = Runtime.getRuntime().exec(offCommand + "-green");
                p.waitFor();
                // ... and let the next lamp shine
                p = Runtime.getRuntime().exec(onCommand + "-yellow");
                p.waitFor();

                Thread.sleep(500);

                p = Runtime.getRuntime().exec(offCommand + "-yellow");
                p.waitFor();
                p = Runtime.getRuntime().exec(onCommand + "-red");
                p.waitFor();

                Thread.sleep(500);

                p = Runtime.getRuntime().exec(offCommand + "-red");
                p.waitFor();
                p = Runtime.getRuntime().exec(onCommand + "-blue");
                p.waitFor();

                Thread.sleep(500);

                p = Runtime.getRuntime().exec(offCommand + "-blue");
                p.waitFor();

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

How could I reduce the use of CPU while retaining the functionality?

EDIT:
The finish element will be changed by a getter and setter. Because it is volaitle, it shouldn't get complications.


texts:
I've done a job interview assignment on shapes (surprising ah?!) which is a C# console application which creates a list of shapes basically. It's available here, but for my question the only relevant part is the following:

This is where shapes are created - AddNewShape method (I presented this in the interview):

switch (pressedKey)
{
    case ConsoleKey.D1:
        shape = new Square(GetNumFromConsoleAndVerifyIt());
        break;
    case ConsoleKey.D2:
        double height = GetNumFromConsoleAndVerifyIt();
        double width = GetNumFromConsoleAndVerifyIt();
        shape = new Rectangle(height, width);
        break;
    case ConsoleKey.D3:
        shape = new Circle(GetNumFromConsoleAndVerifyIt());
        break;
    case ConsoleKey.D4:
        double triangleHeight = GetNumFromConsoleAndVerifyIt();
        double triangleWidth = GetNumFromConsoleAndVerifyIt();
        shape = new RightTriangle(triangleHeight, triangleWidth);
        break;
    default:
        throw new ArgumentException();
}

The problem that was discussed about this section is that it's not "Open for Extension" (Personally I prefer the 'Predicted Variations' version of this principle). So later on I refactored this part:

// Use reflection to get the type and it's required params:
Type shapeType = shapeTypes.Where(t => t.FullName.ToLower().Contains(shapeNameEntered.ToLower())).First();
var ctor = shapeType.GetConstructors()[0];

List<object> sides = new List<object>();
foreach (ParameterInfo pi in ctor.GetParameters())
{
    sides.Add(GetNumFromConsole(pi.Name));
}
shape = (I2DShape)ctor.Invoke(sides.ToArray());

And now you can clone my project and add whatever shape you want, implement I2DShape (also - have only one ctor) and change nothing in the Program.cs etc...

So, does this follow the principle? Did I get it right using reflection or should I have used a different approach?


texts:
I've been practicing my folds and tail-call recursive programming, and I wanted to work on unzip for the general case as opposed to just pairs. This was very easy to do with standard tail call recursion. However, I was also told that any time you can use tail call recursion on a list, you could also use a fold. I was eventually able to figure out an algorithm that only uses folds, but it wasn't nearly as simple as, or even exactly a translation of, the tail recursive version. Are there any improvements or changes I could make to either of these algorithms?

Tail-call recursive

; Unzip a list of equally lengthed lists
; Takes car of every list and conses it to acc, then reverses acc at the end
; (unzip '((1 4 7 10) (2 5 8 11) (3 6 9 12))) => '((1 2 3) (4 5 6) (7 8 9) (10 11 12)
(define (unzip lst [acc '()])
  (if (or (empty? lst) (empty? (car lst)))
      (reverse acc)
      (unzip (map cdr lst) (cons (map car lst) acc))))

Folds only:

; Takes the last element and turns it into a list of singletons as a seed
; For each remaining element, it conses each element onto its respective list
(define (unzip lst)
  (define (list->singletons lst)
    (foldl (λ (x acc) (cons `(,x) acc)) '() (reverse lst)))
  (define (cons* heads tails)
    (foldr (λ (hd tl acc) (cons (cons hd tl) acc)) '() heads tails))
  (if (empty? lst)
      lst
      (foldl (λ (x acc) (cons* x acc))
             (list->singletons (car (reverse lst))) (cdr (reverse lst)))))


texts: Extension Method to append a list of parameters to existing Uri as query

texts:
In Windows Universal, none of the builder classes for web requests are available, nor can I use System.Web.

How would you optimize (shorten, perform) the extension method below, considering the following requirements:

Sample: http://www.foo.com?bar=foo&foobar=bar

Append a list of key/value parameters as uri parameter
Encode the parameters for the web
Append also if the original uri already contains any query parameters (you do not have to check whether there is a identical pair

How much do you like this implementation ?:

    public static Uri AppendParameters(this Uri uri, IDictionary<string, string> parameters)
    {
        var concatenatedParameters = parameters.Select(pair =>
            $"{WebUtility.UrlEncode(pair.Key)}={WebUtility.UrlEncode(pair.Value)}");

        var query = string.Join("&", concatenatedParameters);
        var uriString = string.IsNullOrEmpty(uri.Query) ?
            uri.OriginalString + $"?{query}" :
            uri.OriginalString + $"&{query}";

        return new Uri(uriString);
    }


texts:
I'm new to react and am building a basic react app and have just built a basic area where navigation links render on a page but wonder whether my current start could be optimised - for example, I wonder whether an area like this:
render() {
    return (
        <Root navLinks={this.state.navLinks}></Root>
    );
  }

Could be changed to something like this:
render() {
    return (
        <Root>
           <NavLinks navLinks={this.state.navLinks} />
        </Root>
    );
  }

And I wonder about other aspects of the app such as do I need an App.js file or index.js file and could have one rather than the other?
Any quick basic beginner advice would be much appreciated. The code can be better found in this Stackblitz demo or below:
App.js:
import React, {Component} from "react";
import {navLinks} from "./components/nav-links";
import Root from "./components/Root";

export default class App extends Component {
  constructor() {
    super();

    this.state = {
      navLinks: navLinks
    }
  }

  render() {
    return (
        <Root navLinks={this.state.navLinks}></Root>
    );
  }
}

index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

/components/Root.js:
import React from "react";
import NavMenu from "./nav-menu";
import BodyCode from "./body-code";

export default class Root extends React.Component {
    render() {
        return (

                    <NavMenu navLinks={this.props.navLinks} />

                    <BodyCode />

        )
    }
}

/components/body-code.js:
import React from "react";

export default class bodyCode extends React.Component {
    constructor(props) {
        super(props);
        this.state = {isToggleOn: true}; // boolean for event listener alternative

        // This binding is necessary to make `this` work in the callback
        this.handleClick = this.handleClick.bind(this);
      } // bind is saying make the ‘this’ keyword bind(this), where the 2nd ‘this’ is the ‘this’ of the constructor

      handleClick() {
        this.setState(state => ({
          isToggleOn: !state.isToggleOn // sets state to the opposite of whatever it is
        }));
      }

  render() {
    return (

some body text

          <button onClick={this.handleClick}>
            {this.state.isToggleOn ? 'ON' : 'OFF'}
            </button>

    )
  }
}

/components/nav-links.js:
export const navLinks = [
  {
    name: "home",
    href: "/"
  },
  {
    name: "subs",
    href: "/subs"
  }
];

/components/nav-menu.js:
import React from "react";

export default class navBar extends React.Component {
  render() {
    return (
      this.props.navLinks.map((link) =>  {link.name} )
    )
  }
}


texts:
My programming skill has gotten rusty, so I would like to elicit constructive criticism that can make me write code better. I know the standard design is to use templates, and even obtain the hash function, allocator, etc through it, but I wanted to experiment with patterns, so I'm pretty sure my design here blows. but I'm trying to use the strategy pattern to make a customizable hash table interface, just to reacquaint myself with C++.

How do I design this better (without using all the template parameters, for specifying hash function, etc)? If not the strategy pattern, what pattern would fit better?

//The generic map interface
template <typename K, typename V>
class Map
{
private:

    //Make a reference class so we can enable [] operation
    class reference
    {
        public:
            operator V const () { return map_.Find(key_); }

            reference& operator=(const V& val) { map_.Add(key_, val); return *this; }
            reference& operator=(const reference& ref) { *this = (V&) ref; return *this; }

        private:
            reference (Map& map, const K key) : map_(map), key_(key) {}
            Map& map_;
            K key_;
            friend class Map;
    };

public:
    Map() : hash_(NULL), ds_(NULL), size_(0) { }

    void SetHashStrategy(int hash_type = HashType::SIMPLE_HASH);
    void SetCollisionStrategy(int collision_method = CollisionType::CHAINING);
    void SetDataStructureStrategy(int data_structure_types = DSType::DYNAMIC_MAP);
    virtual ~Map()
    {
        Empty();
        delete hash_;
        delete ds_;
    }

    //Interface functions
    void   Add(K key,V value) { ++size_; ds_->Add(key, value); }
    void   Remove(K key)      { --size_; ds_->Remove(key); }
    V&     Find(K key)        { return ds_->Find(key); }
    size_t Size()             { return size_; }
    void   Empty()            { size_ = 0; ds_->Empty(); }

    //Square bracket access
    reference operator[] (const K& key) { return (reference(*this, key)); }

    //printing
    friend std::ostream& operator<< (std::ostream& o, const V& v) { return o << v; }

private:
    HashType* hash_; //is an ADT
    DataStructureType<K,V>* ds_; //this is also an ADT
    size_t size_;
};

And then, choose the hash object like this:

template <class K, class V>
void Map<K,V>::SetHashStrategy(int hash_type)
{
  if(hash_ != NULL)
  {
    delete hash_;
  }

  if(hash_type == HashType::SIMPLE_HASH)
  {
    hash_ = new SimpleHash;
  }
  else if(hash_type == HashType::MD5_HASH)
  {
    hash_ = new MD5Hash;
  }
}

And choose the data structure like this:

template <class K, class V>
void Map<K,V>::SetDataStructureStrategy(int ds_type)
{
  if(ds_ != NULL)
  {
    delete ds_;
  }

  if(ds_type == DSType::DYNAMIC_MAP)
  {
    ds_ = new DynamicMap<K,V>;
  }
  else if(ds_type == DSType::ARRAY_MAP)
  {
    ds_ = new ArrayMap<K,V>;
  }
}


texts: Find the total number of emails in a folder (with all of the subfolders)

texts:
The Folder struct definition below is given:

type Folder struct {
    ID int
    emailCount int
    childFolderIDs []int
}

Description of the fields are:

Id                 : folder id
emailCount         : number of emails in the folder
childFolderIDS     : if the folder has subfolders, this list contains folder IDS of the subfolders.

I am trying to write a function:

Function is taking two parameters:

First parameter is a list of all folders in the email application

  var folders = []Folder{
        Folder{1, 30, []int{2, 4}},
        Folder{2, 10, []int{3}},
        Folder{4, 60, []int{}},
        Folder{3, 20, []int{}},
  }

Second parameter is folder id of a folder

Function will return a total number of emails with ID=Folder Id and all of its children recursively.

For example:

If the second parameter is:

four, then the function should return 60 (there is no subfolder)
two, then the function should return 30

My code is below:

      package main

      import "fmt"

      type Folder struct {
          ID int
          emailCount int
          childFolderIDs []int
      }

      func InsertIntoMap(data_arr []Folder) map[int]Folder {
          var retval = make(map[int]Folder)
          var child_folders []int
          for _, elem := range data_arr {
            child_folders = elem.childFolderIDs
            var folder Folder
            folder.ID = elem.ID
            folder.emailCount = elem.emailCount
            folder.childFolderIDs = child_folders
            retval[elem.ID] = folder
          }

          return retval
      }

    func GetTotalEmailCount(p_map map[int]Folder, folder_id int) int {
          total := 0
          var child_folders []int
          child_folders = p_map[folder_id].childFolderIDs
          total = total + p_map[folder_id].emailCount

          if len(child_folders) == 0{
            return total
          }else{
            for e := range child_folders {
              return total + GetTotalEmailCount(p_map, child_folders[e])
              }
          }

          return total
    }

      func main() {

        var folders = []Folder{
          Folder{1, 30, []int{2, 4}},
          Folder{2, 10, []int{3}},
          Folder{4, 60, []int{}},
          Folder{3, 20, []int{}},
      }

      var m = InsertIntoMap(folders)

      fmt.Println(GetTotalEmailCount(m,1))  // result is 60
      fmt.Println(GetTotalEmailCount(m,2))  // result is 30
      fmt.Println(GetTotalEmailCount(m,3))  // result is 20
      fmt.Println(GetTotalEmailCount(m,4))  // result is 60

      }
```


texts:
Challenge

There are n citizens voting in this year's HackLand election. Each voter writes the name of their chosen candidate on a ballot and places it in a ballot box.
The candidate with the highest number of votes wins the election;
if two or more candidates have the same number of votes, then the tied candidates' names are ordered alphabetically and the last name wins.

Complete the electionWinner function in your editor. It has 1 parameter: an array of strings, votes, describing the votes in the ballot box. This function must review these votes and return a string representing the name of the winning candidate.

My Code

function electionWinner(votes) {
    const vObj = {};
    for(let v of votes){
        vObj[v] = (vObj[v] || 0) + 1;
    }

    let winners = [];
    let maxVotes = 0;

    for(let name in vObj){
        if(vObj[name] > maxVotes){
            maxVotes = vObj[name];
            winners = [name];
        }
        else if (vObj[name] === maxVotes){
            winners.push(name);
        }
    }

    if(winners.length === 1){
        return winners[0];
    }
    winners.sort();
    return winners[winners.length - 1];
}


texts: Getting a hash string for a very large file

texts:
After reading about large files and memory problems, I'm suspecting that my code below may be inefficient because it reads the entire files into memory before applying the hash algorithm. Is there a better way?

chunk_size = 1024
hasher = hashlib.md5()
while True:
    try:
        data = f.read(chunk_size)
    except IOError, e:
        log.error('error hashing %s on Agent %s' % (path, agent.name))
        return {'error': '%s' % e}
    if not data:
        break
    hasher.update(data)
hash_string = hasher.hexdigest()


texts: Super class knowing the type of its children? Surely there is a better way

texts:
I'm working on a small project that does mathematical calculations based on selected data in a JTable. The goal is to make the program fairly adaptable for adding new mathematical calculations in the future. For reference, some of the current calculations are: calculating the mean (average) of a set of data; calculating the percentile of each item in a set of input data; calculating the least squares linear regression (best fit linear function) for a set of data points.

My current design thought process is that to make things the math utilities flexible, there needs to be a some type of base class for analysis data that serves as input and output to some type of performAnalysis function in a base class for all analysis classes. This lead me to a skeleton design as follows:

public enum AnalysisDataType {
    Scalar,
    Set,
    Map
}

public interface IAnalysisData {
    AnalysisDataType getType();
}

public interface IAnalaysisDataScalar extends IAnalysisData {
    double getValue();
}

public interface IAnalaysisDataSet extends IAnalysisData {
    int getCount();
    IAnalysisData getData(int index);
}

public interface IAnalaysisDataMap extends IAnalysisData {
    IAnalysisData getDomain();
    IAnalysisData getCodomain();
}

public interface IDataAnalysis {
    AnalysisDataType getInputDataType();
    AnalysisDataType getOutputDataType();

    IAnalysisData performAnalysis(IAnalysisData inputData);
}

Then, something for calculating mean would be:

public class DataAnalysisMean implements IDataAnalysis {
    AnalysisDataType getInputDataType() { return AnalysisDataType.Set; }
    AnalysisDataType getInputDataType() { return AnalysisDataType.Scalar; }

    IAnalysisData performAnalysis(IAnalysisData intputData) {

        IAnalysisDataSet inputDataSet = (IAnalysisDataSet)inputData;
        double sum = 0;

        for (int i = 0; i < inputDataSet.getCount(); i++) {
            IAnalysisData dataItem = inputDataSet.getData(i);
            IAnalysisDataScalar dataItem = (IAnalysisDataScalar)dataItem;
            sum += dataItem.getValue();
        }

        return new IAnalysisDataScalar() {
            @Override
            double getValue() {
                return sum / inputDataSet.getCount();
            }

            @Override
            AnalysisDataType getType() {
                return AnalysisDataType.Scalar;
            }
        };
    }
}

I realize a little more work needs to go into "describing" the input and output data items because no where did I mention that the input set contained scalars, but - while I already have an idea how to solve that one - I feel that the whole approach is hackish.

The thought behind this approach is that the code using interfacing with these math utilities could query the IDataAnalysis interface to determine what the expected input and output is and can send the appropriate input as needed and parse the results appropriately. This would allow us to just need to drop-in more functionality at a later time without having to add additional controller logic to tie it in.

I feel like its wrong for a parent class - or interface in this case - to know about its possible children classes (interfaces) through the AnalysisDataType enum and the getType method. As always with OO programming, surely just another layer of abstraction or some type is needed, though perhaps I'm just missing out on some other design pattern that solves this exact problem.

Anyway, if anyone has advice on what I might do to better organize this, I'd much appreciate it. I'd love to hear how wrong my thoughts are and learn a better way.


texts:
I need to run fork workers every 5 seconds. Is there a way to do it more ideomatic? I'm embarrassed about $running variable.

use 5.010;
use strict;
use warnings;

use AnyEvent;
use AnyEvent::Util;

my $running;

sub work1 {
    say "work1";
    sleep 1;
}

sub work2 {
    say "work2";
    sleep 1;
}

sub do_work {

    my $worker_cv = AnyEvent->condvar;

    $worker_cv->begin;
    fork_call {
        work1();
    } sub {
        $worker_cv->end;
    };

    $worker_cv->begin;
    fork_call {
        work2();
    } sub {
        $worker_cv->end;
    };

    $worker_cv->cb(sub {
        $running = 0;
    });
}

my $timer = AnyEvent->timer(
    interval => 5,
    cb => sub {
        unless ($running) {
            $running = 1;
            do_work();
        }
    }
);

my $loop = AnyEvent->condvar;

$loop->recv;


texts: Checking whether a string is a valid number

texts:
I'm developing a Java Helper Library which has useful methods developers don't want to type out over and over. I'm trying to think of the best way of checking whether a string is a valid number.

I've always just tried something like Integer.parseInt(iPromiseImANumber); and if it throws an exception then it's not a valid number (integer in this case). I'm thinking that trying to catch an exception isn't good practice. Is there a better way to do this? (I'm thinking a regular expression could do it, but it doesn't seem to be as reliable as the parse option).

Here's my method as it stands. What could be improved?

/**
* Does a try catch (Exception) on parsing the given string to the given type
*
* @param c the number type. Valid types are (wrappers included): double, int, float, long.
* @param numString number to check
* @return false if there is an exception, true otherwise
*/
public static boolean isValidNumber(Class c, String numString) {
  try {
    if (c == double.class || c == Double.class) {
      Double.parseDouble(numString);
    } else if (c == int.class || c == Integer.class) {
      Integer.parseInt(numString);
    } else if (c == float.class || c == Float.class) {
      Float.parseFloat(numString);
    } else if (c == long.class || c == Long.class) {
      Long.parseLong(numString);
    }
  } catch (Exception ex) {
    return false;
  }
  return true;
}


texts: Return a minimum number of ranges from a collection of ranges

texts:
I'm new to Python and SWE in general so excuse the simple questions. I was given the following coding challenge by an interviewer. And I came up with the following solution. But I was passed over because it didn't meet their performance criteria. I was wondering if anyone could give me pointers on how I can do better on this question and in general for questions like this. I've found other answers solving the question, but I wanted specific answers to my implementation.

Here is the feedback I received:

The while (zip_range_list):line sticks out: you don't see a lot of
while loops in Python, you don't have to put parentheses around the
test expression, and solving this problem with a while loop is a
weird thing to do. Why are while loops a bad idea?
Adding a range to reduced_zip_ranges before it's reduced, and then
continually referring to the element you just added as
reduced_zip_ranges[-1] instead of having a separate binding for it
reads awkwardly. Why is this awkward?
The construct range_check = range(low-1, high+2) may be correct, but it's both strange to look at and ridiculously space-wasteful: instead of comparing endpoints he builds a list of the entire range of numbers just to check
membership in that range. He builds these over and over again in a
loop within a loop. I see the point here. I was trying to avoid a
long if-statement. Wasn't a good idea.
Speaking of "loop within a loop", this is an O(N-squared) algorithm when it could have been O(N) after the sort. I guess I overlooked this, I see 0(n^2) now. How can I avoid this?
The routine has two different non-exceptional return points; the one within the loop is unnecessary (the code works as well with it commented out).

PROBLEM
Given a collection of zip code ranges (each range includes both
their upper and lower bounds),
provide an algorithm that produces the minimum number of ranges required
to represent the same coverage as the input.

Input: [[14,17], [4,7], [2,5], [10,12] , [15,16], [4,9], [11,13]]
Output: [[2,17]]

# Implementation
def zip_range_reducer(zip_range_list):

    if not zip_range_list:
        raise Exception("Empty list of ranges provided!")

    reduced_zip_ranges = []

    zip_range_list.sort()

    while (zip_range_list):
        no_overlap_ranges = []
        reduced_zip_ranges.append(zip_range_list[0])
        if len(zip_range_list) == 1:
            return reduced_zip_ranges
        zip_range_list.pop(0)
        for zip_range in zip_range_list:
            low, high = reduced_zip_ranges[-1][0], reduced_zip_ranges[-1][1]
            range_check = range(low-1, high+2)
            if zip_range[0] in range_check or zip_range[1] in range_check:
                reduced_zip_ranges[-1][0] = min(reduced_zip_ranges[-1][0], zip_range[0])
                reduced_zip_ranges[-1][1] = max(reduced_zip_ranges[-1][1], zip_range[1])
            else:
                no_overlap_ranges.append(zip_range)
        zip_range_list = no_overlap_ranges

    return reduced_zip_ranges


texts: Creates a class that searches for the elements in a list that contain a sequence

texts:
Not sure what I should write here. The code should be self-explanatory.

"""This is a data definition class--Searchable_list.
Searchable_list takes a list of strings and makes it searchable.
Searchable meaning you can find which elements in the list have a pattern.
"""
class Searchable_list(object):
    """this will make your word list searchable.
Note, It will also loose the original order of the list."""
    def __init__(self, lis):
        assert hasattr(lis,"__iter__")
        self.search_dict=dict()
        for word in set(lis):self.add_word(word)

    def add_word(self,word):
        """this will add a word to the search_dict
search dict is of the form: {letter:{nextletter:{(index,word)}}}
"""
        assert type(word) is str#or isinstance(word,str)
        for index,val in enumerate(word[:-1]):
            next_letter=self.search_dict.setdefault(val,dict())
            words_list=next_letter.setdefault(word[index+1],set())#object modification
            words_list.add((index,word))#object modifification

    def find_matches(self,seq):
        """finds all the words in the list with this sequence.
Uses '.' as wildcard.
"""
        s_d=self.search_dict
        assert len(seq)>1
        #could put a try catch to catch key errors
        for index,letter in enumerate(seq[:-1]):
            if not(letter=="."and seq[index+1]=="."):
                #no point if they all match...
                if letter==".":
                    L_m=set.union(*(i.get(seq[index+1],set()) for i in s_d.values()))
                    #.get is important here. not all is have i[seq[index+1]]
                elif seq[index+1]==".":
                    L_m=set.union(*(i for i in s_d[letter].values()))
                else:
                    L_m=s_d[letter].get(seq[index+1],{})#this is a set.
                #L_m==letter_matches
                if index>0:
                    m_m=((i-index,word) for i,word in L_m)
                    #m_m=matches_matches. These words still have the pattern.
                    #your matching all indexes to the original m_s
                    m_s.intersection_update(m_m)
                    #m_s=matches_set
                else:
                    m_s=L_m.copy()
                    #http://stackoverflow.com/questions/23200969/how-to-clone-or-copy-a-set-in-python
        return m_s

EDIT: Because this post was bumped, and I've added some pretty major improvements to it here's a link to the final version of this. It's not very clean, but it has optimizations this doesn't have. If there's an interest I can try to put some comments explaining the optimizations in the github or post something here about it (probably in the form of another answer). https://github.com/user-name-is-taken/words-with-friends/blob/master/WWF_DDC.py (note, the scrabble stuff is just adapting this code for scrabble). For now, the basic idea behind the optimizations is that python's set.intersection is faster than set.union


texts:
I use a Ubuntu 16.04 Nginx server environment with phpmyadmin (PMA). All my ports are closed besides 22, 25, 80, 443, 9000 (for PHP-FPM).

A common criticism of the good software (PMA) as of 2018, is that it doesn't have good defense from Brute Force Attacks (BFAs). There are different common ways to cope with this and I admit I dislike all of them:

Changing the PMA path to something unintuitive and likely uncomfortable (instead of /var/www/html/phpmyadmin).
Using a permanent IP (what if you're traveling between countries)?
Login through a recognized VPN. What if you don't have a free time to seriously learn VPN basics in some era of your life?
Loging with some kind of authentication certificate. What if don't have one?
Using mod_security for Apache users. What if you don't use Apache?
Using a captcha. What if you login frequently? This might be a bit annoying.
Future PMA versions starting from V 4.8.0 are planned to include support for IPSs like Fail2ban, via uthentication logging.
Future PMA versions starting from V 4.8.0 are also planned to include 2factorAuthentication.

I found myself another way which is personal and comfortable (I don't recommend any company with customers to use this way in the form I'll describe below):

SSH tunneling through port 80 to port 80 via Putty/OpenSSH, and use PMA securely and temporarily for 2 hours in a tmux session (It is extremely unlikely that anyone could BFA PMA with a decent varied password in just 2 hours).

Each time I want to use PMA I run this code:

#!/bin/bash

find  ${drt}/ -iname '*phpmyadmin*' -exec rm -rf {} \;
wget -P ${drt}/ https://www.phpmyadmin.net/downloads/phpMyAdmin-latest-all-languages.zip
find  ${drt}/ -type f -iname '*phpmyadmin*.zip' -exec unzip {} \;
find  ${drt}/ -type d -iname 'phpmyadmin-*' -exec mv {} phpmyadmin \;

sleep 2h

find  ${drt}/ -iname '*phpmyadmin*' -exec rm -rf {} \;
tmux kill-session

I run it this way tmux new-session -d 'bash ~/pma.sh', or with a Bash alias pma.

Note: ${drt} stands for document root, which is in my case /var/www/html and defined in /etc/bash.bashrc.

I'd like to know what you think of the code I've written (especially, do you see any way to shorten it)?.


texts:
The program reads a .txt file that contains lines of numbers. The first one has one number N and the second one has \$N\$ numbers as the first line says.

The \$N\$ numbers is \$1 \le N \le 1.000.000\$.

The program read the \$N\$ numbers in an array and performs the following procedure:

  Read the number one by one backwards in the array and check to find the max value. Every time a new max value is found the int total increases by one. In the end we write the total value in an output file.

Is my code well written?

#include <stdio.h>
#include <stdlib.h>

/*---------------------*/
/* defined constants   */
/* for restriction     */
/*---------------------*/
#define MIN 1
#define MAX 1000000

/*---------------------*/
/* function prototypes */
/*---------------------*/
int main(void);
FILE *read_input(char *filename_r);
int count_children(FILE *input);
int pass_heights(FILE *input, int *children,const unsigned int size);
int chck_tall(const int *children,const unsigned int size);
void write_output(const unsigned short total,char *filename_w);

/*----------------------------------*/
/* start of program - Main Function */
/*----------------------------------*/
int main(void) {

    char *filename_r = "xxx.in";
    char *filename_w = "xxx.out";

    FILE *input = read_input(filename_r);

    unsigned int size = count_children(input);

    int *children = malloc(size * sizeof(unsigned short));
    if (children==NULL)
    exit(1); //General application error

    pass_heights(input, children, size);

    fclose(input);

    unsigned short total = chck_tall(children, size);

    free(children);

    write_output(total,filename_w);

    return 0;
}

FILE *read_input(char *filename_r) {

    FILE *input = fopen(filename_r, "r");

    if(input == NULL)
    exit(66); //EXIT_NOINPUT 'cannot open input'

    return input;
}

int count_children(FILE *input) {

    unsigned int count = 0;
    fscanf(input, "%d",&count);

    if(count > MAX || count < MIN)
    exit(1); //General application error

    return count;
}

int pass_heights(FILE *input, int *children,const unsigned int size) {

    for(register int i = 0; i < size; i++)
    fscanf(input, "%d",&children[i]);

    return *children;
}

int chck_tall(const int *children,const unsigned int size) {

    unsigned short total = 0;
    unsigned short tmp_max = 0;
    for(register int i = size - 1; i >= 0; i--)
    {
        if(children[i] > tmp_max) {
            tmp_max = children[i];
            total++;
        }
    }
    return total;
}

void write_output(const unsigned short total,char *filename_w) {

    FILE *output = fopen(filename_w, "w");

    if(output == NULL)
    exit(74); //EXIT_IOERR 'input/output error'

    fprintf(output, "%d\n", total);
    fclose(output);
}


texts:
I just started programming, and something is telling me that this working function looks to big for what it does. Can you give a better version of the code so I can understand how to code faster, shorter code ?

import os, rarfile

xpath= "/root/tree/def/"

dpath="/root/tree/down"

def unrar():
        for rf in os.listdir(dpath):
            f = os.path.join(dpath,rf)
            o = rarfile.RarFile(f)
            for u in o.infolist():
             print (u.filename, u.file_size)
             o.extractall(xpath)


texts: Django Rest Framework ListAPIView - many if-s in get_queryset()

texts:
Please review my DRF ListAPIView code. There are a lot of if statements. I wonder if it's a good approach to put these if-s in get_queryset(). How can I improve this?

class ReportList(ListAPIView):
    serializer_class = ReportSerializer
    permission_classes = [IsAuthenticated, ]

    def get_queryset(self):
        qs = Report.objects.all()

        # search filters
        status = self.request.query_params.get('status', None)
        count = self.request.query_params.get('count', None)
        candidate_name = self.request.query_params.get('candidate_name', None)

        if status:
            qs = qs.filter(status=status)
        if candidate_name:
            qs = qs.filter(user__name__icontains=candidate_name)
        if count:
            qs = qs[:5]

        # per user role objects permission
        user = self.request.user
        if user.is_company_admin:
            return qs.filter(
                user__company=user.company).exclude(status=constants.DRAFT)
        elif user.is_recruiter:
            return qs.filter(
                user__company=user.company).exclude(status=constants.DRAFT)
        elif user.is_approver:
            return qs.filter(
                user__approver=user).exclude(status=constants.DRAFT)

        # if user is requester:
        return qs.filter(user=user, user__company=user.company)


texts:
Blackjack (twenty-one) is a casino game played with cards. The goal of
  the game to draw cards that total as close to 21 points as possible
  without going over. All face cards count as 10 points, aces count as 1
  or 11, and all other cards count their numeric value.

  The game is played against a dealer. The player tries to get closer to
  21 (without going over) than the dealer. If the dealer busts (goes
  over 21) the player automatically wins (provided the player had not
  already busted). The dealer must always take cards according to a
  fixed set of rules. The dealer takes cards until he or she achieves a
  total of at least 17. If the dealer's hand contains an ace, it will be
  counted as 11 when that results in a total between 17 and 21
  inclusive; otherwise, the ace is counted as 1.

  Write a program that simulates multiple games of blackjack and
  estimates the probability that the dealer will bust. Hints: treat the
  deck of cards as infinite. You do not need to keep track of the cards
  in the hand, just the total so far (treating an ace as 1) and a bool
  variable hasace that tells whether or not the hand contains an ace. A
  hand containing an ace should have 10 points added to the total
  exactly when doing so would produce a stopping total(something between
  17 and 21 inclusive).

It runs, but I'm just looking to improve it if possible.

def printIntro():
    print("This program simulates a bunch of blackjack games.")

def getInputs():
    while True:
        n = eval(input("How many games should be simulated? "))
        if n <= 0:
            print("You must enter a number greater than zero!")
        else:
            break

    return n

def simOneGame():
    score = 0
    blacklist = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
    while not gameOver(score):
        blackscore = blacklist[randrange(len(blacklist))]
        score = score + blackscore

        if score >= 17:
             break
        if blackscore == 11 and (score >= 6 and score <= 10):
            score = score + 11
        else:
            score = score + 1

    return score

def simNGames(n):
    holds = 0
    busts = 0
    for i in range(n):
        score = simOneGame()
        if score >= 22:
            busts = busts + 1
        else:
            holds = holds + 1

    return holds, busts

def gameOver(score):
    return score >= 22 or score >= 17

def printSummary(holds, busts):
    n = holds + busts
    print("Number of holds and busts: Holds: {0:0} Busts: {1:0}".format(holds, busts))
    print("Percentage of holds and busts: Holds: {0:0.1%}".format(holds / n), end = " ")
    print("Busts: {0:0.1%}".format(busts / n))

def main():
    printIntro()
    n = getInputs()
    score = simOneGame()
    holds, busts = simNGames(n)
    printSummary(holds, busts)

if __name__ == "__main__":
    main()


texts:
Following is the code to update content via ajax. Please review all aspects of the code.

var ajaxUpdate = {
    init: function(){
        ajaxUpdate.enableHistory();
    },
    _this:null,
    enableHistory: function(){
        History.Adapter.bind(window,'statechange',function() { // Note: We are using statechange instead of popstate
            var State = History.getState();

            console.log('History: '+State.url)
            if(State.data.type == 'maincontainer'){
                if(jQuery('#maincontainer').length){
                    //update content
                    jQuery('#maincontainer').html(State.data.response);

                    //select the menu element
                    jQuery('#main-menu li').removeClass('active');
                    jQuery('#main-menu li:eq('+State.data.main+')').addClass('active');
                }
                else{
                    window.location.href = State.url;
                }
            }/*
            _this.parent().addClass('active');*/
        });
    },
    updateMainContent: function(){
        var _this = ajaxUpdate._this;
        if ( !History.enabled ) {
            return ;
        }

        jQuery.ajax({
            type: 'GET',
            url: _this.attr('href'),
            beforeSend  : function(jqXHR, settings){
                jQuery('#maincontainer').addClass('loading');
            },
            complete: function(jqXHR, textStatus){
                jQuery('#maincontainer').removeClass('loading');
            },
            success: function(response){
                var data = {
                    main : _this.data('main_index'),
                    type: "maincontainer",
                    response: response
                }
                jQuery('#maincontainer').removeClass('loading');
                History.pushState(data, _this.data('title'), this.url);
            },
            error : function(jqXHR, textStatus, errorThrown){
                //processERROR();
            }
        });
        return false;
    },
    mainmenu: function(){
        ajaxUpdate._this = jQuery(this);
        ajaxUpdate._this.data('main_index', ajaxUpdate._this.parent().index());
        return ajaxUpdate.updateMainContent();
    },
    submenu: function(){
        ajaxUpdate._this = jQuery(this);
        ajaxUpdate._this.data('main_index', jQuery('#main-menu li.active').index());
        return ajaxUpdate.updateMainContent();
    },
    search: function(){
        ajaxUpdate._this = jQuery(this);
        ajaxUpdate._this.data('main_index', jQuery('#main-menu li.active').index());
        return ajaxUpdate.updateMainContent();
    }
};

ajaxUpdate.init();

jQuery('#main-menu a').click(ajaxUpdate.mainmenu);
jQuery('#maincontainer').on('click', '.nav a', ajaxUpdate.submenu);
jQuery('#maincontainer').on('submit', 'form', ajaxUpdate.search);


texts: A function that checks if a string subnet mask is valid

texts:
I've written a small helper function that receives a string and checks if it translates to a valid subnet mask value (255.255.255.0 for example).

I would appreciate some peer review!

static bool isValidSubnetMask(IN char *subNetMask)
{
    char *str = NULL;
    char *endptr;
    int counter = 0;
    long int nChainInstance = -1;

    /*Check if string is valid*/
    if (!subNetMask || subNetMask[0] == '\0' || strlen(subNetMask) > 15) {
        return false;
    }

    /*Check string validity*/
    str = strtok(subNetMask, ".");
    while (str != NULL) {
        if (!is_numeric(str)) {
            return false;
        } else {
            /*Save number to be used as entry*/
            nChainInstance = strtol(str, &endptr, 10);
            if (str == endptr) {
                /*Fail to translate string to number*/
                return false;
            }
            if (nChainInstance > 255 || nChainInstance < 0) {
                return false;
            }
        }
        counter++;
        str = strtok(NULL, ".");
    }

    if (counter == 4) {
        return true;
    }
    return false;
}


texts:
We are beginning to learn Node.js and we are not always sure if we do it the right way. We have a strong object oriented background so the adoption is not always easy. Right now we implemented a factory method, but we are not completely sure if our approach is good.

Factory Method:

var fs = require('fs');

module.exports.getHandler = function(type,callback) {
    if(!type) {
        throw new Error('Please specifiy a type');
    }
    var nodeModule = type.ucFirst()+'FieldHandler';
    var file = __dirname+'/'+nodeModule+'.js';
    fs.exists(file, function(exists) {
        if (exists) {
            var handler = require('./'+nodeModule);
            var instance = new handler;
            callback(instance);
        } else {
            throw new Error('Handler for "'+type+'" does not exist. ' +
                'Expect file of handler to have the name "'+file+'"');
        }
    });
};

Object which uses the factory method:

var FieldhandlerFactory = require('./fieldhandler/Factory');
...
...
...
var handleField = function (actualField) {
    var callbackHandler = function (handler) {
        handler.setJson(actualField);
        handler.check();
        fieldString += handler.toView() + '\n';
        actual++;
        if (amountFields == actual) {
            // WE ARE READY DO SOMETHING
        }
    };
    var handler = FieldhandlerFactory.getHandler(type, callbackHandler);
}
for (var index in fields) {
    var field = fields[index];
    type = field.type;
    if (!type) {
        throw new Error('Field on index "' + index + '" has no attribute type');
    }
    var string = handleField(field);
}
...
...
...

The code works, so we are quite happy.  Is this a good approach or do we stick too much to the classical OOP style? Especially with testing we face some problems. How to test the function handleField isolated? And with jasmine-node I'm not able to catch the exception in the factory method when the file is not found.

So we think there are tons of improvements. We are looking forward to learn from you and to exchange experiences.


texts: Bidirectional BFS on a matrix in Python 2.7

texts:
This code is a bidirectional BFS search. Given any two points in a matrix having 0's and 1's, I would like to find if there exists a path between them. Also note that it is forbidden to enter a cell that has a value of 0.

One note I would like to make about the code is that I have maintained a duplicate matrix to check if a particular cell has been visited by the source/destination.

Can someone please let me know if there are any discrepancies in what I have implemented and how I can improve the time efficiency of this? I am new to Python.

import copy

def path_exists(grid, queries):
    #iterate through queries.
    result=[]
    for (x1,y1,x2,y2) in queries:
        print "query",x1,y1,x2,y2
        if isValidIndex((x1,y1),(x2,y2),grid) != 0:
            result.append(findPath(x1,y1,x2,y2,grid))
        else:
            result.append(0)

    return result

def isValidIndex(startIndex,endIndex,grid):
    if startIndex[0] >= len(grid) or startIndex[0] < 0 or startIndex[1] >= len(grid[0]) or startIndex[1] < 0 or endIndex[0] >= len(grid) or endIndex[0] < 0 or endIndex[1] >= len(grid[0]) or endIndex[1] < 0 :
        return 0
    return 1

def findPath(x1,y1,x2,y2,grid):
    queue1=[[x1,y1]]
    queue2=[[x2,y2]]

    bool_grid = copy.deepcopy(grid)

    source_path = 0
    dest_path = 0

    while(1):
       if len(queue1) > 0:
           if find_path_from_source(queue1,grid,bool_grid,3) == 1:
               return 1

       if len(queue2) > 0:
           if find_path_from_source(queue2,grid,bool_grid,4) == 1:
               return 1

       if len(queue1) == 0 and len(queue2) == 0:
           return 0

def find_path_from_source(queue,grid,bool_grid,val):
    x=queue[0][0]
    y=queue[0][1]
    other_val = val

    if val == 3:
        other_val = 4
    else:
        other_val = 3

    if x + 1 < len(grid):
        if bool_grid[x+1][y] == other_val:
            return 1
        elif bool_grid[x+1][y] == 1:
            bool_grid[x+1][y] = val
            queue.append([x+1,y])

    if y + 1 < len(grid[0]):
        if bool_grid[x][y+1] == other_val:
            return 1
        elif bool_grid[x][y+1] == 1:
            bool_grid[x][y+1] = val
            queue.append([x,y+1])

    if x - 1 >= 0:
        if bool_grid[x - 1][y] == other_val:
            return 1
        elif bool_grid[x - 1][y] == 1:
            bool_grid[x - 1][y] = val
            queue.append([x - 1 , y])

    if y - 1 >= 0:
        if bool_grid[x][y - 1] == other_val:
            return 1
        elif bool_grid[x][y - 1] == 1:
            bool_grid[x][y - 1] = val
            queue.append([x, y - 1])

    queue.pop(0)

grid =  [[1,0,0,1,1],
         [0,1,1,1,1],
         [1,1,0,1,1],
         [0,1,1,0,1],
         [1,1,1,0,1]]

queries=((1,2,2,3),(0,0,1,1),(2,0,0,4),(5,0,2,5),(4,4,0,0),(0,4,4,4))

x = path_exists(grid,queries)

print x


texts:
Take a look at following code:

/*abstract*/ class Capturable
{
    object _lock = new object();
    public bool IsCaptured { get; private set; }

    public bool TryCapture()
    {
        if (!IsCaptured)
            lock (_lock)
                if (!IsCaptured)
                    return IsCaptured = true;
        return false;
    }

    public void Release()
    {
        lock (_lock)
            IsCaptured = false;
    }
}

The idea is to inherit from Capturable when I need an object with exclusive access. Object will be used from different places (not necessarily different threads). If this object is needed, then the caller should first call TryCapture() (so theoretically there could be many calls when object is occupied, therefore double check locking is used to quickly return false).

Expected scenarios of usage:

periodically do something (e.g. by timer);
get exclusive access for a duration (e.g. if there is a long operation during which nobody should change state of object);

Both cases are covered with something like:

var obj = Manager.Get<SomeType>();
...
if(obj.TryCapture())
    try
    {
        ...
        obj.SomeMethod();
        ...
    }
    finally
    {
        obj.Release();
    }

The questions:

Is this a good approach to get exclusive access? Code-wise and architecturally? E.g. I can use Monitor.TryEnter instead of double check locking, but not sure how to return IsCaptured then.
Is there a possibility to avoid if+TryCapture+try+finally everywhere? Similar to how clean lock looks like (it covers Monitor calls) or how nice using is to ensure Dispose() call. The problem here comes when multiple of such object has to be captured at the beginning of method, then it will looks like dozens of nested if/try/finally, which I don't like.


texts:
I decided to avoid the trivial isPalindrome lst = lst == reverse lst and tried writing a method with pattern matching and recursion.

allButFirstAndLast :: [a] -> [a]
allButFirstAndLast = tail . init

isPalidrome :: [a] -> Bool
isPalidrome [] = True
isPalindrome [a] = True
isPalindrome [a,b] = a == b
isPalindrome lst = (isPalindrome (allButFirstAndLast lst)) &&
                   ((head lst) == (last lst))


texts:
I am currently working on an algorithm, which involves finding the intersection of two lists. That is, given the following inputs [1,2,2,1],[2,2] the result would be [2,2].

I have implemented it in two ways which hopefully should be easy to understand

Method 1

def intersect(nums1, nums2):
    dict_count = {}
    for num1 in nums1:
        if num1 not in dict_count:
            dict_count[num1] = 1
        else:
            dict_count[num1] += 1

    inter_arr = []

    for num2 in nums2:
        if num2 in dict_count and dict_count[num2] > 0:
            inter_arr.append(num2)
            dict_count[num2] -= 1

    return inter_arr

Method 2

def intersect_v2(nums1, nums2):
    arr_one = sorted(nums1)
    arr_two = sorted(nums2)

    p1, p2 = 0, 0
    inter_arr = []

    while p1 < len(arr_one) and p2 < len(arr_two):
        if arr_one[p1] < arr_two[p2]:
            p1 += 1
        elif arr_one[p1] > arr_two[p2]:
            p2 += 1
        else:
            inter_arr.append(arr_one[p1])
            p1 += 1
            p2 += 1

    return inter_arr

I have two questions about time complexity:

What if nums1's size is small compared to nums2's size? Which algorithm is better? (The original algorithm problem is from Leetcode and this is a follow up question to the problem)

It feels like the pointer method always win, but I can't articulate why.

If the inputs always came in sorted, which algorithm would be more efficient with respect to time and space? (This would mean that first two lines to intersect_v2 would not be needed)

From my understanding intersect would be O(M+N) since you would have to iterate through the two arrays not matter what. The second one is a bit confusing since it feels like the it would be O(Z) where Z is less than Max(M,N) and greater than Min(M,N), is that about right?


texts:
Any reviews/ways to speed up/general improvements for my Merge Sort? Maybe something to simplify it or add more to it?

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

namespace prjT02L08_Predator_Prey
{
    abstract class MergeSort
    {
        public static List<Node> Sort(List<Node> input)
        {
        List<Node> Result = new List<Node>();
        List<Node> Left = new List<Node>();
        List<Node> Right = new List<Node>();

        if (input.Count <= 1)
            return input;

        int midpoint = input.Count / 2;
        for (int i = 0; i < midpoint; i++)
            Left.Add(input[i]);
        for (int i = midpoint; i < input.Count; i++)
            Right.Add(input[i]);

        Left = Sort(Left); //Recursion! :o
        Right = Sort(Right);
        Result = Merge(Left, Right);

        return Result;
    }

    private static List<Node> Merge(List<Node> Left, List<Node> Right)
    {
        List<Node> Result = new List<Node>();
        while (Left.Count > 0 && Right.Count > 0)
        {
            if (Left[0].F < Right[0].F)
            {
                Result.Add(Left[0]);
                Left.RemoveAt(0);
            }
            else
            {
                Result.Add(Right[0]);
                Right.RemoveAt(0);
            }
        }

        while (Left.Count > 0)
        {
            Result.Add(Left[0]);
            Left.RemoveAt(0);
        }

        while (Right.Count > 0)
        {
            Result.Add(Right[0]);
            Right.RemoveAt(0);
        }

        return Result;
    }
}
}


texts:
I have an rspec spec test that has two sets of the same tests (from 24 Pull Requests). I thought I'd refactor the spec whilst I fixed something else.

Normally I just do a basic each ... do array to DRY things up:

require 'spec_helper'

describe ReminderMailer, type: :mailer do

  # Half the code yay! :D
  ['daily','weekly'].each do |time_format|
    describe time_format do
      let(:time_format) { time_format }
      let(:user) do
        mock_model(User, nickname:           'David',
                         email:              'david@example.com',
                         languages:          ['Ruby'],
                         skills:             [],
                         pull_requests:      double(:pull_request, year: []),
                         suggested_projects: [])
      end

      # How do I do this bit better?
      let(:mail) {
        if time_format == 'daily'
          ReminderMailer.daily(user)
        else
          ReminderMailer.weekly(user)
        end
      }

end

I couldn't figure out how to use the time_format with the send command, so I could do something like:

let(:mail) { ReminderMailer.send(timeformat(user) }

How could I do this?


texts:
I wrote this code where I have to rotate an array of 'n' elements by 'd' elements in the anti-clockwise direction.Can it be done in a better and simpler way?

 public class RotateArr{
     public static void rotate(int[] arr,int d,int n){

    System.out.println("Array before rotating : ");

    for(int l=0; l<n; l++){
        System.out.print(arr[l]+" ");
    }
        System.out.println();

    int temp = arr[0];

    for(int i=0; i<d; i++){
        for(int j=1; j<n; j++){
            arr[j-1] = arr[j];
            if(j==(n-1)){
                arr[n-1] = temp;
            }
        }
        temp = arr[0];
    }

    System.out.println("Array after rotating");
    for(int k=0; k<n; k++){
        System.out.print(arr[k]+" ");
    }
}
    public static void main(String[] args) {

    int[] arr = {1,2,3,4,5,6,7};

    int d = 3;

    int n = arr.length;

    rotate(arr,d,n);
      }
   }


texts:
I'm trying to implement the Strategy Pattern into my current code base. I would like to know if i'm going in the right direction on this?

IOracleDB.cs:

/// <summary>
/// Strategy
/// </summary>
interface IOracleDB
{
    DataSet DatabaseQuery(string query, OracleConnection oracleConnection);
    DataSet DatabaseQuery(string procedure, string parameters, OracleConnection oracleConnection);
}

OracleDBContext.cs:

/// <summary>
/// Context
/// </summary>
class OracleDBContext
{
    private readonly string _EmailConnectionString = ConfigurationManager
        .ConnectionStrings["EmailConnectionString"].ConnectionString;

    private readonly string _PhConnectionString = ConfigurationManager
        .ConnectionStrings["PhConnectionString"].ConnectionString;

    private readonly IOracleDB _oracleDB;
    private readonly OracleConnection _oracleConnection;

    public OracleDBContext(IOracleDB oracleDB, string table)
    {
        _oracleDB = oracleDB;

        switch (table.ToUpper())
        {
            case "Email":
                _oracleConnection = new OracleConnection(_EmailConnectionString);
                return;

            case "Ph":
                _oracleConnection = new OracleConnection(_PhConnectionString);
                return;

            default:
                return;
        }
    }

    public void ConnectToDatabase()
    {
        _oracleConnection.Open();
    }

    public void DisconnectFromDatabase()
    {
        _oracleConnection.Close();
        _oracleConnection.Dispose();
    }

    public string ConnectionStatus()
    {
        if (_oracleConnection != null)
        {
            return _oracleConnection.State.ToString();
        }
        return "OracleConnection is null.";
    }

    public DataSet DatabaseQuery(string query)
    {
        return _oracleDB.DatabaseQuery(query, _oracleConnection);
    }

    public DataSet DatabaseQuery(string procedure, string parameters)
    {
        return _oracleDB.DatabaseQuery(procedure, parameters, _oracleConnection);
    }
}

EmailTableClass.cs:

/// <summary>
/// Concrete Strategy
/// </summary>
class EmailTableClass : IOracleDB
{

    public DataSet DatabaseQuery(string query, OracleConnection oracleConnection)
    {
        DataSet dataSet = new DataSet();
        OracleCommand cmd = new OracleCommand(query);
        cmd.CommandType = CommandType.Text;
        cmd.Connection = oracleConnection;

        using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
        {
            dataAdapter.SelectCommand = cmd;
            dataAdapter.Fill(dataSet);
        }

        return dataSet;
    }

    public DataSet DatabaseQuery(string procedure, string parameters, OracleConnection oracleConnection)
    {
        throw new NotImplementedException();
    }
}

PhTableClass.cs:

/// <summary>
/// Concrete Strategy
/// </summary>
class PhTableClass : IOracleDB
{

    public DataSet DatabaseQuery(string query, OracleConnection oracleConnection)
    {
        throw new NotImplementedException();
    }

    public DataSet DatabaseQuery(string procedure, string parameters, OracleConnection oracleConnection)
    {
        DataSet dataSet = new DataSet();
        OracleCommand cmd = new OracleCommand
        {
            CommandText = procedure,
            CommandType = CommandType.StoredProcedure,
            Connection = oracleConnection,
        };

        OracleParameter oracleParameter = new OracleParameter
        {
            ParameterName = parameters
        };

        using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
        {
            dataAdapter.SelectCommand = cmd;
            dataAdapter.Fill(dataSet);
        }

        return dataSet;
    }
}


texts:
I have this piece of code to replace current text inside an array of html divs with values coming from a JSON file:

    $.each($('.something'), function(){
        if($(this).text()=="1"){
            $(this).html(jsondata.CameraTypeLabel1);
        }else if($(this).text()=="2"){
            $(this).html(jsondata.CameraTypeLabel2);
        }
    });

I'd like to make it "dynamic": if I'd have 100 values, I don't want to copy/paste it 100 times.

Maybe it would be better creating an array "CameraTypeLabel" in the JSON string ?

EDIT: Fixed the selector, it was a typo.

Thanks!


texts: Overriding static method with different static variable in java

texts:
Suppose I have 3 classes, Animal, Dog, and Cat
public abstract class Animal {
    private static final List<Animal> allObjects = new ArrayList<>();

    public Animal(){
      allObjects.add(this);
    }

    // Returns immutable list of all Animal objects
    public static List<? extends Animal> getInstantiatedObjects(){
         return allObjects;
    }
}

public class Cat extends Animal {
    private static final List<Cat> allObjects = new ArrayList<>();

    public Cat(){
      super();
      allObjects.add(this);
    }

    // Returns immutable list of all Cat objects
    public static List<? extends Cat> getInstantiatedObjects(){
         return allObjects;
    }
}

While this works, I can't help but think that this is poor design, and it would be better if either the static method would be inheritable and "adapt" to the class (? extends thisClass), or it raised an implementation error if the method wasn't implemented. For instance,
public class Dog extends Animal {
    private static final List<Dog> allObjects = new ArrayList<>();

    public Dog(){
      super();
      allObjects.add(this);
    }

    /* Returns immutable list of all Dog objects
    public static List<? extends Dog> getInstantiatedObjects(){
         return allObjects;
    } */
}

returns no errors and simply uses the static method of the superclass, but that doesn't allow the code to store only objects of its class or lower. Any help would be greatly appreciated!


texts: REST Response: Checking for Success and Error

texts:
I thought this was pretty slick - maybe not, I just wanted to share and maybe get some feedback:

As part of a REST client class:

Accepts the JSON response from REST or REST-like service, searches through to find multiple errors, or return success indicator.

You define success and failure in a small multidimensional array broken down by resource/method, I have it set to count success/failure when it finds the properties with matching names, but could check values too:

private $response_definitions = array(
    'authenticate' => array(
        'success' => array( 'accessHash' ),
        'failure' => array( 'authErrorObj' ),
    ),
    'create_order' => array(
        'success' => array( 'orderSuccessObj' ),
        'failure' => array( 'orderErrorObj', 'deviceErrorObj' ),
    ),
    'cancel_order' => array(
        'success' => array( 'cancelOrderObj' ),
        'failure' => array( 'orderErrorObj' ),
    )
);

You hand it your response - already decoded, in this case

$this->checkResponse($action,json_decode($response));

Loops through our response. Fills a "error" property in the main class for errors, and also returns the success object, defined above, if found.

/**
 * checkForErrors
 * Here we will take whatever response we have, and look for errors in it.
 * sending the thrid parameter as 'false' kicks off a recursive search through the provided response()
 * the search looks for both success and failure properties, defined in the class properties.
 * if it finds an error value, it builds up the class' "error" property
 * if it doesn't find a success, the first iteration (with the false third parameter) adds an error as well
 * @param  action string the action we launched so we can know what kind of errors to look for
 * @param  response object the full response object, converted to a php object with json_decode
 * @param  type string when this is false, it will begin the recursion to look for successes and failures
 * @void
 */
function checkResponse( $action, $response, $type=FALSE )
{
    // the first, non-recursive iteration
    if( $type === FALSE ){
        $this->checkResponse( $action, $response, 'failure' );
        $success_result = $this->checkResponse( $action, $response, 'success' );

        if( $success_result === NULL ){
            $this->errors[] = (object)array(
                'name'        => 'TEK-00000',
                'description' => 'Success Property Not Found!'
            );
        }
    }else // the recursive iterations
    {
        $definitions = $this->response_definitions[$action][$type];
        foreach( $response as $property => $value )
        {
            // if success and property is in 'success' array, then return the property
            if( $type == 'success' && in_array( $property, $definitions ) ){
                return $property;
            }

            // if failure and property is in 'failure' array, then add the error to the error property
            if( $type == 'failure' && in_array( $property, $definitions ) ){
                $this->errors[] = (object)array(
                    'name'        => $value->errorCode,
                    'description' => $value->errorMessage
                );
            }
            // if property is an object or an array, recursively search through it as well
            if ( is_object( $value ) || is_array( $value ) ){
                // if we're looking at successes, be sure to send the result up the recursion chain.
                if    ( $type == 'success' ){ return $this->checkResponse( $action, $value, $type ); }
                elseif( $type == 'failure' ){        $this->checkResponse( $action, $value, $type ); }
            }
        }
    }
}

Anyway, open to improvements I'm sure. I kind of like that you kick it off by setting one flag, then it handles are the recursion within itself and hands any success response up the chain.


texts:
I have this annoying problem in PHP with faking overloading constructors.  I understand the concept, but the code I produce feels kind of ugly. It isn't a lot of code, just bad code. Any ideas on how to make this sane?

/**
 * Instantiate Fencer object from user meta database.
 *
 * If fencer data does not exist in database and USFA ID is provided,
 * it will automatically update from API
 *
 * If USFA ID is not provided, will throw exception
 *
 * If API data is provided, a user ID must also be provided
 * that way we can save the data from the API to the user.
 *
 * @param int|null $user_id
 * @param string|null $usfa_id
 * @param array|null $raw_data
 *
 * @throws InvalidArgumentException
 *  1. If the user does not exist and USFA ID not provided
 *  2. Raw API data is provided, but not a User ID to save it to
 */
private function __construct( $user_id = null, $usfa_id = null, $raw_data = null ) {
    if ( $raw_data === null ) {
        if ( null === $user_id ) {
            $user_id = self::get_user_id_from_usfa_id( $usfa_id );
        }

        $this->wp_id = $user_id;

        $fencerdata = get_user_meta( $user_id, 'fence_plus_fencer_data', true );

        if ( ! empty( $fencerdata ) ) {
            foreach ( $fencerdata as $key => $data ) {
                call_user_func( array( $this, 'set_' . $key ), $data );
                // set all properties by calling internal setters based on fencer user meta data key
            }
        }
        else if ( $usfa_id != null ) {
            $this->usfa_id = $usfa_id;
            $this->update();
            $this->save();
        }
        else {
            throw new InvalidArgumentException( "Fencer data does not exist. Instantiate with USFA ID", 1 );
        }
    }
    else {
        if ( null == $user_id ) {
            throw new InvalidArgumentException( "User ID must be provided when instantiating with raw API data", 2 );
        }

        $this->wp_id = $user_id;
        $this->process_api_data( array( $raw_data ) );
        $this->interpret_data();
        $this->save();
    }
}


texts: Remove pre-loader animations when all assets on page become available

texts:
This code starts when the page loads and when all assets become available, it removes pre-loader animation and page becomes visible.
I know some functions has code repetition, but it can await refactoring stage. For now, I want to understand the basics of good code architecture creation.

(function() {
'use strict';

    /* object with assets and related methods */
    var elements = {
        _images : document.getElementsByTagName('img'),
        _videos : document.getElementsByTagName('video'),

        getImages: function() {
            return this._images;
        },

        getVideos: function() {
            return this._videos;
        },

        getTotalLength: function() {
            var result  = 0,
                keysArr = Object.keys(this);

            for (var i = 0; i < keysArr.length; i++) {
                if (typeof this[keysArr[i]] !== "function") {
                    result += this[keysArr[i]].length;
                }
            }

            return result;
        }
    };

    /* object with counter and related methods (maybe this should be inside another object) */
    var counter = {
        _counter: 0,
        incrementCounter: function() {
            this._counter++;
        },
        getCounter: function() {
            return this._counter;
        }
    };

    /* I think this two functions should compose another object */
    function imagesLoader() { // 1
        var imagesArr = elements.getImages();

        for (var i = 0, len = imagesArr.length; i < len; i++) {

            imagesArr[i].addEventListener('load', loadHandler);
            imagesArr[i].removeAttribute('srcset');
        }
    }

    function videosLoader() { // 2
        var videosArr = elements.getVideos();

        for (var i = 0, len = videosArr.length; i < len; i++) {
            var src = videosArr[i].getAttribute('data-src');

            videosArr[i].addEventListener('canplay', loadHandler);
            videosArr[i].setAttribute('src', src);
        }
    }

    /* this function removes CSS classes that block page rendering */
    function showPage() {
        setInterval(function() {
            document.documentElement.classList.remove('html-loading');
            document.body.classList.remove('body-pause');
        }, 500);
    }

    /* general event handler */
    function loadHandler() {
        counter.incrementCounter();
        if (counter.getCounter() === elements.getTotalLength()) {
            showPage();
        }
    }

    /* This code starts the whole process */
    imagesLoader();
    videosLoader();
})();


texts: Displaying user selection in the browser

texts:
I have the following script that reads JSONified data from within a DIV, generates HTML with values using JavaScript, then sends them to another DIV.

What I'd like to improve is to remove HTML from JavaScript.  Namely, not have HTML inside the JavaScript.  I am not 100% on how to do this.  I want "minimal work" but "most separation" of HTML and JS.

var selection = eval("(" + document.getElementById("result").innerHTML + ")");

/*
 * Relevant Example only:
 * selection[index].couplings = "[{"price":13.00,"description":"Couplings"}]";
 */

/**
 * Show Couplings
 */
if (selection[index].couplings != null)
{
    for (i = 0; i < selection[index].couplings.length; i++) {
        result += '
';
        result += '' + selection[index].couplings[i].description + '	';
        result += '' + moneyFormat(selection[index].couplings[i].price) + '	';
        result += '
';
    }
}

document.getElementById('couplings').innerHTML = result;

/*****************/
/* Number Format */
/*****************/
function moneyFormat(num) {
    return '$' + parseFloat(num).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}


texts: getfloat, the floating point analog of getint

texts:
Write getfloat, the floating-point analog of getint. What types does getfloat return as its function value?

gefloat would also return an integer value.
Here is my solution:

int getfloat(double *pf) {
    int c, sign;
    double power;

    while(isspace(c = getch()))
        ;
    if(!isdigit(c) && c != EOF && c != '-' && c != '+' && c != '.') {
        ungetch(c); /* push the number back in buffer */
        return 0; /* not a valid number */
    }

    sign = (c == '-') ? -1 : 1;
    if(c == '-' || c == '+')
        c = getch();

    if(!isdigit(c) && c != '.') {
        ungetch(c);
        return 0; /* not a number */
    }

    for(*pf = 0.0; isdigit(c); c = getch())
        *pf = *pf * 10 + (c - '0');

    if(c == '.')
        c = getch();

    for(power = 1.0; isdigit(c); c = getch()) {
        *pf = *pf * 10 + (c - '0');
        power *= 10;
    }

    *pf *= sign;
    *pf /= power; /* moving the decimal point */

    if(c != EOF)
        ungetch(c);
    return c; /* it actually returns the value of the charachter that caused the break of the second for */
}

I have changed the type of the parameter *pf to double, thus it will handle the floating point represenation of a number. The condition of the first if-statement was extended, such that it will not push back in to the buffer a decimal point.
The second for computes the decimal part of the number, storing the number of places that the decimal point should pe moved in the variable power. If there is no decimal part, power will have the value 1 - thus, nothing will change if I devide *pf by power when power is 1.


texts: Method to generate a List containing permutation of an input string

texts:
I'm working to understand Big O notation. As such I'm going through examples and the algorithm below generates the permutations for a given input string which contains only distinct characters. IE no duplicated or repeated characters in the input string.

My thought process was to take each character and place it at every position within any previously generated strings.

The single character string "a" can only generate "a".
With "ab" the first character generates "a", as above. The next character 'b' would then be added before and after it to generate "ba" and "ab".
With "abc" this would effectively take the list generated above and repeat the same procedure placing c at position 0, 1, and 2 producing

From "ba": "cba", "bca", "bac"
From "ab": "cab", "acb", "abc"

Etc...

The nested loops, foreach and for, is a big flag as to how inefficient my current implementation is, \$O(n * n * n) = O(n^3)\$ if I've understood the notation correctly. How can I improve the structure to remove this nesting?

public class StringPermutation
{
    public List<string> Generate(string source)
    {
        var list = new List<string>();
        foreach (var c in source) //O(source.Length)
        {
            if (list.Count == 0)
            {
                list.Add(c.ToString());
            }
            else
            {
                var beingBuilt = new List<string>();
                foreach (var tempString in list) //O(list.Count)
                {
                    for (int i = 0; i < tempString.Length + 1; i++) //O(tempString.Length)
                    {
                        var built = tempString.Insert(i, c.ToString());
                        beingBuilt.Add(built);
                    }
                }

                list = beingBuilt;
            }
        }

        return list;
    }
}


texts: Adding a new record to the beginning of the approval chain from the delegation chain

texts:
Table Structure

  ApprovalOrder int

  EntityCode    varchar

  CostCentre varchar

  DelegationCode    varchar

  ProjectCode   varchar

  RoleGroup varchar

  Position  varchar

  DelegationText    varchar

  DelegationAmount  money

  Active    bit

Query / Explanation

The purpose is to pull all records for a delegation chain and add a new record at the beginning of the approval chain. RowID is used when talking with an external system and is a required part of the returned results.

I'm wondering if there's a better way that I could have constructed this query instead of the approach I took below? Beyond that I'm definitely interested in general performance / formatting suggestions.

/* Define ye values */
declare @role_group as int = 55
declare @position as char(55) = 'Asset Analyst'
declare @delegation_text as int = null
declare @delegation_amount as int = 0

declare @entity as int = 1410
declare @project_code as int = 10022
declare @delegation_code as varchar(10) = 'NC'

select top 1
    '1' + cast(@entity as varchar(10)) + @delegation_code as 'RowID' ,
    1 as 'ApprovalOrder' ,
    @entity as 'EntityCode',
    CostCentre as 'CostCentre',
    @delegation_code as 'DelegationCode' ,
    @project_code as 'ProjectCode' ,
    @role_group as 'RoleGroup' ,
    @position as 'Position',
    @delegation_text as 'DelegationText' ,
    @delegation_amount as 'DelegationAmount' ,
    Active
from
    workflow.delegation_engine
where
    EntityCode = @entity
    and ProjectCode = @project_code
    and DelegationCode = @delegation_code

union
select
    de.RowID ,
    cast(de.ApprovalOrder as int) + 1 as 'ApprovalOrder' ,
    de.EntityCode ,
    de.CostCentre ,
    de.DelegationCode ,
    de.ProjectCode ,
    de.RoleGroup ,
    de.Position ,
    de.DelegationText ,
    de.DelegationAmount ,
    de.Active
from
    (
        select
            cast(de.ApprovalOrder + 1 as varchar(4))
                + cast(de.EntityCode as varchar(8))
                + cast(de.DelegationCode as varchar(12)) as 'RowID' ,
            ApprovalOrder ,
            EntityCode ,
            CostCentre ,
            DelegationCode ,
            ProjectCode ,
            RoleGroup ,
            Position ,
            DelegationText ,
            DelegationAmount ,
            Active
        from
            workflow.delegation_engine de
    ) de
where
    de.EntityCode = @entity
    and de.ProjectCode = @project_code
    and de.DelegationCode = @delegation_code


texts: Reading a controll character in a loop in Python

texts:
I have a code snippet below and because of habit from other programming languages I wanted to use a do-while loop instead. But Python offers only the construct which I show as a second code snippet instead of a do-while*loop.
What is the best pythonic way to code this?

ch = getch()
while ch != "q":
  do_something()
  ch = getch()

while True:
  ch = getch()
  do_something()
  if ch == "q":
    break


texts: Java orchestration calls from two CRUD endpoints

texts:
Here is my orchestration endpoint where I call customer endpoint and product endpoint. Product endpoint contains info about what customer have what product. I do not like how it look and smells as shit hope there is a better way to do it. Couldn't find a better way to do it but RestTemplate feels so wrong here.

@RestController
public class ApiController {

    private final static String CUSTOMER_URI = "http://localhost:8090/customers";
    private final static String PRODUCT_URI = "http://localhost:8085/products";
    private final static String PRODUCT_CUSTOM_URI = "http://localhost:8085/products/search/findByOwners";

    @GetMapping("/getCustomerById/{id}")
    public Customer getCustomerById( @PathVariable int id){
        MappingJackson2HttpMessageConverter converter = getMappingJackson2HttpMessageConverter();
        RestTemplate restTemplateHal = new RestTemplate(Collections.<HttpMessageConverter<?>> singletonList(converter));
        RestTemplate restTemplate = new RestTemplate();

        Customer customer = getCustomer(id, restTemplate);
        ArrayList<String> products = getProduct(id, restTemplateHal);
        customer.setProducts(products);
        customer.setId(id);
        return customer;
    }

    private ArrayList<String> getProduct(@PathVariable int id, RestTemplate restTemplateHal) {
        Collection content = restTemplateHal.getForObject(PRODUCT_CUSTOM_URI + "?id=" + id, PagedResources.class).getContent();
        ArrayList<String> products = new ArrayList<>();
        for (Object o : content) {
            System.out.println(o);
            LinkedHashMap<String, String> o1 = (LinkedHashMap<String, String>)o;
            products.add(o1.get("name"));
        }
        return products;
    }

    private Customer getCustomer(@PathVariable int id, RestTemplate restTemplate) {
        ResponseEntity<Customer> responseCustomer
                = restTemplate.getForEntity(CUSTOMER_URI + "/"+id, Customer.class);
        return responseCustomer.getBody();
    }

    private MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.registerModule(new Jackson2HalModule());

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"));
        converter.setObjectMapper(mapper);
        return converter;
    }
}


texts:
I wrote an age verification module in Python 2.5 . How can I improve on current_year? import  time perhaps?

current_year = 2016
year_of_birth = int(raw_input('Enter Year Of Birth: '))
age = current_year - year_of_birth
mytext = 'You are %s years old.'
print(mytext % age)
if age < 18:
    print('YOU SHALL NOT PASS!')
else:
    print('Welcome To The Portal.')


texts: Avoiding code duplication in multiple except blocks in Logger class

texts:
Context:

A logger records events which contain an area, a level, a message and an option indicating that the source replaces another one.

The logger attempts to send the message through HTTP, and on failure, saves it locally. If HTTP service times out, the logger stops attempting using HTTP and stores the message locally directly.

Concern:

I'm concerned with code duplication at the end of the method. The same call is repeated three times. In my opinion:

Creating a function within the method would be an overkill.
Creating a separate class to encompass the four elements and pass an instance of this class would be an overkill as well.
Moving the call to the end and using return would complicate the logic.

What are my options?

class Logger():
    ...
    def _log(self, area, level, message, replacing=None):
        ...
        if self._timedOut:
            self._logToFile(area, level, message, replacing) # ← This line...
            return

        try:
            self._post(json)
        except urllib.error.HTTPError:
            self._logToFile(area, level, message, replacing) # ← ... is duplicated here...
        except socket.timeout:
            self._logToFile(area, level, message, replacing) # ← ... and here.
            self._timedOut = True


texts:
Please review this simple code. When I review it I decide to rewrite so that it doesn't write to a template, but instead directly to output since the whole HTML is fetched from the data layer. I used the tool appengine_admin to get editable HTML for simple html capabilities to an appspot project:

    class Page(db.Model):
      html = db.TextProperty(required=True)

    class AdminPage(appengine_admin.ModelAdmin):

        model = Page
        listFields = (
            'html',
            )
        editFields = (
            'html',
            )

  application = webapp.WSGIApplication([  ('/page/([0-9]+)', PageHandler), ])

  class PageHandler(BaseHandler):
      def get(self, file_id):
        page = Page.get_by_id(long(file_id))
        if not page:
          self.error(404)
          return
        self.render_template(file_id+'.html', {
            'body': page.body,
        })

My 2 to-dos:

change variable file_id to page_id
change writing to direct output instead of template


texts:
I'm learning C# and currently having an assignment on Tic Tac Toe. I'd love to have some feedback on where I can improve.

I've managed to create the end game functions but I feel it could be improved. I'm just not sure how to do it and was hoping someone here could help me.

I hope the information I've provided is enough, this.cells is a multidimensional array containing the Cell objects:

/// <summary>
/// Contains info about what kind of cell we're dealing with
/// </summary>
public enum Cell {
  Empty,
  Circle,
  Cross
}

Below is the part I'm searching feedback on. Too many if statements? What could I have done different or better?

/// <summary>
/// Check all possible combinations for the target cell
/// of winning the game (row, column, or slope).
///
/// Returns true if there is a win condition, false if there isn't.
/// </summary>
private bool IsGameOver(Cell cell) {
    // Row 1
    if (this.cells[0, 0] == cell && this.cells[0, 1] == cell && this.cells[0, 2] == cell) {
        return true;
    }

    // Row 2
    if (this.cells[1, 0] == cell && this.cells[1, 1] == cell && this.cells[1, 2] == cell) {
        return true;
    }

    // Row 3
    if (this.cells[2, 0] == cell && this.cells[2, 1] == cell && this.cells[2, 2] == cell) {
        return true;
    }

    // Clm 1
    if (this.cells[0, 0] == cell && this.cells[1, 0] == cell && this.cells[2, 0] == cell) {
        return true;
    }

    // Clm 2
    if (this.cells[1, 0] == cell && this.cells[1, 1] == cell && this.cells[1, 2] == cell) {
        return true;
    }

    // Clm 3
    if (this.cells[2, 0] == cell && this.cells[2, 1] == cell && this.cells[2, 2] == cell) {
        return true;
    }

    // Horizontal line 1
    if (this.cells[0, 0] == cell && this.cells[1, 1] == cell && this.cells[2, 2] == cell) {
        return true;
    }

    // Horizontal line 2
    if (this.cells[0, 2] == cell && this.cells[1, 1] == cell && this.cells[2, 0] == cell) {
        return true;
    }

    return false;
}


texts: Finding most common contiguous sub-lists in an array of lists

texts:
Objective: Given a set of sequences ( eg: step1->step2->step3, step1->step3->step5) ) arranged in an array of lists, count the number of times every contiguous sub-lists occur

Where I need your help:

The code below works, but is very slow on my original dataset (100M sequences, with 100 unique steps). Can you help me make this more efficient? For larger datasets, is there a more efficient programming method than just brute force?
My code currently depends on each element in the list being a single character. How can I adapt this code to handle multiple-character elements?

Working code:

from collections import Counter

sequences = [['A','B'],['A','B','B'],['A','C','A','B']]
counts = Counter()

for sequence in sequences:
    input = "".join(sequence)

    for j in range(1,len(input)+1):
        counts = counts + Counter(input[i:i+j] for i in range(len(input)-(j-1)))
        print counts

for x in counts:
    print x,":",counts[x]," times"


texts: Dijkstra's algorithm is slow. (For loops)

texts:
I tried to add Dijkstra's algorithm to a js game. First when I got it working it was very very Laggy (5-10 fps) and the browser would crash.. After adding a lot more improvements I got it to like 50-60 fps with 200 tiles (see GRID_SPREADING in script bellow). When I turn off this algorithm I have 120-144 fps, but I am trying to at least get 60+ fps while using 800-1000 tiles (see GRID_SPREADING in script below, I want max to be at least 800). I am not that good at coding yet so I would really be thankfull if you can help me achieve this goal... (here is the video I followed to create this: https://www.youtube.com/watch?v=0faPPgOT--E&t=934s, though, he was doing it in scratch).
Here is the laggy part:
var GRID_SPREADING = {
    dist: 80,
    b_col: 100,
    max: 400,
    show: false
}

// the main player will look and move to the direction of the nearest tile (not the direction to the nearest tile, but the dir property of the nearest tile)
const pathfindLoop = async () => { // pgrids is an object of arrays that holds all dijkstra algorithm's tiles
    if(!doPathfind || !nearestEnemy || dist4(nearestEnemy[1], nearestEnemy[2], enemyMovedPath[0], enemyMovedPath[1]) < 10) {
        await sleep(10);
        pathfindLoop();
        return;
    }
    if(Object.keys(pgrids).length > GRID_SPREADING.max){
        enemyMovedPath[0] = nearestEnemy[1];
        enemyMovedPath[1] = nearestEnemy[2];
        realPgrids = pgrids;
        pgrids = {};
    } else {

        let makeFirstP = true;
        for(let mfp in pgrids) {

            if(dist4(pgrids[mfp].x, pgrids[mfp].y, nearestEnemy[1], nearestEnemy[2]) < 50); {
                makeFirstP = false;
            }
        }
        if(makeFirstP) {
            createPathObj(nearestEnemy[1], nearestEnemy[2], 90);
        }
        for(let o in pgrids) {
            if(!(pgrids[o].checked)) {
                for(let i = 0; i < 4; i++) {
                    if(i == 3) {
                        pgrids[o].checked = true;
                    }
                    let res1 = locwxda(pgrids[o].x, pgrids[o].y, i*90, -GRID_SPREADING.dist);
                    let res = {x: res1.x, y: res1.y};
                    let go = true;

                    for(pgrid in pgrids) {
                        if(dist4(res.x, res.y, pgrids[pgrid].x, pgrids[pgrid].y) < GRID_SPREADING.dist/2.5) {
                            go = false;
                            break;
                        }
                    }
                    if(go) {

                        for(build in builds) { // builds is a large object of arrays: 50-300 properties, but removing this for loop doesn't improve much at all
                            if(dist4(builds[build][1], builds[build][2], res.x, res.y) < GRID_SPREADING.b_col) {
                                go = false;
                                break;
                            }
                        }

                    }

                    if(go) {
                        createPathObj(res.x, res.y, i*90) // a simple short function, adds an array property to object pgrids
                    }
                }
            }
        }
    }

        await sleep(10);
        pathfindLoop();
    }
    pathfindLoop();

I've done many research but I can't find the solution to solve this lag. Is there a completely different and better way to do this?


texts: Doubly linked std::list simple implementation

texts:
I've implemented a simple doubly linked list structure. I would appreciate all criticism relevant to code, style, flow, and so forth.

How to implement end iterator and pop_back/pop_front properly? Where memory may leak?

P.S.I didn't make it template, because this is simple version version.

#include <cstddef>
#include <iterator>

using T = int;

class List {
/// Nodes
public:
    class Node {
    public:
        T data;
        Node *next;
        Node *prev;

    public:
        explicit Node(Node *next_, Node *prev_) : next(next_), prev(prev_) {}

        explicit Node(const T &_data, Node *next_, Node *prev_) :
                data(_data), next(next_), prev(prev_) {}

        ~Node() {}
    };
///

/// Iterators
public:
    class Iterator : public std::iterator<std::bidirectional_iterator_tag, T> {
    public:
        Node *position;
        Node *tail;

    public:
        Iterator(Node *node) : position(node) {}

        Iterator(Node *node, Node *_tail) : position(node), tail(_tail) {
        }

        Iterator &operator++() noexcept {
            position = position->next;
            return *this;
        }

        Iterator operator++(int) noexcept {
            auto old = *this;
            position = position->next;
            return old;
        }

        Iterator &operator--() noexcept {
            if (position == nullptr) position = tail;
            else
                position = position->prev;
            return *this;
        }

        Iterator operator--(int) noexcept {
            auto old = *this;
            if (position == nullptr) position = tail;
            else
                position = position->prev;
            return old;
        }

        T &operator*() const noexcept {
            return (position->data);
        }

        bool operator!=(Iterator other) noexcept {
            return position != other.position;
        }

        bool operator==(Iterator other) noexcept {
            return position == other.position;
        }

        ~Iterator() {}
    };
///

/// list
private:
    Node *head = nullptr;
    Node *tail = nullptr;
    size_t size_ = 0;

public:
    List() {}

    void push_back(const T &_data) {
        Node *node = new Node(_data, nullptr, tail);
        if (tail != nullptr) {
            node->prev = tail;
            tail->next = node;
            tail = node;
        } else {
            head = tail = node;
        }
        ++size_;
    }

    void push_front(const T &_data) {
        Node *node = new Node(_data, head, nullptr);
        if (head != nullptr) {
            head->prev = node;
            node->next = head;
            head = node;
        } else {
            head = tail = node;
        }
        ++size_;
    }

    void pop_back() {
        tail = tail->prev;
        if (tail != nullptr) {
            tail->next = nullptr;
        }
        --size_;
    }

    void pop_front() {
        head = head->next;
        if (head != nullptr) {
            head->prev = nullptr;
        }
        --size_;
    }

    size_t size() {
        return size_;
    }

    size_t size() const {
        return size_;
    }

    Iterator begin() {
        return Iterator(head, tail);
    }

    Iterator begin() const {
        return Iterator(head, tail);
    }

    Iterator end() {
        Iterator iter(nullptr, tail);
        return iter;
    }

    Iterator end() const {
        Iterator iter(nullptr, tail);
        return iter;
    }

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

    ~List() {
        Node * tmp = nullptr;
        while (head)
        {
            tmp = head;
            head = head->next;
            delete tmp;
        }
        head = tail = nullptr;
    }
};


texts: Iterative tree traversal to turn tree into a dictionary and list

texts:
I am trying to iteratively turn a tree into a list.

For example:

                   c1
              c11        c12
          c111   c112

The tree above should return:

        [
            {'value': 'c1', 'children':
                [
                    {'value': 'c12', 'children': []} ,
                    {'value': 'c11', 'children':
                        [
                            {'value': 'c112', 'children': []},
                            {'value': 'c111', 'children': []}
                        ]
                ]
            }
        ]

Below is my code and here is gist for clearer viewing:

class Node():
    def __init__(self, node_list, value):
        self.node_list = node_list
        self.value = value

def reconstruct_iteratively(root):

    stack = list()

    # A tuple that stores node to be traverse and the layer the node is in
    node_tuple = (root, 0)
    stack.append(node_tuple)

    layer = 0
    pre_layer = 0
    level = dict()

    # This is a postorder traversal
    while len(stack) != 0:
        # This case catch the event that next node is the parent layer and this node is not
        #     a termination node

        if node_tuple[1] < pre_layer - 1:
            parent_node = stack.pop()
            parent_node_dict = {'value': parent_node[0].value, 'children': level.pop(layer, None)}
            pre_layer = layer
            layer -= 1

            if layer in level:
                level[layer].append(parent_node_dict)
            else:
                level[layer] = [parent_node_dict]

            if len(stack) != 0:
                node_tuple = stack[-1]

        # This case catch the event for traversing down to the child
        elif node_tuple[0].node_list is not None:
            for child in node_tuple[0].node_list:
                stack.append((child, layer + 1))
            node_tuple = (node_tuple[0].node_list[-1], layer + 1)
            layer += 1
        # This case catch the event that we are at the termination node
        elif node_tuple[0].node_list is None:
            old_node = stack.pop()
            node_dict = {'value': old_node[0].value, 'children': []}
            node_tuple = stack[-1]

            # Two possible scenario
            # 1. The next node is in the same layer
            # 2. The next node is in the parent layer
            if node_tuple[1] == layer:
                if layer in level:
                    level[layer].append(node_dict)
                else:
                    level[layer] = [node_dict]
            else:
                if layer in level:
                    level[layer].append(node_dict)
                else:
                    level[layer] = [node_dict]

                parent_node = stack.pop()
                parent_node_dict = {'value': parent_node[0].value, 'children': level.pop(layer, None)}
                pre_layer = layer
                layer -= 1

                if layer in level:
                    level[layer].append(parent_node_dict)
                else:
                    level[layer] = [parent_node_dict]

                if len(stack) != 0:
                    node_tuple = stack[-1]

    return [parent_node_dict]

I am looking for advices to make the code clearer and more efficient. Any comment would be appreciated.

Thanks


texts:
Awhile ago I created a program that unlocked spreadsheets, for a better understanding of what happens when it's run, see here.

I decided to rewrite it again, and go for a more OOP approach..

My questions being, what can be done better here, Is a module better then a class in this program, and are there better ways to write a log then just writing a text file?

Source:

#!/usr/loca//bin/ruby

require 'rubygems'
require '<mailgem>'
require 'fileutils'

class SpreadsheetManager

  attr_accessor :folio_num

  def initialize(folio_num)
    @folio_num = folio_num
  end

  def check_folio_num
    if folio_num =~ /\A\d{7}\z/
      search_lockfile
    else
      puts <<-EOF
        USAGE: unlock_ss <folio number>
      EOF
    end
  end

  def search_lockfile
    lockfile = "/path/to/file/.~lock.#{@folio_num}.ods#"
    if File.exist?(lockfile)
      puts "File: #{folio_num}.ods, found in lockfiles."
      unlock_file(lockfile)
    else
      puts "File: #{folio_num}.ods, not found within lockfiles."
      send_mail
      raise LoadError.new("#{folio_num} not found, check lockfiles maunaully.")
    end
  end

  def unlock_file(lockfile)
    puts "Removing file from list"
    FileUtils.rm(lockfile)
    puts "Spreadsheet: #{folio_num}.ods; removed from lockfile list."
    log_data
  end

  def log_data
    log = "/path/to/log/sslog.txt"
    x = "[#{Time.now}]::File: #{folio_num}.ods unlocked."
    File.open(log, "a+") { |s| s.puts(x) }
  end

  def send_mail
    MailGem::Mail.new do |m|
      m.from               = '<email-address>'
      m.to                 = '<email-address>'
      m.subject            = 'Folio loading error'
      m.body               = "File: #{folio_num}.ods not found in lockfiles..",
                             "Check folio numbers and lockfiles and try again",
                             "If file is found contact admin."
    end.send
  end
end

manage = SpreadsheetManager.new(ARGV[0])
manage.check_folio_num