texts: Trying for an efficient and readable heap-sort implementation

texts:
I'm looking for any sort of optimization and/or conventional practice tips, such as using the appropriate data types and naming my variables appropriately.
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

constexpr short MIN_ELEMS = 3;
constexpr short MAX_ELEMS = 15;
constexpr short LARGEST_ELEM_INT = 99;

void fill_vector(std::vector<int> &v, short MAX_ELEMS, short LARGEST_ELEM_INT);

void print_vector(const std::vector<int>::iterator start, const std::vector<int>::iterator end);

void max_heap(const std::vector<int>::iterator elem, const std::vector<int>::iterator start, std::vector<int>::iterator end);

void heap_sort(const std::vector<int>::iterator start, const std::vector<int>::iterator end);

int main() {
  srand(time(NULL));
  short random_range = rand() % MAX_ELEMS + 1;
  short num_of_elems = random_range < MIN_ELEMS ? MIN_ELEMS : random_range; // prevents num_of_elems from being less than MIN_ELEMS

  std::vector<int> v;
  fill_vector(v, num_of_elems, LARGEST_ELEM_INT);

  print_vector(v.begin(), v.end());

  heap_sort(v.begin(), v.end());

  print_vector(v.begin(), v.end());
}

void fill_vector(std::vector<int> &v, short num_of_elems, short LARGEST_ELEM_INT) {
  short i = 0;
  while (++i, i <= num_of_elems) {
    v.push_back(rand() % LARGEST_ELEM_INT);
  }
}

void print_vector(const std::vector<int>::iterator start, const std::vector<int>::iterator end) {
  for (auto elem = start; elem != end; ++elem) {
    std::cout << *elem << ' ';
  }
  std::cout << '\n';
}

void max_heap(const std::vector<int>::iterator elem, const std::vector<int>::iterator start, const std::vector<int>::iterator end) {
  auto biggest = elem;

  auto left_child = start+((elem-start)*2+1);
  auto right_child = start+((elem-start)*2+2);

  if (left_child < end && *left_child > *biggest) {
    biggest = left_child;
  }

  if (right_child < end && *right_child > *biggest) {
    biggest = right_child;
  }

  if (elem != biggest) {
    auto val = *biggest;
    *biggest = *elem;
    *elem = val;
    max_heap(biggest, start, end);
  }
}

void heap_sort(const std::vector<int>::iterator start, const std::vector<int>::iterator end) {
  // sort vector to max heap
  for (auto i = start+((end-start)/2)-1; i >= start; --i) {
    max_heap(i, start, end);
  }

  // sort vector in ascending order
  for (auto i = start; i != end-1; ++i) {
    auto val = *start;
    *start = *(start+(end-i-1));
    *(start+(end-i-1)) = val;

    max_heap(start, start, start+(end-i-1));
  }
}


texts: Replace fixed width values over 530px with 100% using RegEx

texts:
Our site sends users transactional html emails. That content is then stored in a DB for retrieval when the user visits the mailbox section of our site.

The emails which get sent contain media queries in the header, which are lost as our system only pulls in the  of the content.

This is why I need to convert at fixed widths that are greater than 530px.

This is my take on replacing fixed widths >= 530px inside then content.

