texts:
Does this code calculate the retention rate per acquisition channel correctly?

$$
R = \frac{E - N}{S} * 100
$$

Where \$E\$ is the number of customer at the end of a period, \$N\$ is the number of new customers acquired during that period, and \$S\$ is the number of customers at the start of that period.

 +-------------+------------+---------------+--------------+
 | users       | orders     | acqus_channel | user_channel |
 +-------------+------------+---------------+--------------+
 | login_id    | orderid    | channel_id    | channel_id   |
 |  last_login | login_id   | channel_name  | login_id     |
 | first_login | total      |               |              |
 | cancel_date | subtotal   |               |              |
 |             | date       |               |              |
 |             | channel_id |               |              |
 |             |            |               |              |
 +-------------+------------+---------------+--------------+

Let's say we are calculating for Feb 2018:

To get end period customers, I calculated (existing + new - cancelled)
Timestamps are unixtime

SELECT e.channel_id channel,
((e.exisiting + n.new - c.cancelled)-n.new)/e.existing))*100 Retention_Rate
from existing_customers e
JOIN new_customers n on e.channel = n.channel
JOIN cancelled_customers c on n.channel = c.channel
GROUP BY channel

(
SELECT a.channel_id channel, COUNT(DISTINCT u.login_id) new from
users u
JOIN user_channel uc on uc.login_id = u.login_id
JOIN acqus_channel ac on ac.channel_id = uc.channel_id
WHERE DATE(u.first_login) BETWEEN '2018-02-01' and '2018-02-28'
AND DATE(u.cancel_date) > '2018-02-28'
GROUP BY channel
) new_customers

(
SELECT a.channel_id channel, COUNT(DISTINCT u.login_id) existing
FROM users u
JOIN user_channel uc on uc.login_id = u.login_id
JOIN acqus_channel ac on ac.channel_id = uc.channel_id
WHERE DATE(u.first_login) < '2018-02-01'
and DATE(u.cancel_date) > '2018-02-01' OR NULL
GROUP BY channel
) existing_customers

(
SELECT a.channel_id channel, COUNT(DISTINCT u.login_id) cancelled
FROM users u
JOIN user_channel uc on uc.login_id = u.login_id
JOIN acqus_channel ac on ac.channel_id = uc.channel_id
WHERE DATE(u.cancel_date) BETWEEN '2018-02-01' and '2018-02-28'
GROUP BY channel
) cancelled_customers


texts: Count the number of riders in each category

texts:
I have a code to get riders from certain teams and calculate the number of riders in those teams in that category:
valid_clubs = []
with open("validclubs.txt") as f:
    for line in f:
        valid_clubs.append(line)

disqualification_reasons = ["WKG", "UPG", "ZP", "HR", "HEIGHT", "ZRVG", "new", "AGE", "DQ", "MAP", "20MINS", "5MINS"]

with open("results.csv", 'rt', encoding='UTF-8',errors='ignore') as file:  # open results file to get breakdown of results
    reader = csv.reader(file, skipinitialspace=True, escapechar='\\')
    # each variable is current number of riders in the category
    A = B = C = D = E = Q = W = 0  # setting all values to 0 so we can work out number of riders in each category
    for row in reader:
        try:
            category = row[0]
            if row[4] in valid_clubs:
                if row[7] == "0":  # if club is in valid_clubs.txt and gender = female
                    W = W + 1  # each time this condition is met increase value of W by 1, where W is the amount of women
                if "A" == category:  # if club is in valid_clubs.txt and category is A
                    A = A + 1  # each time this condition is met increase value of A by 1
                if "B" == category:  # if club is in valid_clubs.txt and category is B
                    B = B + 1  # each time this condition is met increase value of B by 1
                if "C" == category:  # if club is in valid_clubs.txt and category is C
                    C = C + 1  # each time this condition is met increase value of C by 1
                if "D" == category:  # if club is in valid_clubs.txt and category is D
                    D = D + 1  # each time this condition is met increase value of D by 1
                if category in disqualification_reasons:  # all the possible DQ reason
                    Q = Q + 1  # each time this condition is met increase value of Q by 1, where Q is the number of riders DQ'ed
                if "E" == category:  # if club is in valid_clubs.txt and category is E
                    E = E + 1  # each time this condition is met increase value of E by 1
        except IndexError:  # ignore errors where row is empty
            pass
        total = str(A + B + C + D + E + Q)
print("There were", total, "riders", W, " were women:", "\nCat A:", A, "\nCat B:", B, "\nCat C:",
      C, "\nCat D:", D, "\nCat E:", E, "\nDisqualified:", Q)

It is a really repetitive code and I'm sure could be cleaned up. I would appreciate some advice on how you would do this.
Here is an example CSV:
Category.Position,Name,Time,Team,RandomInt1,RandomInt2,Male?
A,1,Person 4,00:54:12.92,2281,343,4.4,1
A,2,Person 3,00:54:13.29,10195,310,4.2,1
A,3,Person 2,00:54:19.19,84,334,5.0,1
A,4,Person 1,00:54:19.33,7535,297,4.9,1

Category would change as you go down the CSV
The Male? column is 1 when the person is male and 0 when they are female,
Validclubs is a list of the team numbers which I want to use, imported from a txt file,
RandomInt1/RandomInt2 are irrelevant for now
I would appreciate any advice on reducing the code so it is cleaner/shorter.
I want to use built-in libraries so not pandas.


texts:
The following piece of code is used to re-position controls on a form considering different options.

Once you have multiple controls this becomes quite messy. I would appreciate your improvement suggestions.

private void dlgOptionsForm_Load(object sender, System.EventArgs e)
    {

        if (_hideAccountingOption)
        {
            grpAccountingOption.Visible = false;
            Height -= grpAccountingOption.Height;

            grpPeriod.Top -= (grpAccountingOption.Height + 8);
            grpPrintOptions.Top -= (grpAccountingOption.Height + 8);
            grpInvoiceInformation.Top -= (grpAccountingOption.Height + 8);
            grpHND.Top -= (grpAccountingOption.Height + 8);
            chkPrint.Checked = false;
            grpArchiveDocument.Top -= (grpAccountingOption.Height + 8);
            grpBalanceControlList.Top -= (grpAccountingOption.Height + 8);
        }

        if (_hidePeriod)
        {
            grpPeriod.Visible = false;
            Height -= grpPeriod.Height;

            grpPrintOptions.Top -= (grpPeriod.Height + 8);
            grpInvoiceInformation.Top -= (grpPeriod.Height + 8);
            grpHND.Top -= (grpPeriod.Height + 8);
            chkPrint.Checked = false;
            grpArchiveDocument.Top -= (grpPeriod.Height + 8);
            grpBalanceControlList.Top -= (grpPeriod.Height + 8);
        }

        if (_hidePrintOptions)
        {
            grpPrintOptions.Visible = false;
            this.Height -= grpPrintOptions.Height;
            grpInvoiceInformation.Top -= (grpPrintOptions.Height + 8);
            grpHND.Top -= (grpPrintOptions.Height + 8);
            chkPrint.Checked = false;
            grpArchiveDocument.Top -= (grpPrintOptions.Height + 8);
            grpBalanceControlList.Top -= (grpPrintOptions.Height + 8);
        }

        ....
    }


texts: Python Tic Tac Toe Building Block Function

texts:
Would appreciate any input on these building blocks functions of tic tac toe.

def display_field(cells):
    print('''\
---------
| {} {} {} |
| {} {} {} |
| {} {} {} |
---------\
'''.format(*cells))

def analyze_field(cells):
    """

    Args:
        cells (str): a string of an XO pattern

    Returns:
        (str): the result of the XO field
    """

    num_x = cells.lower().count('x')
    num_o = cells.lower().count('o')

    rows = [[cells[j] for j in range(i, i + 3)] for i in range(0, 9, 3)]
    columns = [[row[i] for row in rows] for i in range(3)]

    first_diagonal = rows[0][0] + rows[1][1] + rows[2][2]
    second_diagonal = rows[0][2] + rows[1][1] + rows[2][0]

    if abs(num_x - num_o) not in [0, 1]:
        return 'Impossible'

    num_winners = 0
    for row, column in zip(rows, columns):
        if len(set(row)) == 1:
            num_winners += 1
        if len(set(column)) == 1:
            num_winners += 1
    if num_winners > 1:
        return 'Impossible'

    for row in rows:
        if len(set(row)) <= 1:
            return f'{row[0]} wins'

    for column in columns:
        if len(set(column)) <= 1:
            return f'{column[0]} wins'

    if len(set(first_diagonal)) <= 1:
        return f'{first_diagonal[0]} wins'

    elif len(set(second_diagonal)) <= 1:
        return f'{second_diagonal[0]} wins'

    # No winner
    else:
        if '_' in cells or ' ' in cells:
            return 'Game not finished'
        else:
            return 'Draw'

cells = input('Enter cells:')

display_field(cells)

print(analyze_field(cells))

Enter cells:XO_XO_XOX
---------
| X O _ |
| X O _ |
| X O X |
---------
Impossible


texts: Filtering data stored using classes via user-called function the proper way?

texts:
I'm currently working on an API package. Basically what it does is scrapes team data and stores them in list of Team objects. The team object contains data such as Team.name,rank, country etc.

If a user wants to filter that list to find something in it, I have this really messy and ugly (but working) function:

def find_team(self, name=None, country=None, rank_exactly=None, score_exactly=None, rank_change=None, team_id=None,
                  score_lower=None, score_higher=None, partial_name=None, rank_lower=None, rank_higher=None):
        """
        Finds a team by provided keyword attributes, returns a list of teams matching the filter settings
        Keyword Arguments:
        name - exact team name (case insensitive)
        country - team origin country
        rank_exactly - rank exactly
        rank_lower - only teams with lower rank than provided
        rank_higher - only teams with higher rank than provided
        rank_change - the state of ank change
        score_exactly - score exactly
        score_lower - only teams with lower score than provided
        score_higher - only teams with higher score than provided
        team_id = exact team id
        partial_name - part of name
        """
        if not self.teams:
            raise AttributeError("Object team list is empty")
        results = []
        for team in self.teams:
            all_args=[]
            if name:
                if name.lower() == team.name.lower():
                    all_args.append(True)
                else:
                    all_args.append(False)
            if country:
                if country.lower() == team.country.lower():
                    all_args.append(True)
                else:
                    all_args.append(False)
            if rank_exactly:
                if rank_exactly == team.rank:
                    all_args.append(True)
                else:
                    all_args.append(False)
            if rank_higher:
                if int(rank_higher) > int(team.rank):
                    all_args.append(True)
                else:
                    all_args.append(False)
            if rank_lower:
                if int(rank_lower) < int(team.rank):
                    all_args.append(True)
                else:
                    all_args.append(False)
            if score_exactly:
                if score_exactly == team.score:
                    all_args.append(True)
                else:
                    all_args.append(False)
            if rank_change:
                if rank_change == team.rank_change:
                    all_args.append(True)
                else:
                    all_args.append(False)
            if team_id:
                if team_id == team.team_id:
                    all_args.append(True)
                else:
                    all_args.append(False)
            if score_higher:
                if int(score_higher) < int(team.score.replace(',','')):
                    all_args.append(True)
                else:
                    all_args.append(False)
            if score_lower:
                if int(score_lower) > int(team.score.replace(',','')):
                    all_args.append(True)
                else:
                    all_args.append(False)
            if partial_name:
                if partial_name.lower() in team.name.lower():
                    all_args.append(True)
                else:
                    all_args.append(False)
            if all(all_args):
                results.append(team)
        return results

