texts:
I am writing an open-source application for real-time messaging in web. In my application clients from browser can subscribe on channels. But every channel belongs to a certain namespace which determines channel's settings:

client.subscribe('/football/news', function(message) {
    // message from channel received
});

where football is namespace name and news is channel name. football can be a default namespace for project and in this case we can write in this way:

client.subscribe('/news', function(message) {
    // message from channel received
});

i.e. without namespace name. This is how it works right now.

But my question is about / path separator. Is it ok? We need the way do separate namespace name and channel name. / usage was influenced by Bayeux protocol spec. But maybe it would be more simple and correct to write in such manner:

client.subscribe('football', 'news', function(message) {
    // message from channel received
});

or with default namespace:

client.subscribe(null, 'news', function(message) {
    // message from channel received
});

or even:

client.subscribe('news', function(message) {
    // message from channel received
});

I personally feel that the second way is better. But before refactoring I decided to ask for your opinion.


texts:
just tried a little VBA code to transpose existing ListObject Table and creating new ListObject Table with name SrcTable_TRANS

Any thoughts or mischiefs in my code?

Calling sub:

Public Sub main()
    TransposeListObject "T_TREAT_TEST", Cells(16, 11)
End Sub

Transpose Sub:

Public Sub TransposeListObject(srcTable As String, TargetCell As Range)

    Dim i As Long
    Dim ws As Worksheet
    Dim table As ListObject
    Dim table2 As ListObject

    ' Disable ScreenUpdating for faster
    Application.ScreenUpdating = False

    Set ws = ActiveWorkbook.ActiveSheet
    Set table = ws.ListObjects(srcTable)

    ' Clear (DEBUG purposes)
    Range(Cells(15, 9), Cells(25, 22)).Clear

    ' Copy source Table and paste it Transposed to TargetCell
    table.DataBodyRange.Copy
    TargetCell.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

    ' Add first column (header in the past)
    For i = 1 To table.ListColumns.count
        TargetCell.Offset(-1 + i, -1).Value = table.ListColumns(i).Range.Value
    Next i

    ' Creata Table (ListObject)
    Set table2 = ws.ListObjects.Add(xlSrcRange, _
        Range(TargetCell.Offset(0, -1), _
              TargetCell.Offset(table.ListColumns.count - 1, table.ListRows.count - 1)), _
        xlNo, xlGuess, TargetCell)

    ' Rename table TBL_NAME --> TBL_NAME_TRANS
    table2.Name = table.Name & "_TRANS"

    ' Clear selection
    TargetCell.Offset(0, -1).Select
    Application.CutCopyMode = False

    ' Reapply ScreenUpdating for normal behaviour
    Application.ScreenUpdating = True

End Sub

Result:


texts:
I'm new to Python! Kindly suggest me improvements!

Problem statement :

  A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

  As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest
  number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

  Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

My Work:

import math
dict = {}

def get_divisors_sum(num):
    list  = []
    for i in range(1, int(math.sqrt(num)+1), 1):
        if (num%i==0):
            b = num/i
            if (i==b):
                list.append(i)
            else:
                list.append(i)
                list.append(b)
    return sum(list) - num

# print get_divisors(28)

def generate_abundant_numbers():
    list = []
    for i in range(1, 28123, 1):
        if get_divisors_sum(i) > i:
            list.append(i)
    return list

def insert_to_dictionary():
    global dict
    list = generate_abundant_numbers()
    for i in range(0, len(list) - 1, 1):
        for j in range(i, len(list), 1):
            dict[list[i] + list[j]] = 1
    print dict

def print_answer():
    sum = 0
    for i in range(1, 28123, 1):
        if i not in dict:
            print i
            sum += i
    print sum

insert_to_dictionary()
print_answer()


texts: Extracting a number from provided URLs inside a text file

texts:
I need to extract a ID (int number) from a Url.

Example: http://www.example.com/foo/bar/12345

For this I wrote 4 methods where the first one ReadIDsFromFile() is called by my constructor and the return value is set to a properties of this class. The methods are called in the order I posted them below.

private List<string> ReadIDsFromFile(string path)
    {
        // path is the full qualified path to a txt file. C:\text.txt
        List<string> TweetIDsList = new List<string>();
        string temp = string.Empty;

        using (StreamReader sr = new StreamReader(path))
        {
            while ((temp = sr.ReadLine()) != null)
            {
                if (ValidateUrl(temp))
                {
                    TweetIDsList.Add(ExtractID(temp));
                }
                else
                {
                    Logger.Log("Invalid URL: {0}", temp);
                }
            }
        }

        return TweetIDsList;
    }

private bool ValidateUrl(string url)
{
    Uri uriResult;
    bool result;
    return result = Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
}

private string ExtractID(string url)
{
    string id = string.Empty;
    char[] urlArray = url.ToCharArray();
    int result;
    for (int i = urlArray.Length - 1; i >= 0; i--)
    {
        if (Int32.TryParse(urlArray[i].ToString(), out result))
        {
            id += result;
        }
        else
        {
            break; // break loop. If tryparse fails it means we have reached a character which is not a number, probably a forward slash.
        }
    }

    return ReverseNumber(id);
}

private string ReverseNumber(string id)
{
    char[] tempArray = id.ToCharArray();
    string result = string.Empty;
    for (int i = tempArray.Length -1; i >= 0; i--)
    {
        result += tempArray[i];
    }
    return result;
}

My code is working without problems so far but I feel like that it is overly unnecessarily complicated. I am especially concerned about the reversed order of the ID and my attempt to reverse it. Is there a better way?


texts:
I'm working through Yet Another Haskell Tutorial. One of the exercises is to prompt the user to enters numbers, entering a 0 to quit. The program should then both sum and multiply all the given numbers, and then display the factorial of each.

It works, but it's obviously sloppy, with some functions doing more than what is obvious. My main concern is whether it's better to try to format output in the nonpure IO functions, or to do it in the pure functions. Should I separate out calculating the data and formatting the output? Any other tips for how I could tighten this up?

module Main
  where

import System.IO

main = do
  hSetBuffering stdin LineBuffering
  putStrLn "Enter a number, or 0 to quit: "
  numList <- getNumbers
  putStrLn (my_sum numList)
  putStrLn (my_product numList)
  putStrLn (factorial numList)

getNumbers = do
  number <- getLine
  let n = read number :: Int
  if n == 0
    then do
      return []
    else do
      numList <- getNumbers
      return (n : numList)

my_sum [] = "The sum is 0"
my_sum xs = "The sum is " ++ show (foldr (+) 0 xs)

my_product [] = "The product is 0"
my_product xs = "The product is " ++ show (foldr (*) 1 xs)

factorial (x:xs) = show x ++ " factorial is " ++ show (fac x) ++ "\n"
  ++ factorial xs
factorial [] = ""

fac 1 = 1
fac x = x * fac (x - 1)


texts:
I am trying to concatenate the echo statements but I am failing. Also any other tips are appreciated in your review.

<?php
// load all 'category' terms for the post
$terms = get_the_terms($post->ID, 'category');

// we will use the first term to load ACF data from
if( !empty($terms) )
{
    $term = array_pop($terms);

    $custom_field = get_field('category_image', 'category_' . $term->term_id );

    // do something with $custom_field
    echo "";
    echo    "<img src="<?php echo $image; ?>" alt="<?php echo get_cat_name($cat->term_id); ?>" class="item-image">";
    echo "";
}
?>


texts:
A few years back I interviewed with a company for a Javascript position. After a couple of warm-up challenges I was presented with this:

  Please write a function that calls back with true if all
  promises have resolved successfully, or false if at least one
  promise has rejected.

  Given 'Promise' API:

promise.then(
  function resolve() { /* called when some async thing was successful */},
  function reject() { /* the async thing failed */ }
);

and also was given the following function structure and mocking code:

function all (promises, callback) {
    // TODO call back with `true` if all promises resolve(), or `false` if a promise has reject()ed
    promises.forEach(function (promise) {
        promise.then(
          function resolve() {},
          function reject() {}
        );
    });
}

// Some mocking code (NO NEED TO READ THIS):
function P() { return { then: function (resolve, reject) {
  setTimeout(function() { (5*Math.random()|0) ? resolve() : reject() }, Math.random()*1000);
}}}
var promises = [1,2,3,4,5].map(P);

all(promises, function (success) {
  console.log('The promises have ' + ( success ? '' : 'not ' ) + 'all resolved!' )
});

The gist of it: I had to write an almost Promise.all() method that would check if all async functions finished and how they finished (resolve/reject).

I didn't finish the challenge in the allocated time frame, so I failed (and years later, looking at the code I've written to finally solve it, if was the interviewer, I would failed me even if I was done in time...)

My current implementation

A few days ago I found the challenged buried on the hard drive and decided to give it a go (I timed myself to finish it in time):

Does not re-include the mocking code from above, but it is included in the jsbin below

function all (promises, callback) {
    const promisesStatus = [];
    const allPromisesChecked = (promisesArray = promises, promisesStatusArray = promisesStatus) => promisesStatusArray.length === promisesArray.length;
    const allPromisesPassed = (promisesArray = promisesStatus) => {
        if (promisesArray.filter(value => !value).length === 0) { return true; }
        return false;
    };
    promises.forEach(function (promise) {
        promise.then(
          function resolve() {
              promisesStatus.push(true);
              if (allPromisesChecked() && allPromisesPassed()) { callback(true); }
          },
          function reject() {
              promisesStatus.push(false);
              if (allPromisesChecked() && !allPromisesPassed()) { callback(false); }
          }
        );
    });
};

JSBin: https://jsbin.com/dajini/edit?js,console

Questions

Keeping in mind that this is to be done under the clock and under the interviewer's eyes (pair programming), hence under stress...

Implementation - Leaving aside minor performance optimizations, could I have done it better? Another way that I am unaware of ?
Time - How long does it take you ? (ballpark it) - Originally, I had to code two functions that dealt with string manipulations + this one in under 1 hour


texts: Converting anki-furigana to HTML-furigana without parser libraries

texts:
I wrote a converter from anki-style furigana to HTML-style furigana. Eventually I want to do it as a parser, but as a first step I do it without. Furigana is used to write the pronunciation over certain characters in Japanese.

Example:

Anki would write it like this:

林[はやし]さんは 英語[えいご]は 話[はな]せます。

[]contains what's written over the char sequence in question and the char seq in question goes from the last ] to the next [. But if the next sequence begins only later (e.g. 英語), space is used to indicate that (\n works too and there is no nesting of brackets).
HTML has several ways, and I use this:

<ruby><rb>林<rt>はやし</ruby>さんは<ruby><rb>英語<rt>えいご</ruby>は<ruby><rb>話<rt>はな</ruby>せます。

A sequence and its pronunciation are enclosed by <ruby>, <rb> and <rt> to indicate what's on top and on the bottom.

The idea is that the string first gets converted into a sequence of tags that may hold text. That sequence is then grouped and after that the tags are converted to HTML.

I'm just wondering if it is OK so far.

import System.Environment

main :: IO ()
main = do
    args <- getArgs
    file <- readFile (head args)
    putStrLn (anki_2_html file)

anki_2_html = translate_2_html . group . parse'

data Tag = Kana String | Uptext String
     | Furigana String String
     | Blank | Newline

--convert string to tags
parse' :: String -> [Tag]
parse' string = parse string ""