message.replace(/((?:m(?:in|ax)-)?width)\s*(\:\s?|=)\s*(['"\0])?\s*([1-9]\d{3,}|5[3-9][0-9]|[6-9][0-9]{2})(\s*(cm|in|mm|pc|pt|px|q)|(?!%|vw|vh|vmin|vmax|em|ex|ch|rem))[ ]*/gi, '$1$2100%')

It matches both HTML width attributes and CSS based properties that are fixed width values.

Is there a better, more concise way of doing this?

https://regex101.com/r/hdMYGn/6/

Example HTML:

<table align="center" class="container float-center" style="border-spacing: 0; border-collapse: collapse; padding: 0; vertical-align: top; background: #ffffff; width: 580px; margin: 0 auto; Margin: 0 auto; float: none; text-align: center;" width="580">


texts:
Here is my window tiling script for rio window manager in Plan 9. It fetches the current screen size and calculates the locations based on the layout given. How can I improve this program? Am I missing any idioms in rc?

#!/bin/rc
# Usage:
# First save the current windows
# ./tile.rc save >saved.s
# Next switch to tall
# ./tile.rc tall |tee tall.s |rc
# Can go back if you want
# cat saved.s |rc

# get the position from the image input
fn winpos {
      dd -bs 1 -skip 20 -count 40 -quiet 1
}
# get just width and height
fn winsize {
   winpos | awk '{print ($3-$1),($4-$2)}'
}
# of the screen
fn screen {
   cat /mnt/wsys/screen | winsize
}
# get the width of the current windo. We use this
# for wall - where the width of current window
# is kept unchanged.
fn getwidth {
  w=`{cat /mnt/wsys/window | winsize}
  echo $w(1)
}
# generate a move command for the input
# move -r minx miny maxx maxy does not seem
# to work. (see save cmd). So until then
fn movcmd {
  mx=`{echo $2 $4 + p|dc}
  my=`{echo $3 $5 + p|dc}
  echo (echo resize -r $2 $3 $mx $my '>' $1/wctl)
}
# print the commands to get the windows back to
# the original positions. This does not seem to
# work always. (can use wloc too.)
fn savewin {
  windows=/dev/wsys/*
  for (i in $windows) {
     loc=`{cat $i/window | winpos}
     echo (echo resize -r $loc '>' $i/wctl)
  }
}
# Tall configuration, with a main window, on one
# half of the screen, and child windows on the other
# the main window is the window from which command is
# invoked
fn tall {
  maxx=$1
  maxy=$2
  mywin=$3
  windows=/dev/wsys/*
  childht=`{echo $maxy $#windows 1 - / p| dc}
  ylast=0
  xhalf=`{getwidth}
  halfx=`{echo $maxx $xhalf - p| dc}
  for (i in $windows) {
    switch ($i) {
        case /dev/wsys/$mywin
          movcmd $i 0 0 $xhalf $maxy
        case *
          movcmd $i $xhalf $ylast $halfx $childht
          ylast=`{echo $ylast $childht + p| dc}
    }
  }
}
# Rows configuration
fn rows {
  maxx=$1
  maxy=$2
  windows=/dev/wsys/*
  childht=`{echo $maxy $#windows / p| dc}
  ylast=0
  for (i in $windows) {
    movcmd $i 0 $ylast $maxx $childht
    ylast=`{echo $ylast $childht + p| dc}
  }
}

fn main {
  myscreen=`{screen}
  mywin=`{cat /mnt/wsys/winid}
  switch ($1) {
    case rows
      rows $myscreen $mywin
    case tall
      tall $myscreen $mywin
    case save
      savewin
    case *
      echo (supported: tall rows save)
  }
  # For some reason, this line does not
  # really get the original window focus.
  echo (echo current '>' /dev/wsys/$mywin/wctl)
}
main $*


texts: Converting between backend object and object suitable for JSON

texts:
I wrote this method that does the job and passes the assertion tests for a large java backend project but I'm not all happy with the way it reads, perhaps you can tell me how to refactor and/or improve this method?

public Set<ProductOfferingJsonDto> getJsonProductOfferings() {
    Set<ProductOfferingJsonDto> set = new HashSet<ProductOfferingJsonDto>();
    ProductOfferingJsonDto pjson = null;
    Iterator iter = productOfferings.iterator();
    while(iter.hasNext()){
        ProductOfferingDto pdto = (ProductOfferingDto) iter.next();
        if(pdto instanceof BundledProductOfferingDto) {
            Set<ProductOfferingDto> tmp = ((BundledProductOfferingDto) pdto).getProductOfferings();
            Iterator piter = tmp.iterator();
            Set<ProductOfferingJsonDto> tmpset = new HashSet<ProductOfferingJsonDto>();
            while(piter.hasNext()){
                SimpleProductOfferingDto piterdto = (SimpleProductOfferingDto) piter.next();
                tmpset.add(new SimpleProductOfferingJsonDto(piterdto.getId(), piterdto.getName(), piterdto.getDescription(), piterdto.getStatus(),
                        piterdto.getBrand(), piterdto.getValidFor(),
                        piterdto.getProductSpecification(),
                        piterdto.getDescriptorId(), piterdto.getTags(), piterdto.getProductOfferingPrice()));
   }
            BundledProductOfferingDto bpod = (BundledProductOfferingDto) pdto;
            pjson = new BundledProductOfferingJsonDto(bpod.getId(), bpod.getName(), bpod.getDescription(), bpod.getStatus(),
                    bpod.getBrand(), bpod.getValidFor(),
                    tmpset,
                    bpod.getDescriptorId(), bpod.getTags(), bpod.getProductOfferingPrice());
        }
      if(pjson != null) {
        set.add((ProductOfferingJsonDto) pjson);
      }
    }
    return set;
}


texts: Breaking after one of several string replaces occur

texts:
I have a script that matches a string against ~20 different regexs for the purpose of changing it. They are ordered and formed that the string will only ever match against one. How can I avoid checking all the str.replaces after I match once?

My code here works, but I repeat myself a lot and it does not seem optimal.

The while loop exists so I could break, I don't actually need to loop through anything - and in fact I ensure I don't loop at the end of it. I'm merely looking for a way to stop performing replaces, when I know they will do nothing.

function format_number(input){
    var str = input.value;
    str.toString();
    var copy = str;
    var checked = false;
    while (!checked) {
        str = str.replace(/regex1/, 'replace1');
        if (copy != str) {break;}
        str = str.replace(/regex2/, 'replace2');
        if (copy != str) {break;}
        str = str.replace(/regex3/, 'replace3');
        if (copy != str) {break;}
        str = str.replace(/regex4/, 'replace4');
        if (copy != str) {break;}
        str = str.replace(/regex5/, 'replace5');
        if (copy != str) {break;}
        str = str.replace(/regex6/, 'replace6');
        if (copy != str) {break;}
        str = str.replace(/regex7/, 'replace7');
        if (copy != str) {break;}
        str = str.replace(/regex8/, 'replace8');
        if (copy != str) {break;}
        str = str.replace(/regex9/, 'replace9');
        if (copy != str) {break;}
        str = str.replace(/regex10/, 'replace10');
        if (copy != str) {break;}
        str = str.replace(/regex11/, 'replace11');
        if (copy != str) {break;}
        str = str.replace(/regex12/, 'replace12');
        if (copy != str) {break;}
        str = str.replace(/regex13/, 'replace13');
        if (copy != str) {break;}
        str = str.replace(/regex14/, 'replace14');
        if (copy != str) {break;}
        str = str.replace(/regex15/, 'replace15');
        if (copy != str) {break;}
        str = str.replace(/regex16/, 'replace16');
        if (copy != str) {break;}
        str = str.replace(/regex17/, 'replace17');
        if (copy != str) {break;}
        checked = true;
    }
    input.value=str;
}


texts: My simple implementation of a DI container

texts:
I decided to make my own light DI container.

I know about Zenject, etc. I wanted a very light analog.

I'm concerned about a few things:

1) is it correct to use struct instead of class for reference in this context?

2) every time you access _player.Reference, there is a check for null (in the UnityEngine.After the destruction of the Object does not equal null, so use SafeIsUnityNull)

3) Double point. Can I overload the operator so that instead of _player.Reference.AAAAAAAAAAAAA();, it works _player.AAAAAAAAAAAAA(); ??

Container itself:

    public static class DIContainer
    {

        private static readonly Dictionary<System.Type, Object> _references = new Dictionary<System.Type, Object>();

        public static void Bind<T>(T value) where T : Object
        {

            _references[typeof(T)] = value;

        }

        public static T Resolve<T>() where T : Object
        {

            if (_references.TryGetValue(typeof(T), out Object value))
                return (T)value;

            throw new System.InvalidCastException($"DIContainer: invalid resolve object {typeof(T)}");

        }

    }

Field reference:

    public struct DIReference<T> where T : Object
    {

        private T _reference;
        public T Reference => !_reference.SafeIsUnityNull() ? _reference : _reference = DIContainer.Resolve<T>();

    }

Installer:

    public abstract class SceneInstaller : MonoBehaviour
    {
        private void Awake() => InstallBindings();
        protected abstract void InstallBindings();

    }

public class LevelInstaller : SceneInstaller
{

}

Using

Bind:

    [SerializeField] private PlayerController _player;

    protected override void InstallBindings()
    {

        DIContainer.Bind(_player);

    }

Reference:

public class Test
{

    private DIReference<PlayerController> _player;

    private void Foo()
    {

        _player.Reference.AAAAAAAAAAAAA();

    }

}


texts: Is this a good way to implement let-with?

texts:
I've implemented a let-with macro that takes an association list, keyed by symbols, that enables code to bind their corresponding values to local variables.

It's designed to have a similar effect to JavaScript's with, but without with's attendant problems (by making you explicitly list the variables to bind).

(define-syntax let-with
  (syntax-rules ()
    ((let-with alist (key ...) expr ...)
     (let ((key (cond ((assq 'key alist) => cdr))) ...) expr ...))))

I'd love to hear of any improvements to let-with's interface and/or implementation.

Example usage:

(define alist '((first . "Jane")
                (last . "Doe")))
(let-with alist (first last)
  (string-append first " " last))    ; "Jane Doe"

Keys that don't exist in the incoming alist receive an undefined value; they do not fail to get bound, unlike JavaScript's with.


texts:
Edit for posterity: The library you're looking for is Hspec.

I recently started writing Haskell tests with HUnit.
My general setup looks something like this:

import Test.HUnit

import Widget (foo, bar)

tests = TestList [ "foo" ~: testFoo
                 , "bar" ~: testBar
                 ]

testFoo :: Test
testFoo = TestList
  [ "with even numbers" ~:
    4 ~=? foo 4
  , "with odd numbers" ~:
    0 ~=? foo 5
  ]

testBar :: Test
testBar = TestList [ {- omitted -} ]

The semantics of this are fine with me: I'm trying to do expected–actual testing, not property testing like Quickcheck does.
However, there are two things that I don't like about the syntax:

the list syntax feels really clunky, and
I have to write "foo" once and testFoo two times (three counting the type annotations); while I could inline this, that would make the lists even clunkier.

My goal was to be able to write tests like this:

import Test.HUnit (Test, (~=?))
import Describe (toTests, (...), (~:))

import Widget (foo, bar)

tests :: Test
tests = toTests $ do
  "foo" ... do
    "with even numbers" ~:
      4 ~=? foo 4
    "with odd numbers" ~:
      0 ~=? foo 5
  "bar" ... do
    "with true" ~:
      10 ~=? bar True
    "with false" ~:
      -10 ~=? bar False

I managed to accomplish just that!
But to do so I had to resort to what I consider to be a pretty ugly monad.
Here's Describe.hs:

module Describe(group, describe, toTests, (~:), (...)) where

import qualified Test.HUnit as H

data LeftList l r = LeftList [l] ()
                    deriving (Show)

instance Monad (LeftList l) where
  (>>=) = error "LeftList does not support binding; use (>>) instead"
  (LeftList xs a) >> (LeftList ys b) = LeftList (xs ++ ys) b
  return x = LeftList [] ()

group :: String -> LeftList H.Test () -> LeftList H.Test ()
group s (LeftList xs ()) = LeftList [s H.~: xs] ()

(...) = group
infixr 9 ...

describe :: String -> H.Test -> LeftList H.Test ()
describe s x = LeftList [s H.~: x] ()

(~:) = describe
infixr 0 ~:

toTests :: LeftList H.Test () -> H.Test
toTests (LeftList xs _) = H.TestList xs

Obviously, the ugly part is creating this data type that has an unnecessary second type parameter and isn't actually a monad!
That is, my implementation of the do-notation is incomplete; sequencing works fine, but if I wrote x <- "foo" ... do { } I would get the error here.

I don't really mind that I'm shadowing HUnit.~:, although it's not optimal.

So, my question: what's the cleanest way to get the desired test case syntax without making the monads cry?


texts: Code structure for a login modal dialog.

texts:
I'm using twitter mobile and I have a login-dialog.  login-Dialog is a modal dialog.  To call it the user calls loginDialog.show();

I'm not all that comfortable with the coding style I've adopted (i'm very much self schooled in JavaScript) and I'd be interested to hear peoples opinions on the code structure and process handling.  For example I always seem to use expressive functions instead of function declarations.  (some of the nitty gritty is ommitted for focus).

var loginDialog = (function($)
{
    /**
     * Essentially the init function
     */
    var show = function()
    {
        // This actually shows the dialog
        $("#login-dialog").modal({backdrop: "static", keyboard: false});
        applyBindings();
    }

    var hide = function()
    {
        $("#login-dialog").modal("hide");
    }

    var applyBindings = function()
    {
        $("#login-dialog .btn-primary").click(onLoginClick);
    };

    var onLoginClick = function()
    {
       // validate form, attempt login...
       // logginIn is a jQuery Deferred.
    var loggingIn = myApi.login(username, password);
    loggingIn.done( handleResponse );
    loggingIn.fail( handleError );
    };

    var validate = function(username, password)
    {
       // simple form validation
    };

    var handleResponse = function(json)
    {
            // check json psuedo code
    if (json != "Ok")
    {
        handleError();
    }
    else
    {

        handleSuccess();
    }
    };

    var handleError = function(msg)
    {
        msg = msg || "There was a problem communicating with the server";

        var tmpl = _.template($("#alert-tmpl").html(), { head: "Error", body: msg});

        $("#login-dialog form").append(tmpl);
        $("#login-dialog .btn-primary").removeAttr("disabled");
    };

    var handleSuccess = function()
    {
        hide();
    };

    return {
        show: show,
        hide: hide
    }

})(jQuery);


texts:
For a homework assignment, I was asked to complete this CodeStepByStep problem. It's coded correctly and gave me a right answer. I'm just wondering if there's an easier way to solve this problem without the big blocky code in the if statement. The fact that I have to check each lowercase vowel AND THEN the uppercase vowel seems verbose.

Write a function named vowelCount that accepts a string and returns
the number of vowels (a, e, i, o, or u) that the string contains.
For example, the call of vowelCount("kookaburra") should return 5 (two
o's, 2 a's, and one u). When passed a string without any vowels (such
as an empty string, "01234", or "sky"), 0 should be returned.

function vowelCount(string) {
    if(string.length == 0) { return 0; }
    let count = 0;
    for(let i = 0; i < string.length; i++) {
        let v = string[i];
        if(v == "a" || v == "e" || v == "i" || v == "o" || v == "u" ||
           v == "A" || v == "E" || v == "I" || v == "O" || v == "U") {
            count += 1;
        }
    }
    return count;
}


texts:
I came across this question in a coding competition (Java-restricted) and I got a time-length-exceeded. I am unable to provide a link as the contest is closed now. Can I know how can I optimise this?

Unique Subsequences:  You are given a randomly generated string of characters ranging from a to z. You are required to determine the
number of unique subsequences that can be formed equal to this string
'abcdefghijklmnopqrstuvwxyz'.
Input Format :

The first line will contain t denoting the number of test cases
The first line of each test case contains n denoting the size of the string
The second line of each test case contains string s of size n

We are supposed to print the count of unique subsequences that are
possible in a-z format
Constraints:
$$1 \le t \le 10$$
$$1 \le n \le 100000$$
$$1 \le |S| \le 100000$$
For Example :
abcdefghijklmnopqrstuvwxyzz = 2
abz = 0 (Doesn't have all the characters from a-z)
abcdefghijklmnopqrstuvwxyyzz = 4

import java.util.*;
import java.io.*;
class TestClass {
    public static boolean check_String(String str) {
      boolean flag = str.replaceAll("[^a-z]", "")
                .replaceAll("(.)(?=.*\\1)", "")
                .length() == 26;
        if(flag) {
            return true;
        }
        return false;
    }
    public static void main(String args[] ) throws Exception {
        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
        int testcases = Integer.parseInt(buffer.readLine());
        for(int itr = 0; itr < testcases; itr++) {
            long ans = 1;
            int str_len = Integer.parseInt(buffer.readLine());
            StringBuilder strbd = new StringBuilder();
            strbd.append(buffer.readLine());
            strbd.toString();
            if(str_len >= 26) {
                if(check_String(strbd.toString())) {
                    HashMap<Character,Integer> hashmap = new HashMap<>();
                    for(int itr2 = 0; itr2 < str_len; itr2++) {

                        if(hashmap.containsKey(strbd.charAt(itr2))) {
                            hashmap.put(strbd.charAt(itr2),hashmap.get(strbd.charAt(itr2))+1);
                        } else {
                            hashmap.put(strbd.charAt(itr2),1);
                        }
                    }
                    for(int itr3 : hashmap.values()) {
                        ans = (ans * itr3)%1000000007;
                    }
                }
            } else {
                ans = 0;
            }
            System.out.println(ans);
        }

    }
}


texts: UPenn CIS 194 Homework 1: Validating credit card numbers

texts:
I am working through UPenn CIS 194: Introduction to Haskell (Spring 2013). Since I am not able to take the course for real I am asking for CR (feedback) as it could be from teacher in that course.
HW1 - Validating Credit Card Numbers - Full description
A shortened problem statement:

Validate a credit card number by the following steps:

Double the value of every second digit from the right
Take the sum of the digits of the new values
Check whether the sum modulo 10 is 0.

Write the functions toDigits, toDigitsRev and doubleEveryOther for the first task, sumDigits for the second, and validate for the third.

toDigitsRev :: Integer -> [Integer]
toDigitsRev 0 = []
toDigitsRev n
  | n < 0 = []
  | n < 10 = [n]
  | otherwise = n `mod` 10 : toDigitsRev (n `div` 10)

toDigits :: Integer -> [Integer]
toDigits n = reverse (toDigitsRev n)

doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther [] = []
doubleEveryOther (x:[]) = [x]
doubleEveryOther (x:y:zx)
  | length (x:y:zx) `mod` 2 == 0 = 2*x : y : doubleEveryOther zx
  | otherwise = x : 2*y : doubleEveryOther zx

sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x:[]) = x
sumDigits (x:xs)
  | x < 10 = x + sumDigits xs
  | otherwise = sumDigits (toDigits x) + sumDigits xs

validate :: Integer -> Bool
validate 0 = False
validate n = (sumDigits (doubleEveryOther (toDigits n))) `mod` 10 == 0

type Peg = String
type Move = (Peg, Peg)
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi n a b c
  | n == 0 = []
  | n == 1 = (a, b) : hanoi 0 a b c
  | otherwise =  hanoi (n-1)  a c b ++ [(a, b)] ++  hanoi (n-1) c b a


texts:
I am learning about OOP so it would be great if you can give me feedback on how to improve my code and OOP design.

This is a currency converter. Firstly, it will call a method to add 2 currencies and commission information and then it converts to another currency whose input is source currency and amount:

import pytest

class Bank:

    def addRate(self,first, second, rate):
        self.first_currency = first
        self.second_currency = second
        self.rate = rate

    def addCommission(self,commision):
        self.commission = commision

    def convert(self, currency, amount):
        if currency == self.first_currency:
            return (amount / self.rate) * (1-self.commission)
        else:
            return (amount * self.rate) * (1-self.commission)

@pytest.fixture()
def bank():
    return Bank()

def test_Bank_addRate(bank):

    bank.addRate("USD","GBP",2)
    assert bank.first_currency == "USD"
    assert bank.second_currency == "GBP"
    assert bank.rate == 2

def test_Bank_addCommision(bank):
    bank.addCommission(0.015)
    assert bank.commission == 0.015

def test_Bank_convert(bank):
    bank.addRate("USD", "GBP", 2)
    bank.addCommission(0.015)
    assert bank.convert("USD", 100) == 49.25


texts:
After cleaning up & some refactoring, one module of my code became like below.
However, I'm feeling like there's still some unnecessary redundancy, and it can be improved further and look neater.

But I can't come up with exactly how to do it.

'use strict';

// === showing the execution context ==============

const express = require('express');
const router = express.Router();

const moment = require("moment");
const momentDurationSetup = require("moment-duration-format");
const DB = require('./DBOperator');
const _ = require('lodash');

const Promise = require("bluebird");
const request = require('superagent-bluebird-promise');

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

// ========== main concern area ===============

function realTime(queryFunction, payload, req, res, next) {
    queryFunction((err, results) => {
        if (err) {
            console.log(err);
            next();
        } else {
            res.json({data: _.get(results[0].rows[0], payload, -1)});
        }
    });
}

router.get('/online-buyer-count', utils.mcache(15), (req, res, next) => {
    realTime(DB.onlinebuyerNumQuery, 'onlinebuyerNum', req, res, next);
});

router.get('/offline-buyer-count', utils.mcache(15), (req, res, next) => {
    realTime(DB.offlinebuyerNumQuery, 'offlinebuyerNum', req, res, next);
});

router.get('/online-seller-count', utils.mcache(15), (req, res, next) => {
    realTime(DB.onlinesellerNumQuery, 'onlinesellerNum', req, res, next);
});

router.get('/offline-seller-count', utils.mcache(15), (req, res, next) => {
    realTime(DB.offlinesellerNumQuery, 'offlinesellerNum', req, res, next);
});

/ ===========================

module.exports = router;


texts:
I have written a helper method which computes the sum of values in some custom grid, given the column indexes. The method appears to work (for a decimal - as Anthony pointed out, I need to test this further), but I am not at ease with the following conversions:

decimal valIfNull = (decimal)(object)valueIfNull;
return (T)(object)sum;

They seem too indirect, but Convert.ChangeType also returns an object type, so another cast is needed anyway. Also, I believe that Convert.ChangeType can convert a string such as "123.456" into a proper decimal value, but this is not the behavior I want in this case. I would like to see an invalid cast exception in that case. So, is what I have good enough, or is there a better way?

    private T SumColumns<T>(T valueIfNull, params short[] columnIndexes)
        where T : struct, IConvertible
    {
        // Since we do not know what exactly T is, we will compute things as if it was a decimal.
        // If this works reasonably well, then this trick should be used elsewhere.

        // I am not sure if this is the best way to go about casting
        decimal valIfNull = (decimal)(object)valueIfNull;

        // Here this.GetCurrentRowValue<decimal> is another generic function I wrote ...
        decimal sum = columnIndexes.Select(columnIndex => this.GetCurrentRowValue<decimal>(columnIndex: columnIndex, valueIfNull: valIfNull)).Sum();
        return (T)(object)sum;
    }


texts: Get most recent modified time of a folder recursively with PHP

texts:
I'm relatively new to php and any advice is appreciated.

I have written a code to the most recently updated time for a folder in php.
Can you please correct me if I am doing anything wrong.

And here the code I use:

function get_m_time_dir ($directory)
{
$last_modified_time = 0;
$handler = opendir ($directory);
while ($file = readdir ($handler))
{
    if ($file == '.' || $file == '..')
    {
        continue;
    }
    if (is_file ($directory . DIRECTORY_SEPARATOR . $file))
    {
        $filemtime = filemtime ($directory . DIRECTORY_SEPARATOR . $file);
        if ($filemtime > $last_modified_time)
        {
            $last_modified_time = $filemtime;
        }
    } else
    {
        $filemtime = get_m_time_dir ($directory . DIRECTORY_SEPARATOR . $file);
        if ($filemtime > $last_modified_time)
        {
            $last_modified_time = $filemtime;
        }
    }
}
return $last_modified_time;
}


texts: Finding and moving the next obstacle in a player's path

texts:
This code finds the next obstacle in the player's path, then moves it. I am trying to make it more efficient, because this code runs for each frame, and it lags a bit. It does work though.

There are 8 blockers, which are basically obstacles. We subtract from the players rotation until the rotation is equal to one of these eight blockers. Then we move the blocker.  Each blocker cannot be moved two times in a row, though.

You might be wondering why rotation determines if the player collides. That is because my game is based around a planet, to where the player rotates.

whileLoop:
    while (true) {

        for (Blocker blocker : blockers) {
            if (playerRotation == (int) blocker.getRotation()) {
                if(lastBlockerMoved != blocker) {
                    lastBlockerMoved = blocker;
                    float gap = Tools.generateFloat(Config.minBlockerGap, Config.maxBlockerGap);
                    float y = Tools.generateFloat(Config.minBlockerY, Config.maxBlockerY - gap);
                    float duration = Tools.generateFloat(Config.minBlockerYDuration, Config.maxBlockerYDuration);
                    blocker.addAction(Actions.moveTo(blocker.getX(), y, duration, Config.blockerInterpolation));
                    blocker.addAction(GapSizeAction.getGapSizeAction(gap, duration));
                }

                break whileLoop;
            }
        }

        playerRotation--; //-- is going right, ++ would be going left
        while (playerRotation > 360) {
            playerRotation -= 360;
        }
        while (playerRotation <= 0) {
            playerRotation += 360;
        }
    }


texts: shared_ptr and FILE for wrapping cstdio (update: also dlfcn.h)

texts:
Even in the presence of <fstream>, there may be reason for using the <cstdio> file interface. I was wondering if wrapping a FILE* into a shared_ptr would be a useful construction, or if it has any dangerous pitfalls:

#include <cstdio>
#include <memory>

std::shared_ptr<std::FILE> make_file(const char * filename, const char * flags)
{
  std::FILE * const fp = std::fopen(filename, flags);
  return fp ? std::shared_ptr<std::FILE>(fp, std::fclose) : std::shared_ptr<std::FILE>();
}

int main()
{
  auto fp = make_file("hello.txt", "wb");
  fprintf(fp.get(), "Hello world.");
}

Update: I just realized that it is not allowed to fclose a null pointer. I modified make_file accordingly so that in the event of failure there won't be a special deleter.

Second update: I also realized that a unique_ptr might be a more suitable than shared_ptr. Here is a more general approach:

typedef std::unique_ptr<std::FILE, int (*)(std::FILE *)> unique_file_ptr;
typedef std::shared_ptr<std::FILE> shared_file_ptr;

static shared_file_ptr make_shared_file(const char * filename, const char * flags)
{
  std::FILE * const fp = std::fopen(filename, flags);
  return fp ? shared_file_ptr(fp, std::fclose) : shared_file_ptr();
}

static unique_file_ptr make_file(const char * filename, const char * flags)
{
  return unique_file_ptr(std::fopen(filename, flags), std::fclose);
}

Edit. Unlike shared_ptr, unique_ptr only invokes the deleter if the pointer is non-zero, so we can simplify the implementation of make_file.

Third Update: It is possible to construct a shared pointer from a unique pointer:

unique_file_ptr up = make_file("thefile.txt", "r");
shared_file_ptr fp(up ? std::move(up) : nullptr);  // don't forget to check

Fourth Update: A similar construction can be used for dlopen()/dlclose():

#include <dlfcn.h>
#include <memory>

typedef std::unique_ptr<void,  int (*)(void *)> unique_library_ptr;

static unique_library_ptr make_library(const char * filename, int flags)
{
  return unique_library_ptr(dlopen(filename, flags), dlclose);
}


texts: Red-black tree appears to be slower than std::multimap

texts:
I've written a red-black tree in C as an exercise. The tree works and it is not bad, but it is about 10% slower than std::multimap from libstdc++ which I'm comparing it against.

Full code of my implementation is here. libstdc++'s red-black tree written in C++ is here and here.

I'm using the following code to compare implementations:

void
test_torture() {
    std::vector<uint64_t> v;
    std::multimap<uint64_t, uint64_t> map;
    uint64_t range = 10 * 1000 * 1000 * 1000LL;
    uint64_t count = 10 * 1000 * 1000;
    for (uint64_t i = 0; i < count; i++) {
        uint64_t key = rand() % range;
        map.insert(std::make_pair(key, key));
        v.push_back(key);
    }
    for (uint64_t i = 0; i < count; i++) {
        uint64_t key = v[i];
        map.erase(key);
    }
    assert(map.size() == 0);
}

So it adds 10m random nodes to the tree, then deletes them all again. My code is almost exactly as fast as std::multimap when doing the insertion part, but it lags behind when it comes to erasing nodes. When profiling, the hottest part of my code is my loop for inserting nodes:

rbtree *
rbt_add(rbtree *me, ptr key, ptr value) {
    // Find insertion point.
    rbtree **addr = &me;
    rbtree *parent = NULL;
    while (*addr) {
        parent = *addr;
        addr = &parent->childs[key >= parent->key];
    }
    *addr = rbt_init(parent, key, value);
    return rbt_add_fixup(me, *addr);
}

But I can't think of any way to improve that. My functions for rebalancing the tree after addition and deletion (which I think are the most interesting part) are below.

static rbtree *
rbt_add_fixup(rbtree *root, rbtree *x) {
    while (x != root && x->parent->is_red) {
        bstdir dir = BST_DIR_OF(x->parent);
        rbtree *y = x->parent->parent->childs[!dir];
        if (y && y->is_red) {
            x->parent->is_red = false;
            y->is_red = false;
            x->parent->parent->is_red = true;
            x = x->parent->parent;
        } else {
            if (BST_DIR_OF(x) != dir) {
                x = x->parent;
                root = rbt_rotate(root, x, dir);
            }
            x->parent->is_red = false;
            x->parent->parent->is_red = true;
            root = rbt_rotate(root, x->parent->parent, !dir);
        }
    }
    root->is_red = false;
    return root;
}

static rbtree *
rbt_remove_fixup(rbtree *root, rbtree *x, rbtree *x_parent) {
    while (x != root && IS_BLACK(x)) {
        bstdir dir = BST_DIR_OF2(x, x_parent);
        rbtree *w = x_parent->childs[!dir];
        if (w && w->is_red) {
            w->is_red = false;
            x_parent->is_red = true;
            root = rbt_rotate(root, x_parent, dir);
            w = x_parent->childs[!dir];
        }
        if (BOTH_CHILDREN_BLACK(w)) {
            if (w) {
                w->is_red = true;
            }
            x = x_parent;
            x_parent = x->parent;
        } else {
            if (IS_BLACK(w->childs[!dir])) {
                w->childs[dir]->is_red = false;
                w->is_red = true;
                root = rbt_rotate(root, w, !dir);
                w = x_parent->childs[!dir];
            }
            w->is_red = x_parent->is_red;
            x_parent->is_red = false;
            w->childs[!dir]->is_red = false;
            root = rbt_rotate(root, x_parent, dir);
            x = root;
        }
    }
    if (x) {
        x->is_red = false;
    }
    return root;
}

I'd be very grateful for suggestions on how to increase the performance of the code.

The definition of the node type is:

typedef struct _rbtree {
    struct _rbtree *parent;
    struct _rbtree *childs[2];
    bstkey key;
    bool is_red;
    ptr value;
} rbtree;


texts:
I wrote this code that makes a fairly long function call multiple times using some of the same parameters

match key {
    Key { code: KeyCode::Left, .. } => self.map.move_object_by(PLAYER, -1, 0),
    Key { code: KeyCode::Right, .. } => self.map.move_object_by(PLAYER, 1, 0),
    Key { code: KeyCode::Up, .. } => self.map.move_object_by(PLAYER, 0, -1),
    Key { code: KeyCode::Down, .. } => self.map.move_object_by(PLAYER, 0, 1),
}

I was looking for a way to shortened this function call with something simlar to C/C++ macros. I looked into Rust Macros but they are clearly very different. The solution I came up with is creating a function pointer to a closure that calls the function self.map.move_object_by

let mut move_player = |x, y| self.map.move_object_by(PLAYER, x, y);

match key {
    Key { code: KeyCode::Left, .. } => move_player(-1, 0),
    Key { code: KeyCode::Right, .. } => move_player(1, 0),
    Key { code: KeyCode::Up, .. } => move_player(0, -1),
    Key { code: KeyCode::Down, .. } => move_player(0, 1),
}

Is this bad? Will this cause any real slow downs or bugs? Are there other/better ways of doing this?


texts:
This function checks whether or not a substring needle exists in another string haystack and returns the position if it does or 0 if it doesn't, unless the position is 0 in which case, it won't be located.

Looking for ways to improve this code, specifically better error handling.

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

size_t contains(const char * needle, const char *haystack);

int main(void)
{
    char *needle = "test";
    char *haystack = "This is a dinosaurtest.";
    printf("Position: %lu", contains(needle, haystack));

    return EXIT_SUCCESS;
}

size_t contains(const char * needle, const char *haystack)
{
    if(needle == NULL || haystack == NULL)
    {
        return 0;
    }
    long int first_char_pos = -1;
    size_t len_h = strlen(haystack);
    size_t len_n = strlen(needle);
    size_t i, j;
    size_t exist_count = 0;

    // Find the first character. If it doesn't exist, we're done.
    for(i = 0; i < len_h; i++)
    {
            if((haystack[i] == needle[0]) && (first_char_pos == -1))
            {
                first_char_pos = i;
                exist_count++;
            }
    }

    if(first_char_pos == -1)
    {
        return 0;
    }
    printf("First char match index: %li\n", first_char_pos);
    printf("Char: %c\n", haystack[first_char_pos]);
    size_t current_index = (size_t) first_char_pos;
    for(i = first_char_pos; i < len_h; i++)
    {
        if(haystack[i] == needle[exist_count] && (i == (current_index + 1)))
        {
            current_index = i;
            exist_count++;
        }
        printf("Exist count: %lu\n", exist_count); //<--Debugging
        if(exist_count == len_n)
        {
            return first_char_pos;
        }
    }
    return 0;
}


texts:
Write a program to sort an array of 0's,1's and 2's in ascending
  order.

  Input:

  The first line contains an integer 'T' denoting the total number of
  test cases. In each test cases, First line is number of elements in
  array 'N' and second its values.

  Output:

  Print the sorted array of 0's, 1's and 2's.

  Constraints:

  1 <= T <= 100
  1 <= N <= 105
  0 <= arr[i] <= 2

  Example:

  Input :

2
5
0 2 1 2 0
3
0 1 0

  Output:

0 0 1 2 2
0 0 1

My approach:

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

class GFG {

    private static void printSortedArr (int[] arr) {
        int count0 = 0, count1 = 0, count2 = 0;

        for (Integer elem : arr) {
            if (elem == 0) {
                count0++;
            }
            else if (elem == 1) {
                count1++;
            }
            else {
                count2++;
            }
        }

        while (count0 != 0) {
            System.out.print(0 + " ");
            count0--;
        }

        while (count1 != 0) {
            System.out.print(1 + " ");
            count1--;
        }

        while (count2 != 0) {
            System.out.print(2 + " ");
            count2--;
        }
        System.out.println();
    }

    public static void main (String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();
        int numTests = Integer.parseInt(line);

        for (int i = 0; i < numTests; i++) {
            String line2 = br.readLine();
            int size = Integer.parseInt(line2);
            int[] arr = new int[size];
            String line3 = br.readLine();
            String[] inps = line3.split(" ");

            for (int j = 0; j < size; j++) {
                arr[j] = Integer.parseInt(inps[j]);
            }

            printSortedArr(arr);
        }
    }
}

I have the following questions with regards to the above code:

How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?

Reference


texts:
The following function determines the amount of indentation of a string. It returns two values. The first is an effective indentation where tabs are expanded such that their end aligns with 4 spaces steps. The second is just the amount of spaces and tabs before the first non-tab/space character.

roundup is a method that rounds the first argument to next higher multiple of the second argument. The rest is standard CL.

(defun indentation (line)
  (let ((spaces 0))
    (dotimes (index (length line) (values spaces index))
      (case (aref line index)
        (#\Space (incf spaces))
        (#\Tab (setf spaces (roundup (1+ spaces) 4)))
        (otherwise (return (values spaces index)))))))

I don't like having to state the return value twice.


texts: A Blum Blum Shub pseudorandom RNG implementation in JavaScript

texts:
I made a Blum Blum Shub pseudorandom number generator implementation in JavaScript.

  Blum Blum Shub (B.B.S.) is a pseudorandom number generator proposed in
  1986 by Lenore Blum, Manuel Blum and Michael Shub that is derived
  from Michael O. Rabin's oblivious transfer mapping.

  Blum Blum Shub takes the form

  \$x_{n+1}=x_{n}^{2}{\bmod {M}}\$

  where M = pq is the product of two large primes p and q. At each step
  of the algorithm, some output is derived from \$x_{n+1}\$; the output is
  commonly either the bit parity of \$x_{n+1}\$ or one or more of the least
  significant bits of \$x_{n+1}\$.

  The seed \$x_0\$ should be an integer that is co-prime to M (i.e. p and q
  are not factors of \$x_0\$) and not 1 or 0.

  The two primes, p and q, should both be congruent to 3 (mod 4) (this
  guarantees that each quadratic residue has one square root which is
  also a quadratic residue) and gcd(φ(p − 1), φ(q − 1)) should be small
  (this makes the cycle length large).

-- from Wikipedia

var p = 5651;
var q = 5623;
var M = p * q;

var x = undefined;

/** Get the gcd of two numbers, A and B. */
function gcd(a, b) {
    while(a != b) {
        if(a > b) {
            a = a - b;
        } else {
            b = b - a;
        }
    }
    return a;
}

/** Seed the random number generator. */
function seed(s) {
    if(s == 0) {
        throw new Error("The seed x[0] cannot be 0");
    } else if(s == 1) {
        throw new Error("The seed x[0] cannot be 1");
    } else if(gcd(s, M) != 1) {
        throw new Error("The seed x[0] must be co-prime to " + M.toString());
    } else {
        x = s;
        return s;
    }
}

/** Get next item from the random number generator. */
function next() {
    var cachedx = x;
    cachedx = cachedx * x;
    cachedx = cachedx % M;
    x = cachedx;
    return x;
}

The code might be able to be refactored to an object and a factory generating such objects, for independent states and functions of the generator. I'm interested if there are any more problems with this code.


texts:
I was trying, just for fun, to solve http://code.google.com/codejam/contest/dashboard?c=2075486#s=p4

I can easily solve the small set, but I struggle to solve the big one (my implementation would use approx. 30GB or RAM, which is a bit too much. Any hint or direction is appreciated!

def solve_maze(case_no):
    case = cases[case_no]
    case_no += 1
    edges = case['edges']
    #quick and dirty check. Can we reach the goal?
    if case['goal'] not in sum([i.values() for i in edges.values()],[]):
        return "Case #%s: Infinity" % case_no
    last_position = 1
    l = 0
    states = set()
    memory = [1 for i in range(1,1+case['goal'])]
    while not last_position==case['goal']:
        direction = memory[last_position]
        memory[last_position] *= -1
        move = edges[last_position][direction]
        states.add(hash((move,tuple(memory))))
        l+=1
        if len(states) != l:
            return "Case #%s: Infinity" % case_no
        last_position = move
    else:
        return "Case #%s: %d" % (case_no,len(states))

with open("/xxx/test-small.in","rb") as f:
    inp = f.read()[:-1].split("\n")
    N = int(inp[0])
    cases = []
    it = 0
    for line in inp[1:]:
        if line.find(" ") == -1:
            #print int(line)
            cases.append({"goal":int(line),"edges":{}})
            it = 0
        else:
            it+=1
            cases[-1]['edges'][it] = dict(zip([1,-1],map(int,line.split())))
    for i in range(len(cases)):
        print solve_maze(i)


texts: Race Condition in ScheduledExecutorService.scheduleAtFixedRate

texts:
Im planning to use Strategy design pattern to put it in
ScheduledExecutorService.scheduleAtFixedRate. I can use create as many scheduleAtFixedrate depends on the data to be pulled. Will this cause a race condition?
    public abstract class DefaultStrategy {

        protected Map<String, String> transactionMap;
        protected AuthParam authParam;

        public DefaultStrategy(Map<String, String> transactionMap, Projection projection) {
            this.transactionMap = transactionMap;
            this.projection= projection;
        }
    }

    public class BankStrategy extends DefaultStrategy implements Runnable{

        public BankStrategy (Map<String, String> transactionMap, Projection projection) {
            super(transactionMap, projection);
        }

        @Override
        public void run() {
            String transaction = transactionMap.get("branch1");
            String balance = projection.getBalance();
            // do something with transaction and balance
        }
    }

    public class LoanSharkStrategy extends DefaultStrategy implements Runnable{

        public LoanSharkStrategy(Map<String, String> transactionMap, Projection projection) {
            super(transactionMap, projection);
        }

        @Override
        public void run() {
            String transaction = transactionMap.get("branch2");
            String balance = projection.getBalance();
            // do something with transaction and balance
        }
    }

public class Handler {

    private static final ScheduledExecutorService scheduledExecutorServiceFirst = MDScheduledExecutorService.wrap(
            new ScheduledThreadPoolExecutor(5), "first-thread-%d");

   //assuming this is the main method to call
   private void main() {
      //assuming there is a list of Param with transactionMap and projection that was populated in other function..
      List<Param> loanSharkStrategyParams = getParamsFromOtherFucnction();

      loanSharkStrategyParams.forEach(param -> {
        scheduledExecutorServiceFirst.scheduleAtFixedRate(new
        LoanSharkStrategy(param.getTransactionMap, param.getProjection())), 1, 3600, SECONDS);
      });

   }
 }


texts:
Each new term in the Fibonacci sequence is generated by adding the previous two terms.

  By starting with 1 and 2, the first 10 terms will be:

1,2,3,5,8,13,21,34,55,89,...

  By considering the terms in the Fibonacci sequence whose values do not exceed N, find the sum of the even-valued terms.

I'd like to reduce the complexity of my code.

import java.math.BigInteger;
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int testCases = sc.nextInt();
        for (int i = 0; i < testCases; i++) {
            BigInteger input = sc.nextBigInteger();
            System.out.println(calculate(input));
        }
    }

    public static BigInteger calculate(BigInteger input) {
        BigInteger fib1 = new BigInteger("0");
        BigInteger fib2 = new BigInteger("1");
         BigInteger sum = new BigInteger("0");

        BigInteger fib = new BigInteger("0");
        while (input.compareTo(fib)>0) {

            if (fib.doubleValue() % 2 == 0)
                sum = sum.add(fib);
            fib = fib1.add(fib2);
            fib1 = fib2;
            fib2 = fib;

        }

        return sum;
    }

}


texts: Singleton class to contain a DocumentClient instance, that can be overridden for testing

texts:
The DocumentClient is an object that accesses CosmosDb, but Microsoft recommends its kept as a Singleton class. I'm relying on System.Lazy to ensure thread safety.

In addition, I want to be able to overwrite my DocumentClient when I need to test. Is this correct?

public sealed class DocumentClientSingleton
{
    public static IDocumentClient GetInstance()
    {
        return _lazy.Value;
    }

    /// <summary>
    /// Only use this for testing!
    /// </summary>
    /// <returns></returns>
    public static IDocumentClient SetInstanceForTesting(IDocumentClient client)
    {
        _lazy = new Lazy<IDocumentClient>(() => client );
        return _lazy.Value;
    }

    private static  Lazy<IDocumentClient> _lazy =
        new Lazy<IDocumentClient>(InstantiateDocument);

    private static IDocumentClient InstantiateDocument()
    {
        return new DocumentClient(
            new Uri(ConfigurationManager.AppSettings["endpoint"]),
            ConfigurationManager.AppSettings["authKey"],
            new ConnectionPolicy
            {
                ConnectionMode = ConnectionMode.Direct,
                ConnectionProtocol = Protocol.Tcp
            }
        );
    }
}


texts: Sorting and slicing array, based on another "weight" array?

texts:
I have the following input array:

$arr = array(
'water' => array(0, 1, 2, 3, 4, 5),
'apple' => array(1, 5, 3, 4, 0, 0),
'beer' => array(0, 0, 0, 0, 0, 0)
);

Now I want to know which element has largest sum, so I have the following code:

$arrWeight = array();

foreach ($arr as $key => $value)
{
    $arrWeight[$key] = is_array($value) ? array_sum($value) : 0;
}

Then, I want to sort array based on weight. That's easy.

arsort($arrWeight);

Now, I want to slice the original array ($arr) based on generated weights and limit.

$arrAllowedKeys = array_slice($arrWeight, 0, self::METRICS_BREAKDOWN_LIMIT, true);

foreach ($arr as $key => $value)
{
    if (!array_key_exists($key, $arrAllowedKeys))
    {
        unset($arr[$key]);
    }
}

For example, if I have self::METRICS_BREAKDOWN_LIMIT equals to 2, I'd expect the following output:

$arr = array(
'water' => array(0, 1, 2, 3, 4, 5),
'apple' => array(1, 5, 3, 4, 0, 0),
);

So, basically, the above solution is working, but I'm looking for better approach.


texts: Computing resilience of the network presented as an undirected graph in Python

texts:
The idea is to compute resilience of the network presented as an undirected graph in form {node: (set of its neighbors)} for each node in the graph}. The function removes nodes from the graph in the specified order one by one and calculates the size of the largest remaining connected component. The function returns a list whose k+1th entry is the size of the largest connected component after the removal of the first k nodes. The helper function bfs_visited() returns the set of nodes that are still connected to the given node.