How could I make this more Pythonic and just better in general?


texts: Generic class for displaying UIAlertView / UIAlertController on iOS

texts:
To address backwards compatibility for UIAlertView, I have come up with an interface that would seem to work for both iOS versions 8 and lower.

This is not something I would like to roll out in production hence I would appreciate few extra pair of eyes taking a look at it.

Here is a link to the GitHub gist.

//UIAlertMode.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

typedef void (^AlertViewSelectionBlock) (NSInteger);
typedef void (^AlertControllerDefaultAction ) (UIAlertAction *);
typedef void (^AlertControllerCancelAction) (UIAlertAction *);
typedef void (^GenericBlock) (void *);

@interface UIAlertMode : NSObject

@property (assign, nonatomic) AlertViewSelectionBlock alertViewBlock;
@property (assign, nonatomic) AlertControllerCancelAction cancelAlertAction;
@property (assign, nonatomic) AlertControllerDefaultAction defaultAlertAction;

- (id) initAlertWith:(NSString *) title
                    :(NSString *) message
                    :(NSString *) cancelButtonTitle
                    :(NSString *) otherButtonTitle;

- (BOOL) supportsiOS8;
- (void) showAlertFor:(AlertViewSelectionBlock) alertViewBlock;
- (void) showAlertControllerFor:(AlertControllerDefaultAction) defaultAction :(AlertControllerCancelAction) cancelAction;
- (void) showAlertWith:(GenericBlock) block;
@end

// UIAlertMode.m

#import "UIAlertMode.h"
#import <objc/objc-runtime.h>
#import "AppDelegate.h"

@interface UIAlertMode () <UIAlertViewDelegate> {
    UIAlertView       *_alertView;
    UIAlertController *_alertController;
}

@end

@implementation UIAlertMode

@synthesize alertViewBlock;
@synthesize defaultAlertAction;
@synthesize cancelAlertAction;

- (id) init {
    self = [super init];
    return self;
}

- (id) initAlertWith:(NSString *) title
                    :(NSString *) message
                    :(NSString *) cancelButtonTitle
                    :(NSString *) otherButtonTitle {
    self = [super init];
    if ([self supportsiOS8]) {
        _alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if (self.defaultAlertAction) {
                self.defaultAlertAction(action);
            }
        }];

        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            if (self.cancelAlertAction) {
                self.cancelAlertAction(action);
            }
        }];

        [_alertController addAction:defaultAction];
        [_alertController addAction:cancelAction];

    } else {
        _alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitle, nil];
    }
    return self;
}
#pragma mark - Public API

- (BOOL) supportsiOS8 {
    Class kAlertViewClass = NSClassFromString(@"UIAlertController");
    return !kAlertViewClass ? NO : YES;
}

- (void) showAlertFor:(AlertViewSelectionBlock) alertBlock {
    self.alertViewBlock = alertBlock;
    [_alertView show];
}
- (void) showAlertControllerFor:(AlertControllerDefaultAction) defaultAction :(AlertControllerCancelAction) cancelAction {
    self.cancelAlertAction = cancelAction;
    self.defaultAlertAction = defaultAction;
    dispatch_async(dispatch_get_main_queue(), ^{
        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [delegate.window.rootViewController presentViewController:_alertController animated:YES completion:nil];
    });
}

#pragma mark - UIAlertView delegate method

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (self.alertViewBlock) {
        self.alertViewBlock(buttonIndex);
    }
}

I would like to get feedback on design, scalability, and memory management.


texts: UnionFind data structure implemented in Python

texts:
This class is used to create sets out of nodes to from a graph-like structure (or grouping since I remove most of the normal graph structure and all child nodes have the same parent).

Is there anything I can do to improve the design of this class? Is the use of static methods here appropriate?

class UnionFind(object):
    '''
    Used to initialize the set and then holds the required functions
    to operate on them
    '''

    def __init__(self, vertex):
        self.rank = 0
        self.parent = self
        self.vertex = vertex

    @staticmethod
    def find(x):
        if x != x.parent:
            x.parent = UnionFind.find(x.parent)
        return x

    @staticmethod
    def union(x,y):
        xroot = UnionFind.find(x)
        yroot = UnionFind.find(y)

        if xroot == yroot:
            return
        if xroot.rank > yroot.rank:
            yroot.parent = xroot
        else:
            xroot.parent = yroot
            if xroot.rank == yroot.rank:
                yroot.rank += 1


texts:
I'm a new programmer who is currently working on a personal project. It is supposed to be a login program which stores user data in a SQLite database.
I was wondering if anyone could look at my code and provide any constructive criticism. Please contribute, regardless of how insignificant the flaw may seem.
Anyway without further ado, here is my code:
import sqlite3, time

def is_valid_username(username):

    find_user = ("SELECT * FROM user WHERE username = ?")
    cursor.execute(find_user,[(username)])
    results = cursor.fetchall()
    return results

def is_valid_password(username, password):

    find_user = ("SELECT * FROM user WHERE username = ? AND password = ?")
    cursor.execute(find_user, [(username), (password)])
    result = cursor.fetchall()
    return result

def create_new_user():
    while True:
        username = input("Enter a new username: ")
        find_user = ("SELECT * FROM user WHERE username = ?")
        cursor.execute(find_user, [(username)])

        if (cursor.fetchall()):
            print("Username taken, please try again")
        else:
            break
    firstName = input("Enter your first name: ")
    surname = input("Enter your surname: ")
    password = input("Enter your password: ")
    repassword = input("Reenter your password: ")
    while password != repassword:
        print("Passwords do not match, try again.")
        password = input("Enter your password: ")
        repassword = input("Reenter your password: ")
    insert = "INSERT INTO user(username, firstname, surname, password) VALUES(?,?,?,?)"
    cursor.execute(insert, [(username), (firstName), (surname), (password)])
    db.commit()
    print("Account created")
    time.sleep(2)
    return

with sqlite3.connect("Users.db") as db:
    cursor = db.cursor()

    cursor.execute('''
    CREATE TABLE IF NOT EXISTS user(
    userID INTEGER PRIMARY KEY,
    username VARCHAR(20) NOT NULL,
    firstname VARCHAR(20) NOT NULL,
    surname VARCHAR(20) NOT NULL,
    password VARCHAR(20) NOT NULL);
    ''')

for i in range(3):
    username = input("Please input username: ")
    if (is_valid_username(username)):
        password = input("Please input password: ")
        if is_valid_password(username, password):
            print('Username and password accepted, welcome.')
            time.sleep(3)
            exit()
        else:
            print("Incorrect password, please try again?: ")
    else:
        Q1 = input("Not valid user. Would you like to create an account?: ")
        reply_yes = ('y', 'yes')
        if Q1.lower() in reply_yes:
            create_new_user()'


texts:
I've got the following code to find the shortest path between two nodes using almost-Dijkstra's-algorithm which was written for an exercise, and I'm looking for things to improve my general Scala style. What I currently have:

  object Graphs {
    case class Node[T](value : T)
    case class Edge[T](from : Node[T], to : Node[T], dist : Int)

    def shortest[T](edges : Set[Edge[T]], start : T, end : T) : Option[List[Edge[T]]] = {

      val tentative = edges.flatMap(e => Set(e.from, e.to)).map(n => (n, if (n.value == start)  Some(List.empty[Edge[T]]) else None )).toMap

      def rec(tentative : Map[Node[T], Option[List[Edge[T]]]]) : Option[List[Edge[T]]] = {
        val current = tentative.collect{ case (node, Some(route)) => (node, route)}.toList.sortBy(_._2.length).headOption

        current match {
          case None => None
          case Some((node, route)) => {
            if (node.value == end) Some(route)
            else {
              val fromHere = edges.filter(e => e.from == node)
              val tentupdates = for(edge <- fromHere if tentative.contains(edge.to)) yield {
                tentative.get(edge.to) match {
                  case None => throw new Error("broken algorithm")
                  case Some(Some(knownroute)) if (knownroute.map(_.dist).sum < route.map(_.dist).sum + edge.dist) => (edge.to, Some(knownroute))
                  case _ =>(edge.to, Some(edge :: route))
                }
              }

              val newtentative = (tentative ++ tentupdates) - node
              rec(newtentative)
            }
          }
        }
      }
      rec(tentative)
    }
  }

First of, getting some feedback on the correctness would be nice.

For the algorithm itself, I already know it could be refined by keeping track of the unevaluated edges, and for a more general solution keeping a second accumulator with the solved set wouldn't cost me much more, but I get the general idea of how to implement that.

I'm thinking of replacing Node with Scalaz TypeTags, and would like some feedback on whether that's a good idea.

Other than that, I'd like some feedback on general style, and how to improve readability - I have quite long lines now for example. Also, types like Map[Node[T], Option[List[Edge[T]]]] sort of hurt my eyes, I'd love to know how I could improve that.

Lastly, I really don't like my

case Some(Some(knownroute)) if (knownroute.map(_.dist).sum < route.map(_.dist).sum + edge.dist) => (edge.to, Some(knownroute))
case _ => (edge.to, Some(edge :: route))

the first case is only used as a filter, I'm actually looking for something like

case None || Some(Some(knownroute)) if (knownroute.map(_.dist).sum > route.map(_.dist).sum + edge.dist) => (edge.to, Some(edge :: route))

but I don't know how to express that.


texts:
I took a stab at implementing Promise.all():

"use strict";

function all (...promises) {
   const promise = new Promise((resolve, reject) => {
      let counter = 0;
      const values = [];
      let rejected = false;
      promises.forEach(
         (promise, idx) => {
            promise.then(val => {
                  counter++;
                  values[idx] = val;
                  if (counter === promises.length)
                     resolve(values);
               },
               () => {
                  if (!rejected) {
                     reject(new Error(`${promise} was rejected!`));
                     rejected = true;
                  }
               }
            );
         }
      );
   });
   return promise;
};


texts: Generate all possible combination of n-pair parentheses

texts:
The task is taken from LeetCode

  Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

  For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

My solution

is based on backtracking. Maybe there's a better approach than that? The reason I do this task is because I want to improve my skills. So, if you got any improvement suggestions or an alternative approach - no matter how fancy it is - feel free to post it here.

/**
 * @param {number} n
 * @return {string[]}
 */
var generateParenthesis = function(n) {
  const addParanthesis = (cur, open, close) => {
    if (cur.length === n * 2) {
      res.push(cur);
      return;
    }
    if (open < n) { addParanthesis(cur + '(', open + 1, close); }
    if (close < open) { addParanthesis(cur + ')', open, close + 1); }
  };
  const res = [];
  addParanthesis('', 0, 0);
  return res;
};


texts: Interview adjacency list graph problems in C++: proper graph implementation

texts:
I know this type of question has been asked before. However, my reason for asking it is gaining insight into what is expected in a 45 min interview when asked to implement graph algorithms. I have never had to give an interview, but have been asked in several interviews, questions pertaining to graphs. Specifically adjacency lists implementations. Several times I have asked the interviewer if they would like me to just implement the algorithm, or if they would prefer the basic structure of the graph too. Most times the response was to provide some level of structure before implementing the algorithm.

Provided the information above, my review request is as follows:

Is my implementation of a graph (provided below) sufficient?
Would you as a reviewer of the code be appalled provided I wrote it in under 20 min?
How would you simplify the code below such that it would be suitable for an interview, and sufficient enough to convey that you could solve problems like depth or breadth first search with it?

namespace graph
{
  template <typename T>
  struct directed_node
  {
    typedef typename std::list<std::shared_ptr<directed_node<T>>> adjacency_t;

    explicit directed_node(const T &t) :
      m_t(t)
    {}

    void connect(std::shared_ptr<directed_node<T>> node,
      typename adjacency_t::iterator addr)
    {
      auto it = m_adjacents.begin();
      for (it = m_adjacents.begin(); it != m_adjacents.end(); ++it) {
        if (node->m_t == (*it)->m_t) {
          break;
        }
      }

      if (it == m_adjacents.end()) {
        m_adjacents.push_back(node);
        node->m_adjacent_addr = addr;
      }
    }

    T m_t;
    adjacency_t m_adjacents;
    typename adjacency_t::iterator m_adjacent_addr;
  };

  template <typename T>
  struct directed
  {
    typedef typename std::list<std::shared_ptr<directed_node<T>>> adjacency_t;
    adjacency_t m_adjacency_list;

    typename adjacency_t::iterator insert(typename
      std::shared_ptr<directed_node<T>> node)
    {
      auto it = m_adjacency_list.begin();
      for (it = m_adjacency_list.begin(); it != m_adjacency_list.end(); ++it) {
        if ((*it)->m_t == node->m_t) {
          return it;
        }
      }

      return m_adjacency_list.insert(m_adjacency_list.end(), node);
    }
  };

  template <typename T>
  std::shared_ptr<directed<T>> create_directed()
  {
    return std::make_shared<directed<T>>();
  }

  template <typename T>
  std::shared_ptr<directed_node<T>> connect_directed(directed<T> &g,
    const T &from, const T &to)
  {
    std::shared_ptr<graph::directed_node<T>> n1 =
    std::make_shared<graph::directed_node<T>>(from);
    auto it1 = g.insert(n1);
    if (it1 != g.m_adjacency_list.end()) {
      n1 = (*it1);
    }

    std::shared_ptr<graph::directed_node<T>> n2 =
      std::make_shared<graph::directed_node<T>>(to);
    auto it2 = g.insert(n2);
    if (it2 != g.m_adjacency_list.end()) {
      n2 = (*it2);
    }

    n1->connect(n2, it2);

    return n1;
  }
}

int main()
{
  std::shared_ptr<graph::directed<int>> g = graph::create_directed<int>();
  graph::connect_directed(*g, 1, 2);
  return 0;
}


texts: how to properly expose an ES class function residing inside a module?

texts:
I have a little class for loading a config file:

// index.js:

class Config {
    constructor(path) {
        this.path = path || this.defaultPath;
        this.config = fs.readFileSync(this.path, { encoding: 'utf8' });
        this.config = JSON.parse(this.config);
    }
    get() {
        return this.config;
    }
}
Config.prototype.defaultPath = './config/config.json';

module.exports = {
    Config: Config,
};

And I test it like so:

// test.js:

const index = require('../index');

let config;

describe('config ', () => {
    before(() => {
        config = new index.Config().get();
    });
});

It works, but I'm wary of including a capitalized property in module.exports (mostly because I haven't seen this done before). Is there a best practice for achieving this in other ways? Should I just make the config class into its own .js file?


texts:
I have solved one programming problem where we have to find all the permutations of given numbers.

For example, \$[1,2,3]\$ have the following permutations:

$$[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]$$

I have written the code for it and my code successfully cleared all the tests. But, I am not really sure about its complexity.

public List<List<Integer>> permute(int[] num) {
    List<List<Integer>> res=new ArrayList<List<Integer>>();
    res.add(new ArrayList<Integer>()); // Add an empty list
    for(int number = 0; number < num.length; number++)
    {
        List<List<Integer>> curr = new ArrayList<List<Integer>>();
        for(List<Integer> nestedL : res)
        {
            for(int j = 0; j < nestedL.size() + 1 ;j++)
            {
                nestedL.add(j,num[number]);
                List<Integer> temp = new ArrayList(nestedL);
                curr.add(temp);
                nestedL.remove(j);
            }
        }
        res = new ArrayList<List<Integer>>(curr);
    }

   return res;
}

First, look at the algorithm, which suggests that it is a \$O(n^3)\$. But, I am not sure if it it correct. Would somebody like to throw more light on the complexity of this algorithm?


texts:
I am building a Rails marketplace application using TDD. I would like to get advice on the way in which I have built the User associated Profile associations and way in which these are then handled in the controllers.

User model

class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy
  has_many :listings, dependent: :destroy
  has_many :watches, dependent: :destroy
  has_many :watched_listings,  -> { uniq }, :through => :watches, dependent: :destroy

  # Include default devise modules. Others available are:

  acts_as_messageable

  def mailboxer_email(object)
    email
  end

  def self.search(search)
    where("email ILIKE ?", "%#{search}%")
  end

  after_create :build_profile

end

Profile model

class Profile < ActiveRecord::Base
  belongs_to :user

  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
end

Users controller

class UsersController < ApplicationController
  def index
    @users = User.all
    if params[:search]
      @users = User.search(params[:search]).order("created_at DESC")
    else
      @users = User.all.order('created_at DESC')
    end
  end

  def show
    @user = User.find(params[:id])
  end

  def watchlist
    @watched_listings = current_user.watched_listings.all
  end
end

Profiles controller

class ProfilesController < ApplicationController

  before_filter :authenticate_user!, :only [:edit, :update]
  before_filter :correct_user, :only [:edit, :update]

  def show
    @profile = Profile.find_by(user_id: params[:user_id])
  end

  def edit
    @profile = Profile.find_by user_id: current_user.id
  end

  def update
    @profile = Profile.find_by user_id: current_user.id
    if @profile.update(profile_params)
      flash[:notices] = ["Your profile was successfully updated"]
      render 'show'
    else
      flash[:notices] = ["Your profile could not be updated"]
      render 'edit'
    end
  end

  private

  def profile_params
    params.require(:profile).permit(:city, :country, :avatar)
  end

  def correct_user
    @profile = Profile.find_by(user_id: params[:user_id])
    redirect_to(root_path) unless current_user?(@profile)
  end
end

I have also defined:

Profiles helper

module ProfilesHelper
  def current_user?(user)
    user == current_user
  end
end

Within my Application Controller:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  def after_sign_in_path_for(resource)
    edit_user_profile_path(resource)
  end

  def after_sign_up_path_for(resource)
    edit_user_profile_path(resource)
  end
end

I'm very keen to get any feedback on:

If the use of the after_create :build_profile is appropriate. Does this violate SRP principles by making the user model responsible for the creation of a profile?
The best way to validate the correct user in the profile controller - to enforce whether a user can edit a profile or not.
Mainly whether it is required that I be finding profiles by Profile.find_by(user_id: params[:user_id]) rather than by a Profile ID.
Any other improvements to the code!

I have RSpec and Capybara tests to back this here.


texts:
Here is the code for the CString class that I created.

public class CString {

    public String reverse(String s) {
        char[] array = new char[s.length()];
        array = s.toCharArray();
        for(int i=0; i<array.length/2; i++) {
            char tmp = array[i];
            array[i] = array[array.length-1-i];
            array[array.length-1-i] = tmp;
        }
        return charArrayToString(array);
    }

    public String charArrayToString(char[] array) {
        StringBuffer sb = new StringBuffer();
        sb.append(array);
        return sb.toString();
    }
}

Is there any bug in the code? Are there more efficient ways to reverse a string?


texts:
This is a simple password generator. What do you think about it? I am learning C for a while at school and at home. This just has a mix of symbols, lowercase, uppercase and numbers, with a configurable length.

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