parse :: String -> String -> [Tag]
parse [] []  = []
parse [] acc = [Kana acc]
parse (l:ls) ""  | l == '['  = parseUpText ls ""
                 | l == ' '  = Blank   : parse ls ""
                 | l == '\n' = Newline : parse ls ""
                 | otherwise = parse ls [l]

parse (l:ls) acc | l == '['        = Kana acc : parseUpText ls ""
                 | l `elem` " \n"  = Kana acc : parse (l:ls) ""
                 | otherwise       = parse ls (acc++[l])

parseUpText :: String -> String -> [Tag]
parseUpText  [] []  = []
parseUpText  [] acc = [Kana (' ':acc)]
parseUpText  (l:ls) []  | l == ']'  = parse  ls ""
                        | otherwise = parseUpText ls [l]

parseUpText  (l:ls) acc | l == ']'   = Uptext acc : parse  ls ""
                        | otherwise = parseUpText ls (acc++[l])

--group patterns of Tags
group :: [Tag] -> [Tag]
group (Blank   : Kana kj : Uptext ka : ms) = Furigana kj ka : group ms
group           (Kana kj : Uptext ka : ms) = Furigana kj ka : group ms
group (m:ms) = m : group ms
group [] = []

translate_2_html ::  [Tag] -> String
translate_2_html = foldl1 (++) . map m2s
          where
            m2s (Furigana below above) = "<ruby><rb>"++below++"<rt>"++above++"</ruby>"
            m2s (Kana k) = k
            m2s (Uptext f) = "<f>" ++ f ++ "</f>"
            m2s Blank  = " "
            m2s Newline= "<br>\n"


texts: Laravel - super long relation, it doesn't feel right

texts:
Okay, This is my method:

public function edit(Request $request, $ent, $room, $obj)
{
    $input = $request->except(['_token']);

    Enterprise::where('bedrijfsnaam', $ent)->first()->rooms()->where('name', $room)->first()->objects()->where('name', $obj)->first()->update($input);

    return redirect('/enterprise/'.$ent.'/room/'.$room);
}

As you can see, at Enterprise::where() I have a really long relation, But it doesn't feel right to have such a long relation. Is it just okay to have one this large or is there a better way to do it?


texts:
I wrote this login method:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel logModel, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.InvalidCredentials;
            return RedirectToAction("LoginFailed");
        }
        User user;
        try
        {
            user = _usersRepository.SingleOrDefault(u => String.Equals(u.Username, logModel.LoginUsername));
        }
        catch(Exception ex)
        {
            //log it
            TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.DatabaseException;
            return RedirectToAction("LoginFailed");
        }
        if (user == null)
        {
            TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.InvalidCredentials;
            return RedirectToAction("LoginFailed");
        }

        //if we got so far it means that username does exist
        //is user blocked?
        if (user.IsLockedOut)
        {
            TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.AccountBlocked;
            return RedirectToAction("LoginFailed");
        }
        //is the password correct?
        string passHash = ComputePasswordHash(logModel.LoginPassword, user.Salt);
        if (!String.Equals(passHash, user.Password))
        {
            user.FailedPasswordAttemptCount++;
            try
            {
                _usersRepository.Update(user);
            }
            catch(Exception ex)
            {
                //just log it, not a big deal the FailedPasswordAttemptCount could not be updated
                user.FailedPasswordAttemptCount--;
            }
            TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.InvalidCredentials;
            TempData[Keys.ACCOUNT_TEMPDATA_INVALIDATTEMPTS] = user.FailedPasswordAttemptCount;
            return RedirectToAction("LoginFailed");
        }
        //is the account activated?
        if (!user.IsApproved)
        {
            TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.AccountNotAcctivated;
            return RedirectToAction("LoginFailed");
        }
        //if we got so far then everything is ok
        FormsAuthentication.SetAuthCookie(logModel.LoginUsername, false);
        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
        {
            return Redirect(returnUrl);
        }
        else
        {
            return RedirectToAction("Index", "Home");
        }
    }

Is it ok to retrieve all the user related information, specifically sensitive info like password? Should I first check if that username exists, then select the salt, compute the password hash and check if there is a user with that username and that password hash?
What would you improve?


texts:
I have an assignment for which I need to write an AVL tree. This is what I have written so far. It works on all of my tests, but suddenly fails in checking system with TL (time limit exceeded).

Personally I think there could be a bug with input data in test (although I have already solved this problem with Cartesian tree).

struct node
{
    int key;
    int data;

    int height;

    struct node* left;
    struct node* right;
};

typedef struct node node;

node* new_node(int key, int data)
{
    node* p = malloc(sizeof(*p));

    p -> key    = key;
    p -> data   = data;
    p -> height = 1;
    p -> left   = NULL;
    p -> right  = NULL;

    return p;
}

int max(int a, int b)
{
    return a > b ? a : b;
}

int height(node* p)
{
    return p ? p -> height : 0;
}

void recalc(node* p)
{
    p -> height = 1 + max(height(p -> left), height(p -> right));
}

node* rotate_right(node* p)
{
    node* q = p -> left;

    p -> left = q -> right;
    q -> right = p;

    recalc(p);
    recalc(q);

    return q;
}

node* rotate_left(node* p)
{
    node* q = p -> right;
    p -> right = q -> left;
    q -> left = p;

    recalc(p);
    recalc(q);

    return q;
}

node* balance(node* p)
{
    recalc(p);

    if ( height(p -> left) - height(p -> right) == 2 )
    {
        if ( height(p -> left -> right) > height(p -> left -> left) )
            p -> left = rotate_left(p -> left);
        return rotate_right(p);
    }
    else if ( height(p -> right) - height(p -> left) == 2 )
    {
        if ( height(p -> right -> left) > height(p -> right -> right) )
            p -> right = rotate_right(p -> right);
        return rotate_left(p);
    }

    return p;
}

node* search(node* p, int key)
{
    if ( !p )
        return NULL;

    if ( key < p -> key )
        return search(p -> left, key);
    else if ( key > p -> key )
        return search(p -> right, key);
    else
        return p;
}

node* insert(node* p, int key, int data)
{
    if ( !p )
        return new_node(key, data);

    if ( key < p -> key )
        p -> left = insert(p -> left, key, data);
    else if ( key > p -> key )
        p -> right = insert(p -> right, key, data);
    else
        p -> data = data;

    return balance(p);
}

node* find_min(node* p)
{
    if ( p -> left != NULL )
        return find_min(p -> left);
    else
        return p;
}

node* remove_min(node* p)
{
    if ( p -> left == NULL )
        return p -> right;

    p -> left = remove_min(p -> left);
    return balance(p);
}

node* remove_item(node* p, int key)
{
    if ( !p )
        return NULL;

    if ( key < p -> key )
        p -> left = remove_item(p -> left, key);
    else if ( key > p -> key )
        p -> right = remove_item(p -> right, key);
    else
    {
        node* l = p -> left;
        node* r = p -> right;
        free(p);

        if ( r == NULL )
            return l;

        node* m = find_min(r);
        m -> left = l;
        m -> right = remove_min(r);

        return balance(m);
    }

    return balance(p);
}

void free_tree(node* p)
{
    if ( !p )
        return;

    free_tree(p -> left);
    free_tree(p -> right);
    free(p);
}

int main(void)
{
    node* root = NULL;

    char c;
    int k, d;
    while ( scanf("%c", &c) && c != 'F' )
    {
        if ( c == 'A' )
        {
            scanf("%d %d", &k, &d);
            root = insert(root, k, d);
        }
        else if ( c == 'S' )
        {
            scanf("%d", &k);
            node* n = search(root, k);
            if ( n )
                printf("%d %d\n", n -> key, n -> data);
        }
        else if ( c == 'D' )
        {
            scanf("%d", &k);
            root = remove_item(root, k);
        }
    }

    free_tree(root);

    return 0;
}


texts:
Is it possible to simplify the code below?

dynamic model = GetExpandoObject(); //model type of ExpandoObject

var result = model.FirstOrDefault(x => x.Key == "node").Value;

if (result != null)
{
    result = ((ExpandoObject)result).FirstOrDefault(x => x.Key == "children");

    if (result != null)
    {
        result = ((IList<object>)((KeyValuePair<string, object>)result).Value).FirstOrDefault();

        if (result != null)
        {
            if (result != null)
            {
                result = ((ExpandoObject)result).FirstOrDefault(x => x.Key == "node").Value;

                if (result != null)
                {
                    result = ((ExpandoObject)result).FirstOrDefault(x => x.Key == "stuff");
                }
            }
        }
    }
}

Maybe it is possible to implement similar logic with Linq?  Any thoughts?


texts:
I am writing a lambda function to make a request and fetch data from API.
I am using as a class based approach which I think could refactor it and write in correct way.
May be we can change this class based approach if required. Below is the approach which I have implemented.
app.js
const  apiService = require('./apiService.js');

exports.handler = (async(event, context, callback) => {

    if ((event["type"]) && event["type"] != "" ){
      let apiServices = new apiService(event["type"], context);
      let successResponse = await apiServices.beginProcess();
      let response = return {
        'body': JSON.stringify(successResponse),
        'statusCode': 200
      };
    } else {
       response = {
        'body':"invalid request",
        'statusCode': 200
      };
      return response
    }
});

apiService.js
const getCredentialsService = require('./modules/getCredentials')
let getCredentials = new getCredentialsService();

class apiService {
    constructor(eventType, event, context) {
        this.event = event;
        this.context = context;
    }

    beginProcess() {
        return new Promise(async (resolve, reject) => {
          if (this.event["type"] == "getcredentials") {
                let credentialsData = await this.fetchCredentials();
                resolve(credentialsData);
            }
        });
    }

    fetchCredentials() {
        return new Promise(async (resolve, reject) => {
             let response = await getCredentials.getCredentialsData(this.event);
             resolve(response);
        });
    }
}

module.exports = apiService;

getCredentials.js
var request = require('request');
var moment = require('moment');
const AWS = require("aws-sdk");
let sts = new AWS.STS();
class getCredentialsService {

    getCredentialsData = async (event) => {
        const data = await sts.assumeRole(params1).promise();
        const athena = new AWS.Athena({
            accessKeyId: data.Credentials.AccessKeyId,
            secretAccessKey: data.Credentials.SecretAccessKey,
            sessionToken: data.Credentials.SessionToken,
        });

        // Next athena query exectuion
        await athena.startQueryExecution(queryParams, async function(err, data) {
            if (err) {
                console.log(err, err.stack);
            } else {
                var QueryExecutionId = data["QueryExecutionId"];
                const data1 = await getQueryResult(QueryExecutionId, data)
                resolve(data1);
            }
        });

    };
}

module.exports = getCredentials;


texts: Validator extended to handle domain objects / entities

texts:
I started improving my validator library even more, and I think I'm at the last final element (domain object / entity validations) before I can gladly say that my Validator library is completely done and it supports all of it.

Here you can see that my validator can already deal with regular variable inputs or non-entity inputs (certain forms for example).

I started figuring out how I could extend my validator to create domain object validators and here is my attempt.

Could anybody review it and see if you find any room for improvements and give constructive feedback?

User

class User
{
    public $name;
    public $email;
    public $age;
}

UserValidator