How can I improve the implementation of the algorithm (currently it is very slow)?

def bfs_visited(graph, node):
    """undirected graph {Vertex: {neighbors}}
    Returns the set of all nodes visited by the algrorithm"""
    queue = deque()
    queue.append(node)
    visited = set([node])
    while queue:
        current_node = queue.popleft()
        for neighbor in graph[current_node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
    return visited

def cc_visited(graph):
    """ undirected graph {Vertex: {neighbors}}
    Returns a list of sets of connected components"""
    remaining_nodes = set(graph.keys())
    connected_components = []
    for node in remaining_nodes:
        visited = bfs_visited(graph, node)
        if visited not in connected_components:
            connected_components.append(visited)
        remaining_nodes = remaining_nodes - visited
        #print(node, remaining_nodes)
    return connected_components

def largest_cc_size(ugraph):
    """returns the size (an integer) of the largest connected component in the ugraph."""
    if not ugraph:
        return 0
    res = [(len(ccc), ccc) for ccc in cc_visited(ugraph)]
    res.sort()
    return res[-1][0]

def compute_resilience(ugraph, attack_order):
    """
    input: a graph {V: N}

    returns a list whose k+1th entry is the size of the largest connected component after the removal of the first k nodes
    """
    res = [len(ugraph)]
    for node in attack_order:
        neighbors = ugraph[node]
        for neighbor in neighbors:
            ugraph[neighbor].remove(node)
        ugraph.pop(node)
        res.append(largest_cc_size(ugraph))
    return res


texts: Testing whether to launch debugger based on build & command line arguments

texts:
I have a C# application that may be spawned by another process using Shell or its equivalent. As such, it is not trivial to simply F5 into a breakpoint nor launching an external program will work since a brand new process get spawned. Thus it is problematic especially when doing integration tests or diagnosing unusual problem that requires the same context than the one provided by automated tests.

I thought of passing in a debug flag but I don't want it to be accepted in a release build. I adapted the code from this SO thread by making it a complete function that returns a private struct. The important part is the check within the Main procedure where we inspect whether a -debug flag has been passed via the command line argument and if so, confirm this is a debug build, not a release build. This seems to work well enough; but I want to know if this is reasonably good way to enable debugging on demand without exposing too much. Thus, the review is to see if this could be improved upon:

Note: I don't currently use all the member of the struct in the code; I don't know if there may be other use yet and didn't bother eliminating the unused members.

Note #2: I belatedly realized that I could have wrapped the check and the supporting function inside a #if DEBUG block, which would also prevent the code from ever being included in a release build. However, it got me thinking if there might be legitimate scenario to launch debugger on a release build (even though the debug information will be sparse due to optimizations), so we can leave the question with the expectation that it could be used in release. Would it be an acceptable way or are there better ways?

internal class Program
{
    [STAThread]
    private static int Main(string[] args)
    {
        if (args.Any(a => a == "--debug") && GetDebugData().BuildType.ToLowerInvariant() == "debug")
        {
            Debugger.Launch();
        }

        // do something interesting....
    }

    private struct AssemblyDebugData
    {
        internal bool HasDebuggableAttribute;
        internal bool IsJITOptimized;
        internal string BuildType;
        internal string DebugOutput;
    }

    private static AssemblyDebugData GetDebugData()
    {
        AssemblyDebugData result = new AssemblyDebugData();

        object[] attribs = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(DebuggableAttribute), false);

        // If the 'DebuggableAttribute' is not found then it is definitely an OPTIMIZED build
        if (attribs.Length > 0)
        {
            // Just because the 'DebuggableAttribute' is found doesn't necessarily mean
            // it's a DEBUG build; we have to check the JIT Optimization flag
            // i.e. it could have the "generate PDB" checked but have JIT Optimization enabled
            DebuggableAttribute debuggableAttribute = attribs[0] as DebuggableAttribute;
            if (debuggableAttribute != null)
            {
                result.HasDebuggableAttribute = true;
                result.IsJITOptimized = !debuggableAttribute.IsJITOptimizerDisabled;
                result.BuildType = debuggableAttribute.IsJITOptimizerDisabled ? "Debug" : "Release";

                // check for Debug Output "full" or "pdb-only"
                result.DebugOutput = (debuggableAttribute.DebuggingFlags &
                               DebuggableAttribute.DebuggingModes.Default) !=
                              DebuggableAttribute.DebuggingModes.None
                    ? "Full" : "pdb-only";
            }
        }
        else
        {
            result.IsJITOptimized = true;
            result.BuildType = "Release";
        }

        return result;
    }
}