int main()
{
    int i = 0;
    int n = 0;
    int randomizer = 0;
    srand((unsigned int)(time(NULL)));
    char numbers [] = "1234567890";
    char letter [] = "abcdefghijklmnoqprstuvwyzx";
    char letterr [] = "ABCDEFGHIJKLMNOQPRSTUYWVZX";
    char symbols [] = "!@#$%^&*(){}[]:<>?,./";
    printf("\nHow long password:");
    scanf("%d", &n);
    char password[n];
    randomizer = rand() % 4;
    for (i=0;i<n;i++)
    {
        if(randomizer == 1)
        {
            password[i] = numbers[rand() % 10];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else if (randomizer == 2)
        {
            password[i] = symbols[rand() % 26];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else if (randomizer == 3)
        {
            password[i] = letterr[rand() % 26];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else
        {
            password[i] = letter[rand() % 21];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
    }
    return main();
}


texts:
I have a grid of different sized images. I made a click event function that grabs the image inside any clicked grid-item. It then saves the coordinates and size of the image and animates from the grid into its final resting place in the article. I was able to get the effect working perfectly the problem is that I need to make the click event more modular so I can reuse it. But I'm having trouble wrapping my head around it. I was hoping that someone could review my code and give me a few pointers on how to make this click event more modular:

var $ourWork = $('.ourWork'),
    $ourWorkChild = $('.ourWorkChild'),
    $body = $('body'),
    $workHdrMsg = $('.work .header-message'),
    $imgGhost = $('.img--ghost'),
    time = 0.25;

var $workGrid = $('.ourWork .grid').packery({
   columnWidth: '.ourWork .grid-sizer',
   itemSelector: '.ourWork .grid-item',
   percentPosition: true
});

$workGrid.on( 'click', '.grid-item', function( event ) {

   // find img.grow element inside of the work-grid element
   var rg = event.currentTarget,
      // ripple
       r = rg.querySelector('.ripplelink'),
      //  ripple_image
       rImg = r.querySelector('.img--grow'),
       // ripple image info
       riInfo = rImg.getBoundingClientRect(),
       ri_height = riInfo.height,
       ri_width = riInfo.width,
       ri_top = riInfo.top,
       ri_left = riInfo.left,
       $body = document.body,
       dupImg = rImg.cloneNode(true);

 // get size/position of the ghost image
  var gi = document.body.querySelector('.img--ghost'),
      giInfo = gi.getBoundingClientRect(),
      gi_height = giInfo.height,
      gi_width = giInfo.width,
      gi_top = giInfo.top,
      gi_left = giInfo.left,
      offsetY = window.pageYOffset;

      dupImg.style.width = ri_width + 'px';
      dupImg.style.height = ri_height + 'px';
      dupImg.style.left = ri_left + 'px';
      dupImg.style.top = ri_top + 'px';
      dupImg.style.position = 'absolute';

       $body.appendChild(dupImg);

   var t1 = new TimelineMax();
       t1
       .to([$workGrid, $workHdrMsg], time * 1.15, {delay: time, transformOrigin: '50% 100%', scale: .98, autoAlpha: 0, display:'none', ease: Power1.easeOut}, 0)
       .to($body, time * 1.15, {backgroundColor: '#4ba8f4', ease: Power1.easeOut}, 0)
       .set($ourWork, {display: 'none'})
       .set($ourWorkChild, {transformOrigin: '50% 100%', autoAlpha: 0, y: '+=25px', scale: .96, display: 'block'}, 0)
       .to(dupImg, time * 1.15, {width: gi_width, height: gi_height, x: gi_left - ri_left, y: gi_top - ri_top + offsetY, transformOrigin:'0% 0%', ease: Power1.easeOut}, '+=0.01')
       .to($ourWorkChild, time * 1.15 , {autoAlpha: 1, y: 0, scale: 1, ease: Power1.easeOut}, '+=0.015')
       .set(dupImg, {display: 'none'})
       .set($imgGhost, {opacity: '1'});

});


texts: JavaScript Array Comparison (aka Set Comparison)

texts:
I want to compare the values in two arrays. The order of the values doesn't matter. Basically they are two Sets. This function returns true if the values are the same in both arrays, or false otherwise.

function compareSets(a1, a2) {
    if (a1.length !== a2.length) {
        return false;
    }

    var len = a1.length;
    var a1Set = {};

    // Convert a1 into a Set
    for (var i = 0; i < len; i++) {
        var value1 = a1[i];
        a1Set[value1] = true;
    }

    // Compare a2 values to a1 values
    for (var i = 0; i < len; i++) {
        var value2 = a2[i];
        if (!(value2 in a1Set)) {
            return false;
        }
    }

    return true;
}

This is an \$O(n)\$ solution which is better than the naive \$O(n^2)\$. I think it is always safe to say that if the lengths are different, the arrays are not the same.

Is there any way I can make this more concise?


texts:
As a beginner in coding, I have just written this code.

The code should Add a form with a button to each user profile, it named Follow or Unfollow. It updates the user meta named "following" for the user who clicked the button. So we have to use the user IDs as a serialized array. Then we should use a query for the user meta "following" to get a list of all authors the current user has subscribed to and then query for the posts from these authors.

<?php

 if($_GET['follow']){fun1();}

 function fun1()
 {
$fauid = get_user_by( 'slug', get_query_var( 'author_name' ) );
$user_id= get_current_user_id();
$key = 'following';
$themeta = get_user_meta($user_id , $key, TRUE);
if($themeta != '') {
$user_id= get_current_user_id;
update_user_meta($user_id, 'following', $fauid); }

else {

$user_id= get_current_user_id;
add_user_meta($user_id , 'following' , $fauid , true );
update_user_meta($user_id, 'following', $fauid);
}
}

?>

<html>
    <button id="Button" name="Button" onClick='location.href="?follow=1"'>Follow Me <3 <3</button>
</html>

Is the code true or not?


texts: Executing an SQL command on a number of files

texts:
Is this thread safe?

I have a program that executes an SQL command on a number of files (selected by the user).

Here is where I create the threads:

var allThreads = new List<Task<bool>>();
if (fileList != null)
{

    foreach (var file in fileList)
    {
        var fileName = Path.GetFileName(file);
        if (File.Exists(file))
        {
            Log.AddToLog("Beginning to Process File: " + fileName);
            if (!ValidateFile(file))
            {
                Log.AddToLog(String.Format("Error! {0} is not a valid file for the {1}. Skipping this file.", fileName, JsonSettingsList.NameId));
                IsErrorsInLog = true;
            }
            else
            {
                var fileToProcess = file; //need to make copy for threading loop, otherwise it acts screwy
                var newTask = Task.Factory.StartNew<bool>(() => ProcessFile(fileToProcess));
                allThreads.Add(newTask);
            }
        }
        else
        {
            Log.AddToLog(String.Format(CultureInfo.CurrentCulture, "File {0} Does not Exist. File not processed.", fileName));
            IsErrorsInLog = true;
        }
    }

    //check result, if any of them return true, then there are errors in the log, and the user needs to be alerted.
    foreach (var task in allThreads)
    {
        try
        {
            var didThreadFail = task.Result;
            if (!IsErrorsInLog)
            {
                IsErrorsInLog = didThreadFail;
            }
        }
        catch (AggregateException aggEx)
        {
            foreach (Exception ex in aggEx.InnerExceptions)
            {
                Log.AddToLog(string.Format("Caught exception '{0}'",
                    ex.Message));
                IsErrorsInLog = true;
            }
        }
        finally
        {
            task.Dispose();
        }
    }
}

and then here is the code where I am actually accessing the database, inside of the ProcessFile() function:

//initialize oracle connection
oraConnection.Open();
using (var command = new OracleCommand(sqlText, oraConnection))
{
    command.Transaction = command.Connection.BeginTransaction();
    foreach (var line in fileByLine.Where((i, index) => index > 0))
    {
        if (!String.IsNullOrWhiteSpace(line))
        {
            //add parameters
            command.ExecuteNonQuery();
        }
    }

    command.Transaction.Commit();
    Log.AddToLog("Successfully Processed " + filePath);
}

oraConnection.Close();

The comments are where I have omitted unnecessary code for the sake of simplicity.


texts:
I am learning C and tried to make a basic singly linked list. I am looking for some feedback on my implementation. I have implemented deletion and reversal functions. Be hard on me as I am trying to improve.

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

//very basic linked list implimentation in C.
//basic node structure. No typedef.
struct node
{
  int val;
  struct node *next;
};

struct node *deleteNode(struct node *first, int num)
{
  struct node *prev=NULL;
  struct node *root = first;
  while (root != NULL)
  {
    if (root->val == num)
    {
      if (prev != NULL && root->next != NULL) //middle elements
      {
        prev->next = root -> next;
        free(root);
      }
      else if (prev == NULL) //first element
      {
        free(first);
        first = root->next;
        root = root->next;
      }
      else if (root->next == NULL) //last element
      {
        prev->next = NULL;
        free(root);
      }
    }
    prev = root;
    root = root -> next;
  }
  return first;
}

struct node *reverseList(struct node *root)
{
  struct node *temp= NULL;
  struct node *prev= NULL;

  while (root!= NULL)
  {
    temp = root->next;
    root->next = prev;
    prev = root;
    root = temp;
  }
  return prev;
}

void printList(struct node *root)
{
 while (root!= NULL)
 {
   printf("Value: %d\n", root -> val);
   root = root -> next;
 }
}

int main()
{
 struct node *root = NULL, *tail = NULL;

 int i=1;
 for (;i<=20; ++i)
 {
     struct node *current = malloc(sizeof(struct node));
     current -> val = i;
     current -> next = NULL;

     if (root==NULL) root = current;
     else tail -> next = current;

     tail = current;
 }

 //delete first,last and middle element
 root = deleteNode(root, 20);
 root = deleteNode(root, 1);
 root = deleteNode(root, 10);
 root = reverseList(root);
 printList(root);

 return 0;
}


texts: Sublime Text 2 R Build System (source file, send selection to interactive session)

texts:
The following is the description of the R build system I am using (very happy) with Sublime Text 2 on linux (Crunchbang). With it, I am able to:

to source the current file.R to an interactive R session;
to send the current selection to an interactive R session (supports multi selection);
to output plots and *.Rout files (non-interactive);

xsel, xdotool, terminator (or some other terminal that supports custom titles) and a bash script (see below) are requisites. Please, attention for the locations of each file.

The open_and_run_r.sh script is the object of revision (see its commented lines for details). But feel free to give your considerations about the whole picture.

Build File:

  .config/sublime-text-2/Packages/User/r.sublime-build

{       // source( $file ) into interactive session
        "shell": true,
        "cmd":
        [   "echo 'source(\"'$file'\")' | xsel -i -b; if xdotool search --name 'Running R' windowactivate --sync; then xdotool key --window 0 ctrl+shift+v; else open_and_run_r.sh; fi; xsel -c -b"
        ],

    "selector": "source.r",

    "variants":
    [
        {   // send current selection of $file to interactive session; supports ST2 multi-selection as well :)
            "name":     "r_send_selection",
            "shell":    true,
            "cmd":
            [   "xdotool getactivewindow key ctrl+c; if xdotool search --name \"Running R\" windowactivate --sync; then xdotool key --window 0 ctrl+shift+v Return; fi"
            ]
        },

        {   // generate custom output.Rout file (not the output.Rout from R CMD BATCH), non-interactive
            "name":     "r_output",
            "cmd":

            [   "/usr/bin/R --quiet --slave < $file > output.Rout"
            ]
        }
    ]
}

Lets give a proper formatting to the bash commands:

# source file, note:
   # escaped \" for JSON compatibility;
   # $file is ST2 global variable;
   # 'source()' is an R command
echo 'source(\"'$file'\")' | xsel -i -b;
if xdotool search --name 'Running R' windowactivate --sync;
    then xdotool key --window 0 ctrl+shift+v;
else open_and_run_r.sh;
fi;
xsel -c -b

# send selection
xdotool getactivewindow key ctrl+c;
if xdotool search --name \"Running R\" windowactivate --sync;
    then xdotool key --window 0 ctrl+shift+v Return;
fi

Finally the open_and_run_r.sh script (run as program enabled).

  ~/bin/open_and_run_r.sh

#!/bin/sh
echo 'Initializing Terminator...'
terminator --title "Running R" --command='R' &

# in this workaround
# I could not find a better way to properly
# catch the terminator ending,
# after it receives the 'Running R' name.

a=0

while [ $a = 0 ]; do
    if xdotool search --name 'Running R' windowactivate --sync;
        then a=1;
        xdotool key --window 0 ctrl+shift+v;
        echo 'Initialized.'
    fi;
    sleep 2; # decreasing the value increases asynchrony behavior.
done

Keymap file, for keyboard shortcuts.

  .config/sublime-text-2/Packages/User/Default (Linux).sublime-keymap

[

// R Build / [ctrl+b] see r.sublime-build/source current $file into interactive R

// R build / send current selection to interactive R
    {"keys": ["super+'"], "command": "build", "args": {"variant": "r_send_selection"} },

// R build / generate output.Rout and plots files from, non-interactive
    {"keys": ["ctrl+shift+b"], "command": "build", "args": {"variant": "r_output"} }

]


texts: JavaScript Symbol Table implementation using Binary Search

texts:
I'm currently going over Robert Sedgewick's Algorithms book. I implemented a Symbol Table using two parallel arrays one for keys and one for values. The keys array is ordered and the Symbol Table uses binary search to find the position of the elements in the array.
In the practice section, the implementation of the delete and floor method were left as exercises. Here are the directions for delete and floor:

I would like to see if there is any feedback in the implementation of those elements. Specially floor.
I come from Ruby, so any feedback regarding best practices in JavaScript is also welcome.
Here is the code:
class BinarySearchSt {
  constructor() {
    this.n = 0;
    this.keys = [];
    this.vals = [];
  }

  isEmpty() {
    return this.n === 0;
  }

  get(key) {
    if(this.isEmpty() === true) {
      return null;
    }

    let i = this.rank(key);

    if (i < this.n && this.keys[i] === key) {
      return this.vals[i];
    } else {
      return null;
    }
  }

  put(key, val) {
    let i = this.rank(key);
    if(i < this.n && this.keys[i] === key) {
      return this.vals[i] = val;
    }

    for(let j = this.n; j > i; j--) {
      this.keys[j] = this.keys[j - 1];
      this.vals[j] = this.vals[j - 1];
    }
    this.keys[i] = key;
    this.vals[i] = val;
    this.n++;
  }

  rank(key) {
    let lo = 0;
    let hi = this.n - 1;

    while(lo <= hi) {
      let mid = lo + Math.floor((hi - lo) / 2);
      let cmp = this.compareTo(key, this.keys[mid]);
      if(cmp < 0) {
        hi = mid - 1;
      } else if(cmp > 0) {
        lo = mid + 1;
      } else {
        return mid;
      }
    }
    return lo;
  }

  compareTo(val1, val2) {
    if((val1 === null || val2 === null) || (typeof val1 !== typeof val2)) {
      return null;
    }
    if (typeof val1 === 'string') {
      return (val1).localeCompare(val2);
    } else {
      if(val1 > val2){
        return 1;
      } else if (val1 < val2) {
        return -1;
      }
      return 0;
    }
  }

  min() {
    return this.keys[0];
  }

  max() {
    return this.keys[-1]
  }

  select(index) {
    return this.keys[index];
  }

  ceiling(key) {
    let i = this.rank(key);
    return this.keys[i];
  }

  floor(key) {
    if(this.n === 0) {
      throw 'noSuchElementException';
    }
    if(key === null) {
      throw 'ilegalArgumentException';
    }
    let i = this.rank(key);
    if(this.keys[i] === key || i === 0){
      return this.keys[i];
    }
    else {
      return this.keys[i - 1];
    }
  }

  delete(key) {
    if(key === null) { throw 'ilegalArgumentException' };
    let i = this.rank(key);
    this.keys.splice(i, 1);
    this.vals.splice(i, 1);
  }
}

const bst = new BinarySearchSt();

bst.put('s', 0)
bst.put('e', 1)
bst.put('a', 2)
bst.put('r', 3)
bst.put('c', 4)
bst.put('h', 5)
bst.put('e', 6)
bst.put('x', 7)
bst.put('a', 8)
bst.put('m', 9)
bst.put('p', 10)
bst.put('l', 11)
bst.put('e', 12)

console.log(bst.get('e'))


texts:
I've built a simple command line flashcard game for learning Korean. I'm a beginner programmer, so I just wanted to make sure I'm following best practices, especially pertaining to OOP principles.

Any feedback would be greatly appreciated.

Here's GitHub link and reposted below:

class FlashCard

  def initialize
    # TODO: load from file
    @korean_dict = {
      "사과" => "apple",
      "맥주" => "beer",
      "책" => "book",
      "의자" => "chair",
      "피아노" => "piano"
    }
    @english_dict = @korean_dict.invert
    @correct = 0
  end

  # starts the game
  def play
    puts '----------------'
    puts 'KOREAN FLASHCARD'
    puts '----------------'

    dict = pick_dict
    ask_questions(dict)
    print_results(dict)
  end

  # select korean-to-english or english-to-korean dictionary
  def pick_dict
    user_input = -1
    until (user_input == 1 || user_input == 2)
        print "Korean to English [press 1] or English to Korean [press 2]: "
        user_input = gets.chomp.to_i
    end
    user_input == 1 ? @korean_dict : @english_dict
  end

  # loop through dictionary and prompt user for answers
  def ask_questions(dict)
    dict.each_with_index do |(key, val), i|
      print "Question #{i+1}: #{key} is "
      input = gets.chomp
      check_answer(input, val, i)
    end
  end

  # check if user input matches correct translation
  def check_answer(input, val, index)
    if (input == val)
      @correct += 1
      puts "Correct! #{@correct} of #{index+1} correct.\n\n"
    else
      print "Sorry, the correct answer is #{val}."
      print " #{@correct} of #{index+1} correct.\n\n"
    end
  end

  def print_results(dict)
    puts "-------------------------------------"
    puts "Your final score: #{@correct} of #{dict.length}."
    puts "Below is a list of words in the quiz: "
    dict.each { |key, val| puts "#{key} --- #{val}" }
    puts "-------------------------------------\n\n"
  end

end

##################
# Runs Program
##################

fc = FlashCard.new
fc.play


texts: A little Python roguelike with mostly using standard libraries

texts:
So, I made this in order to practice my Python OOP and algorithms skills, and refactored it a bit after a few months of s tale. May anybody review it in a PR please? Want to see the flaws that could be fixed, considering I didn't improve much since the initial development of this.
https://github.com/fen0s/TABSlike/
One that especially makes me worries is the implementation of getting a 3x3 area around the unit to check for enemy units... Is it fine, and can you understand it overall?

def check_surroundings(self, y_coord, x_coord):
        y_coord -= 1 #to check y level above unit
        enemies = []
        for _ in range(3):
                if self.engine.check_inbounds(y_coord, x_coord-1) and self.engine.check_inbounds(y_coord, x_coord+2):
                    for entity in self.engine.techmap[y_coord][x_coord-1:x_coord+1]:
                        if entity and entity.team != self.team:
                            enemies.append(entity)
                y_coord+=1
        return enemies


texts:
This currently starts out with the speed of 2000 pages/min but shortly after starting it becomes very slow with a speed of about 200 pages/min. Why is this happening? How can I improve this scraper?

import scrapy
from scrapy.crawler import CrawlerProcess
from time import time

def isAscii(s):
    return all(ord(c) < 128 for c in s)

region = input('Region? ')
start = int(input('Start page? '))
end = int(input('End page? '))

startTime = time()

class LolSpider(scrapy.Spider):
    name = 'lolspider'
    start_urls = ['http://lolprofile.net/leaderboards/{}/{}'.format(region, page) for page in range(start, end)]
    def parse(self, response):
        for name in response.xpath('//span[not(@class)]/text()').extract():
            with open('lolusernames.txt', 'a') as f:
                if (' ' not in name) and (name != 'LoL') and isAscii(name):
                    f.write(name+'\n')

process = CrawlerProcess({})

process.crawl(LolSpider)
process.start()

endTime = time()
print('Completed in {:.2f} seconds'.format(endTime-startTime))

My main goal is to be as fast as possible and that's why I used scrapy. If anyone knows of a faster alternative I'd love to hear it.


texts: A Cipher with 2 methods for encryption/decryption

texts:
I'd like advice on how this could be written more efficiently, idiomatically, or just anything that could be improved upon.

I'd also like to know if there's an alternative to my forString method; I couldn't find anything similar in the library (and Scalex seems to be down, so I couldn't search).

There are 2 provided ways of encrypting a message:

val message:String = "Hello World!"
val key:String = "Key"

val encrypted = Cipher(message).simpleOffset(5)
println(encrypted) "Mjqqt%\twqi&"
val decrypted = Cipher(encrypted).simpleOffset(-5)
println(decrypted) "Hello World!"

val encrypted2 = Cipher(message).encryptWith(key)
println(encrypted2) "5l?Yv;Dv?Yk<"
val decrypted2 = Cipher(encrypted2).decryptWith(key)
println(decrypted2) "Hello World!"

and the code:

class Cipher(message:String) {
    val cHARMIN = 32 //Lower bound
    val cHARMAX = 126 //Upper bound

    //"Wraps" a character, so it doesn't go under cHARMIN, or over cHARMAX
    //Takes an Int so the Char can't underflow prior to being passed in
    private def wrap(n:Int):Char =
        if (n > cHARMAX) (n - cHARMAX + cHARMIN).toChar
        else if (n < cHARMIN) (n - cHARMIN + cHARMAX).toChar
        else n.toChar

    private def forString(str:String)(f:Char => Char):String = {
        var newStr = ""
        for(c <- str) { newStr += f(c) }
        newStr
    }

    //Creates a repeated key that's at least as long as the message to be encrypted
    private def getRepKey(key:String):String =
        if (key.length >= message.length) key
            else key * (message.length / key.length + 1)

    //Modifies a letter in the message, based on the respective letter in the key,
    //    and the given binary operator
    private def modifyWithStringWith(f:(Int,Int) => Int)(strKey:String):String = {
        var newString = ""
        (message zip getRepKey(strKey)).foreach { case (c1,c2) =>
                newString += wrap( f(c1,c2) ) }
        newString
    }

    //Offsets each character in a String by a given offset
    def simpleOffset(offset:Int):String =
        forString(message) { (c:Char) =>
            wrap((c + offset).toChar)
    }

    //Encrypts/Decrypts using another String as the key
    def encryptWith(key:String):String =
        modifyWithStringWith(_+_)(key)

    def decryptWith(key:String):String =
        modifyWithStringWith(_-_)(key)
}

object Cipher {
    def apply(msg:String):Cipher = new Cipher(msg)
}


texts:
Not sure how subjective this question is however I am looking for a peer review and general feedback on the intuitiveness and scaffolding potential of a framework concept. I have a gist on GitHub here: node.js MVVM framework concept

Is this more or less intuitive then using pseudo code and a template engine, such as handlebars, for rendering html?

The markup module will use three objects, the first being out design object:

var welcomeDesign = [{
  handle:'pageTitle'
  tag:'h1',
  attr:{
    class:'mainHeading'
  }
},{
  tag:'p',
  handle:'welcomeParagraph',
  content:[{
    content:'Welcome!',
    handle:'welcomeContent'
  },{
    tag:'img'
    handle:'welcomeBanner'
  }]
}];

The second object is our data:

var data = [{
  published:'11-8-13',
  title:'Hello World',
  content:'Welcome to...'
  assets:[{
    type:'img',
    path:'/images/'
    name:'cat.jpg'
  }]
}];

The third will be our mapping logic:

var imageAsset = {
    attr:{
      src:{
        key:'assets',
        map:function(obj, values){
          return values[0].path + values[0].name
        }
      }
    }
};

var welcome = {
  pageTitle:{
    content: {
      key:['published','title']
      map: function(object, values){
        return values[0] + ': ' + values[1];
      }
    }
  },
  welcomeContent:{
    content:{
      key:'content'
    }
  },
  welcomeBanner:imageAsset
};

and finally the methods for bringing them together:

var markup = require('markup'); //our module

var welcomeMessage = markup.design(welcomeDesign); //create a design instance

var homeWelcome = new welcomeMessage(data); //instantiate with our data
homeWelcome.render(welcome); //render with our logic


texts: Method Of Retrieving Random Value Depending on Type

texts:
I was wondering what would be the most appealing way of achieving this goal.

I have a blackbox. I give it a supported type and it returns a random value base off of the type.

For my supported types, I have an enum defined as follows:

public enum Types
{
    INTEGER,
    DOUBLE,
    BIGINTEGER,
    BIGDECIMAL,
    STRING,
    BOOLEAN,
    CHAR
}

I thought the easiest way would be to create a static function which returns an Object based off of the Type

public static Object getRandomValue(Types type)
{
    switch(type)
    {
        case INTEGER:
            return randomInt();
        case DOUBLE:
            return randomDouble();
        case BIGINTEGER:
            return randomBigInt();
        case BIGDECIMAL:
            return randomBigDecimal();
        case STRING:
            return randomString();
        case BOOLEAN:
            return randomBool();
        case CHAR:
            return randomChar();
    }
}

The problem is that an additional cast would have to be made each time that I want to retrieve a random value based off of this method.

I've looked into the design patterns abstract factory and factory, and I can't decide if there's an advantage into implementing either of those. Or if there's a different design pattern that seems to be more appropriate.

Assume that all my random methods are defined.


texts:
Given

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

Solution
def max_factor(num):
    """Find the maximum prime factor."""
    factor = 2
    while factor * factor <= num:
        while num % factor == 0:
            num /= factor
        factor += 1
    if (num > 1):
        return num
    return factor

print max_factor(33) #11
print max_factor(38) #19
print max_factor(600851475143) #6857

This problem is already discussed a lot. I am more interested in finding the running time complexity. Since input here is just a number how to relate the running time to the input size. Also, I sense that running time should be logarithmic but how to derive that exactly seems quite tough.


texts:
I have a class Vector3d with 3 double components and want to store several of them in a Field. For reasons of efficiency when sending a Field over a network via MPI, I would like to allocate contiguous memory in the Field class and let the Vector3ds store their components in that chunk of memory. In addition, Vector3ds should also be able to live without a Field; in this case, they have to care about their own memory allocation.

#include <cstddef>
#include <iostream>
#include <vector>

class Field;

class Vector3d
{
    friend class Field;

    public:
        Vector3d() : components_(new double[3]) {}
        ~Vector3d() { delete[] components_; }
        Vector3d(const Vector3d &v) : components_(new double[3])
        {
            components_[0] = v.components_[0];
            components_[1] = v.components_[1];
            components_[2] = v.components_[2];
        }
        double & operator()(const std::size_t index) { return components_[index]; }

    private:
        Vector3d(double *ptr) : components_(ptr) {};
        double *components_;
};

class Field
{
    public:
        Field(std::size_t size);
        ~Field();
        Vector3d & operator()(const std::size_t index) { return *(vectors_[index]); }

    private:
        std::vector<double> components_;
        std::vector<Vector3d *> vectors_;
};

Field::Field(std::size_t size) : components_(std::vector<double>(3 * size)), vectors_(std::vector<Vector3d *>(size, new Vector3d(0)))
{
    double *ptr = &components_[0];
    for (auto it = vectors_.begin(); it != vectors_.end(); ++it)
    {
        (*it)->components_ = ptr;
        ptr += 3;
    }
}

Field::~Field()
{
    for (auto it = vectors_.begin(); it != vectors_.end(); ++it)
        (*it)->components_ = 0;
}

int main(int argc, char *argv[])
{
    Field field(2);
    Vector3d &v = field(1);
    v(2) = 5;

    Vector3d v2 = v;
    v2(2) = 2;

    std::cout << field(1)(2) << std::endl;

    return 0;
}

I would like to hear what you think about this piece of code. Can this be considered a good solution or what would you change?


texts:
I've built a small library for comparing objects based on their members here (related SO question).

There's a need to compute hash function in order to conform to IEqualityComparer<T> interface. In my case this function has to be computed based on the hash functions of members. So the main problem is how to compose them.

I use the following approach currently:

public int GetHashCode(T obj)
{
    VerifyHaveMembersSetup();

    if (TypeTester<T>.IsNull(obj))
    {
        return 0;
    }

    if (getHashCodeBehavior == GetHashCodeBehavior.Cache && cachedHashCode.HasValue)
    {
        return cachedHashCode.Value;
    }

    int hashCode = 0;

    for (int i = 0; i < memberSetups.Count; ++i)
    {
        int leftShift = i % 32;
        int rightShift = 32 - leftShift;

        int memberHashCode = memberSetups[i].GetMemberHashCode(obj);

        hashCode = hashCode ^ ((memberHashCode << leftShift) | (memberHashCode >> rightShift));
    }

    if (getHashCodeBehavior == GetHashCodeBehavior.ImmutableCheck
        && cachedHashCode.HasValue && cachedHashCode.Value != hashCode)
    {
        throw new InvalidOperationException("Hash code value changed");
    }

    cachedHashCode = hashCode;

    return hashCode;
}

Are there any problems with this code?
I don't like the way many people implement composite functions. With multiplication and addition, significant bits are shifted away and are lost.

That's why I use bitshift operators << and >>. Still I'm not completely sure how good would be a hash function generated such way. Especially when it's computed over small collection of memberSetups of bools for example (since bool has only 2 hash values in .NET: 1 and 0).


texts: simplifying regex expression for timestamp

texts:
I was wondering if it's possible to simplify this regex string (JS):
function validateDateString(date){
    const regex = /[0-1][0-9]-[0-3][0-9]-[0-9]{4} [0-2][0-9]:[0-5][0-9] [A|P][M]/;
    return regex.test(date)
}

It is supposed to validate a string in the following format: MM-DD-YYYY hh:mm A


texts: Copying files locally with rsync and subprocess

texts:
I have Python code to copy the Files locally on the Server from one Directory to another using rsync and subprocess module, this is just in continuation of the post from this post where I tried to get various insight but opted to use below code finally.

Please advise if this further can be improved or optimized in pythonic way and help to provide your esteemed reviews please.

#!/bin/python3
import os
import glob
import datetime
import subprocess

def Copy_Logs():
   # Variable Declaration to get the month and Curr_date_month
    Info_month = datetime.datetime.now().strftime("%B")
    Curr_date_month = datetime.datetime.now().strftime("%b_%d_%y")
    Sourcedir = "/data1/logs"
    Destdir = "/data2/logs/"
    ###### End of your variable section #######################
    # The result of the below glob _is_ a full path
    for filename in glob.glob("{2}/{0}/{1}/*.txt".format(Info_month, Curr_date_month, Sourcedir)):
        if os.path.getsize(filename) > 0:
            if not os.path.exists(Destdir + os.path.basename(filename)):
                subprocess.call(['rsync', '-avz', '--min-size=1', filename, Destdir ])

if __name__ == '__main__':
    Copy_Logs()


texts:
The MediaWiki API may return multiple errors. Is this a idiomatic way of representing them?

type MediaWikiError struct {
    Code    string      `json:"code"`
    Data    interface{} `json:"data"`
    Message string      `json:"text"`
    Module  string      `json:"module"`
}

func (e *MediaWikiError) Error() string {
    return fmt.Sprintf("MediaWiki module \"%s\" reported an error: %s (%s)", e.Module, e.Message, e.Code)
}

type MediaWikiErrors []*MediaWikiError

func (e MediaWikiErrors) Error() string {
    switch len(e) {
    case 0:
        return ""
    case 1:
        return e[0].Error()
    default:
        codes := make([]string, len(e))
        for i, err := range e {
            codes[i] = err.Code
        }
        return fmt.Sprintf("MediaWiki API reported multiple errors: %s", strings.Join(codes, ", "))
    }
}


texts: Numeric parser for integers, big integers, and doubles

texts:
I have written the following numeric parser. It may not be as fast as Boost's lexical_cast, nor as convenient, but it does get the job done and it does look good. I'm very proud of the end result, and I believe it may be useful for some! How can I improve it even more?

#include <iostream>
#include <sstream>
#include <string>

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

enum class tag {
    INTEGER,
    BIG_INTEGER,
    DOUBLE,
    ERROR
};

template <typename t>
struct result {
    bool const ok;
    t const value;
};

tag is_number(std::string const & s);
void print_tag(tag const t);

result<int64_t> parse_int(std::string const & s);
result<double> parse_double(std::string const & s);

int main() {

    auto x {parse_int("4")};
    auto y {parse_double(".8")};
    cout << x.value << '\n';
    cout << y.value << '\n';

    auto z {parse_int("abc")};
    if (z.ok) {
        cout << z.value << '\n';
    } else {
        cout << "ERROR" << '\n';
    }

    print_tag(is_number("9223372036854775807"));
    print_tag(is_number("9223372036854775808"));

    print_tag(is_number("-9223372036854775808"));
    print_tag(is_number("-9223372036854775809"));

    print_tag(is_number("    "));

    return 0;
}

tag is_number(std::string const & s) {
    if (s.empty()) {
        return tag::ERROR;
    }
    if (s.size() == 1 && (s[0] == '.' || s[0] == '+' || s[0] == '-')) {
        return tag::ERROR;
    }
    size_t index {s.find_first_not_of(" \t\n\v\f\r")};
    if (index == std::string::npos) {
        return tag::ERROR;
    }
    bool is_int {true};
    bool is_dot {true};
    bool is_pos {true};
    bool is_eul {true};
    switch (s[index]) {
        case '.': is_int = !is_int; is_dot = !is_dot; ++index; break;
        case '+':
        case '-': is_pos = !is_pos; ++index;
    }
    for (size_t i {index}; i < s.size(); ++i) {
        if (isspace(s[i])) {
            if (s[i - 1] == '.' || s[i - 1] == '+' || s[i - 1] == '-') {
                return tag::ERROR;
            }
            break;
        }
        if (s[i] == '.') {
            if (!is_dot) {
                return tag::ERROR;
            }
            is_int = !is_int;
            is_dot = !is_dot;
            continue;
        }
        if (s[i] == 'e' || s[i] == 'E') {
            if (!is_eul) {
                return tag::ERROR;
            }
            is_eul = !is_eul;
            if (i + 1 == s.size()) {
                return tag::ERROR;
            }
            ++i;
            if (s[i] == '+' || s[i] == '-') {
                if (i + 1 == s.size()) {
                    return tag::ERROR;
                }
                continue;
            }
            if (!isdigit(s[i])) {
                return tag::ERROR;
            }
            continue;
        }
        if (!isdigit(s[i])) {
            return tag::ERROR;
        }
    }
    return is_int
        ? s.compare(index, 19, is_pos
                ? "9223372036854775808"
                : "9223372036854775809") < 0
            ? tag::INTEGER
            : tag::BIG_INTEGER
        : tag::DOUBLE;
}

void print_tag(tag const t) {
    switch (t) {
        case tag::INTEGER: cout << "INTEGER\n"; break;
        case tag::BIG_INTEGER: cout << "BIG INTEGER\n"; break;
        case tag::DOUBLE: cout << "DOUBLE\n"; break;
        case tag::ERROR: cout << "ERROR\n"; break;
    }
}

result<int64_t> parse_int(std::string const & s) {
    if (is_number(s) == tag::INTEGER) {
        std::istringstream input {s};
        int64_t output;
        input >> output;
        return {true, output};
    }
    return {false, 0};
}

result<double> parse_double(std::string const & s) {
    tag t {is_number(s)};
    if (t == tag::INTEGER || t == tag::DOUBLE) {
        std::istringstream input {s};
        double output;
        input >> output;
        return {true, output};
    }
    return {false, 0.0};
}


texts: Web-service for wiki-like movie database

texts:
I'm making a web-service for an app with a (partially) crowdsourced movie database.

These two functions allows users to add and remove which genres a movie is liked to, and get the log of whom have done what changes.

I need to make many very similar functions for other data.

    [HttpPost]
    [Authorize(Roles = "User")]
    public IHttpActionResult PostMovieGenre([FromBody]MovieGenreBindingModel edit)
    {
        string[] IDs = edit.genre_ids.Split(',');

        using (var db = new DBEntities())
        {
            var movie = db.movies.Find(edit.movie_id);

            if (movie == null)//Confirm that the movie was found
                return BadRequest("Movie not found");

            foreach (string sid in IDs)
            {
                int g_id = Convert.ToInt32(sid);
                if (edit.action == "add")
                {
                    movie.movies_genres.Add(new movies_genres
                    {
                        movies_id = edit.movie_id,
                        genres_id = g_id
                    });
                }
                else if (edit.action == "remove")
                {
                    var m_g = movie.movies_genres.Where(g => g.genres_id == g_id).First(); //Find the movies_genres object
                    db.movies_genres.Remove(m_g); //Remove it
                }
                else
                {
                    return BadRequest("Invalid action");
                }

                db.movies_genres_changes.Add(new movies_genres_changes //Log the change
                {
                    action = edit.action,
                    genres_id = g_id,
                    movies_id = edit.movie_id,
                    time = DateTime.UtcNow,
                    user_id = UserManager.FindByName(User.Identity.Name).Id
                });
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception e)
            {
                return BadRequest();
            }
        }
        return Ok();
    }

    [ResponseType(typeof(List<RMovieGenresChange>))]
    [HttpGet]
    [Authorize(Roles = "User")]
    public IHttpActionResult GetMovieGenresChanges(int movie_id)
    {
        List<RMovieGenresChange> retchanges = new List<RMovieGenresChange>();

        using (var db = new DBEntities())
        {
            try
            {
                var dbRevs = db.movies.Find(movie_id).movies_genres_changes;

                if (dbRevs == null)
                    return BadRequest("No revision for an movie entry with id " + movie_id);

                foreach (movies_genres_changes m in dbRevs)
                {
                    retchanges.Insert(0, new RMovieGenresChange() // Put newest change first in list
                    {
                        action = m.action,
                        genre = new RGenre
                        {
                            id = m.genres_id,
                            name = m.genres.name
                        },
                        movie_id = m.movies_id,
                        time = m.time,
                        user = new RUserShort
                        {
                            user_id = m.user_id,
                            user_name = User.Identity.Name
                        }
                    });
                }
            }
            catch (Exception e)
            {
                return BadRequest();
            }
        }

        return Ok(retchanges);
    }


texts: Program that reads a string from the keyboard and tests whether it contains a valid date

texts:
I know this task could be done in more practical ways, but the professor only want us to solve it with the "if" statement. I tested and it meets the condition for each task, but I still feel this code looks a bit awkward, I think there is an easier way to get it done. Can someone give me any advice?

import javax.swing.JOptionPane;
public class ValidDate {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String Smonth =
                JOptionPane.showInputDialog ("Enter the Month");
        int month = Integer.parseInt(Smonth);

        if (month <= 0 || month > 12)
        {
            JOptionPane.showMessageDialog (null, " The month you entered is wrong" );
            System.exit (0);
        }

        String Sday =
                JOptionPane.showInputDialog ("Enter the Day");
        int day = Integer.parseInt(Sday);

         if (day <= 0 || day > 31)
            {
                JOptionPane.showMessageDialog (null, " The day you entered is wrong" );
                System.exit (0);
            }
         else if (month == 4 || month == 6 || month == 9 || month == 11 && day > 30)
            {
                JOptionPane.showMessageDialog (null, " The day you entered is wrong because " + month + " month has only 30 days");
                System.exit (0);
            }

        String Syear =
                JOptionPane.showInputDialog ("Enter the Year");
        int year = Integer.parseInt(Syear);
        boolean leap = ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0));

         if (leap == false && month == 2 && day >=29)
        {
            JOptionPane.showMessageDialog (null, " The Date you entered is wrong since " + year +" is not a leap year" );
            System.exit (0);
        }
        else
            JOptionPane.showMessageDialog (null, " The Date you entered is " + month + "/" + day + "/" + year);

    }

}