class UserValidator extends Validator
{
    public function __construct()
    {
        $rules['name']  = [new MaxChars(20), new Alpha(true)];
        $rules['email'] = [new Email()];
        $rules['age']   = [new Numeric(), new Between(13, 17)];

        $this->setRule('name',  $rules['name']);
        $this->setRule('email', $rules['email']);
        $this->setRule('age',   $rules['age']);
    }

    public function validate(User $user)
    {
        $this->errors = [];

        parent::validate('name',  $user->name);
        parent::validate('email', $user->email);
        parent::validate('age',   $user->age);

        return empty($this->errors);
    }
}

Validator

class Validator
{
    protected $rules  = [];
    protected $errors = [];

    public function getErrors($rulename = null)
    {
        if ($rulename) {
            return isset($this->errors[$rulename]) ? $this->errors[$rulename] : [];
        }

        return $this->errors;
    }

    public function setRule($name, Array $rules, $required = true)
    {
        $this->rules[$name]['rules'] = $rules;

        switch (true) {
            case ($required === true):
                $this->rules[$name]['required'] = 'Must not be null or empty.';
                break;
            case ($required === false):
                $this->rules[$name]['required'] = false;
                break;
            default:
                $this->rules[$name]['required'] = $required;
                break;
        }
    }

    public function validate($rulename, $input)
    {
        if ($this->rules[$rulename]['required']) {
            if (empty($input)) {
                $this->errors[$rulename][] = $this->rules[$rulename]['required'];
            }

            foreach ($this->rules[$rulename]['rules'] as $rule) {
                if (!$rule->check($input)) {
                    $this->errors[$rulename][] = $rule->getError();
                }
            }
        } elseif (!empty($input)) {
            foreach ($this->rules[$rulename]['rules'] as $rule) {
                if (!$rule->check($input)) {
                    $this->errors[$rulename][] = $rule->getError();
                }
            }
        }

        return isset($this->errors[$rulename]);
    }
}

Example

$user        = new User();
$user->name  = 'John Doe';
$user->email = 'john@doe.com';
$user->age   = 13;

$uv = new UserValidator();

$uv->validate($user)); //true
$uv->getErrors());     //empty array


texts:
I have a method which extracts filedata and converts it into a String array:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import org.apache.james.mime4j.message.BodyPart;
import org.apache.james.mime4j.message.Message;
import org.apache.james.mime4j.message.Multipart;
import org.apache.james.mime4j.message.TextBody;

protected String[] extractLedesText(byte[] fileData) {
    // Remove the BOM if present
    byte[] array = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
    byte[] data =  { fileData[0], fileData[1], fileData[2] };
    if (fileData.length > 3 && Arrays.equals(data, array)) {
        fileData = ArrayUtils.subarray(fileData, 3, fileData.length-1);
    }

    String ledes = new String(fileData);
    if (ledes.startsWith("MIME")) {

        try {
            ledes = null;
            Message signed = new Message(new ByteArrayInputStream(fileData));
            for (BodyPart part : ((Multipart) signed.getBody()).getBodyParts()) {
                if (part.getMimeType().equalsIgnoreCase("text/plain")) {
                    TextBody tb = (TextBody) part.getBody();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    tb.writeTo(baos);
                    return extractLedesText(baos.toByteArray());
                }
            }
            throw new BaseApplicationException(
                    "No MIME part found with MIME type of 'text/plain' while parsing submitted invoice file.");
        } catch (IOException ioe) {
            throw new BaseApplicationException(ioe);
        }
    } else {
        return ledes.split("\\[]");
    }

}

For example, below is the leads file:

LEDES98BI V2[]
INVOICE_DATE|INVOICE_NUMBER|CLIENT_ID|LAW_FIRM_MATTER_ID|INVOICE_TOTAL[]
20150301|INV-Error_Test1|160|LF_MAT_1221|22[]
20150301|INV-Error_Test1|160|LF_MAT_1221|22[]
20150301|INV-Error_Test1|160|LF_MAT_1221|22[]

The extractLedesText method converts the above file data to string array of lines.

We recently upgraded to Java 8 and am wondering whether this method can be optimized further.


texts:
I've implemented a Caesar cipher in C++ and would like for you to review it. It works as expected, at least with the inputs I've tried.

Feel free to suggest improvements, warn about bad practices or mistakes that I might be doing or give general tips.

// Caesar Cipher implementation

#include <iostream>
#include <string>
#include <algorithm>
#include <fstream>
#include <vector>
#include <cassert>
#include <iterator>

std::string encodeStr(const std::string& str, int shift, bool decodeFlag = false)
{
    std::string str_enc;
    // not sure if this function is doing to much
    std::transform(str.cbegin(), str.cend(), std::back_inserter(str_enc), [&](char ch) -> char
    {
        if (ch == 'z' || ch == 'Z')
        {
            return ch - 25;
        }
        else if (isspace(ch))
        {
            return ' ';
        }
        else
        {
            if (islower(ch))
                ch ^= 0x20; // XOR 6th bit don't care if it's lower case.
            if (decodeFlag)
            {
                return ((ch - 'A' + 26) - shift) % 26 + 'A';
            }
            else
            {
                return ((ch - 'A') + shift) % 26 + 'A';
            }
        }
    });
    return str_enc;
}

std::vector<std::string> encodeVec(const std::vector<std::string>& strVector, int shift, bool decodeFlag = false)
{
    std::vector<std::string> tempMsg;
    tempMsg.reserve(strVector.size());

    std::transform(strVector.cbegin(), strVector.cend(), std::back_inserter(tempMsg),
        [&](const std::string& s) { return encodeStr(s, shift, decodeFlag); });

    return tempMsg;
}

int main(int argc, char *argv[])
{
    int choice;
    std::cout << "What do you want to do? 1.Encrypt, 2.Decrypt: ";
    std::cin >> choice;

    if (!(choice == 1 || choice == 2)) {
        return EXIT_FAILURE;
    }

    int key;
    std::cout << "Enter desired shift: ";
    std::cin >> key;

    std::ifstream inFile("test.txt"); // Might ask for the file instead of hard coding it...
    if (!inFile)
    {
        std::cout << "There was a problem with the file!";
        return EXIT_FAILURE;
    }

    std::string line;
    std::vector<std::string> lines;

    while (std::getline(inFile, line))
    {
        lines.push_back(line);
    }

    const std::vector<std::string> finalResult = [&]()
    {
        return choice == 1 ? encodeVec(lines, key) : encodeVec(lines, key, true);
    }();

    std::ofstream outFile("test.txt");
    std::copy(finalResult.cbegin(), finalResult.cend(),
        std::ostream_iterator<std::string>(outFile, "\n"));

    return EXIT_SUCCESS;
}


texts: unit-testing / mocking a class which contains functionality which depends on itself

texts:
Take the below code:

public interface ISettingsManager
{
    SettingData GetSettingByIdentifierOrCreateIfDoesNotExist(Enum identifier);
    T GetSetting<T>(Enum identifier);

}

[IocComponent]
public class SettingsManager : ISettingsManager
{
    private readonly ISettingGetItemByIdentifierService _settingGetItemByIdentifierService;

    public SettingsManager(
        ISettingGetItemByIdentifierService settingGetItemByIdentifierService)
    {
        _settingGetItemByIdentifierService = settingGetItemByIdentifierService;
    }

    public SettingData GetSettingByIdentifierOrCreateIfDoesNotExist(Enum identifier)
    {
        SettingData setting = //GetSetting from database;
        return setting;
    }

    #region ISettingsManager Members

    public T GetSetting<T>(Enum identifier)
    {
        var setting = GetSettingByIdentifierOrCreateIfDoesNotExist(identifier);
        return (T)setting.Value;
    }

    #endregion
}

The ISettingsManager is created to retrieve settings for an application.  The main logic is done in GetSettingByIdentifierOrCreateIfDoesNotExist.  The logic is not shown in the example, but this should try to get the setting from the database.

The method GetSetting is a convenience method which basically retrieves the setting from the other method, and casts it to the required value as setting.Value is of type object.

I am trying to follow the Test-Driven-Development guidelines, and hence I assume a unit-test should be created for this method as well.   As it is, one cannot just mock the GetSettingByIdentifierOrCreateIfDoesNotExist, as it is in the same class.

Does it make sense to split this out in another class, so one can mock it?  Personally, I think that these two go together.  Any ideas how one would approach this would be greatly appreciated :)


texts: Extracting two columns from exported iTunes playlist

texts:
My friend wanted me to send her a list of songs from one of my iTunes playlists, so I exported the playlist within the app itself.  It comes as a plain text file, where each field is separated a '\t' and each line is separated by a '\r'. Since there is so much extraneous information, I decided to write a Python script that would delete all fields but the song title and artist name.

How is the design and format of my code? How does it fit in with Python best practices? Is there a much easier way to do accomplish the same job that I just overlooked?

The input file looks like:

Name\tArtist\tComposer\tAlbum\tGrouping\tGenre\tSize\tTime\tDisc Number\tDisc Count\tTrack Number\tTrack Count\tYear\tDate Modified\tDate Added\tBit Rate\tSample Rate\tVolume Adjustment\tKind\tEqualizer\tComments\tPlays\tLast Played\tSkips\tLast Skipped\tMy Rating\tLocation

You Shook Me All Night Long\tAC/DC\t\tThe Very Best\t\tHard Rock\t5468228\t212\t\t\t9\t\t2001\t4/17/12, 2:29 PM\t4/17/12, 2:26 PM\t192\t44100\t\tMPEG audio file\t\t\t5\t3/12/13, 10:41 PM\t\t\t\tMacintosh HD:Users:UserName:Music:iTunes:iTunes Media:Music:AC_DC:The Very Best:09 You Shook Me All Night Long.mp3

The output file looks like:

Name\tArtist\t

You Shook Me All Night Long\tAC/DC\t

Miss Murder\tAFI\t

My code is:

from sys import argv

def main(file):
    with open(argv[1], 'r') as file:
        data = file.read()
        newdata = data.split('\r')
        output = []
        for line in newdata:
            tabc = 0
            newline = ""
            for char in line:
                newline += char
                if char == '\t':
                    tabc += 1
                    if tabc == 2: break
            output.append(newline)
        outPutString = '\n'.join(output)
    with open(argv[1][:-4]+'Out.txt', 'w') as file:
        file.write(outPutString)

if __name__ == '__main__':
    file = argv[1]
    main(file)


texts:
I'm working on a photo website, the markup looks like this:

Photo 1

Photo 2

    ...

I've come up with some SCSS code that presents the images as expected (a justified strip of fixed height with a white line at the top and bottom. Here's the SCSS:

$background_color: #333;
$border_color: #EEE;

$thumbnail-height: 87px;

html, figure, img, div {
    margin: 0;
    padding: 0;
}
body {
    font-size: 100%;
    line-height: 1;
    margin: 1em;
    background: $background_color;
}
.gallery {
    text-align: justify;
    margin: 0 -4px -1px 0;
    padding: 1px 0 0 0;
    overflow: hidden;
    figure {
        position: relative;
        border-top: 1px solid $border_color;
        border-bottom: 1px solid $border_color;
        height: $thumbnail-height;
        display: inline-block;
        margin: -1px 4px 0 0;
        vertical-align: top;
        &:before {
            content: "";
            position: absolute;
            top: -1px;
            bottom: -1px;
            left: -9999px;
            width: 9999px;
            z-index: -1;
            border-top: 1px solid $border_color;
            border-bottom: 1px solid $border_color;
        }
        img {
            height: 100%;
            display: block;
        }
        figcaption {
            display: none;
        }
    }
}