texts: Rectangularize a list-of-lists structure

texts:
Considering I have an iterated "lists of lists ..." (up to 4 dimensions), now I wish to make the full list "rectangular" (or well each dimension equal in size). For a 4 dimensional case I've written out a specific version:

x=[[[[4,3,4,5],[1],[2,2]],[[3,6,7],[2,3],[1]]],[[[1]]]]

length0 = len(x)
length1 = len(sorted(x,key=len, reverse=True)[0])
length2 = 0
length3 = 0
for xi in x:
    lengthi = len(sorted(xi,key=len, reverse=True)[0])
    for xii in xi:
        lengthii = len(sorted(xii,key=len, reverse=True)[0])
        length3 = max(lengthii, length3)
    length2 = max(lengthi, length2)
tlist3 = [None]
tlist2 = [tlist3 * length3]
tlist1 = [tlist2 * length2]

for xi in x:
    for xii in xi:
        for xiii in xii:
            xiii.extend(tlist3*(length3 - len(xiii) ))
        xii.extend(tlist2*(length2 - len(xii)))
    xi.extend(tlist1 * (length1 - len(xi)))

print(x)

It works, but that's everything I can say about this code (it doesn't look clean, nor is it scalable to more dimensions easily).

Ideally I would've a function that goes up to N dimensions into a given list, and rectangulars everything