texts: Set default value for remaining size of list by use of Java 8 and Stream

texts:
I have written a method which will return the size 16 List every time. If the input List has size less than 16, the remaining list object will be filled with default values.  Is there any way to remove the if and for condition from the enrichAddress method?.
@Component
public class TestService{

public List<TestB> enrichAddress(List<TestA> cardAccountDetails) {
if (CollectionUtils.isEmpty(cardAccountDetails)) return Collections.emptyList();

List<TestB> testBList = cardAccountDetails.stream().map(AccountService::buildAddress).collect(Collectors.toList());
if (testBList.size() < 16) {
  int accountCounts = testBList.size();
  for (; accountCounts < 16; accountCounts++) {
    testBList.add(buildDefaultAddress());
  }
}
return testBList;
}

private TestA buildDefaultAddress() {
TestA testA = new TestA();

testA.setA("NONE");
testA.setAccS("TEST_STATUS");

testA.setAccT("TEST_ACCOUNT_TYPE");
testA.setADes("");

return testA;
}

private static TestA buildAddress(TestB testB) {
TestA testA = new TestA();

testA.setDes(testB.getDes());
testA.setAcc(testB.getAcN());
testA.setAccSt(testB.getAccS());

testA.setAccT(testB.getAcCT());
testA.setAc(testB.getAct());

return testA;
 }
}