There is a fiddle demo here.

This gives an acceptable layout on most modern browsers, but I'm not very proud of this code:

It's too complicated
It uses negative margins, that I view as a hack
It uses large :before pseudo-element that are trimmed by overflow: hidden, and that also needs a negative z-index

I would be grateful for any tips that would help improve that code.


texts:
Here's my approach to an extensible version of the FizzBuzz challenge in Swift (so one can add more numbers to be checked against other than just 3 and 5).

I initially tried using dictionaries but since they don't necessarily preserve the order of elements it could lead to BuzzFizz return values.

I personally think that, while the program does work as expected, it isn't clear how it works. I mean, it's not as readable as I'd like it to be for doing such a simple task.

How can I improve it?

func fizzBuzz (n: Int, responsesByMultiples: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]) -> String {
    var result: String = ""

    for key in responsesByMultiples {
        let (multiple, response) = key,
            isMultiple: Bool = (n % multiple) == 0

        if isMultiple {
            result += response
        }
    }
    return result == "" ? String(n) : result
}
for i in 1...100 {
    print(fizzBuzz(n: i))
}


texts:
I wrote a function that takes a number and finds the next palindromic number. Time complexity is currently O(n2), which is really bad. How could one make this function more efficient?

function nextPalindrome(n) {
  // first we create a function to check if a single number is a palindrome
  function isPalindrome(num) {
    const forward = num.toString();
    let backward = [];
    for (let i = forward.length - 1; i >= 0; i--) {
      backward.push(forward[i]);
    }
    backward = backward.join('');
    return forward === backward;
  }
  // now let's create a counter variable to increment our number (n)
  // we'll initialize it as n + 1 since we know we're not going to check the first number
  let countUp = n + 1;
  // we also need a nextPalindrome variable
  let nextP;
  // now we need to begin some sort of loop
  // perhaps a while loop will do
  while (true) {
    if (isPalindrome(countUp)) {
      return countUp;
    } else {
      countUp += 1;
    }
  }

}


texts:
I have the code below that gets hit several hundred times per second. I'm wondering what I can do to improve performance. It seems that there should be some way to build up a substring index. Is there some existing examples of that or an explanation on how to do this?

using System;
using System.Collections.Generic;
using System.Linq;
using Asi.Server.Interfaces.History;

namespace Asi.Server.History.AssetHistory
{
    public class TelemetrySubscriptionFilter: ITelemetryLogFilter, ITelemetryLogAutosubscriber
    {
        private readonly List<string> _shouldNotLogs = new List<string>
        {
            "Local Position Service",
            "Global Position Service",
            "PositionGroup.",
            "DKS/"
        };

        public bool ShouldNotLog(string telemetryName)
        {
            float period;
            if (ShouldAutoSubscribe(telemetryName, out period))
                return false;

            // telemetryName is longer than our filter texts
            return _shouldNotLogs.Any(s => telemetryName.IndexOf(s, StringComparison.Ordinal) >= 0);
        }

        private readonly List<string> _shouldAutoSubscribe = new List<string>
        {
            "Manual Mode",
            "Autonomous Driven",
            "Battery Voltage",
            "RPM",
            "Engine On",
            "Parking Brake",
            "Gear",
            "Stopping Distance",
            "Ready For Motion",
            "GPS Correction Sent",
            "Setpoint",
            "Dead Reckon",
            "VCU uC",
            "Feedback",
            "Off Path",
            "RMS",
            "Yaw Rate",
            "Stop Enabled",
            "Arbiter",
            "Velocity Error",
            "Processor"
        };

        public bool ShouldAutoSubscribe(string telemetryName, out float period)
        {
            period = 0.375f; // chosen somewhat arbitrarily
            return _shouldAutoSubscribe.Any(s => telemetryName.IndexOf(s, StringComparison.Ordinal) >= 0);
        }
    }
}


texts:
I have written the following code using a dynamic programming technique.  Can I use ArrayList here?  Please let me know if I can improve this code.

package com.java.fib;

import java.math.BigInteger;
import java.util.HashMap;

public class Fibonaci {

    public static void main(String[] args) {
        System.out.println(" number ");
        long startTime = System.currentTimeMillis();
        HashMap<Integer, BigInteger> memoized = new HashMap<Integer, BigInteger>();
         fibonanci(220, memoized);
        System.out.println(" Total Time "
                + (System.currentTimeMillis() - startTime));
    }

    private static BigInteger fibonanci(int n, HashMap<Integer, BigInteger> memoized) {
        if (memoized.containsKey(n)) {
            return memoized.get(n);
        }
        if (n <= 0) {
             return BigInteger.ZERO;
        }
        if (n <= 2) {
            return BigInteger.ONE;
        } else {
            BigInteger  febonani = fibonanci(n - 1, memoized).add (fibonanci(n - 2, memoized));
            System.out.println(" febonani " + febonani);
                memoized.put(n, febonani);
            return febonani;
        }
    }
}


texts:
I very infrequently use SQL. I need more experience, so I have created a data explorer query to find those users with most of any particular badge (have to edit the query itself right now to alter it). I like following best practices, so please feel free to nit-pick and really do this right (indentation, capitalization, everything).

I have commented code that I cannot get to work (I would like it to work by user input), I hope my intent is quite obvious.

--declare @BadgeName nvarchar(50) = ##BadgeName:string##
--declare @MyTop int = ##MyTop:int##

select
--  top @MyTop
    top 100
    Badges.UserId as [User Link],
    Users.Reputation,
    --Badges.Name,
    count(Badges.Id) as NumberOfBadges
  from
      Badges
    inner join
      Users On Users.Id=Badges.UserId
  where
--    Badges.Name = @BadgeName and
      Badges.Name = 'Great Answer' and
      Users.Reputation > 10000
group by
    Badges.UserId, Users.Reputation
order by
    NumberOfBadges desc

Here's the actual query if you want to run it:

http://data.stackexchange.com/stackoverflow/query/271133/search-users-by-number-of-badges


texts:
I have created a proof of concept jQuery based flow diagram based upon kayen's answer to this post.

This diagram shows the flow diagram that I am seeking to create in jQuery:

I also wanted to make the UI as clean as possible, so I have set it that only the current question is displayed as the users works their way through the various questions.

The user can also go back to the last question at any time before they are given an answer.

The code will be used on a website.

As my code is long, I have set it out in full in my jsFiddle. The basic structure is:

HTML:

<!—question 2-->
<fieldset id="question2" style="display:none;">
    <legend>question 2</legend>

                <input type="radio" name="question2" value="Yes" id="rdYes" />Yes

                <input type="radio" name="question2" value="No" id="rdNo" />No

            <input type="button" value="Back to last question" id="back2-1" />

</fieldset>

jQuery:

//Test for question 2
jQuery("input[name=question2]").change(function () {

    if ($(this).val() == "Yes") {
        jQuery("#question2A").show();
        jQuery("#question2").hide();
    } else {
        jQuery("#question3").show();
        jQuery("#question2").hide();
    }
});

//Back button to question 1 from 2
jQuery("#back2-1").click(function () {
    jQuery("#q1").show();
    jQuery("input:radio").attr("checked", false);
    jQuery("#question2").hide();
});

It works, but as this is my first project it would really help me and others learning code, if someone could confirm:

Is there a more efficient way to code this in jQuery?
Would it be better to code it in another language, i.e. to avoid problems with older browsers?


texts: Composing an HTML email body in PHP swiftmailer

texts:
The following code is what I'm using to send a password reset email. The specific part I'm referring to is how I'm setting $message. Would there be a cleaner way to do this or is this about as clean as you can get?

/**
 * Attempt to send reset link
 * @return bool True if success, false if not
 */
public function try() {
    // Update users email hash
    $this->_updateResetHash();
    $user = $this->_grabUser();

    $resetLink = $_SERVER["HTTP_ORIGIN"] . "/reset/" . $this->_hash . "/" . $user['uid'];

    $message = "Hello, " . ucfirst($user["first_name"]) . ",

";
    $message .= "We received a request to reset your password.

";
    $message .= "Please click here to reset your password
";
    $message .= "
If you did not make this request you do not need to worry. The only way your password can be reset is through the email that is on the account. Unless someone has taken control of you email, your account is safe and no one except you can gain access.
";

    // If email is sent
    if (!Mail::send("Password reset link", $message, ["no-reply@.com" => "No-Reply@"], $this->_email, 'text/html')) {
        return false;
    }

    return true;
}

Also, I'm not too sure how or if it exists but I heard somewhere that Twig / Slim, which I'm using, have a way of using templates for swiftmailer.


texts: Rewriting C# implementation of Snake class in F#

texts:
This is my C# class, which takes 2.6s:

class Snake
{
    readonly Symbol _mySymbol;
    readonly int _multiplier;
    readonly int _hit;
    readonly int _payout;
    readonly Snake _bestSnake;

    public Symbol MySymbol { get { return _mySymbol; } }
    public int Multiplier { get { return _multiplier; } }
    public int Hit { get { return _hit; } }
    public int Payout { get { return _payout; } }

    public Snake BestSnake { get { return _bestSnake; } }

    public Snake(Apple myApple)
    {
        this._mySymbol = myApple.MySymbol;
        this._multiplier = myApple.Multiplier;
        this._hit = 1;
        this._payout = _mySymbol.Payout_[0] * (_multiplier == 0 ? 1 : _multiplier);
        this._bestSnake = this;
    }

    Snake(Symbol mySymbol, int multiplier, int hit)
    {
        this._mySymbol = mySymbol;
        this._multiplier = multiplier;
        this._hit = hit;
        this._payout = _mySymbol.Payout_[hit - 1] * (multiplier == 0 ? 1 : multiplier);
        this._bestSnake = this;
    }

    Snake(Symbol mySymbol, int multiplier, int hit, Snake bestRecentSnake)
        : this(mySymbol, multiplier, hit)
    {
        if (_payout < bestRecentSnake._payout)
        {
            this._bestSnake = bestRecentSnake;
        }
        else if (_payout == bestRecentSnake._payout)
        {
            if (bestRecentSnake._mySymbol.Type == 1 && mySymbol.Type != 1)
            {
                this._bestSnake = bestRecentSnake;
            }
        }
    }