As a side note: this is for insertion into a NumPy array.


texts: Validate that a given string (name) meets certain requirements

texts:
String Name = "yyyy MM DD abjwg kelk.exe"

public static bool IsNameRight(string Name)
{
    string[] temp = Name.Split(' ');
    string[] de= Name.Split('.');

    if (de[1] == "pdf" && temp .Length == 5)
    {
        if (temp [0].Length == 4
            && temp [1].Length == 2
            && temp [3].Length == 2
            && temp [4] == "abjwg"
            && temp [5] == "kelk.exe")
            return true;
        else
            return false;
    }
    return false;
}

I am using .NET 3.5 and C#

EDIT

You could use Regular expressions but I have never used it or know how to use it, and don't know if it is a good practice.


texts: Finding the sum of all the segment counts of a 7-segment display in a range

texts:
I'm working on a programming challenge and the question is as follows:
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (https://en.wikipedia.org/wiki/Seven-segment_display).

Max starts to type all the values from a to b. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator.
For example if a = 1 and b = 3 then at first the calculator will print 2 segments, then — 5 segments and at last it will print 5 segments. So the total number of printed segments is 12.
Input
The only line contains two integers a, b (1 ≤ a ≤ b ≤ 106) — the first and the last number typed by Max.
Output
Print the only integer a — the total number of printed segments.
Examples
input
1 3
output
12
input
10 15
output
39
Here's my attempt:
#include <iostream>
#include <unordered_map>

static std::unordered_map<char, int>
         segment_count = {
                            {'1', 2},
                            {'2', 5},
                            {'3', 5},
                            {'4', 4},
                            {'5', 5},
                            {'6', 6},
                            {'7', 3},
                            {'8', 7},
                            {'9', 6},
                            {'0', 6}
                         };

int get_number_of_segments(char num) {
  return segment_count[num];
}

int main() {
  int start, end, sum = 0;

  std::cin >> start >> end;

  for(int i = start; i <= end; ++i) {
    std::string current_num = std::to_string(i);
    for(auto c: current_num) {
      sum += get_number_of_segments(c);
    }
  }
  std::cout << sum << '\n';
}

When I submit the code, it fails on a timeout for a test case (unknown test case). How can I make it more efficient? All tests should run in under 1 second.
One idea I've had is to store the numbers not in the "one's place" - these won't change.
For instance: in the sequence 10, 11, 12, 13, 14, ..., I don't need to lookup 1 each time. I only need to look at the last digit until I see a 9.
Perhaps there are better ways to do this, though.
Any help would be appreciated!


texts: Importing data into PostgreSQL from remote text file using ftplib class

texts:
I need to read a remote file using FTP and process it and insert the processed data to a PostgreSQL database in another server.

The below code is working fine, but i want some advice to modify few things.

In this line i don't want to write the actual details, I want that to
be hidden from my script. How can i do that?

ftp = FTP('server.com','user_name','password')

The script downloads the file to my local system and process it as
it is a local file. Is there any way to read and process it without
downloading it to the source server (there might be permission issues
also)?
If there is no way rather than downloading it to the source, should I
specify a path where this file would be downloaded
rather than the way I have written it?
Is there anything which i can do to improve this code?

Any guidance will be of great help.

import psycopg2
import time
import os
#import MySQLdb
#import paramiko
from ftplib import FTP
#from utils.config import Configuration as Config
#from utils.utils import get_global_config

start_time = time.perf_counter()

cnx_psql = psycopg2.connect(host="localhost", database="postgres", user="postgres",
                        password="postgres", port="5432")

# Cursors initializations
cur_psql = cnx_psql.cursor()

def getFile(ftp, filename):
    try:
        local_filename = os.path.join(r"/Users/linu/Downloads/", filename)
        lf = open(local_filename, "wb")
        ftp.retrbinary("RETR " + filename ,lf.write)
        print("file copied")
    except:
        print ("Error")
try:

    filePath='''/Users/linu/Downloads/log'''
    #filePath='''/cmd/log/stk/log.txt'''
    table='staging.stock_dump'

    SQL="""DROP TABLE IF EXISTS """+  table + """;CREATE TABLE IF NOT EXISTS """+ table + """
    (created_date TEXT, product_sku TEXT, previous_stock TEXT, current_stock TEXT );"""

    cur_psql.execute(SQL)
    cnx_psql.commit()

    ftp = FTP('server.com','user_name','password')
    print("FTP connection succesful")
    data = []
    ftp.cwd('/stockitem/')
    getFile(ftp,'log')

    read_file = open(filePath, "r")
    my_file_data = read_file.readlines()

    for line in my_file_data:
        if 'Stock:' in line:
            fields=line.split(" ")
            date_part1=fields[0]
            date_part2=fields[1][:-1]
            sku=fields[3]
            prev_stock=fields[5]
            current_stock=fields[7]
            if prev_stock.strip()==current_stock.strip():
                continue
            else:
               cur_psql.execute("insert into " + table+"(created_date, product_sku, previous_stock , current_stock)" + " select CAST('" + date_part1+ " "+ date_part2 + "' AS TEXT)" +", CAST('"+sku+"' AS TEXT),CAST('" + prev_stock +"' AS TEXT),CAST('" +current_stock  + "' AS TEXT);")
    cnx_psql.commit()
    cur_psql.close()
    cnx_psql.close()
    print("Data loaded to DWH from text file")
    print("Data porting took %s seconds to finish---" % (time.perf_counter() - start_time))
except (Exception, psycopg2.Error) as error:
        print ("Error while fetching data from PostgreSQL", error)
        print("Error adding  information.")
        quit()
finally:
    ftp.close()


texts: Bottleneck encountered returning records for my grid

texts:
I am using MVC 4.0/C#/EF4.0 and I have a grid page that grabs results that are filtered, sorted and paged. It's filtering results from a table that has 45,000 records. How do I improve performance? This page takes over 30 seconds to load.

  var filteredresults = _unitOfWork.ModifiedDataRepository.Get();

            NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
            int ID = (String.IsNullOrEmpty(nvc["sSearch_0"]) ? 0 : Convert.ToInt32(nvc["sSearch_0"]));
            int TaxYear = (String.IsNullOrEmpty(nvc["sSearch_1"]) ? 0 : Convert.ToInt32(nvc["sSearch_1"]));
            int AdditionalTax = (String.IsNullOrEmpty(nvc["sSearch_2"]) ? 0 : Convert.ToInt32(nvc["sSearch_2"]));

            filteredresults = filteredresults.Where(i => (ID == 0 || i.ID == ID)
                                                                     && (TaxYear == 0 || i.TaxYear == TaxYear)
                                                                     && (AdditionalTax == 0 || i.AdditionalChildTaxCreditAmount == AdditionalTax)
                                                                     );

            int Count = filteredresults.Count();

            string sortCol = param.sColumns.Split(',')[param.iSortCol_0];
            string sortExpression = sortCol + " " + param.sSortDir_0;

            filteredresults = filteredresults.OrderBy(sortExpression);
            filteredresults = from p in filteredresults
                              orderby (sortExpression)
                              select p;

            var parents = filteredresults.Skip(param.iDisplayStart).Take(param.iDisplayLength);

            var result = from c in parents.ToList()
                         select new MODIFIED_DATA()
                         {
                             ID = c.ID,
                             TaxYear = c.TaxYear,
                             AdditionalChildTaxCreditAmount = c.AdditionalChildTaxCreditAmount,
                             ArrivalDate = c.ArrivalDate,
                             ChildCareCredit = c.ChildCareCredit,
                             DLN = c.DLN,
                             EftCd = c.EftCd,
                             EicAmt = c.EicAmt,
                             ElfSourceCd = c.ElfSourceCd,
                             FilingStatusCd = c.FilingStatusCd,
                             MakingWorkPayCreditAmount = c.MakingWorkPayCreditAmount,
                             PrimPrisonerNmCd = c.PrimPrisonerNmCd
                         };

            var CustomerPaged = new DataTablePager<MODIFIED_DATA>();

            CustomerPaged.sEcho = param.sEcho;
            CustomerPaged.iTotalRecords = Count;
            CustomerPaged.iTotalDisplayRecords = Count;
            CustomerPaged.aaData = result.ToList();

            return CustomerPaged;


texts:
I'm trying to implement a system of restricted access. Right now I'm focusing on the "session fixation". I am concerned about the following aspects:

Control of a "fingerprint" of the user created by mixing UserAgent, IPAddress and a salt key. If the fingerprint were to change, destroy the user's session.
Using the same session id for a certain number of times, after which regeneration session id.
Regenerate the session id every time change the level of user authentication

What I want to know is whether my approach is right and if it is safe enough.
I apologize if the code is long, I tried to remove all the unnecessary parts.

I do not want a code review, but the opinions about it ... particularly if the mine is a safe approach.

<?php
class oLogonUser
{
    const SESSION_LIMIT = 10;
    const SESSION_SALT  = 'AS86F(,sa)8as7d+/234N&&"$£%';

    function __construct()
    {
        // init session
        $this->InitSession();

        // check if user logged
        if( $this->isUserLogged() )
        {
            // Check if finger print is valid
            if( !$this->isValidFingerPrint() )
                $this->LogOutUser(); // log out
        }
    }

    private function InitSession()
    {
        // check if session already start
        if( session_id() == '' )
            session_start();

        // Set user's fingerprint
        $this->setUserFingerPrint();

        // Session counter
        if( isset($_SESSION['UserSessionCounter']) )
            $_SESSION['UserSessionCounter'] = (int)$_SESSION['UserSessionCounter'] + 1;
        else
            $_SESSION['UserSessionCounter'] = 0;

        // if session counter exeed limit, regenerate session id
        if( $_SESSION['UserSessionCounter'] > self::SESSION_LIMIT )
        {
            $_SESSION['UserSessionCounter'] = 0;
            session_regenerate_id();
        }
    }

    private function isValidFingerPrint()
    {
        // checking if the user fingerprint is the same as that stored in session
        if( isset($_SESSION['UserFingerPrint']) )
            return ( $_SESSION['UserFingerPrint'] === $this->getUserFingerPrint() );

        return false;
    }

    private function getUserFingerPrint()
    {
        // return user fingerprint
        return md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . self::SESSION_SALT );
    }

    private function setUserFingerPrint()
    {
        // store in session user fingerprint
        if( !isset($_SESSION['UserFingerPrint']) )
            $_SESSION['UserFingerPrint'] = $this->getUserFingerPrint();
    }

    public function LogOnUser($UserName, $Password)
    {
        //NB: in fact control the credentials in the database
        if( $UserName == 'test' && $Password == 'test' )
            $this->setUserLogged();
    }

    public function LogOutUser($UserName, $Password)
    {
        // destroy user session
        session_destroy();
        session_regenerate_id();
    }

    private function setUserLogged()
    {
        session_regenerate_id();

        // set user logged
        $_SESSION['UserLogged'] = TRUE;
    }

    public function isUserLogged()
    {
        // check if user is logged
        return (isset($_SESSION['UserLogged']) && $_SESSION['UserLogged'] == TRUE );
    }
}