texts:
My code calculates primes from one to n. I have verified that the code always produces all the primes in that range correctly.

Are there any optimizations that I can make? Are there any bad programming practices besides variable names (e.g. l is close to 1)? Any better normal Windows API? I am using the Sieve of Eratosthenes.

#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include <Windows.h>

using namespace std;

#define printprimes() //for each(bool b in primes) cout << b << endl;

int main(int argc, char* argv[])
{
    const double s = GetTickCount();
    unsigned long long numt;
    if(argc < 2) {
        cout << "Usage: "<<argv[0]<<" <primes until...>" << endl;
        return 1;
    }

    else if(atoi(argv[1])<1) {
        cout << "Usage: "<<argv[0]<<" <primes until...>" << endl;
        return 1;
    }
    numt = atol(argv[1])+1;

    bool skipprint = false;

    if(argc >=3) if(!strcmp(argv[2], "noprint")) skipprint = true;

    vector<bool> primes(numt);

    primes.assign(numt, true);

    primes[0] = false;
    primes[1] = false;

    long double sqrtt = sqrt(numt);
    for(unsigned long long l = 0; l<=sqrtt; l++) {
        if(!primes[l]) {
            //cout << l << " is false" << endl;
            continue;
        }
        for(unsigned long long cl = 2*l; cl < numt; cl+= l) {
            //cout << cl << ", a multiple of " << l << endl;
            primes[cl] = false;
        }
    }
    const double m = GetTickCount();
    unsigned long long count = 0;
    if(!skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) {
        cout << l << endl;
        count ++;
    }
    if(skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) count ++;
    const double e = GetTickCount();
    cout << endl;
    cout << count << " primes less than or equal to " << numt-1 << endl;
    cout << "Calculation took " << m-s << " ms";
    if(!skipprint) cout << " and printing took " << e-m << " ms";
    else cout << " and counting took " << e-m << " ms";
    cout <<"." << endl;
    //for each(bool b in primes) cout << b << endl;

    return 0;
}