    public Snake Eat(Apple nextApple)
    {
        var resultSymbol = Symbol.Add(_mySymbol, nextApple.MySymbol);
        if (resultSymbol == null)
            return null;

        var newSnake = new Snake(resultSymbol, Math.Max(_multiplier, nextApple.Multiplier), Hit + 1, _bestSnake);

        return newSnake;
    }

This is my F# class, which takes 5s:

type Snake (mySymbol: Symbol, multiplier, hit, best: Option<Snake>) =

let payout (mySymbol: Symbol) hit multiplier =
    match multiplier with
    | 0 -> mySymbol.Payout_.[hit-1]
    | a -> mySymbol.Payout_.[hit-1] * a

new (myApple: Apple) = Snake (myApple.MySymbol, myApple.Multiplier, 1, None)

member this.BestSnake =
    match best with
    | Some a when this.Payout < a.Payout -> a
    | Some a when this.Payout = a.Payout && a.MySymbol.Type = 1 && mySymbol.Type <> 1 -> a
    | _ -> this

member this.MySymbol = mySymbol
member this.Payout = payout mySymbol hit multiplier
member this.Multiplier = multiplier
member this.Hit = hit

member this.Eat (myApple: Apple) =
    let tmp = Symbol.Add mySymbol myApple.MySymbol
    match tmp with
    | None -> Operators.Unchecked.defaultof<Snake>
    | Some a -> Snake (a, (max multiplier myApple.Multiplier), hit+1, Some this.BestSnake)


texts: A web scraper that looks for pre-defined words in news articles

texts:
I'm still fairly new to Python and web-scraping, but a colleague asked asked me if I could build a web-scraper that could be used by a think tank he's a member of to find news articles matching a pre-defined list of trigger words of interest to the organisation.

The purpose of the following script is as follows:

Parse an RSS feed of news articles published by a British news
outlet
Read each news article listed in the feed by accessing the link
for each item in the RSS feed.
Search each article for pre-defined words and phrases
Write the results (matching trigger word/phrase and link to article)
to a CSV.

Here's the code:

import feedparser
from bs4 import BeautifulSoup
from lxml import html
import requests
import re

import csv

words = ['divorce', 'custody battle', 'meal ticket', 'behind closed doors', 'detail of the case emerged on a legal database', ]

hit_article = []
links_list = []
hits = []
hit_link = []

d = feedparser.parse('http://www.dailymail.co.uk/articles.rss')

for item in d.entries:
    link = ( item[ "link" ] )
    links_list.append(link)
    title = ( item ["title"])

for link in links_list[:100]:
    page = requests.get(link)
    tree = html.fromstring(page.content)

    soup = BeautifulSoup(page.text, 'html.parser')

    text = soup.find('body')
    text = text.text