// Test it
$objLogonUser = new oLogonUser();

if( !$objLogonUser->isUserLogged() )
    $objLogonUser->LogOnUser('test', 'test');

echo session_id() . '<BR />';

print_r($_SESSION);


texts: Node comparison using priority queue for Dijkstra's Shortest Path Algorithm

texts:
Instead of using a MinHeap that will allow me to change the vertex priorities I am using the Java library PriorityQueue.

Here is how I have implemented the vertices which will generate the vertex array. Also, I have not maintained any separate array for storing the shortest distance to a vertex from source. Instead, I have a class variable will handle that and more importantly allow the priority queue to sort the elements by implementing a different version of compareTo method.

class indivisualvertex implements Comparable<indivisualvertex> {

int data;                                  //data associated with the vertex
double distanceFromSource;                 //will store the distances from the source vertex
int previousVertexOnShortestPathFromSource;//will store the previous vertex on the path
neighbours adjacentPointsList;             // neighbouring vertices stored in a linked list

//for sorting the vertices in the priority queue according to their distances from the source
public int compareTo(indivisualvertex other) {
    if (this.equals(other)) {
        return 0;
    } else if (this.distanceFromSource > other.distanceFromSource) {
        return 1;
    } else {
        return -1;
    }

}
}

Here's also my implementation for the edge relaxation method used after a vertex is chosen from the priority queue. Since there isn't any method to modify the elements inside of a priority queue, the code picks out the desired vertex, changes its distanceFromSource and previousVertexOnShortestPathFromSource variables and then puts it back, sorting the queue in the process.

 private void relax(indivisualvertex indx) {

 //traverse the neighbouring edges
 for (neighbours nbr = indx.adjacentPointsList; nbr != null; nbr = nbr.next){

        //condition where a vertex is unvisited and also provides a shorter path
        if (visited[nbr.pointer_of_vertex] == false && vertices[nbr.pointer_of_vertex].distanceFromSource > vertices[nbr.from].distanceFromSource + nbr.weight) {
            pq.remove(vertices[nbr.pointer_of_vertex]);
            vertices[nbr.pointer_of_vertex].distanceFromSource = vertices[nbr.from].distanceFromSource + nbr.weight;
            vertices[nbr.pointer_of_vertex].previousVertexOnShortestPathFromSource = nbr.from;
            pq.add(vertices[nbr.pointer_of_vertex]);
        }
    }
}

The implementation works fine. I need to know if there can be any disadvantages to to not building our own minimum heap for this purpose. Also, while relaxing the edges the method extracts the vertex and then puts it back. Is this an expensive operation? How much does it affects the performance of the algorithm?