texts:
I have a large log file in the following format. Do note that this is already sorted alphabetically. I wish to split it into smaller pieces, and with file names reflecting the content of the file (first three char of the row).

I wish for the code to be efficient. Speed and simplicity is the key. The log file is in 10s of GB in size, and there are 1000s of such logs.

Secondly, for large output files (only if the output file is greater than 4 lines), the script should sub-split the file into smaller pieces, using the next alphabet. I am aware this can be done by 2 separate awk commands, but that would not be efficient. Can you pls help me update the existing code?

Input file:

Jon1,details
Jon2,details
Jon4,details
Ron1,detailsaa
Ron1,detailsbb
Ron1,detailscc
Ron1,detailsdd
Ron1,detailsee
Ron2,detailsff

Output I wish for:

cat Jon
Jon1,details
Jon2,details
Jon4,details

cat Ron1
Ron1,detailsaa
Ron1,detailsbb
Ron1,detailscc
Ron1,detailsdd
Ron1,detailsee

cat Ron2
Ron2,detailsff

Current code

awk '
  fname != $1{
    close(fname)
    fname=$1
  }
  {print $0 > fname}' FS="[[:digit:]]+" ./hugeFile


texts:
I have a the beginnings of a class (in this case for a NeuralNet).
I'm not very happy with how I am initializing self.ws, seems a bit off.
What is the pythonic way to do this?

import numpy as np
class NeuralNet:
    def __init__(self,layerSizes):
        self.ws = self._generateStartingWeights(layerSizes)

    def _generateStartingWeights(self,layerSizes):
        def randMatrix(szThis,szNext): return np.matrix(np.random.normal(0,0.01,(szThis,szNext)))
       return [randMatrix(szThis,szNext) for (szThis,szNext) in pairwise(layerSizes)]


texts: Most pythonic way to combine elements of arbitrary lists into a single list

texts:
I have a list of lists which represents the options I can chose from.

I have a sequence of indices which represent which option lists I want to take elements from, and in which order.

E.g. if I have

choices = [
    [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ]
]

sequence = [ 2, 0, 1, 1 ]

I want my output to be

[7, 8, 9, 1, 2, 3, 4, 5, 6, 4, 5, 6]
#index 2  index 0  index 1  index 1

I have found three possible solutions:

choice = sum( ( choices[i] for i in sequence ), [] )

choice = reduce( operator.add, ( choices[i] for i in sequence ) )

choice = [ element for i in sequence for element in choices[i] ]

I would like to know which of these do people find the most pythonic and to know if there are any other elegant solutions.


texts: Calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999)

texts:
Are there any efficient ways to solve this problem,
for example using bitwise operator?

    public static boolean isPal(long num)
    {
        String numStr = Long.toString(num);
        String rNumStr = "";

        boolean result = false;

        for (int i = numStr.length() - 1; i >= 0 ; --i)
            rNumStr += numStr.charAt(i);

        //System.out.println(numStr + "," + rNumStr);
        try
        {
            if (Long.parseLong(numStr) == Long.parseLong(rNumStr))
                result = true;
            else
                result = false;
        }catch (NumberFormatException e) {
            //System.err.println("Unable to format. " + e);
        }
        return result;

    }

    public static void calcPal(int rangeMin, int rangeMax)
    {
        long maxp = 0, maxq = 0, maxP = 0;
        for (int p = rangeMax; p > rangeMin; p--)
            for (int q = rangeMax; q > rangeMin; q--)
            {
                long P = p * q;
                if (isPal(P))
                    if (P > maxP)
                    {
                        maxp = p; maxq = q; maxP = P;
                    }
            }
        System.out.println(maxp + "*" + maxq + "=" + maxP);
    }

    public static void main(String[] args)
    {
        calcPal(10, 99);
        calcPal(100, 999);
        calcPal(9000, 9999);
        calcPal(10000, 99999);
        calcPal(990000, 999999);
    }

The largest palindrome which can be made from the product of two 2-digit (10 to 99) numbers is 9009 (91 × 99). Write a function to calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999).


texts: Extract climate variables on species range from worldclim and save into CSV

texts:
My code is currently taking too long to extract climate variables from the worldclim dataset. I would like to download the climate data from the link and find the maximum temperature over my species distribution polygons and save as a CSV file in a directory.

The code is working, but taking too long (say, 3-4 days on my PC). Can anybody suggest how to improve the performance of my code?

# download the climate dataset and unzip. I can download and unzip this into my pc. Please suggest me on main codes for improvement

download.file("http://biogeo.ucdavis.edu/data/climate/cmip5/30s/mi85tx50.zip", destfile = "E://ClimateDataOutputs//MIROC-ESM-CHEM_rcp85TX", mode="wb")

unzip("E://ClimateDataOutputs//MIROC-ESM-CHEM_rcp85TX")

# Codes for improvement

# load required packages

require(sp)

require(rgdal)

require(raster)

require(lsr)

require(maptools)

# For Bioclim - Need to project species polygons

projection <- CRS ("+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs")

polygons <- readShapePoly("F:\\9. Other projects\\All projected maps\\AllP.shp", proj4string = projection)

polygons$BINOMIAL <- as.character(polygons$BINOMIAL)

names=c(polygons$BINOMIAL)

stats_out<- data.frame(matrix(NA, ncol = 4, nrow = 579))

colnames(stats_out)<-c("BINOMIAL", "AAD", "mean", "obs")

stats_out[,1]<-names

# iterate over species polygons