    for word in words:
        regex = r"\b"+ re.escape(word) + r"\b"
        match = re.search(regex, text)
        if match:
            print (word, ' ', title, "________found")
            hits.append(word)
            hit_link.append(str(link))

match_dictionary = dict(zip(hit_link, hits))

print (match_dictionary)

w = csv.writer(open("output.csv", "w"))
for key, val in match_dictionary.items():
    w.writerow([key, val])

The code does what I want it to do, but I know it stinks (particularly where I fall back into two for loops.

How can I achieve the same result more cleanly and Pythonically?


texts:
There is a function that returns digits as vector of given number. Is it idiomatic way to solve this problem in Rust? Can you suggest more concise solution?

#[allow(dead_code)]
fn num_digits(num: i32) -> Vec<i32> {
    let mut x = num;
    let mut result: Vec<i32> = Vec::new();

    loop {
        result.push(x % 10);
        x /= 10;
        if x == 0 {break}
    }

    result.reverse();
    result
}

#[test]
fn digits() {
    assert_eq!(num_digits(0), [0]);
    assert_eq!(num_digits(-1), [-1]);
    assert_eq!(num_digits(-123), [-1, -2, -3]);
    assert_eq!(num_digits(1), [1]);
    assert_eq!(num_digits(12), [1, 2]);
    assert_eq!(num_digits(456464), [4, 5, 6, 4, 6, 4]);
}


texts: Is there a better way to count seconds in python

texts:
def stopWatchSeconds(secondCnt) :
    """ counts second for secondCnt seconds """

    # is there a better way to do this?
    startTime = time.clock()
    ellapsed = 0
    for x in range(0, secondCnt, 1) :
        print "loop cycle time: %f, seconds cnt: %02d" % (ellapsed , x)
        ellapsed = 1 - (time.clock() - startTime)
        time.sleep(ellapsed)
        startTime = time.clock()

I'm reviewing some source code for a buddy of mine and came across this function. I am very new to Python so it is more of a learning experience for me. I see that he put in a comment about is there a better way to do this. I started thinking about it, and I know how I would do it in C#, but since python is so much more laxed it does seem like this function could be improved.


texts: Modelling articals and authors in Django

texts:
I need to understand if the way I am modelling data in a Django application is correct. The idea is of a news site that has sources, authors and articles.

I want:

Source to have many Article
Author to have many Article
Article to have many Author

Does the below model do this correctly? I am worried there is a loop on 2 and 3. DO I only need to define the ManyToManyField in one of these?

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models

class Source(models.Model):
    source_id = models.CharField(max_length=20)
    name = models.CharField(max_length=50)
    articles = models.ForeignKey(Article, on_delete=models.CASCADE)

class Article(models.Model):
    authors = models.ManyToManyField(Author)

    title = models.CharField(max_length=200)
    description = models.CharField(max_length=200)
    url = models.CharField(max_length=200)
    urlToImage = models.CharField(max_length=200)
    publishedAt = models.DateTimeField(max_length=100)
    content = models.CharField(max_length=5000)

class Author(models.Model):
    name = models.CharField(max_length=50)
    articles = models.ManyToManyField(Article)


texts:
I have this piece of code which given a list returns another list which combines every element with every other element (without repetitions) using a given function as a combiner. I came up with three different version (2 of them listed below, fastest to slowest), and now I'm asking for help to optimize it/them even further. Currently, my perms3 does not utilize multithreading at all, and since I'm quite new to Haskell I can't seem to figure out why, but I'm thinking that in its current state my algorithm isn't parallelizable, even though it can be.

I've also concluded that the length of the output list will always be \$ \binom{x}{2} + x = x(x-1)/2 + x\$ where \$x\$ is the length of the input list, but I dont know how to use that in my algorithm either to minimize the allocations.

The reason the why I'm asking is because I want to know more about the inner workings of Haskell, how lazy-evaluation affects performance and what is considered good/bad Haskell code.

My two permutation functions:

perms3  c l             = perms3' c l l
perms3' _ []      _     = []
perms3' c (a:b)   [x]   = c a x:perms3' c b b -- the outer loop
perms3' c l@(a:_) (h:t) = c a h:perms3' c l t -- the inner loop

perms2 _ [] = [] --this can probably be 2 folds, the inner fold might be parallelizable?
perms2 c l@(h:t)= foldr (\x acc -> c h x:acc) [] l ++ perms2 c t

Input:  (,) ['a'..'c']
Output: [('a','a'),('a','b'),('a','c'),('b','b'),('b','c'),('c','c')]

Input   (+) [1..5]
Output: [2,3,4,5,6,4,5,6,7,6,7,8,8,9,10]

Unsurprisingly, perms3 is a fair bit faster than perms2.

Testing perms3:

import Control.Monad
import System.Environment

main :: IO ()
main = liftM (length . perms3 (,) . enumFromTo 1 . read . head) getArgs >>= print

perms3 :: (a -> a -> t) -> [a] -> [t]
perms3  c l             = perms3' c l l
perms3' _ []      _     = []
perms3' c (a:b)   [x]   = c a x:perms3' c b b
perms3' c l@(a:_) (h:t) = c a h:perms3' c l t

Running it:

$ ghc -O3 main && time ./main 10000
50005000

real    0m0.615s

$ ghc -O3 main && time ./main 30000
450015000

real    0m5.347s

Question(s):

Is this a good way to write Haskell code?
Can I squeeze any more performance out of my function?
Should I prefer the imperative do-notation instead of arrows in my main function?


texts:
I have been working on a small game lately and I was tired of looking up and copy-pasting game loops so I tried to make one as you can see. It works perfectly so if you want to feel free to use it, but for those who are good at making these I would like to ask if I can improve it, make it more efficient and overall is it a good solution to run two of these one to render, the other to tick.

package engine;

public abstract class RapidExecutor extends Thread {

    Application app;

    /*
    the field app is here because the abstract tick method can
    only acces the stuff needed to render or to tick
    objects so if you want to use it for anything else
    you can just delete it
    */

    private final int TPS;

    private boolean running;

    public RapidExecutor(Application app, int TPS) {

        this.app = app;

        this.TPS = TPS;

        if (TPS > 1000 || TPS < 1)
            try {
                throw new Exception("Invalid TPS count");
            } catch (Exception e) {
                e.printStackTrace();
            }

    }

    public abstract void tick();

    public void run() {

        try {

            this.running = true;

            long now, startTime;

            int delta, TPSCount = 1000 / this.TPS;

            while (this.running) {

                startTime = System.currentTimeMillis();

                tick();

                now = System.currentTimeMillis();

                delta = (int) (TPSCount - (now - startTime));

                if (delta < 0) this.stopThread();

                sleep(delta);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public synchronized void stopThread() {

        try {

            this.running = false;
            this.join();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Feel free to use the code and if you have any thoughts I would be very glad to hear them.


texts:
I have the following query

SELECT [u].[ActivityRecordID],
       [u].[ActCstID],
       [u].[ResCstID],
       SUM([u].[VolAmt]) AS VolAmt,
       [u].[ActCnt],
       SUM([u].[TotOCst]) AS TotOCst,
       SUM([u].[TotFCst]) AS TotCst
INTO [__EpisodeCostCtp]
FROM
    (
        SELECT [s1].[EpiSer] as ActivityRecordID,
               [s1].[CTPActivityGroupCode] as ActCstID,
               [t].[ResCstID],
               [s1].[VolAmt],
               [s1].[CTPQty] AS ActCnt,
               SUM([s1].[VolAmt] * [t].[OCostUnit]) AS TotOCst,
               SUM([s1].[VolAmt] * [t].[FCostUnit]) AS TotFCst
        FROM [ServDataCtp_Stage1] AS s1
          INNER JOIN
              (
                  SELECT [dexp].[VolNum],
                         [dexp].[CostItem],
                         [dexp].[OCostUnit],
                         [dexp].[FCostUnit],
                         [lci].[CTPResourceGroup] AS ResCstID
                  FROM [DriversExp] AS dexp
                      INNER JOIN [ListCostItem] AS lci ON [dexp].[CostItem] = [lci].[CostItemCode]
              ) AS t ON [s1].[VolNum] = [t].[VolNum]
        GROUP BY [s1].[EpiSer],
                 [s1].[CTPActivityGroupCode],
                 [t].[ResCstID],
                 [s1].[VolAmt],
                 [s1].[CTPQty]
    ) AS u
GROUP BY [u].[ActivityRecordID],
         [u].[ActCstID],
         [u].[ResCstID],
         [u].[ActCnt];
GO

which involves the use of two temporary tables which was far from ideal - but this slipped through the net. This was written very quickly with a view to getting some data exported to some clients. However, it is now starting to be used regularly and it will clearly start to suffer from disk usage and bloating of tempdb as the data grows very large, which it will.

So, to get around the potential problem of a bloating tempdb, I have merely split the query in to three as follows

SELECT [dexp].[VolNum],
       [dexp].[CostItem],
       [dexp].[OCostUnit],
       [dexp].[FCostUnit],
       [lci].[CTPResourceGroup] AS ResCstID
INTO TmpA
FROM [DriversExp] AS dexp
    INNER JOIN [ListCostItem] AS lci
        ON [dexp].[CostItem] = [lci].[CostItemCode];
GO

SELECT [s1].[EpiSer] as ActivityRecordID,
       [s1].[CTPActivityGroupCode] as ActCstID,
       [t].[ResCstID],
       [s1].[VolAmt],
       [s1].[CTPQty] AS ActCnt,
       SUM([s1].[VolAmt] * [t].[OCostUnit]) AS TotOCst,
       SUM([s1].[VolAmt] * [t].[FCostUnit]) AS TotFCst
INTO TmpB
FROM [ServDataCtp_Stage1] AS s1
    INNER JOIN
        TmpA AS t ON [s1].[VolNum] = [t].[VolNum]
GROUP BY [s1].[EpiSer],
            [s1].[CTPActivityGroupCode],
            [t].[ResCstID],
            [s1].[VolAmt],
            [s1].[CTPQty];
GO

-- DROP TmpA

SELECT [u].[ActivityRecordID],
       [u].[ActCstID],
       [u].[ResCstID],
       SUM([u].[VolAmt]) AS VolAmt,
       [u].[ActCnt],
       SUM([u].[TotOCst]) AS TotOCst,
       SUM([u].[TotFCst]) AS TotCst
INTO [__EpisodeCostCtp]
FROM TmpB AS u
GROUP BY [u].[ActivityRecordID],
        [u].[ActCstID],
        [u].[ResCstID],
        [u].[ActCnt];
GO

-- Drop TmpB

Is there any glaring problem with this?
Is there any way of improving this splitting of the initial [poorly written] query to increase performance in terms of CPU time?


texts: how to allow user to input results in Array using java?

texts:
I want to allow the user to enter a number of race results (A minimum of 2 participants and a maximum of 7) I feel that I could use a much shorter code, (I am a beginner of Java only 2 months so any recommendation would be highly useful! thank you
Code below:

int entrants = 0;
String[][] runners = new String[2][2];
boolean valid = false; //this is for the initial number of runners question - it will stay false and keep us in the loop until a number between 2-7 is entered
System.out.println("Please enter the number of runners for this race (2 to 7 entrants permitted)");
entrants = input.nextInt();
input.nextLine();

while(valid == false){

    if(entrants < 2) {
        System.out.println("You need at least 2 runners for a race, please re-enter the number of runners");
        entrants = input.nextInt();
        input.nextLine();
    } else if (entrants > 7) {
        System.out.println("You have entered too many runners for this race (max runners is 7). Please re-enter the number of runners");
        entrants = input.nextInt();
        input.nextLine();
    } else {
        System.out.printf("You have entered %d runners\n", entrants);
        runners = new String[entrants][2];
        valid = true;
    }
}


texts:
I have following input range (slider), values allowed are from 0 to 100.
I need to map values from the slider to a input text, with the following rules:

      range => text
          0 => 2000
        100 =>  200

With the value in between accordingly.
Currently I am using the following script, which works, but I would like to know if there is a better way to do it.

var slider = document.querySelector('#slider');
var result = document.querySelector('#result');
slider.addEventListener('change', function(event) {
  var sliderValue = event.target.value;
  var maxValue = 2000;
  var coef = 18;
  var calc;
  calc = maxValue - (sliderValue * coef);
  result.value = calc;
});
<input id="slider" type="range" name="points" min="0" max="100" value=0>
<input id="result" type="text" name="result">


texts: Sort dictionary by increasing length of its values

texts:
Given a dictionary where the values are iterables, print the dictionary sorted by the length of its values.

def sort_dict_by_value_len(lst):
    while lst:
        min_key = min([(len(v), k) for (k, v) in lst.items()])
        print(min_key[1], lst.pop(min_key[1]))

sort_dict_by_value_len({1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'})

1 one
2 two
6 six
10 ten
4 four
5 five
9 nine
3 three
7 seven
8 eight

I feel like I'm doing too much computations, and worst of all, I'm emptying the input list. Is there any better way to achieve this, with or without using sort or sorted, and optionally keeping the dictionary intact?


texts:
This is my solution for Day 2 of Advent of Code 2019.

It's the eval function I want to get reviewed. Is this acceptable Haskell code? Is it even close to being idiomatic? Also, is it OK to leverage laziness this way?

module Day2 where

import Data.Vector (Vector, fromList, head, (!), (//))
import Data.List.Split (splitOn)

type Intcode = Vector Int

data Op = Add | Mult | Noop

intToOp :: Int -> Op
intToOp 1 = Add
intToOp 2 = Mult
intToOp 99 = Noop
intToOp x = error $ "invalid opCode, should not happen" ++ show x

eval :: Intcode -> Intcode
eval intcode = go intcode 0
  where
    go intcode currentIndex =
      let
        op = intToOp $ intcode ! currentIndex
        v1Pos = intcode ! (currentIndex + 1)
        v2Pos = intcode ! (currentIndex + 2)
        savePos = intcode ! (currentIndex + 3)
        nextIndex = currentIndex + 4
        v1 = intcode ! v1Pos
        v2 = intcode ! v2Pos
      in
        case op of
          Add -> go (intcode // [(savePos, (v1 + v2))]) nextIndex
          Mult -> go (intcode // [(savePos, (v1 * v2))]) nextIndex
          Noop -> intcode

part1 :: IO ()
part1 = do
  input <- readFile "../input/day2.txt"
  let intcode = fromList (read <$> splitOn "," input)
  let result = eval $ intcode // [(1, 12), (2, 2)]
  putStrLn $ show $ result ! 0

part2 :: IO ()
part2 = do
  input <- readFile "../input/day2.txt"
  let memory = fromList (read <$> splitOn "," input)
  let inputs = [(i, j) | i <- [0..99], j <- [0..99]]
  let results = fmap (\(noun, verb) -> (eval $ memory // [(1, noun), (2, verb)], noun, verb)) inputs
  let (result, noun, verb) = Prelude.head $ filter (\(res, _, _) -> (res ! 0) == 19690720) results
  putStrLn $ show $ 100 * noun + verb


texts:
I am studying the book Realm of Racket.

On chapter 5, there is a challenge:

Find an image of a locomotive. Create an animation that runs the locomotive
from just past the left margin to just past the right margin of the screen. Next, modify your program so the locomotive wraps around to the left side of the screen after passing the right margin.

I created the following code using Racket and Dr. Racket.

However, I bet it could be improved.

My doubt is specially about the transition from the right side to the left side. I think there should be a better way of doing this:

#lang racket

(require 2htdp/universe 2htdp/image)

(define LOCOMOTIVE image-inserted-through-DrRacket )

(define HEIGHT 800)

(define WIDTH 800)

;essa função muda a velocidade com que a figura se mexe

(define (add-3-to-state current-state)
  (if (< current-state 1055)
      (+ current-state 6)
      (- current-state 800)))

(define (locomotive-running current-state)
  (place-image LOCOMOTIVE current-state (/ WIDTH 2)
               (empty-scene WIDTH HEIGHT)))

(big-bang 0
          (on-tick add-3-to-state)
          (to-draw locomotive-running))

That's the image that I used:


texts:
Is there an algorithmically better way of doing this?

import numpy as np
l=np.random.permutation(10)
p=list(range(10))
print(l,p)
i=0
k=0
prod=1
z=0
def gcd(a, b):

    while b:
        a, b = b, a % b
    return a
def lcm(a, b):

    return a * b // gcd(a, b)

while z<10:
    """count how many times we have crossed (-1-ed) a number from p"""
    k=0
    while p[k]==-1 and k<9 :
        """find the first non -1 element in p (it's here that I feel that the code is especially clumsy) """

        k=k+1
    i=k
    """k is the first element in the cycle """
    print(l[i])
    p[k]=-1
    z=z+1
    j=1
    while l[i]!=k:
        """go from i to l[i] until we get back to k, closing the cycle """
        p[l[i]]=-1
        z=z+1
        i=l[i]
        j+=1
        """g is just used to find the lcm """

        print(l[i])
    prod=lcm(prod,j)
    print('------')
print(prod)


texts:
First of all, I am a beginner in Python trying to learn optimizations and proper coding standards.

Here is a snippet of code that checks if a number follows the rule: first AND last N digits contain all unique numbers from 1 to N, but in any order. This also means that in either first N or last N digits, each number appears exactly once.

import time

start_time = time.time()

def is_pandigital(nr, n):
    digits = ''.join(map(str, range(1, n + 1)))
    nr = str(nr)
    for i in digits:
        if str(i) not in nr[0:9]:
            return False
        if str(i) not in nr[-9:]:
            return False

    return True

assert is_pandigital(1423, 4) is True
assert is_pandigital(1423, 5) is False
assert is_pandigital(14235554123, 4) is True
assert is_pandigital(14235552222, 4) is False # !important
assert is_pandigital(1444, 4) is False
assert is_pandigital(123564987, 9) is True

pandigitals = []
# this loop is strictly for benchmarking is_pandigital
for i in range(100000, 999999):
    if is_pandigital(i, 6):
        pandigitals.append(i)

print pandigitals

print time.time() - start_time, "seconds"

When running this, the result is:

[123456, .......]
2.968 seconds

Process finished with exit code 0

The code seems to work fine, but it doesn't appear to be very efficient. Would you have any tips to improve it?  Any piece of code and/or idea would be highly appreciated.

PS: I chose this loop so that any improvements to the is_pandigital function would be immediately obvious.

Example of numbers I am looking for:

321XXXXXXXXXXXXXXX132 - good

321XXXXXXXXXXXXXXX133 - not good, because the last 3 digits dont contain 1, 2 and 3

231 - good


texts: Using "Generics" to implement "Unit Of Work"

texts:
I need to design a generic "Unit Of Work", basically so that I can "change the context of the Database" only changing the implementation of IUnitOfWork on my DI container. I will exemplify below.
So far, I have following solution:
IUnitOfWork.cs
public interface IUnitOfWork
{
    TTransactionType GetCurrentTransaction<TTransactionType>();

    Task CommitAsync(CancellationToken cancellationToken);
    Task BeginTransactionAsync(CancellationToken cancellationToken);
}

UnitOfWorkMongoDB.cs
public class UnitOfWorkMongoDB : IUnitOfWork
{
    IClientSessionHandle _session;
    readonly IMongoDbContext _mongoDbContext;

    public UOLMongoDB(IMongoDbContext mongoDbContext)
    {
        _mongoDbContext = mongoDbContext;
    }

    public TTransactionType GetCurrentTransaction<TTransactionType>() => (TTransactionType)_session;

    public async Task CommitAsync(CancellationToken cancellationToken)
    {
        await _session.CommitTransactionAsync();
    }

    public async Task BeginTransactionAsync(CancellationToken cancellationToken)
    {
        _session = await _mongoDbContext.MongoClient.StartSessionAsync(cancellationToken: cancellationToken);
        _session.StartTransaction();
    }
}

DI Resolution
 services.AddScoped<IUnitOfWork, UnitOfWorkMongoDB>();

Using the solution
public class MyServiceA
{
    public MyServiceA(IUnitOfWork unitOfWork)
    {
        /*...*/
    }
}

public class MyServiceB
{
    public MyService(IUnitOfWork unitOfWork)
    {
        /*...*/
    }
}

Considerations

The IUnitOfWork interface is not really generic, the only
"generic thing" used, was TTransactionType, since each Database
driver manufacturer has a different implementation of transaction
handling. Like:

MongoDB = IClientSessionHandler.cs
MySql = MySqlTransaction.cs
Oracle = OracleTransaction.cs

The IUnitOfWork interface is non generic in attempt to avoid refactoring
code when we change his implementation on D.I resolution.

Samples with non generic IUnitOfWork:
 services.AddScoped<IUnitOfWork, UnitOfWorkPostgreSQL>(); //OR
 services.AddScoped<IUnitOfWork, UnitOfWorkOracle>(); //OR
 services.AddScoped<IUnitOfWork, UnitOfWorkMySQL>(); //OR

Dependencies not break:
public class MyServiceA
{
    public MyServiceA(IUnitOfWork unitOfWork)
    {
        /*...*/
    }
}

"Problems" with with a generic IUnitOfWork<TUnitOfWork>.

If we change the resolution on D.I, all services dependecies will break, like:
services.AddScoped<IUnitOfWork<UnitOfWorkPostgreSQL>, UnitOfWorkPostgreSQL>();

On MyServiceB.cs for example, before he depends of IUnitOfWork<UnitOfWorkMongoDB> and now, my D.I container not solves it. This can cause several changes on application code base.
public class MyServiceB
{
    public MyServiceB(IUnitOfWork<UnitOfWorkMongoDB> unitOfWork)
    {
        /*...*/
    }
}

I still feel uncomfortable with the explicit conversion (TTransactionType)_session; on GetCurrentTransaction<TTransactionType>() method, is there any other approach to make this method? Or am I worrying too much?
What do you think can be improved in this solution? Any evaluation/improvement is welcome!
P.S I created a little repo with this implementation here.


texts: Print the Twelve Days of Christmas without loops or conditionals

texts:
For my AP Computer Science class, I am required to write a program that prints the Twelve Days of Christmas without loops or conditionals using static methods.

public class TwelveDaysOfChristmas {

    public static final String[] lines = new String[] {
        "A partridge in a pear tree",
        "Two turtle doves and",
        "Three French Hens,",
        "Four calling birds",
        "Five golden rings.",
        "Six geese a-laying,",
        "Seven swans a-swimming,",
        "Eight maids a-milking,",
        "Nine ladies dancing,",
        "Ten lords a-leaping,",
        "Eleven Pipers piping,",
        "Twelve drummers drumming,"
    };

    public static final String[] days = new String[] {
        "first",
        "second",
        "third",
        "fourth",
        "fifth",
        "sixth",
        "seventh",
        "eighth",
        "ninth",
        "tenth",
        "eleventh",
        "twelfth"
    };

    public static final String verseText =
        "On the %s day of Christmas,\n" +
        "My true love sent to me\n" +
        "%s";

    public static void main(String[] args) {
        //Print the song
        System.out.println(song());
    }

    public static String song() {
        //The song consists of all verses up to verse 12, but the index starts from 0
        //Print verses 0 to 11
        return versesBelow(11);
    }

    public static String versesBelow(int verse) {
        //Evil hack that allows me to check whether the input is zero without using a conditional ;)
        try {
            //Divide by verse. If the verse is zero, then an ArithmeticException is thrown.
            //I am not using a conditional here!!!
            int i = 1 / verse;
        }
        catch(ArithmeticException ex) {
            //Stop the recursion
            return verse(verse);
        }
        //else return this verse and all the verses below this one.
        return versesBelow(verse - 1) + verse(verse);
    }

    public static String verse(int verse) {
        //Format the string with the correct day and verse and add a newline for a blank space after
        return String.format(verseText, days[verse], linesBelow(verse)) + '\n';
    }

    public static String linesBelow(int line) {
        //Same evil hack
        try {
            int i = 1 / line;
        }
        catch(ArithmeticException ex) {
            //Stop the recursion if line is zero
            return line(line);
        }
        //Else return this line and all the lines below this line
        return line(line) + linesBelow(line - 1);
    }

    public static String line(int line) {
        //Return this line and a newline
        return lines[line] + '\n';
    }
}

Is there a better way to accomplish this than my way? I do kind of cheat a little, but it's not technically a conditional, is it?


texts:
I have a large amount of data from a hardware device that needs to be cleaned up so it can be analyzed in Excel.

I wrote a simple find/replace VBA macro in word to convert it to .csv, but the macro takes a long time to run through large sets of data.

I'm looking for suggestions on a faster way to code this. Alternately, if there is another option for cleaning the data that would work better than Word and VBA, I'm willing to switch to it.

Sub CleanText()

Application.ScreenUpdating = False

' clean data for import to excel
'
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "^p" & "^p"
    .Replacement.Text = "wvw"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
   .Text = "^p"
    .Replacement.Text = ","

End With
Selection.Find.Execute Replace:=wdReplaceAll

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
   .Text = "wvw"
    .Replacement.Text = "^p"
    .Forward = True

End With
Selection.Find.Execute Replace:=wdReplaceAll

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
   .Text = "$GPGGA" & "(*)" & "$GPRMC"
    .Replacement.Text = "$GPRMC"
    .MatchWildcards = True

End With
Selection.Find.Execute Replace:=wdReplaceAll

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
   .Text = "W" & "(*)" & "S"
    .Replacement.Text = "W,"
End With
Selection.Find.Execute Replace:=wdReplaceAll

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
   .Text = "V" & "(*)" & "S"
    .Replacement.Text = "V,,,,,"
End With
Selection.Find.Execute Replace:=wdReplaceAll

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
   .Text = "$GPRMC,"
    .Replacement.Text = ""
End With
Selection.Find.Execute Replace:=wdReplaceAll

Application.ScreenUpdating = True

End Sub


texts: Expect script that tests if a passwordless connection is setup

texts:
I have written a simple expect script to tell me if a passwordless connection is set up.
#!/usr/bin/expect -f

if {[llength $argv] < 2} {
  puts "usage: test-nopass user server"
  exit 1
}

set user     [lindex $argv 0]
set server   [lindex $argv 1]

set pwd_prompt "*assword:"
set prompt "*$ "

set rc 0

log_user 0
spawn ssh $user@$server

expect {
  "$pwd_prompt" { exit 1 }
  eof           { exit 2 }
  timeout       { exit 3 }

  "$prompt"     {
    send "hostname\r"
    expect {
      "*$server*" { exit 0 }
      eof         { exit 4 }
      timeout     { exit 5 }
    }
  }
}

log_user 1

exit $rc
```


texts: Same PyObject for a shared_ptr C++ object

texts:
I have a similar problem as in this mail. I want that every time I return the same C++ managed object to Python, I get the same PyObject. With the standard converter I get always a new wrapper-PyObject. The solution should fulfill the following requirements:

get() == get() (the Python object is always equal, whatever function returns the same C++ object)
get() is get()
The same is valid for any objects returned in containers (which the solution from the mail lacks) getArray()[0] == get()
I can instance attributes (get().new_var = "xx" -> get().new_var == "xx")

I wrote a template converter which takes as input a shared_ptr. It looks in a static map, if this shared_ptr is already returned, than it returns the existing PyObject, else a new one is created. I haven't found a solution there I can automatically remove unused objects.

In this case, I added a function to manually remove an entry. This works because the object is managed in C++ and I can intercept than the object should be removed from the C++ side. If Python has still a reference to this object, it's ok to wait for the GC to collect the Python side and implicitly remove the C++ object. If the last reference is removed in Python, the PyObject is still valid, because the map holds still a reference. Also , as long as the PyObject inside the map exists, the C++ object cannot be removed from the heap.

I made a couple of test, which shows the validity, that can be found here.

The usage is:

boost::python::to_python_converter<boost::shared_ptr<A>,
        c_ptr_to_cached_python<A>>();

Is the following code enough to fulfill the requirements for any C++ class wrapped in a shared_ptr? Is the PyObject generation valid and can it be improved?

#pragma once
#include <boost/python.hpp>
#include <map>
#include <iostream>

template<typename C_CLASS>
using storage_map = std::map<C_CLASS*, PyObject*>;

template<typename C_CLASS>
storage_map<C_CLASS>* getCachedObjects() {
    static storage_map<C_CLASS> *storage = new storage_map<C_CLASS>();
    return storage;
}

template<typename C_CLASS>
using c_sptr = boost::shared_ptr<C_CLASS>;

template<typename C_CLASS>
using py_ptr = typename boost::python::pointee<boost::shared_ptr<C_CLASS>>::type;

template<typename C_CLASS>
PyObject * createObject(const c_sptr<C_CLASS>& obj) {
    return boost::python::objects::make_ptr_instance<py_ptr<C_CLASS>,
            boost::python::objects::pointer_holder<c_sptr<C_CLASS>,
                    py_ptr<C_CLASS>>>::execute(obj);
}

template<typename C_CLASS>
void cleanMap() {
    auto map = getCachedObjects<C_CLASS>();
    for (auto it = map->begin(); it != map->end();) {
        auto py_obj = it->second;
        Py_DecRef(py_obj);
        map->erase(it++);
    }
}

template<typename C_CLASS>
void removeObject(const c_sptr<C_CLASS>& obj) {
    auto map = getCachedObjects<C_CLASS>();
    auto raw_ptr = obj.get();
    auto it = map->find(raw_ptr);
    if (it == map->end()) {
        throw std::logic_error("Object was already removed.");
    }
    auto py_obj = it->second;
    Py_DecRef(py_obj);
    map->erase(it);
}

template<typename C_CLASS>
struct c_ptr_to_cached_python {
    static PyObject* convert(const c_sptr<C_CLASS> &obj) {
        auto raw_ptr = obj.get();
        auto map = getCachedObjects<C_CLASS>();
        auto it = map->find(raw_ptr);
        if (it == map->end()) {
            auto py_obj = createObject<C_CLASS>(obj);
            (*map)[raw_ptr] = py_obj;
            Py_INCREF(py_obj); // Increment to store in map
            return py_obj;
        } else {
            auto old_py_obj = it->second;
            Py_INCREF(old_py_obj);
            return old_py_obj;
        }
    }
};


texts:
I'm looking for a code review of this python I wrote - this code reads the zipcode column value from a CSV file and calls an API to retrieve lat, long, state and city info.

It works fine and gives me the correct results, but I'm looking for ways to improve the code/my approach and exception handling. I am pretty sure there are better ways to write this long code.

All comments and suggestions as brutal as may be are mostly appreciated.

import requests
import pandas as pd
import time
from ratelimiter import RateLimiter
API_KEY = "some_key"
zip_code_col_name = "zipcode"
RETURN_FULL_RESULTS = False
excel_data = pd.read_csv("Downloads/test_order.csv", encoding='utf8')
if zip_code_col_name not in excel_data.columns:
    raise ValueError("Missing zipcode column")
# This will put all zipcodes from column to list including duplicates , hence avoiding it.
#zipcodes = excel_data[zip_code_col_name].tolist()
zipcodes =[]
for i in excel_data.zipcode:
    if i not in zipcodes:
        zipcodes.append(i)

def get_geo_info(zipcode, API_KEY, return_full_response=False):

    init_url = "some_url"
    if API_KEY is not None:
        url = init_url+API_KEY+"/info.json/"+format(zipcode)+"/degrees"

    # Ping site for the reuslts:
    r= requests.get(url)
    if r.status_code != 200:
        #this will print error code to but in reuslt set it will be empty
        print("error is" + str(r.status_code))
    data = r.json()
    output = {
            "zipcode" : data.get('zip_code'),
        "lat" : data.get('lat'),
         "lng" : data.get('lng'),
        "city" : data.get('city'),
        "state" : data.get('state')

            }

    return output

def limited(until):
    duration = int(round(until - time.time()))
    print('Rate limited, sleeping for {:d} seconds'.format(duration))

results = []

### Putting max call to 49 for 1 hour, we can paramterized it also
rate_limiter = RateLimiter(max_calls=49, period=3600, callback=limited)

for zipcode in zipcodes:
    with rate_limiter:
        geocode_result = get_geo_info(zipcode, API_KEY, return_full_response=RETURN_FULL_RESULTS)
        results.append(geocode_result)
#print(results)
ddf = pd.DataFrame(results)
### This is to put the geo_info into same file however I would prefer it to write it to antoher file load it int staging table. to keep it for future refrence purposes.
""""df = pd.read_csv("Downloads/test_order.csv")
df['state'] = ddf.state
df['city'] = ddf.city
df['lattitude'] = ddf.lat
df['Longitude'] = ddf.lng
df['api_zip'] = ddf.zipcode
df.to_csv('Downloads/test_order.csv',index = False)"""
### This is to create a new file with the results
ddf.to_csv('Downloads/geo_info.csv',index = False)


texts: Advent of Code 2017 Day 6 (part 1) in Functional Programming (FP)

texts:
I wanted to practice functional programming (FP) without using any library but using vanilla JS only. So I took a problem from Advent of Code (the 1st part of Day 6):

http://adventofcode.com/2017/day/6

  A debugger program here is having an issue: it is trying to repair a
  memory reallocation routine, but it keeps getting stuck in an infinite
  loop.

  In this area, there are sixteen memory banks; each memory bank can
  hold any number of blocks. The goal of the reallocation routine is to
  balance the blocks between the memory banks.

  The reallocation routine operates in cycles. In each cycle, it finds
  the memory bank with the most blocks (ties won by the lowest-numbered
  memory bank) and redistributes those blocks among the banks. To do
  this, it removes all of the blocks from the selected bank, then moves
  to the next (by index) memory bank and inserts one of the blocks. It
  continues doing this until it runs out of blocks; if it reaches the
  last memory bank, it wraps around to the first one.

  The debugger would like to know how many redistributions can be done
  before a blocks-in-banks configuration is produced that has been seen
  before.

  For example, imagine a scenario with only four memory banks:

  The banks start with 0, 2, 7, and 0 blocks. The third bank has the most blocks, so it is chosen for redistribution.
  Starting with the next bank (the fourth bank) and then continuing to the first bank, the second bank, and so on, the 7 blocks are spread
  out over the memory banks. The fourth, first, and second banks get two
  blocks each, and the third bank gets one back. The final result looks
  like this: 2 4 1 2.
  Next, the second bank is chosen because it contains the most blocks (four). Because there are four memory banks, each gets one block. The
  result is: 3 1 2 3.
  Now, there is a tie between the first and fourth memory banks, both of which have three blocks. The first bank wins the tie, and its three
  blocks are distributed evenly over the other three banks, leaving it
  with none: 0 2 3 4.
  The fourth bank is chosen, and its four blocks are distributed such that each of the four banks receives one: 1 3 4 1.
  The third bank is chosen, and the same thing happens: 2 4 1 2.

  At this point, we've reached a state we've seen before: 2 4 1 2 was
  already seen. The infinite loop is detected after the fifth block
  redistribution cycle, and so the answer in this example is 5.

  Given the initial block counts in your puzzle input, how many
  redistribution cycles must be completed before a configuration is
  produced that has been seen before?

  Your Input: 2    8   8   5   4   2   3   1   5   5   1   2   15  13  5   14

My solution in FP:

const banks = `2\t8\t8\t5\t4\t2\t3\t1\t5\t5\t1\t2\t15\t13\t5\t14`;

const parse = input => input
  .split('\t')
  .map(c => parseInt(c));

const copy = input => input.slice();

const isUnique = toCheck => state => toCheck.toString() !== state.toString();

const INPUT = parse(banks);

const redistribute = (input, index, toBeDistributed) => {
  if (!toBeDistributed) return input;
  const nextIndex = index + 1;
  const nextInput = input;
  ++nextInput[nextIndex % input.length];
  return redistribute(nextInput, nextIndex, --toBeDistributed);
};

const solveDaySix = input => {
  let banks = copy(input);
  const states = [input];
  let cycle = 0;
  while (true) {
    ++cycle;
    const max = Math.max(...banks);
    const index = banks.indexOf(max);
    banks[index] = 0;
    banks = copy(redistribute(banks, index, max));
    const stateIsUnique = isUnique(banks);

    if (!states.every(stateIsUnique)) break;
    states.push(copy(banks));
  }
  return cycle;
};

console.log("solution ", solveDaySix(INPUT));

Do you think my solution is consistent with the idea of FP (I used loops and mutate variables inside my functions)? Is there a better way to write the solution in FP? Any other improvement suggestions are welcomed.


texts: scan the RAM of a computer, displaying the services and executables

texts:
I wanted to write a program in python which it scans the RAM of a computer, by displaying the services and the executables.
import psutil
import wmi
from time import sleep
from progress.bar import Bar

# Connecting
c = wmi.WMI()
# stock here Process Id
proc = []

# function to get the Size
def get_size(bytes, suffix="B"):
    factor = 1028
    for unit in["","K","M","G","T","P"]:
        if bytes < factor:
            return f"{bytes:.2f} {unit}{suffix}"
        bytes /= factor
# End

print("Scanning RAM: \n")
print("system virtual memory: \n")
# Return statistics about system memory usage
with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar:
    for i in range(100):
        sleep(0.02)
        svmem = psutil.virtual_memory() # physical memory usage
        bar.next()

    # to calculate percentage of available memory
    avmem = psutil.virtual_memory().available * 100 / psutil.virtual_memory().total
    prcntg = '{:.1f} %'.format(avmem)
bar.finish()
# put the object in a dictionary
mem = {'Total': get_size(svmem.total), 'Percentage-available': prcntg, 'Available': get_size(svmem.available), 'Percentage-used': f'{svmem.percent} %', 'Used': get_size(svmem.used), 'Free': get_size(svmem.free)}
print(mem)
# End

print("\n")

print("system swap memory: \n")
# Return system swap memory statistics as a named tuple including the following fields
with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar:
    for i in range(100):
        sleep(0.02)
        swap = psutil.swap_memory() # the percentage usage calculated as (total - available) / total * 100
        bar.next()
bar.finish()
mem2 = {'Total': get_size(swap.total), 'Used': get_size(swap.used), 'Free': get_size(swap.free), 'Percentage': f'{swap.percent} %'}
print(mem2)
# End

'''
# Return an iterator yielding a WindowsService class instance for all Windows services installed.
# Get a Windows service by name, returning a WindowsService instance.
with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar:
    for i in range(100):
        sleep(0.02)
        winserv = list(psutil.win_service_iter())
        s = psutil.win_service_get('alg') # windows service by name
        bar.next()
bar.finish()
print(winserv)
print("\n")
print(s.as_dict())
# End
'''

print("\n")

print("Services: \n")
# Get all Windows services using the WMI module
with Bar('Progress:', fill='▋', suffix='%(percent).1f%% complete') as bar:
    for i in range(100):
        sleep(0.02)

        bar.next()
print("ID:     Name:\n")
for process in c.Win32_Process ():
    print (f"{process.ProcessId}       {process.Name}")
bar.finish()

# Get get a specific Windows service
for process in c.Win32_Process (name="notepad.exe"):
    print (f"{process.ProcessId}       {process.Name}")
# End

# calculate how much Processes are runnig
for process in c.Win32_Process():
    proc.append(process.ProcessId)
print(f"{len(proc)} Processes are running in your Device.")
# End

is it correct?


texts: Find the first missing positive integer in an array of integers

texts:
The problem is the one explained in Given an unsorted integer array, find the first missing positive integer

  Given an unsorted integer array, find the first missing positive
  integer.

  For example,
  Given [1,2,0] return 3,
  and [3,4,-1,1] return 2.

  Your algorithm should run in \$O(n)\$ time and use constant space.

I am trying to learn Java 8+ and wrote the following code. Request any improvisations possible.

int firstPositive(int[] inputArray) {

    //Convert all negative numbers to 0.
    IntStream.range(0, inputArray.length).forEach(idx -> {
        if (inputArray[idx] < 0) inputArray[idx] = 0;
    });

    IntStream.range(0, inputArray.length).forEach(idx -> {
        if (Math.abs(inputArray[idx]) == 0) {
            inputArray[0] = -Math.abs(inputArray[0]);
        }
        else if (Math.abs(inputArray[idx]) - 1 < inputArray.length && inputArray[Math.abs(inputArray[idx]) - 1] > 0) {
            inputArray[Math.abs(inputArray[idx]) - 1] *= -1;
        }
    });

    OptionalInt res = IntStream.range(0, inputArray.length).filter(idx -> inputArray[idx] >= 0).findFirst();

    if (res.isPresent()) {
        return res.getAsInt()+1;
    }

    return inputArray.length+1;
}


texts: Find all pairs of numbers such that the number of binary 1's in their OR is maximum

texts:
So, I tried to solve this question and my code did not execute within time-limits.
https://www.hackerrank.com/challenges/acm-icpc-team

Here's my code,

from itertools import combinations
nm =input().split()
n = int(nm[0])
m = int(nm[1])
mat=[]
z=[]
for i in range(n):
    mat.append(input())
a=combinations(range(1,n+1),2)

for i in a:
    count=0
    for j in range(m):
        if mat[i[0]-1][j]=="0" and mat[i[1]-1][j]=="0":
            count=count+1
    z.append(m-count)
print(max(z))
print(z.count(max(z)))

How can I improve it?


texts:
I have the following class for Quicksorting.

import java.util.Random;

public class QuickSorter {
    public static void main(String[] args) {
        Random random = new Random();
        int[] randoms = new int[10000];
        for(int i = 0; i < randoms.length; i++) randoms[i] = random.nextInt(10000);

        quickSort(randoms, 0, randoms.length);
        System.out.println(Arrays.toString(randoms));
    }

    /** Same as {@link #quickSort(int[], int, int)}, but assumes the whole array should be sorted. */
    public static void quickSort(int[] in) {quickSort(in, 0, in.length);}
    /** Sorts an array of integers using the Quicksort algorithm, in the range [{@code start}, {@code end}).
     * @param in The full array to sort
     * @param start The starting index, inclusive
     * @param end The ending index, exclusive
     * @see #quickSort(int[]) */
    public static void quickSort(int[] in, int start, int end) {
        int pivot = (start + end) / 2;

        /* Temporary array containing the ordered sub-list */
        int[] sub = new int[end - start];
        int left = 0, right = sub.length;

        /* Populate the sub-list */
        for(int i = start; i < end; i++) {
            if(i == pivot) continue;

            if(in[i] < in[pivot]) {
                sub[left++] = in[i];
            } else {
                sub[--right] = in[i];
            }
        }
        /* Add in the original pivot in its new position */
        sub[left] = in[pivot];

        /* Copy back into the original array */
        for(int k = start; k < end; k++) {
            in[k] = sub[k - start];
        }

        /* Translate new pivot position into full list index */
        left += start;
        if(left - start > 0) quickSort(in, start, left);
        /* The start of the right branch should not include the pivot */
        left++;
        if(end - left > 0) quickSort(in, left, end);
    }
}

Is this the most efficient way to Quicksort? I feel as if copying the values from sub back into in can be done better somehow.

And of course, I know this won't cause any huge issues with arrays of size 10000. But, I'd like this to hold up all the way up to 2^31-1 (to the limits of max array size).