texts:
This implements binary search on an array of cstrings. One thing I'm wondering about is it faster or slower to pass a variable as const i.e. len. Also strcmp() gets called a lot and since I can't find any specific details on how it works, is it worthwhile to make my own function? For example does it immediately return a value if the first character of each arguments are different?

/*
*IN: scope: array of cstrings to be searched
*IN: len: length of array
*IN: find: cstring to be found
*OUT: true if find is in scope, otherwise false
*/
bool binSrch(char** scope, const int len, char* find)
{
   int c, first, last, middle;

   first = 0;
   last = len - 1;
   middle = (first+last)/2;

   while( first <= last )
   {
      if (strcmp(scope[middle], find) < 0 )
         first = middle + 1;
      else if (strcmp(scope[middle], find) == 0)
      {
         return true;
      }
      else
         last = middle - 1;

      middle = (first + last)/2;
   }
   if ( first > last )
      return false;
}

EDIT: is there a way to intelligently choose the pivot point? For example if your looking in a phone book for a name starting with Z you wouldn't start at the middle you'd start closer to the back.


texts:
I have 30 icons, and after hover, different icons are shown. How can I write this shorter?

jQuery

$('#iconTech01').hover(
        function() {
            $('#iconTechBig01').stop(true, true).fadeIn("slow");
            $('#iconTech01 img').stop(true, true).fadeOut("slow");
        },
        function() {
            $('#iconTechBig01').stop(true, true).fadeOut("slow");
            $('#iconTech01 img').stop(true, true).fadeIn("slow");
    });

    $('#iconTech02').hover(
        function() {
            $('#iconTechBig02').stop(true, true).fadeIn("slow");
            $('#iconTech02 img').stop(true, true).fadeOut("slow");
        },
        function() {
            $('#iconTechBig02').stop(true, true).fadeOut("slow");
            $('#iconTech02 img').stop(true, true).fadeIn("slow");
    });

    $('#iconTech03').hover(
        function() {
            $('#iconTechBig03').stop(true, true).fadeIn("slow");
            $('#iconTech03 img').stop(true, true).fadeOut("slow");
        },
        function() {
            $('#iconTechBig03').stop(true, true).fadeOut("slow");
            $('#iconTech03 img').stop(true, true).fadeIn("slow");
    });

    $('#iconTech04').hover(
        function() {
            $('#iconTechBig04').stop(true, true).fadeIn("slow");
            $('#iconTech04 img').stop(true, true).fadeOut("slow");
        },
        function() {
            $('#iconTechBig04').stop(true, true).fadeOut("slow");
            $('#iconTech04 img').stop(true, true).fadeIn("slow");
    });

    $('#iconTech05').hover(
        function() {
            $('#iconTechBig05').stop(true, true).fadeIn("slow");
            $('#iconTech05 img').stop(true, true).fadeOut("slow");
        },
        function() {
            $('#iconTechBig05').stop(true, true).fadeOut("slow");
            $('#iconTech05 img').stop(true, true).fadeIn("slow");
    });

HTML


texts: Efficiently update string (in XML format) in MongoDb

texts:
public async void Execute()
{
    var mongoClient = new MongoClient(connectionStringBuilder.ToMongoUrl());
    var db = mongoClient.GetDatabase(connectionStringBuilder.DatabaseName);
    var jobInfoDocuments = db.GetCollection<JobInfoRecord>("JobInfoRecords");

    var encryptedKeys = new[] { "AccountKey", "PrivateKey", "APIKey", "DefectiveKeyGracefulExpiration" };
    var keyPatternMatching = string.Format("({0})", string.Join("|", encryptedKeys));

    // This string is used to scan tags (in the xml string) that contain "password" in their names (case-insensitive match mode),
    // and the tags which are called exactly the same as in the encryptedKeys
    var regex = string.Format(@"(?si)<([^\s<]*password[^\s<]*|{0})>.*?</\1>", keyPatternMatching);

    var filter = Builders<JobInfoRecord>.Filter.Regex(x => x.SerializedBackgroundJobInfo, new BsonRegularExpression(regex));
    var requiredDocuments = await jobInfoDocuments.Find(filter).ToListAsync();
    foreach (var document in requiredDocuments)
    {
        const string EmptyTag = "<$1></$1>";

        var jobIdFilter = Builders<JobInfoRecord>.Filter.Eq("_id", document.JobId);
        var newInfo = Regex.Replace(document.SerializedBackgroundJobInfo, regex, EmptyTag);
        var update = Builders<JobInfoRecord>.Update.Set("SerializedBackgroundJobInfo", newInfo);

        jobInfoDocuments.UpdateOneAsync(jobIdFilter, update).Wait();
     }
}

I'm changing the values of tags in xml string that contains "password" in their names (or called exactly the same as in the encryptedKeys) to empty tag.

I have a collection with 500 000 documents, of which I am performing updates each minute (hopefully) of approx. 3000 documents.

Do I have a bugs? Maybe I can increase performance of the update operation?

I'm using Mongo driver 2.0.2


texts:
I want you to pick my code apart and give me some feedback on how I could make it better or more simple. This code finds inorder successor in a binary tree.

public class Successor {

    private TreeNode root;

    private class TreeNode {
        TreeNode left;
        TreeNode right;
        TreeNode parent;
        int item;

        TreeNode(TreeNode left, TreeNode right, TreeNode parent, int item) {
            this.left = left;
            this.right = right;
            this.parent = parent;
            this.item = item;
        }
    }

    public void makeBinarySearchTree(int[] a) {
        for (int i : a) {
            addElement(i);
        }
    }

    public void addElement(int element) {
        if (root == null) {
            root = new TreeNode(null, null, null, element);
        } else {
            TreeNode prevNode = null;
            TreeNode node = root;

            while (node != null) {
                prevNode = node;
                // no definition exists, and for convenience we will stick to this one.
                if (element < node.item) {
                    node = node.left;
                } else {
                    node = node.right;
                }
            }

            if (element < prevNode.item) {
                prevNode.left = new TreeNode(null, null, prevNode, element);
            } else {
                prevNode.right = new TreeNode(null, null, prevNode, element);
            }
        }
    }

    private TreeNode search (int x) {
        TreeNode node = root;

        while (node != null) {
            if (x < node.item) {
                node = node.left;
            } else if (x  > node.item) {
                node = node.right;
            } else {
               return node;
            }
        }

        return null;
    }

    public Integer getSucessor(int val) {
        TreeNode node = getInorderSuccessor(search(val));
        return node == null ? null : node.item;
    }

    private TreeNode getInorderSuccessor(TreeNode node) {
        if (node == null) return null;

        if (node.right != null) {
            node = node.right;
            while (node.left != null) {
                node = node.left;
            }
            return node;
        } else {
            while (node.parent != null && node == node.parent.right) {
                node = node.parent;
            }
            return node.parent;
        }
    }
  }


texts:
Write a function that given a max argument will print a nicely aligned multiplication tables, for example, if max = 8

  1   2   3   4   5   6   7   8
  2   4   6   8  10  12  14  16
  3   6   9  12  15  18  21  24
  4   8  12  16  20  24  28  32
  5  10  15  20  25  30  35  40
  6  12  18  24  30  36  42  48
  7  14  21  28  35  42  49  56
  8  16  24  32  40  48  56  64

The code is pretty straightforward, but I am interested in any possible improvement.

def print_multiplication_table(max)
  pad = (1 + (max*max).to_s.length)
  puts (1..max)
    .to_a
    .product((1..max).to_a)
    .map{|a, b| a * b}
    .each_slice(max)
    .map{ |x| x.map(&:to_s).map{ |x| " " * (pad - x.length) + x}.join(' ')}
    .join("\n")
end

print_multiplication_table(8)


texts:
My goal is to get a list of related statementIds in order of most repeated.

In my database I have stems(Words):

+---------+-----------------+
|  Stem   |   StatementId   |
+---------+-----------------+
| Hello   | [2,46,62]       |
| Good    | [1,123,45]      |
| Morning | [23,2436,12312] |
+---------+-----------------+

My steps:

Get all statementIds

[6, 86],[6],[4],[3, 86],[...]
Create an empty object, and everytime i see a number,increase its value (or set to 1 if it hasen't been seen before)

 {2: 1, 3: 4, 4: 1, 6: 11, 85: 1, 86: 5, 87: 1, 89: 1}

Sort the object by the attribute and put it in an array of relevancy.

 ["6", "86", "3", "89", "87", "85", "4", "2"]

Full code:

getAllStatementIdFromStem = async (stems: string[]) => {
    const ids: { [key: number]: number } = {};
    await this.getBulkStem(stems).toArray((stems: Stem[]) =>
      stems.map(({ statements }) =>
        statements.forEach((statementId: number) => {
          typeof ids[statementId] === "undefined"
            ? (ids[statementId] = 1)
            : ids[statementId]++;
        })
      )
    );
    return Object.entries(ids)
      .sort((a, b) => a[1] - b[1])
      .reverse()
      .map(x => x[0]);
  };

Could I be doing something more effectively? I feel like I am doing way too many extra steps.


texts:
System I'm building has Users and Articles. Users can upvote/downvote Articles and cancel their votes if they want to. Each vote changes article's score. Score equals to sum of all vote values together.

So I created three models: User, Article, ArticleVote. Even though the most natural way for me would be to be able to do user.upvote(article), for separation of concerns reasons I've put it in ArticleVote model:

class ArticleVote < ActiveRecord::Base
  belongs_to :article
  belongs_to :user

  before_destroy :before_destroy

  validates :value, inclusion: {in: [1, -1]}

  def self.upvote(user, article)
    cast_vote(user, article, 1)
  end

  def self.downvote(user, article)
    cast_vote(user, article, -1)
  end

private

  def self.cast_vote(user, article, value)
    vote = ArticleVote.where(user_id: user.id, article_id: article.id).first_or_initialize
    vote.value = value
    vote.save!
    article.score += value
    article.save!
  end

  def before_destroy
    article.score -= value
    article.save
  end
end

So now I call upvote via ArticleVote.upvote(user, article) which doesn't look too bad, but because of Rails' behavior, this doesn't work very good.

If I want to cancel an upvote for example:

article = Article.find(528953)
# article.score = 5 at this point (for example)
vote = ArticleVote.where(user: current_user, article: article).first.destroy
# article.score = 5 !!!!
article.reload
# article.score = 4

So even though I already fetched an Article from database, and used instance of it to find ArticleVote I have to fetch it again to get the actual score value. I would expect ActiveRecord to automatically set vote.article to reference my article, so when I modify it's state, I wouldn't have to fetch it once again.

Is there a way I can avoid this unnecessary article.reload call and still have valid article.score value?

(Using Rails version 4)


texts: Transfer learning CNNs for image classification in TensorFlow

texts:
This code works, and I'm pretty sure it's mathematically/algorithmically correct:
model = tf.keras.applications.MobileNet(include_top=False,input_shape=INPUT_SHAPE)
model.trainable = False
model = tf.keras.Sequential([
    model,
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(
        1, "sigmoid"
    ),
])

try:
    model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=False),
                  optimizer=tf.keras.optimizers.RMSprop(),
                  metrics=['accuracy', tf.keras.metrics.AUC(curve="PR")])

    model.fit(train_dataset,
              epochs=2,
              validation_data=validation_dataset)
finally:
    for directory in tempdirs:
        rmtree(directory)