for (i in 1:579) {

    poly<-polygons[i,]

    print(poly$BINOMIAL)

    data_out<-data.frame(matrix(NA, ncol = 1))

    colnames(data_out)<-c("MaxTemp2050rcp85_MIROC_ESM_CHEM")`

    for (j in 1:12) {

        filename<-c(paste("E:\\ClimateDataOutputs\\mi85tx50",j,".tif", sep=""))

        ##print(filename)

        grid<-raster(filename)

        ##plot(grid)

        ##plot(poly, add=TRUE)

        data<-extract(grid, poly)

        data1<-as.data.frame(data)

        colnames(data1)<-c("MaxTemp2050rcp85_MIROC_ESM_CHEM")

        data_out= rbind(data_out,data1)

        }

    M<-mean(data_out$MaxTemp2050rcp85_MIROC_ESM_CHEM, na.rm=TRUE)

    AAD<-aad(data_out$MaxTemp2050rcp85_MIROC_ESM_CHEM, na.rm=TRUE)

    stats_out$AAD[i]<-AAD

    stats_out$mean[i]<-M

    stats_out$obs[i]<-nrow(data_out)

  }

print(stats_out)

write.csv(stats_out, "E://ClimateDataOutputs//MaxTemp2050rcp85_MIROC_ESM_CHEM_AAD.csv")


texts: Program to insert, search for and delete an element from an array

texts:
I'd like this code to be improved.

package com.array.demo;

import java.util.Arrays;

public class ArraysDemo {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    // array initialization
    int[] arr = { 5, 10, 12, 22, 4 };

    int size = arr.length;

    int i,pos; // loop counter

    System.out.println(arr); // // prints something like '[I@3343c8b3'

    System.out.println("Elements in the array" + Arrays.toString(arr));

    System.out.println(" The size of the array is  " + size);

    // array-search
    int searchKey = 11;

    for ( i = 0; i < size; i++) {
        if (arr[i] == searchKey)
            break;
    }

    if(i==size)
        System.out.println(" Element not found");
    else
        System.out.println("Element found in the position " +i);

    int elemDel=5;

    for ( pos = 0; pos < size; pos++) {
        if (arr[pos] == elemDel)
            break;
    }

    if(pos==size)
        System.out.println("Element not found");
    else
    {
        while(pos<size-1){
            arr[pos] = arr[pos+1];
            pos++;
        }
        size--;
    }

// display the element after deletion
for(i=0;i<size;i++){
    System.out.print(arr[i] + " ");
}
    //System.out.println("Elements in the array" + Arrays.toString(arr));

}

}


texts:
I have made slight edits to a simple PHP contact form that I have found online. Can you see anything else that I could do to ensure that I am protected from email injections and spam? I have used trim, stripslashes and htmlspecialchars and made a simple question to act as spam prevention.

<?php

$myemail = "YOUR EMAIL ADDRESS";

$name = check_input($_POST['name'], "Enter your name");
$email = check_input($_POST['email']);
$message = check_input($_POST['message'], "Write your message");
$captcha = check_input($_POST['captcha']);

if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}

if (!preg_match("/5/", $captcha))
{
show_error("Check your math");
}

$message = "

Name: $name
E-mail: $email

Message:
$message

";

mail($myemail, $subject, $message);

header('Location: thanks.html');
exit();

function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);

if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}

function show_error($myError)
{
?>

Please correct the following error:

<?php echo $myError; ?>

Hit the back button and try again

<?php
exit();
}
?>


texts:
I've tried to write an "OOP" approach to printing a website using the DOMDocument class. I'm kind of stuck here because I feel like I am blundering in how I am passing and using the DOMDocument. I found that I can just return the object from the class and use it that way.

What are some safe practices here? Best approach? I know it's far from OOP, but I at least want to be considerate of the model while learning. I realize my approach is probably all backwards.  How bad is this code and what are some ways to improve this?

All styling is done in CSS, any and all critique is welcome about any aspect of the code.

If this isn't considered to be a useful question let me know and I will remove it.

<?php
require 'viewer.php'
//new viewer class
$v= new viewer();
//read html document structure from a template
$page= $v->setPage('template.html');
//find body
$body= $v->returnBody();
//create new element and attach it to body
$v->newElement('div', $body, "id=container");

$cont = $v->getElement("container");

$v->newElement('div', $cont, "id=title", "My Website");
$v->newElement('ul', $cont, "id=menu;class=menu");
$v->newElement('li', $v->getElement("menu"), NULL, "Forums" );

$v->newElement('div', $cont, "id=content");
$v->newElement('div', $v->getElement("content"), "id=content_title", "Content Title Here!");
$v->newElement('div', $v->getElement("content"), "id=content_box");

$mb = $v->getElement("content_box");
$v->newElement('a',$mb,NULL,"Some Link");

$content = " And after the link, this is the content.";

$dd=$v->rDOM();
$c=$dd->createTextNode($content);
$mb->appendChild($c);
$v->printHTML();
?>

Where the Viewer class is:

<?php
class viewer {
    protected $dom;

    public function __construct(){
        $this->dom = new DOMDocument();
    }

    //Creates an element of the type passed in string, appends parameters passed in string
    //and finally inserts into the passed node
    public function newElement($type, $insertInto = NULL, $params=NULL, $content=""){
        $element = $this->dom->createElement($type, $content);
        if(gettype($params) == "string" && strlen($params) > 0){
            $attrCollec = preg_split("/;/", $params);
            foreach($attrCollec as $attr){
                $value = preg_split("/=/", $attr);
                $element->setAttribute($value[0], $value[1]);
            }
        }
        $insertInto->appendChild($element);
    }
    public function getElement($param){
        //if($this->dom->validate()){
            $elem = $this->dom->getElementById($param);

            return $elem;
        //}
    }
    public function setPage($fileName){
        //does this even work? should validate before each getElement call?
        $this->dom->validateOnParse = true;
        $this->dom->loadHTMLFile($fileName);
    }
    public function printHTML(){

        echo $this->dom->saveHTML();
    }
    public function returnBody(){
        $nodeList = $this->dom->getElementsByTagName('body');
        $body = $nodeList->item(0);

        return $body;
    }
    public function rDOM(){
        return $this->dom;
    }
}
?>


texts:
Please review this JavaScript text editing webapp. Review the code quality. Give me suggestions to simplify the code.

var textarea = document.getElementById("textarea"),
  statusBar = document.getElementById("status-bar"),
  inputFile = document.getElementById("input-file"),
  appname = "Notepad",
  isModified = false,
  statusBarOn,
  filename;

function changeDocTitle(newFilename) {
  filename = newFilename;
  document.title = filename + " - " + appname;
}

function dontSave() {
  if (!textarea.value || confirm("You have unsaved changes that will be lost.")) {
    isModified = false;
    return true;
  }
}

function newDoc(text, newFilename) {
  if (!isModified || dontSave()) {
    textarea.value = text || "";
    changeDocTitle(newFilename || "untitled.txt");
  }
  if (statusBarOn) updateStatusBar();
  textarea.focus();
}

function openDoc() {
  if (!isModified || dontSave()) inputFile.click();
  textarea.focus();
}

function renameDoc() {
  var newFilename = prompt("Name this document:", filename);
  if (newFilename !== null) {
    if (newFilename === "")
      changeDocTitle("untitled.txt");
    else
      changeDocTitle(newFilename.lastIndexOf(".txt") == -1 ? newFilename + ".txt" : newFilename);
    return true;
  }
}

function saveDoc() {
  if (renameDoc()) {
    var blob = new Blob([textarea.value.replace(/\n/g, "\r\n")], {
      type: "text/plain;charset=utf-8"
    });
    saveAs(blob, filename);
    isModified = false;
  }
  textarea.focus();
}

function updateStatusBar() {
  var text = textarea.value,
    chars = text.length,
    words = text.split(/\b\S+\b/g).length - 1,
    lines = text.split("\n").length;
  statusBar.value = lines + " lines, " + words + " words, " + chars + " characters";
}

function showHideStatusBar(toState) {
  statusBarOn = toState;
  if (statusBarOn) {
    textarea.style.height = "calc(100% - 21px)";
    statusBar.removeAttribute("hidden");
    updateStatusBar();
  } else {
    textarea.style.height = "";
    statusBar.setAttribute("hidden", "");
  }
}

textarea.addEventListener("input", function() {
  isModified = true;
  if (statusBarOn) updateStatusBar();
});

inputFile.addEventListener("change", function() { // load file
  var file = inputFile.files[0],
    reader = new FileReader();
  reader.onload = function() {
    newDoc(reader.result, file.name);
  };
  reader.readAsText(file);
});

document.addEventListener("keydown", function(e) { // shortcuts
  var key = {
    66: function() { // B
      showHideStatusBar(statusBarOn ? false : true); // toggle
    },
    79: openDoc, // O
    82: newDoc, // R
    83: saveDoc, // S
    191: function() { // /
      alert("Welcome to " + appname + "!");
    },
    "noctrl9": function() { // tab
      var sStart = textarea.selectionStart,
        text = textarea.value;
      textarea.value = text.substring(0, sStart) + "\t" + text.substring(textarea.selectionEnd);
      textarea.selectionEnd = sStart + 1;
    }
  }, fn = e.ctrlKey ? key[e.keyCode] : key["noctrl" + e.keyCode];
  if (fn) {
    e.preventDefault();
    fn();
  }
});

onunload = function() { // store localStorage
  if (isModified) {
    localStorage.setItem("text", textarea.value);
    localStorage.setItem("filename", filename);
  } else
    localStorage.removeItem("text");
  localStorage.setItem("statusBarOn", statusBarOn);
};

onload = function() { // load localStorage
  if (localStorage.getItem("text")) {
    newDoc(localStorage.getItem("text"), localStorage.getItem("filename"));
    isModified = true;
  } else
    newDoc();
  if (localStorage.getItem("statusBarOn"))
    showHideStatusBar(JSON.parse(localStorage.getItem("statusBarOn")) ? true : false);
  else
    showHideStatusBar(true); // default
};


texts: Writing a safe class method in terms of a dangerous one

texts:
I commonly need to trim characters from the end of a string (when building SQL queries, I have trailing commas, brackets, even words sometimes), so I wrote the following:

class String
  def trim(amount=1)
    self[0..-(amount+1)]
  end

  def trim!(amount=1)
    self[0..-1] = trim(amount)
  end
end

The dangerous method, trim!, calls the safe method, trim. According to the Ruby Style Guide, this is backwards.

How do I rewrite this so the safe method calls the dangerous method, without changing the functionality?

Sample output:

str = "Hello World!"
puts str            #=> "Hello World!"
puts str.trim       #=> "Hello World"
puts str.trim 7     #=> "Hello"
puts str            #=> "Hello World!"
puts str.trim!      #=> "Hello World"
puts str.trim! 6    #=> "Hello"
puts str            #=> "Hello"


texts: Displaying a greeting to one user selected from a database

texts:
I execute the following SQL statement to get back an data object into a variable.

  try {
    $getUser = $db->query('select * from user where user.user_id = '.$user_id);
  } catch (Exception $e) {
    echo $e->getMessage();
    die();
  }

from this I print out the information on the page where necessary e.g. the following:

  <?php
  foreach ($getUser as $user) {
    echo '

Welcome, '.$user['email'].'

    ';
  }
  ?>

The question is I know the size of the $getUser array to always be one.
Am I doing this the correct way when returning the information? Is there a better way where I do not need to use a foreach loop everytime.