For completion, here is my dataset setup and imports, I'm being very verbose and not using tf.data.Dataset.from_tensor_slices and/or builtin random dataset utility functions, to keep things like my real workflow:
from tempfile import mkdtemp
from os import path, mkdir
from shutil import rmtree
import tensorflow as tf
import numpy as np
from PIL import Image

NUM_CLASSES = 2
INPUT_SHAPE = 256, 256, 3

def create_random_ds(tempdir):
    for class_num in range(NUM_CLASSES):
        directory = path.join(tempdir, 'class{}'.format(class_num))
        mkdir(directory)
        for i in range(20):
            Image \
              .fromarray((np.random.rand(*INPUT_SHAPE) * 255).astype('uint8')) \
              .convert('RGBA') \
              .save(path.join(directory, 'image{}.png'.format(i)))

    return tf.keras.preprocessing.image_dataset_from_directory(
        tempdir, labels='inferred', label_mode='int',
    )

tempdirs = mkdtemp(), mkdtemp()

train_dataset = create_random_ds(tempdirs[0])
validation_dataset = create_random_ds(tempdirs[1])

What do you think, is it correct, and how can it be improved?


texts: divide a range of numbers into groups of 10, 100, 1000, 10000 and so on

texts:
Given a start and end of a range as string, for example:

String start = "1230000";
String end   = "1285999";

Generate the shortest list possible with prefixes that include the whole range,
so that for any number from the given range there is a list elemnet which can be used as a prefix. For above example the list would contain:

 123,124,125,126,127,1280,1281,1282,1283,1284,1285

Explanation

The length of the strings may vary (6 - 12) but start.length() and end.length() are always equal.
The above range can be manually divided into the sub ranges:

    //1230000 - 1239999
    //1240000 - 1249999
    //1250000 - 1259999
    //1260000 - 1269999
    //1270000 - 1279999
    //1280000 - 1289999 this range is not completly included so make the ranges smaller with a factor 10
    //1280000 - 1280999
    //1281000 - 1281999
    //1282000 - 1282999
    //1283000 - 1283999
    //1284000 - 1284999
    //1285000 - 1285999

By storing the common substring of each start and end number of the subranges one can easliy validiate that any given number from the range starts with 123,124,125,126,127,1280,1281,1282,1283,1284 or 1285.

Here is a very naive but working solution to print the prefixes:

public static void main(String[] args) {
    String start = "1230000";
    String end   = "1285999";

    while(start.charAt(start.length()-1) == '0' && end.charAt(start.length()-1) == '9'){
        start = start.substring(0,start.length()-1);
        end = end.substring(0,end.length()-1);
    }

    long st = Long.parseLong(start);
    long en = Long.parseLong(end);
    for(long i = st; i <= en; ){
         if(i % 1000 == 0 && i + 999 <= en){
            System.out.println(i/1000);
            i = i + 1000;
        }
        else if(i % 100 == 0 && i + 99 <= en){
            System.out.println(i/100);
            i = i + 100;
        }
        else if(i % 10 == 0 && i + 9 <= en){
            System.out.println(i/10);
            i = i + 10;
        }
        else {
            System.out.println(i);
            i = i + 1;
        }
    }
}

For some not so nice ranges like the above I have to extend my for loop:

public static void main(String[] args) {
    String start = "1279995";
    String end   = "1285999";

    while(start.charAt(start.length()-1) == '0' && end.charAt(start.length()-1) == '9'){
        start = start.substring(0,start.length()-1);
        end = end.substring(0,end.length()-1);
    }

    long st = Long.parseLong(start);
    long en = Long.parseLong(end);
    for(long i = st; i <= en; ){
        if(i % 1000000 == 0 && i + 999999 <= en){
            System.out.println(i/1000000);
            i = i + 1000000;
        }
        else if(i % 100000 == 0 && i + 99999 <= en){
            System.out.println(i/100000);
            i = i + 100000;
        }
        else if(i % 10000 == 0 && i + 9999 <= en){
            System.out.println(i/10000);
            i = i + 10000;
        }
        else if(i % 1000 == 0 && i + 999 <= en){
            System.out.println(i/1000);
            i = i + 1000;
        }
        else if(i % 100 == 0 && i + 99 <= en){
            System.out.println(i/100);
            i = i + 100;
        }
        else if(i % 10 == 0 && i + 9 <= en){
            System.out.println(i/10);
            i = i + 10;
        }
        else {
            System.out.println(i);
            i = i + 1;
        }
    }
}

Which I found not very nice. Any ideas how to optimise my approach or do some one have another approach (I am open to everything, Regex, streams, recursion .. )?


texts:
I have an AD Group I keep up-to-date based on a CSV file. Users not present in the file should be removed from the AD Group.

#Import New List
$NewList= (Import-Csv E:\Group_Update\newlist.csv).SamAccountName

#backup old members
Get-ADGroupMember LAB_HR | select SamAccountName | Export-Csv E:\Group_Update\Group_B4_update.csv -NoTypeInformation

# Get old members
$oldusers= (Get-ADGroupMember LAB_HR | select SamAccountName).SamAccountName

# List group members not listed in the new list -- To be Deleted
$RemoveMembers= $oldusers | where {$NewList -notcontains $_}

# add new members
foreach ($user in $NewList) {

Add-ADGroupMember lAB_HR $user
Write-Host $user "has been added to Group"

}

# delete members not in the new list
foreach ($remove in $RemoveMembers){

Remove-ADGroupMember LAB_HR $remove -Confirm:$false

Write-Host $remove "has been removed from group "
}


texts:
Intro

I've decided to learn haskell, because I've always enjoyed the functional aspect of Python and want to explore other languages that use this concept. I'm still stumbling in the dark most of the time, so would greatly appreciate any improvements.

Description

Challenge source

A road system is considered efficient if it is possible to travel from any city to any other city by traversing at most 2 roads.

Example

For n = 6 and roads = [[3, 0], [0, 4], [5, 0], [2, 1], [1, 4], [2, 3], [5, 2]]

the output should be True

Here's how the road system can be represented:

Code

middlePoints k n roads  = [i | i <- [0..n-1], elem [k,i] roads || elem [i,k] roads]

thoughMiddlePoints k x n roads = or [(elem [points !! i,x] roads || elem [x, points !! i] roads) | i <- [0..(length points - 1)]]
    where
    points = middlePoints k n roads

reachable k x n roads = elem [k,x] roads || elem [x,k] roads || (thoughMiddlePoints k x n roads)

efficientRoadNetwork n roads = all (==True) [ all (==True)[(reachable i j n roads) | j <- [0..n-1], i /= j] | i <- [0..n-1]]


texts:
I have been coding for some time (3 years I think), and have recently been wondering if my coding pattern is any good. Any kind of feedback is welcome:

EDIT: The thing that concerns me most is that I have read a lot around that getters/setters are bad for OOP. Is this true?

//Point3D.as
public class Point3D
{
    private var _x:int;
    private var _y:int;
    private var _z:int;

    public function Point3D(tx:int = 0, ty:int = 0, tz:int = 0)
    {
        _x = tx;
        _y = ty;
        _z = tz;
    }

    public function get x():int { return _x; }
    public function set x(tv:int):void { _x = tv; }

    public function get y():int { return _y; }
    public function set y(tv:int):void { _y = tv; }

    public function get z():int { return _z; }
    public function set z(tv:int):void { _z = tv; }

}

//Geometry3D.as
public class Geometry3D
{
    private var _indices:Vector.<uint>;
    private var _vertices:Vector.<Number>;

    public function Geometry3D(tindices:Vector.<uint>,
    tvertices:Vector.<Number>)
    {
        _indices = tindices;
        _vertices = tvertices;
    }

    public function get indices():Vector.<uint> { return _indices; }
    public function get vertices():Vector.<Number> { return _vertices; }

}

//Primitive3D.as
public class Primitive3D
{
    private var _position:Point3D;
    private var _geometry:Geometry3D;

    public function Primitive3D(tx:int, ty:int, tz:int, tgeometry:Geometry3D)
    {
        _position = new Point3D(tx, ty, tz);
        _geometry = tgeometry;
    }

    public function get position():Point3D { return _position; }
    public function get geometry():Geometry3D { return _geometry; }

    public function render():void
    {
        //add render code here
    }

}

//TrianglePrimitive.as
public class TrianglePrimitive extends Primitive3D
{

    public function TrianglePrimitive(tx:int, ty:int, tz:int)
    {
        var indices:Vector.<uint> = Vector.<uint>([
        0, 1, 2]);
        var vertices:Vector.<Number> = Vector.<Number>([
        ]);

        var geo:Geometry3D = new Geometry3D(indices, vertices);
        super(tx, ty, tz, geo);
    }

    public function spin(tradians:Number):void
    {
        //add spin code here
    }

}

//Main.as
...
var tri:TrianglePrimitive = new TrianglePrimitive(0, 0, 0);
tri.position.z = -4;
tri.spin(Math.PI / 2); //90 degrees
tri.render();
...

Again, thanks a bunch for any feedback!


texts: Dictionary brute force on DES encrypted passwords

texts:
For a school project I am tasked to decrypt DES passwords.  I have sample code provided below and I want to know if this is the best method. Also should I code in error handling for the dictionary file or does the while condition take care of this?

#include <stdio.h>
#include <crypt.h>
#include <unistd.h>
#include <string.h>

#define _XOPEN_SOURCE

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./crack <password>\n");
        return 1;
    }

    int n = strlen(argv[1]);
    char password[n];

    for (int i = 0; i < n; i++)
    {
        password[i] = argv[1][i];
    }

    char salt[2];
    salt[0] = password[0];
    salt[1] = password[1];

    FILE *fp;
    fp = fopen("/usr/share/dict/words", "r");
    char line[50];

    while(fgets(line,50,fp)!= NULL)
    {
        line[strlen(line) - 1] = '\0';
        if (!strcmp(argv[1], crypt(line, salt)))
        {
            printf("Password found!\n");
            return 0;
        }
    }
    printf("Not found\n");
    fclose(fp);
    return 0;
}


texts: Determining whether one vector is a prefix of the other

texts:
I am learning from C++ Primer 5th edition. This is exercise 5.17:

  Given two vectors of ints, write a program to determine whether one vector is a prefix of the other. For vectors of unequal length, compare the number of elements of the smaller vector. For example, given the vectors containing 0, 1, 1, and 2 and 0, 1, 1, 2, 3, 5, 8, respectively your program should return true.

#include <iostream>
#include <string>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::end;
using std::begin;

int main()
{
    vector<int> i{0,1,1,2}, n{0,1,1,2,3,5,8}, smlr;
    char sml, bgr;
    long j = (i.end()-i.begin()) ,k = (n.end()-n.begin());
    if ( j > k)
    {
        sml = 'n', bgr = 'i', smlr = n;
    }

    else if (j < k)
    {
        sml = 'i', bgr = 'n', smlr = i;
    }
    else if ( j == k)
    {
        cout << "both are of equal length";

        for (vector<int>::size_type a = 0; a < i.size() ; ++a ) {
            if (i[a] != n[a]) {
                cout << "both vectors are unequal and are not prefixes of the other";
                return -1;
            }
        }
    }

    for ( int l = 0; l < smlr.size() && i[l] == n[l]; ++l )
    {
            if(l == (smlr.size()-1))
            {
            cout << sml << " is a prefix of " << bgr;
            return 0;
            }
    }
    cout << sml << " is not a prefix of " << bgr;
    return 0;
}

Is my code efficient?
Am I using too many variables?
Is it better to write more code and use less variables or use less variables and less code?

I am a beginner, so please be harsh.