texts: Python file reader/writer, with processing pipeline and context manager

texts:
The following code does three things:

The filename is determined by the RawData class
The reader and writer send data through a processing pipeline
(Hopefully) makes changes and extensions easy

Regarding (2), the processing pipeline consists of "processors", that can process and deprocess data.  For example, if you run the code below and look in ortho_animals.txt, you'll see the JSON version of a dict with (keys, values) reversed.

I left comments out to keep the size of the code to a minimum.  Please let me know what you think, with a particular eye on the class designs and interactions.

import contextlib
import json

class Processor(object):

  @classmethod
  def process(cls, data):
    raise NotImplementedError

  @classmethod
  def deprocess(cls, data):
    raise NotImplementedError

class JsonProcessor(Processor):
  @classmethod
  def process(cls, data):
    return json.dumps(data)

  @classmethod
  def deprocess(cls, data):
    return json.loads(data)

class SwapProcessor(Processor):
  @classmethod
  def process(cls, data):
    return cls.swap(data)

  @classmethod
  def deprocess(cls, data):
    return cls.swap(data)

  @classmethod
  def swap(cls, data):
    return {v: k for k, v in data.iteritems()}

class AggregateProcessor(Processor):
  def __init__(self, processors):
    self.processors = processors

  def process(self, data):
    return reduce(lambda d, kls: kls.process(d), self.processors, data)

  def deprocess(self, data):
    return reduce(lambda d, kls: kls.deprocess(d), self.processors[::-1], data)

class RawReader(object):
  def __init__(self, file_obj, processor):
    self._file = file_obj
    self._processor = processor

  def read(self):
    data = self._file.read()
    return self._processor.deprocess(data)

class RawWriter(object):
  def __init__(self, file_obj, processor):
    self._file = file_obj
    self._processor = processor

  def write(self, data):
    new_data = self._processor.process(data)
    self._file.write(new_data)

class RawData(object):
  processors = [SwapProcessor, JsonProcessor]
  aggregator = AggregateProcessor(processors)

  def __init__(self, obj_type, key):
    self.obj_type = obj_type
    self.key = key

  def _build_filename(self):
    return self.obj_type + '_' + self.key + '.txt'

  @contextlib.contextmanager
  def writer(self):
    filename = self._build_filename()
    with open(filename, 'w') as f:
      yield RawWriter(f, self.aggregator)

  @contextlib.contextmanager
  def reader(self):
    filename = self._build_filename()
    with open(filename, 'r') as f:
      yield RawReader(f, self.aggregator)

if __name__ == '__main__':
  data = {'cats': 'suck', 'dogs': 'rule'}
  rd = RawData('ortho', key='animals')

  with rd.writer() as writer:
    writer.write(data)

  with rd.reader() as reader:
    new_data = reader.read()

  assert(new_data['cats'] == data['cats'])


texts: Receiving a user's registration submission and inserting row into database #2

texts:
I asked this question before and mickmackusa and Your Common Sense gave me some good answers. I went over them and made as much changes as I could because some of the code didn't work properly for me. So again i want to know if this is a good way to have my registration code for people to sign up.
//check if form is submitted
if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register'])) {

    // looks like a hack, send to index.php
    header('Location: ../../index.php');
    die();
}

require '../../config/connect.php';
$con = new mysqli(...$dbCredentials);

$first_name = $_POST['first_name'] ?? '';
$last_name = $_POST['last_name'] ?? '';
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
$pw = $_POST['pw'] ?? '';
$pw2 = $_POST['pw2'] ?? '';

$errors = [];

if (!trim($first_name)) {

    $errors[] = "Fill in first name to sign up";
}
if (!ctype_alnum($first_name)) {
    $errors[] = "Invalid first name, it only may contain letters or digits";
}

if (!trim($last_name)) {

    $errors[] = "Fill in last name to sign up";
}
if (!ctype_alnum($last_name)) {
    $errors[] = "Invalid last name, only letters and/or digits.";
}

if (!trim($username)) {

    $errors[] = "Fill in last name to sign up";
}
if (!ctype_alnum($username)) {
    $errors[] = "Invalid last name, only letters and/or digits.";
}

if (!trim($pw)) {
    $errors[] = "Fill in password to sign up";
}
if (!trim($pw2)) {
    $errors[] = "Confirm password to sign up";
}

if (!trim($email)) {
    $errors[] = "Fill in email to sign up";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Invalid email";
}

if ($pw !== $pw2) {

    echo "Your passwords do not match";
}

if (!$errors) {

    $check_email = $con->prepare("SELECT username FROM users WHERE username=?");
    $check_email->bind_param("s", $username);
    $check_email->execute();
    $row = $check_email->get_result()->fetch_assoc();

    if ($row) {

        echo "That username is already in use";
        die();
    }
}

if (!$errors) {

    $check_username = $con->prepare("SELECT email FROM users WHERE email=?");
    $check_username->bind_param("s", $email);
    $check_username->execute();
    $row = $check_username->get_result()->fetch_assoc();

    if ($row) {
        echo "That email is already in use";
        die();
    }
}

if (!$errors) {

    $pw = password_hash($_POST['pw'], PASSWORD_BCRYPT, array('cost' => 14));

    $stmt = $con->prepare("INSERT INTO users (first_name, last_name, username, email, pw)
        VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("sssss", $first_name, $last_name, $username, $email, $pw);
    $stmt->execute();

    $_SESSION["id"] = $_POST['username'];
    header("Location: ../../index.php");
    exit();

} else {
    // The foreach construct provides an easy way to iterate over arrays.
    foreach ($errors as $error) {
        $errors[] = 'An error occurred.';
    }

}


texts: Proxying Socket.io requests and other HTTP requests

texts:
I have written a proxy server using node HTTP proxy, which can also be found on Github. I am bit unsure about whether I am proxying the web sockets correctly.

/* This is a proxy server that uses http-proxy. It can be used to host multiple websites on your computer.
 * It proxies http and websocket requests as well, which are useful for socket.io.
 * It logs someof the useful pieces of information for the requests. Also it does not log requests from a particular location i.e. from your own network.
 * To use, please replace yourwebsite with the domain name of your website. Also replace yourroutername.dyndns.org with the name for your router. If you are not sure about this, you may comment the call to the function logIfNotFromMyself.
 * Author : Ankit Jain ankitjainst at gmail dot com
 */
var http = require('http'),
    httpProxy = require('http-proxy'),
    proxy = httpProxy.createProxyServer({ws:true}),
    url = require('url');
var fs = require('fs');

proxy.on('error', function (err, req, res) {
  res.writeHead(500, {
    'Content-Type': 'text/plain'
  });

  res.end('Something went wrong. And we are reporting a custom error message.');
});

var proxyServer = http.createServer(function(req, res) {
if(req.headers != null && req.headers.host != null)
{
    var hostname = req.headers.host.split(":")[0];
    var pathname = url.parse(req.url).pathname;

    logMsg = '\n'+req.url+','+req.headers['referer']+","+req.connection.remoteAddress+','+getDateTime()+','+req.headers['user-agent'];

    switch(hostname)
    {
    case 'yourwebsite.com':
    case 'www.yourwebsite.com':
        proxy.web(req, res, { target: 'http://192.168.0.101:6002' });
        logIfNotFromMyself('mywebsitelogs.txt', logMsg, req.connection.remoteAddress);
        break;
    default:
        console.log("defaulting for "+ hostname);
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.write('Page is not available');
        res.end();
    }
}});

proxyServer.on('upgrade', function (req, socket, head) {
    if(req.headers != null && req.headers.host != null)
    {
        var hostname = req.headers.host.split(":")[0];
        var pathname = url.parse(req.url).pathname;
        switch(hostname)
        {
            case 'yourwebsite.com':
            case 'www.yourwebsite.com':
                console.log('proxying '+ req.url);
                proxy.ws(req, socket, head, { target: 'http://192.168.0.101:6002' });
            break;
        }
    }
});

proxyServer.listen(4000, function() {
    console.log('proxy listening on port 4000');
});

function getDateTime() {
    var date = new Date();
    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;
    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;
    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;

    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}

function logIfNotFromMyself(file, message, ip)
{
    var dns = require('dns');

    dns.lookup('yourroutername.dyndns.org', function onLookup(err, addresses, family) {
        var ipParts = ip.split(':');
        var theIP = ipParts[ipParts.length-1];

        //console.log('my address is', addresses+ 'ip of request is '+theIP);
        if (!(theIP == addresses))
            fs.appendFile(file, message, function (err) {  if (err) throw err; });
        else
            fs.appendFile(file+".self", message, function (err) {  if (err) throw err; });
    });
}


texts:
I'm using mongoose to seed a mongodb database based on my mongoose models.
I'm particular interested in improving the seed code.

I have two models, an article and a category.
The relationship between the models are as follows:

A category has many articles
An article has a parent category

The model schemas I'm using are listed below:

The category schema

var mongoose = require('mongoose');

var categorySchema = mongoose.Schema({
    title: String,
    articles : [{ type: mongoose.Schema.Types.ObjectId, ref: 'Article' }]
});

mongoose.model('Category', categorySchema);

The article schema

var mongoose = require('mongoose');

var articleSchema = mongoose.Schema({
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
    title: String
});

mongoose.model('Article', articleSchema);

I'm using the following code to seed:

Seeding the category

var CategoryModel = require('mongoose').model('Category');

exports.seedCategories = function seedCategories() {
    CategoryModel.find({}).exec(function (err, collection) {
        if (collection.length === 0) {
            CategoryModel.create({ title: 'Category One' });
            CategoryModel.create({ title: 'Category Two' });
        }
    });
}

Seeding the article

var CategoryModel = require('mongoose').model('Category');
var ArticleModel = require('mongoose').model('Article');

exports.seedArticles = function seedArticles() {

    ArticleModel.find({}).exec(function (err, collection) {
        if (collection.length === 0) {
            seedArticle('Category One', 'Article One');
            seedArticle('Category One', 'Article Two');
            seedArticle('Category Two', 'Article Three');
            seedArticle('Category Two', 'Article Four');
        }
    });

    function seedArticle(categoryTitle, articleTitle) {
        var parentCategory;
        CategoryModel.findOne({ title: categoryTitle }).exec()
            .then(function (category) {
                parentCategory = category;
                return ArticleModel.create({ title: articleTitle, _category: parentCategory._id });
            }).then(function (article) {
                parentCategory.articles.push(article._id);
                parentCategory.save(function (saveError) {
                    if (!saveError) {
                        console.log("Seeded article");
                    } else {
                        console.log(saveError);
                    }
                });
            });
    }
}

I'm particularly interested in methods for preventing the Christmas tree of doom, and removing the obstruent error handling. Any recommendations are welcome, and thanks in advance for the help. I hope this code helps others.

Mongoose have just implemented promises returned from saves, so that should help. It will be available in mongoose 3.10.


texts: React - am i overusing props or is it exactly how they are suppoused to be used?

texts:
After learning some basic concepts of ReactJs I tried to create a form. Now I'm not sure if I'm using props the way they are intented so here is sample of my relevant code:

<Input type={"text"} placeholder={"Username"} id={"registerUsername"} class={"input"} />
<Input type={"password"} placeholder={"Password"} id={"registerPassword"} class={"input"} />

Input class:

export class Input extends React.Component{
 render(){
  return (
   <input type={this.props.type} placeholder={this.props.placeholder} id={this.props.id} className={this.props.class} />
  )
 }
}

When passing many props in one component for whatever reason it feels like I'm overusing them, but maybe that's just me?


texts:
Struggling to write a simple tool to quickly sum up the last reported versions in a bunch of files. I'm using a named pipe to get the count out the loop for the final value, but the $version isn't populated which I don't understand.

mkfifo mypipe
for i in stats/*
do
    tail -1 $i
done | sort -n > mypipe &

while read version
do

    if test "$version" = "$last"
    then
        count=$(($count + 1))
    else
        echo $last $count
        count=1
        last=$version
    fi

done < mypipe

# $version is not printed, what's the workaroud?
echo version $version count $count

Perhaps people can suggest a better cleaner more suck less solution?


texts: A push style parser combinator in Haskell

texts:
Usually, parser combinators in Haskell based on the parser type like

newtype Parser t r = Parser ([t] -> [(r,[t])])

This allows back tracking and multiple results. However I think it would be good to have it in "push" style, means the parser will have a set of result when no more input given, and have a transition function that for a given token, results in a new state of the parser. This results in the defintion

newtype PushParser t r = PushParser ([r], Maybe (t -> PushParser t r))

(We could have a data constructor that have two fields, however I prefer to use the more efficient newtype keyword so have to have only one field as a tuple)

To parse a list of tokens, we define the parse function as following:

parse :: PushParser t r -> [t] -> [r]
--No input, rs is the result
parse ~(PushParser (rs, _)) [] = rs
--No parsing function, this is an error state. No result
parse (PushParser (_,Nothing)) _ = []
--Otherwise, drop the results, apply the pasing function with the input and continue
parse (PushParser (_,Just f)) (t:ts) = parse (f t) ts

We can then define a fmap to make it a Functor like the following:

instance Functor (PushParser t) where
    fmap f ~(PushParser (r,mg)) = PushParser ((map f r), do {g<-mg; return (fmap f.g)})

Instance of Applicative is more tricky, but the easiest way is to make it depend on the not yet implemented instance of Monad.

instance Applicative (PushParser t) where
    pure x = PushParser ([x],Nothing)
    pf <*> pv = do
        f <- pf
        v <- pv
        return (f v)

But before giving the definition of Monad I want to introduce the definition of Alternative:

instance Alternative (PushParser t) where
    empty = PushParser ([],Nothing)
    (PushParser (r1,Nothing)) <|> (PushParser (r2,f)) = PushParser ((r1++r2), f)
    (PushParser (r1,f)) <|> (PushParser (r2,Nothing)) = PushParser ((r1++r2), f)
    (PushParser (r1,Just f1)) <|> (PushParser (r2,Just f2)) =
        PushParser ((r1 ++ r2), Just (\t -> f1 t <|> f2 t))

I have tried out different ways for the instance of Monad, but finally I believe the best way to give definition of (>>=) is to define unwrap (or join in the monad library) first.

instance Monad (PushParser t) where
    p >>= f = unwrap (fmap f p) where
        unwrap ~(PushParser (prs, mf)) =
            foldr (<|>) (PushParser ([], do { f<-mf; return (unwrap.f)})) prs

The above works perfectally fine, and although it does not make sense to make it an instance of Parser (in Text.Parser.Combinators) as we don't allow trace back, the other combinators that only requires Alternative worked perfectally fine.

However, the performance seems to be too bad. It is possibly as it keeps all possible parsing path and so consumes too much memory. For example, a simple parse (many (some (char '.'))) "...." will return 8 results, with all combinations of dots.

But I think there should be some way to improve the performance. Please advise me how to improve on this.


texts:
This is one of my first useful scripts. I run it on a highlighted text selection within Notepad++, but I've provided a sample formula and commented out the Scintilla-specific references.

I'm a rank amateur: Am I using good idiom? Is my approach to a state machine sensible?

# input_text = editor.getSelText()
input_text = '=HLOOKUP(TablePeriods[[#Headers],[YearMonth]],TablePeriods[[#All],[YearMonth]],MATCH([@Date],INDIRECT("TablePeriods[[#All],["&[@Account]&"]]"),-1))'

# initialize the state table
EVENTS = 11
STATES = 7
state_table = [[[0,0] for x in range(EVENTS)] for x in range(STATES)]

# event list and corresponding state table
event_list =     [ "\"",   "&",   "(",   ")",   ",", "\n\r\t ",    "[",   "]",   "{",   "}"    ] # last event is anything that doesn't match one of the other actions
state_table[0] = [[1,0], [0,1], [5,0], [0,3], [0,4],     [0,5],  [2,0], [0,0], [6,0], [0,0], [0,0]] # normal state
state_table[1] = [[0,0], [1,0], [1,0], [1,0], [1,0],     [1,0],  [1,0], [1,0], [1,0], [1,0], [1,0]] # double-quote comment
state_table[2] = [[2,0], [2,0], [2,0], [2,0], [2,0],     [2,0],  [3,0], [0,0], [2,0], [2,0], [2,0]] # inside bracketed table reference
state_table[3] = [[3,0], [3,0], [3,0], [3,0], [3,0],     [3,0],  [4,0], [2,0], [3,0], [3,0], [3,0]] # inside double-bracketed table reference
state_table[4] = [[4,0], [4,0], [4,0], [4,0], [4,0],     [4,0], [-1,0], [3,0], [4,0], [4,0], [4,0]] # inside triple-bracketed table reference (I don't think this exists)
state_table[5] = [[1,2], [0,2], [5,2], [0,0], [0,2],     [0,5],  [2,2], [0,2], [0,2], [0,2], [0,2]] # found left-paren; only wrap and insert if not empty, like =row()
state_table[6] = [[6,0], [6,0], [6,0], [6,0], [6,0],     [6,0],  [6,0], [6,0], [6,0], [0,0], [6,0]] # inside curly-braced array

# initialize the state, parenthesis depth, and output text
current_state = 0
paren_depth = 0
output_text = ""

# define the tab and new line characters
TAB_CHAR = "\t"
NEW_LINE = "\r\n"

for z in input_text:
    for a in range(len(event_list)):
        if z in event_list[a]:
            takeaction = state_table[current_state][a][1]
            current_state = state_table[current_state][a][0]
            break
    else:
        takeaction = state_table[current_state][-1][1] # this sets takeaction to the value when the test character does not match any event
        current_state = state_table[current_state][-1][0] # this sets current_state to the value when the test character does not match any event
    if current_state == -1:
        current_state = 5 # -1 is an error and should be handled with some sort of error operation
    if takeaction == 0: # just pass the characters along
        output_text += z
    elif takeaction == 1: # place character at same depth as only one on line
        output_text += NEW_LINE + TAB_CHAR*paren_depth + z + NEW_LINE + TAB_CHAR*paren_depth
    elif takeaction == 2: # previous character was a left paren and this one is not a right-paren
        paren_depth = paren_depth + 1
        output_text += NEW_LINE + TAB_CHAR*paren_depth + z
    elif takeaction == 3: # character is a right paren not immediately following a left paren
        paren_depth = paren_depth - 1
        output_text += NEW_LINE + TAB_CHAR*paren_depth + z
    elif takeaction == 4: # character is a comma, so start a new line at the paren depth
        output_text += z + NEW_LINE + TAB_CHAR*paren_depth
    elif takeaction == 5: # strip whitespace from the input outside of quotes
        pass
    else:
        pass # should raise error, since the state table includes more actions than are defined

# editor.replaceSel(output_text)
print(output_text)

My code, without sample, is on Gisthub.


texts:
The code displays a video that will play a video and then display some text on the screen at specific locations on the video screen.

The code works but I would like to see if I could change somethings to make it better and how I would do that. You should be able to just copy the code into a web browser and it should work fine.

<!doctype html>
<html>
<head>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
var videoElement;
var videoDiv;

function eventWindowLoaded() {
    videoElement = document.createElement("video");
    videoDiv     = document.createElement('div');

    document.body.appendChild(videoDiv);
    videoDiv.appendChild(videoElement);
    videoDiv.setAttribute("style", "display:none;");
    var videoType = supportedVideoFormat(videoElement);

    videoElement.addEventListener("canplaythrough",videoLoaded,false);
    videoElement.setAttribute("src", "muirbeach." + videoType);
}

function supportedVideoFormat(video) {
    var returnExtension = "";
    if (video.canPlayType("video/webm") =="probably" || video.canPlayType("video/webm") == "maybe") {
        returnExtension = "webm";
    } else if(video.canPlayType("video/mp4") == "probably" || video.canPlayType("video/mp4") == "maybe") {
        returnExtension = "mp4";
    } else if(video.canPlayType("video/ogg") =="probably" || video.canPlayType("video/ogg") == "maybe") {
        returnExtension = "ogg";
    }
    return returnExtension;
}

function canvasSupport () {
    return Modernizr.canvas;
}

function videoLoaded() {
    canvasApp();
}

function canvasApp() {
    function  drawScreen () {
        //Background and redraw background screen
        context.fillStyle = '#ffffaa';
        context.fillRect(0,0,theCanvas.width,theCanvas.height);
        context.strokeStyle = '#000000';
        context.strokeRect(5,5,theCanvas.width-10,theCanvas.height-10);

        context.drawImage(videoElement,85,30);

        context.fillStyle = "#000000";
        context.font      = "10px sans";
        context.fillText  ("Duration:"     + videoElement.duration,10,280);
        context.fillText  ("Current time:" + videoElement.currentTime,260,280);
        context.fillText  ("Loop: "        + videoElement.loop,10,290);
        context.fillText  ("Autoplay: "    + videoElement.autoplay,80,290);
        context.fillText  ("Muted: "       + videoElement.muted,160,290);
        context.fillText  ("Controls: "    + videoElement.controls,240,290);
        context.fillText  ("Volume: "      + videoElement.volume,320,290);

        //Display Message
        for (var i =0; i < messages.length ; i++) {
            var tempMessage = messages[i];
            if (videoElement.currentTime > tempMessage.time) {
                context.font = "bold 14px sans";
                context.fillStyle    = "#FFFF00";
                context.fillText  (tempMessage.message,  tempMessage.x                                                                 ,
                            tempMessage.y);
            }
        }
    }

    var messages = new Array();
    messages[0] = {time:7,message:"", x:0 ,y:0};
    messages[1] = {time:1,message:"I love David Mathews Band!", x:90 ,y:200};
    messages[2] = {time:4,message:"Look At Those Waves!", x:240 ,y:240};
    messages[3] = {time:8,message:"Look At Those Rocks!", x:100 ,y:100};

    var theCanvas = document.getElementById('canvasOne');
    var context   = theCanvas.getContext('2d');
    videoElement.play();

    function gameLoop() {
        window.setTimeout(gameLoop, 20);
        drawScreen();
    }

    gameLoop();
}
</script>

</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
       <canvas id="canvasOne" width="500" height="300"></canvas>
</div>

</body>
</html>


texts: Implement array element swap in a functional language

texts:
Sorting algorithms involve swapping element positions in an array. This is my implementation of swap:

let swap (array: 'a[]) (first: int) (second: int): 'a[] =
    let originalFirst = array.[first]
    array.[first] <- array.[second];
    array.[second] <- originalFirst;
    array

Though it works, I am wondering whether mutating an array is canonical F#. If not, what is the canonical way to swap array element positions?

The F# documentation says that arrays are mutable. Am I misunderstanding immutability?

Any and all comments on the above implementation are most welcome.


texts:
Write a C program that will implement the basic operations of table processors.
The input will be text data read from a .txt file, operations will be defined using terminal arguments, and the output will be in a .txt file as well.
Program should be run the following way:
./main [-d delimiter] [name of the function for the table] <in.txt >out.txt

Where the -d argument determines which symbols can be interpreted as separators of single cells, by default the delimiter is a space character.
Multiple cases of the same sign in the delimiter are ignored.
The first sign in the delimiter character will be used as the separator of output values.
name of the function is the identifier of the function that will be called to perform certain tasks on the table. <in.txt redirects reading from stdin to reading from in.txt, >out.txt redirects outputting to stdout to outputting to out.txt.
Here's what I wrote:
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
    if((argc > 2) && (strcmp(argv[1], "-d") == 0)) {
        char delim = *argv[2];

        for (int i; (i = getchar()) != EOF; ) {
            if(i == '\n')
                putchar(i);

            if(!((i >= '0' && i <= '9') || (i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z')) ){
                putchar(delim);
                continue;
            }
            putchar(i);
        }

    }

    else if((argc == 2) && strcmp(argv[1], "-d") == 0) {
        char delim = ' ';

        for (int i; (i = getchar()) != EOF; ) {
            if(i == '\n')
                putchar(i);

            if(!((i >= '0' && i <= '9') || (i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z')) ){
                putchar(delim);
                continue;
            }
            putchar(i);
        }

    }

    return 0;
}

The code works and does what it's supposed to, but I am not sure about the effectivity of the implementation. The requirements are: input table can't be an empty file, maximum length of a row (both input & output) is 10KiB, otherwise an error message should be shown. Using global variables isn't allowed, preprocessor macro #define is. Functions for working with files and dynamic memory allocation aren't allowed as well.
What are the ways to change my code?


texts: Variable declaration closer to usage Vs Declaring at the top of Method

texts:
As part of our sprints, we do peer review each others code.

Here is the code that I am reviewing.

public void SendEmail()
{

    string emailAddress = string.Empty;
    string managerEmailAddress = string.Empty;

    if (//condition)
    {
        //do something
        //Retrieve emailAddress and managerEmailAddress
        EmailMessage.To = emailAddress;
        EmailMessage.CC = managerEmailAddress;
    }
}

The suggestion from Resharper was to have the string declarations closer to the usage. However, my colleague suggest that it is not a good idea to have them closer to the usage and have them declared right at the beginning. And, I sort of agree with him because for methods where the variables are used in multiple places with different values being assigned depending upon conditions...it would make sense to have them all grouped right at the top but for smaller methods, where there is just one if condition, stick them along with the usage (for instance the above mentioned code).

What do you think?


texts:
Challenge: Design a cash register program

Specifications: Your register currently has the following bills/coins within it:

  'PENNY': .01,

  'NICKEL': .05,

  'DIME': .10,

  'QUARTER': .25,

  'HALF DOLLAR': .50,

  'ONE': 1.00,

  'TWO': 2.00,

  'FIVE': 5.00,

  'TEN': 10.00,

  'TWENTY': 20.00,

  'FIFTY': 50.00,

  'ONE HUNDRED': 100.00

  Your program should accept as its first argument a path to a filename.
  The input file contains several lines. Each line is one test case.
  Each line contains two numbers which are separated by a semicolon.
  The first is the Purchase price (PP) and the second is the cash(CH).

  For each set of input produce a single line of output,
  which is the cashBack to be returned to the customer.
  In case the CH < PP, print out ERROR. If CH == PP, print out ZERO.
  For all other cases print the amount that needs to be returned,
  in terms of the currency values provided.
  The output should be sorted in highest-to-lowest order

Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CashRegister {
    public static void main(String[] args) throws FileNotFoundException {
        File file = new File(args[0]);
        Scanner fileInput = new Scanner(file);

        while (fileInput.hasNextLine()) {
            printCashChange(fileInput.nextLine());
        }
    }

    private static void printCashChange(String line) {
        float pp = Float.parseFloat(line.split(";")[0]);
        float ch = Float.parseFloat(line.split(";")[1]);

        System.out.println(getCashChange(pp, ch));
    }

    private static String getCashChange(float price, float cash) {
        if (cash < price) { return "ERROR"; }
        if (cash == price) { return "ZERO"; }
        float cashBack = cash - price;

        StringBuilder change = new StringBuilder();

        while (cashBack > 0.01f) {
            if (cashBack >= 100.0f) {
                change.append("ONE HUNDRED");
                cashBack -= 100.0f;
            } else if (cashBack >= 50.0f) {
                change.append("FIFTY");
                cashBack -= 50.0f;
            } else if (cashBack >= 20.0f) {
                change.append("TWENTY");
                cashBack -= 20.0f;
            } else if (cashBack >= 10.0f) {
                change.append("TEN");
                cashBack -= 10.0f;
            } else if (cashBack >= 5.0f) {
                change.append("FIVE");
                cashBack -= 5.0f;
            } else if (cashBack >= 2.0f) {
                change.append("TWO");
                cashBack -= 2.0f;
            } else if (cashBack >= 1.0f) {
                change.append("ONE");
                cashBack -= 1.0f;
            } else if (cashBack >= 0.5f) {
                change.append("HALF DOLLAR");
                cashBack -= 0.5f;
            } else if (cashBack >= 0.25f) {
                change.append("QUARTER");
                cashBack -= 0.25f;
            } else if (cashBack >= 0.1f) {
                change.append("DIME");
                cashBack -= 0.1f;
            } else if (cashBack >= 0.05f) {
                change.append("NICKEL");
                cashBack -= 0.05f;
            } else {
                change.append("PENNY");
                cashBack -= 0.01f;
            }
            change.append(",");
        }
        change.setLength(change.length() - 1);

        return change.toString();
    }
}

Every now and then one creates a solution that works but really comes off as sub-optimal, this is one of those times for this CRer. It really seems verbose, I'd appreciate any tips on improving performance and general structure.


texts:
I have implemented a metaclass in Python 3 that, apart from the usual instance constructor (i.e. __init__), enables you to define a class constructor (as a class method that I called __init_class__). The metaclass extends abc.ABCMeta so it supports abstract classes, i.e. the class constructor is not called if a class is abstract.

I've written up some tests for it, they pass, and the metaclass also works in practice for me, but I'd like to know:

Is this even a good approach for adding a class constructor functionality?
Are there any problematic corner-cases that I might run into with my code?
Am I testing it correctly?
Any comments about my code being (or not) pythonic?

Implementation:

import abc
import inspect

class MyType(abc.ABCMeta):
    """
        Metaclass.

        It adds extra functionality of an optional class constructor, which might by added
        to the class by adding a class method __init_class__(cls) to the class definition.

        Class constructor takes no arguments.
    """

    def __init__(cls, name, bases, nmspc):
        super().__init__(name, bases, nmspc)
        cls.__has_init_class__ = hasattr(cls, '__init_class__')
        if cls.__has_init_class__ and not inspect.isabstract(cls):
            cls.__init_class__()

Tests:

import unittest

class MyTypeTests(unittest.TestCase):
    """ Unit tests for MyType metaclass. """

    def test_class_constructor(self):
        """ Is the class constructor invoked? """

        class WithoutInit(metaclass=MyType): # pylint: disable=R0903
            """ Dummy class. """
            initialized = False

        class AbstractWithoutInit(metaclass=MyType): # pylint: disable=R0903
            """ Dummy abstract class. """
            initialized = False
            @abc.abstractmethod
            def spam(self):
                """ Dummy abstract method. """
                pass

        class WithInit(metaclass=MyType): # pylint: disable=R0903
            """ Dummy class with class constructor. """
            initialized = False
            @classmethod
            def __init_class__(cls):
                cls.initialized = True

        class AbstractWithInit(metaclass=MyType): # pylint: disable=R0903
            """ Dummy abstract class with class constructor. """
            initialized = False
            @abc.abstractmethod
            def spam(self):
                """ Dummy abstract method. """
                pass
            @classmethod
            def __init_class__(cls):
                cls.initialized = True

        self.assertFalse(WithoutInit.initialized)
        self.assertFalse(AbstractWithoutInit.initialized)
        self.assertTrue(WithInit.initialized)
        self.assertFalse(AbstractWithInit.initialized)


texts: Matrix multiplication using functions in C

texts:
This exercise surprised me a little bit. I did not expect that gcc (GCC 6.3.0 in the MinGW suite) would use the C11 standard by default, which I realised after I read the documentation. Here's the code that compiles without any errors or warnings:

matrix.c

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

void input(int m, int n, int a[m][n])
{
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            printf("%d, %d : ", i, j);
            scanf("%d", &a[i][j]);
        }
    }
}

void print(int m, int n, int a[m][n])
{
    int i, j;
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("%3d ", a[i][j]);
        }
        printf("\n");
    }
}

void multiply(int m, int n, int p, int a[m][n], int b[n][p], int c[m][p])
{
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < p; j++) {
            c[i][j] = 0;
            for (int k = 0; k < n; k++) {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }
}

int main()
{
    int r1, c1, r2, c2;
    printf("Row and column for matrix #1 :\n");
    scanf("%d %d", &r1, &c1);
    printf("Row and column for matrix #2 :\n");
    scanf("%d %d", &r2, &c2);

    if (r2 != c1) {
        printf("The matrices are incompatible.\n");
        exit(EXIT_FAILURE);
    }

    int mat1[r1][c1], mat2[r2][c2], ans[r1][c2];
    printf("Enter elements of the first matrix.\n");
    input(r1, c1, mat1);
    printf("The elements of the first matrix are :\n");
    print(r1, c1, mat1);
    printf("Enter elements of the second matrix.\n");
    input(r2, c2, mat2);
    printf("The elements of the second matrix are :\n");
    print(r2, c2, mat2);

    multiply(r1, r2, c2, mat1, mat2, ans);
    printf("The product is :\n");
    print(r1, c2, ans);

    return EXIT_SUCCESS;
}

Feedback and criticism on any and all aspects are welcome.


texts: Django Rest Framework - add/remove to a list

texts:
I have a model Collection which has a many to many relation to a model Item.

I want to be able to add or remove items to this collection using Django Rest Framework.

Option1 - make an action:

class CollectionViewSet(viewsets.ModelViewSet):
    queryset = Collection.objects.all()
    serializer_class = CollectionSerializer

    @action()
    def update_items(self, request, **kwargs):
        collection = self.get_object()
        add_items_id = request.DATA.pop('add_items', [])
        remove_items_id = request.DATA.pop('remove_items', [])
        items_add = Item.objects.filter(id__in=add_items_id).all()
        collection.items.add(*items_add)
        items_remove = Item.objects.filter(id__in=remove_items_id).all()
        collection.items.remove(*items_remove)
        return Response()

I see two downsides with this:

I cannot make one single request to update the collection with items and other fields (not without also modifying these.
I do not get the "API documentation" for free.

Option2 - override the update method and use two different serializers

class CollectionSerializer(serializers.HyperlinkedModelSerializer):
    items = ItemSerializer(many=True, read_only=True)

    class Meta:
        model = Collection
        fields = ('id', 'title', 'items')

class CollectionUpdateSerializer(serializers.HyperlinkedModelSerializer):
    add_items = serializers.PrimaryKeyRelatedField(many=True, source='items', queryset=Item.objects.all())
    remove_items = serializers.PrimaryKeyRelatedField(many=True, source='items', queryset=Item.objects.all())

    class Meta:
        model = Collection
        fields = ('id', 'title', 'add_items', 'remove_items')

class CollectionViewSet(viewsets.ModelViewSet):
    queryset = Collection.objects.all()

    def update(self, request, *args, **kwargs):
        collection = self.get_object()
        add_items_id = request.DATA.pop('add_items', [])
        remove_items_id = request.DATA.pop('remove_items', [])
        items_add = Item.objects.filter(id__in=add_items_id).all()
        collection.items.add(*items_add)
        items_remove = Item.objects.filter(id__in=remove_items_id).all()
        collection.items.remove(*items_remove)
        # fool DRF to set items to the new list of items (add_items/remove_items has source 'items')
        request.DATA['add_items'] = collection.items.values_list('id', flat=True)
        request.DATA['remove_items'] = request.DATA['add_items']
        return super().update(request, *args, **kwargs)

    def get_serializer_class(self):
        if self.request.method == "PUT":
            return CollectionUpdateSerializer
        return CollectionSerializer

Unfortunately, option2 has this horrible and inefficient hack. Here is why:

Super is called to handle the other properties (in this case only 'title'), it will see that add_items/remove_items is on the source 'items', (and at this point add_items/remove_items params would be empty) so it would remove all items.

What would be the canonical way to handle add/remove of items in a list via django-rest-framework, such that we still get:
- 1 request to update the object (i.e. not via a separate action request)
- re-using DRF patterns / auto-generated API


texts:
There is a problem which discusses in how many ways can the words in a sentence be permuted . I wrote a code as follows which works for the sentences (I think so) . It would be helpful if anyone can assure me if it's actually correct or not . Besides , any suggestion regarding the shortening of code or easing the logic is appreciated . Thanks...

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

int factorial(int x)
{
    if(x<=0) return 1;
    else return x*factorial(x-1);
};

int main(void)
{
    int T;//number of test cases
    scanf("%d",&T);
    while(T--){
    char str[20];
    scanf(" %[^\n]",str);
    int i,j,k,m,count=0,l,p=1,n;
    l=strlen(str);
    for(i=0;i<l;i++){
        if(str[i]==' '){
            count++;
        }
    }
    m=count+1;
    char arr[m][50];
    int check[m],func[m];
    for(i=0,k=0,j=0;j<=l;j++){
        if(str[j]==' '||j==l){
            check[i]=0;func[i]=1;
            arr[i][k]='\0';
            i++;
            k=0;
        }
        else{
            arr[i][k]=str[j];
            k++;
        }
    }
    for(i=0;i<m;i++){
  for(j=i+1;j<m;j++){
    if(check[i]==0&&strcmp(arr[i],arr[j])==0){
        check[j]++;
        func[i]++;
    }
  }
}
for(i=0;i<m;i++){
    p*=factorial(func[i]);
}
n=factorial(m)/p;
printf("%d/%d\n",1,n);
   }
 return 0;
}

Input:

       2

       I eat rice

       no game no life

Output:

       1/6

       1/12

N.B.: The permutation within a word is to be ignored .


texts:
I'm trying to create a C# brute force MD5 password checker. If I run it with "test1" without MD5, it completes in 15 seconds. I would like to make it faster, but I'm a c# beginner, and don't know how to optimize code anymore.

Basically, instead of nested for loops, if using flags (of type boolean), so if you have 4 char long pass it goes like this:

_ _ _ _ -> try every letter and number at last place, then set last flag on true. If last flag == true then increment counter for third place.

private string bruteForce(int lenght)
    {
        MD5 md55 = System.Security.Cryptography.MD5.Create();
        char[] words =
        {
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 'q', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','R','Q','S','T','U','V','W','X','Y','Z',
            '0','1','2','3','4','5','6','7','8','9'

        };

        bool[] konec = new bool[lenght];

        int flag = lenght;
        char[] pass = new char[flag];
        int[] signal = new int[lenght];
        for (int j = 0; j < lenght; j++)
        {
            signal[j] = -1;
            konec[j] = false;
        }
        flag--;
        string tmp = "";
        bool over=false;

        while (!over)
        {

            for (int k = 0; k < lenght; k++)
            {
                if (konec[k])
                {
                    if (k == 0) return "not found";
                    int t = ++signal[k - 1];
                    if (t == words.Length - 1) {konec[k - 1] = true;
                        signal[k - 1] = 0;

                        break;
                    }
                    pass[k - 1] = words[t];
                    konec[k] = false;

                }
            }
            for (int i = 0; i < words.Length; i++)
            {

                if (!konec[flag])
                {
                    pass[flag] = words[i];
                    tmp = new string(pass);
                    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(tmp);
                    byte[] hash = md55.ComputeHash(inputBytes);

                    // step 2, convert byte array to hex string
                  string  emde= BitConverter.ToString(hash).Replace("-", "");
                  emde = emde.ToLower();
                  if (tmp == target)
                    {
                        MessageBox.Show(tmp + "    " + target);
                        over = true;
                        break;
                    }
                }

            }
          konec[flag] = true;
        }
        return tmp;
    }

This is call on button click:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        int l = Convert.ToInt32(stevilo.Text);
       // lenght = 1;
       // string a = "";

        if (md5)
        {

            if (brute)
            {
                Stopwatch time = new Stopwatch();
                time.Start();

                target = zgoscevalna.Text;
                for (int i = 1; i < l+1; i++)
                {
                    int _i = i;
                     Thread t = new Thread(() =>
                    {
                        string a = bruteForce(_i);
                        if (a != "not found")
                        {
                            Dispatcher.Invoke(() =>
                            {
                                password.Text = a;
                                tajm.Text = (time.Elapsed.TotalSeconds).ToString();
                            });

                            Thread.CurrentThread.Abort();

                        }
                        else
                        {
                            Thread.CurrentThread.Abort();
                        }

                    });
                    t.Start();

                }

            }

            else
            {
            }
        }


texts: Sublime Text plugin to modify text before it's pasted

texts:
It's my first plugin and it's super simple but there could easily be some things worth knowing from this e.g. Python coding practices and potential bugs.

import sublime
import sublime_plugin

class EscapeAndPasteCommand(sublime_plugin.TextCommand):
    def run(self, edit, **kwargs):
        # Get the clipboard text
        originalText = textToPaste = sublime.get_clipboard()
        # Loop through the arguments making changes where possible
        for replacement in kwargs:
            # print("replacing '" + replacement + "'' with '" + kwargs[replacement] + "'")
            textToPaste = textToPaste.replace(replacement,kwargs[replacement])
        # Place the text back into the clipboard and paste in place
        sublime.set_clipboard(textToPaste)
        self.view.run_command("paste")

        # Restore the original text to the clipboard
        sublime.set_clipboard(originalText)

The idea is you feed this a dictionary of matches and replacements that it will perform on the clipboard object. Once those changes are made it restores the untouched text to the clipboard.

I made a key binding for this so that when I am pasting text, in my markdown files, that has file paths it will autoescape it for me, such as underscores and slashes that are meant to be just that.

{ "keys": ["ctrl+shift+v"],
    "command": "escape_and_paste",
    "args": {
        "\\": "\\\\",
        "_" : "\\_",
        "*" : "\\*"
    }
}

It works well for me and I think I would be lost without it now as it makes my documentation processes easier.


texts: Should I create an empty string and append through a foreach loop or should I use StringBuilder?

texts:
Here's the current code:

    static string GetResources(string header, string filter, string resourceTemplate)
    {
        string themeName;
        if (!TryGetHeaderValue(header, "theme", out themeName)) return "";

        var resources = "";
        var path = Path.Combine(HtmlPreview.BaseDirectory, themeName);

        foreach (var resource in Directory.GetFiles(path, filter))
        {
            resources += String.Format(
                resourceTemplate,
                themeName,
                Path.GetFileName(resource));
        }

        return resources;
    }

I was wondering if I should use string builder instead:

static string GetResources(string header, string filter, string resourceTemplate)
    {
        string themeName;
        if (!TryGetHeaderValue(header, "theme", out themeName)) return "";

        var resourcesStringBuilder = new StringBuilder();
        var path = Path.Combine(HtmlPreview.BaseDirectory, themeName);

        foreach (var resource in Directory.GetFiles(path, filter))
        {
            resourcesStringBuilder.Append(String.Format(
                resourceTemplate,
                themeName,
                Path.GetFileName(resource)));
        }

        return resourcesStringBuilder.ToString();
    }

Resharper simply suggests it is possible to replace the original code with a LINQ statement:

    static string GetResources(string header, string filter, string resourceTemplate)
    {
        string themeName;
        if (!TryGetHeaderValue(header, "theme", out themeName)) return "";

        var path = Path.Combine(HtmlPreview.BaseDirectory, themeName);

        return Directory.GetFiles(path, filter)
            .Aggregate("",
            (current, resource) => current +
                String.Format(resourceTemplate,
                themeName,
                Path.GetFileName(resource)));
    }

Thank you! The original code with context is also on github.


texts:
I have an interface named ICodeRunner, defined like this:

public interface ICodeRunner
{
        ExecutionResult Run(string code);
}

I have more classes that implement ICodeRunner, but regardless of which one is used, in some contexts only I have to impose a time limit on the execution of the Run method. This is a regular timeout: "if it's not done in x seconds, throw an exception."

To achieve this, I have created a class called CodeRunnerTimeLimitDecorator that can wrap any class implementing ICodeRunner and provide this functionality.

This is how the class is implemented:

public class CodeRunnerTimeLimitDecorator : ICodeRunner
{
        private readonly ICodeRunner _wrapped;
        private readonly int _timeoutInSeconds;

        public CodeRunnerTimeLimitDecorator(ICodeRunner wrapped, int timeoutInSeconds)
        {
                _wrapped = wrapped;
                _timeoutInSeconds = timeoutInSeconds;
        }

        public ExecutionResult Run(string code)
        {
                var executionResult = new ExecutionResult();

                var t = new Thread(() => executionResult = _wrapped.Run(code));

                t.Start();

                var completed = t.Join(_timeoutInSeconds * 1000);

                if (completed)
                        return executionResult;

                throw new ApplicationException(
                        string.Format("Code took longer than {0} seconds to run, so it was aborted.", _timeoutInSeconds));
        }
}

While I welcome any advice about how to make this code better, I'm particularly interested in comments/improvements regarding the time limit mechanism.

Update:

More specifically, the questions are:

Is there an easier/cleaner way to do it?
Would it be OK if I called t.Abort() in case the timeout had elapsed*?

*I do not control the process that goes on inside _wrapped.Run(code), so I cannot implement Task Cancellation or similar techniques.


texts: Generating random sequences while keeping sum fixed

texts:
The output is a random sequence, and the input is the sum of the sequence.

My solution is generating a random number rand_num from (0, sum_seq) at first, then draw another number randomly from (0, sum_seq - rand_num). By the way, all random numbers are integers.

import random

rand_list = [] # Random sequences buffer
def generater_random_list(num) :
    rand_num = random.randint(0, num)
    rand_list.append(rand_num)
    if num - rand_num == 0 :
        return 0
    else :
        return generater_random_list(num - rand_num)

It seems strange to create a buffer out of the function, so how can I improve it?


texts: Extract data labels from a chart in PowerPoint to Excel

texts:
Would like to check if anyone here is able to simplify the following code.
What it does: Extract data labels value from a chart in powerpoint to excel.

Sub Extract_Datalabels3()
'Goal: To extract datalabels of Chart's series collection and write to excel
'Working

    Dim sh As Shape
    Dim sld As slide
    Dim chtnow As Chart

    Dim x As Integer
    Dim z As Integer

    Dim xlApp As New Excel.Application
    Dim xlWorkbook As Excel.Workbook
    Dim xlworksheet As Excel.Worksheet

    Set xlWorkbook = xlApp.Workbooks.Add
    Set xlworksheet = xlWorkbook.Worksheets.Add
    xlApp.Visible = True

Set chtnow = ActiveWindow.Selection.ShapeRange(1).Chart

z = ActiveWindow.Selection.ShapeRange(1).Chart.SeriesCollection(1).DataLabels.Count

For x = 1 To z
xlWorkbook.Sheets(1).Range("A" & x).Value = chtnow.SeriesCollection(1).DataLabels(x).Text
Next

For x = 1 To z
xlWorkbook.Sheets(1).Range("B" & x).Value = chtnow.SeriesCollection(2).DataLabels(x).Text
Next

For x = 1 To z
xlWorkbook.Sheets(1).Range("C" & x).Value = chtnow.SeriesCollection(3).DataLabels(x).Text
Next

For x = 1 To z
xlWorkbook.Sheets(1).Range("D" & x).Value = chtnow.SeriesCollection(4).DataLabels(x).Text
Next

For x = 1 To z
xlWorkbook.Sheets(1).Range("E" & x).Value = chtnow.SeriesCollection(5).DataLabels(x).Text
Next

For x = 1 To z
xlWorkbook.Sheets(1).Range("F" & x).Value = chtnow.SeriesCollection(6).DataLabels(x).Text
Next

For x = 1 To z
xlWorkbook.Sheets(1).Range("G" & x).Value = chtnow.SeriesCollection(7).DataLabels(x).Text
Next

For x = 1 To z
xlWorkbook.Sheets(1).Range("H" & x).Value = chtnow.SeriesCollection(8).DataLabels(x).Text
Next

For x = 1 To z
xlWorkbook.Sheets(1).Range("I" & x).Value = chtnow.SeriesCollection(9).DataLabels(x).Text
Next

For x = 1 To z
xlWorkbook.Sheets(1).Range("J" & x).Value = chtnow.SeriesCollection(10).DataLabels(x).Text
Next

End Sub


texts:
Rewrite appropiate programs from earlier chapters and exercises with pointers instead of array indexing. Good posibilities include getline(Chapter 1 and 4), atoi, itoa, and their variants(Chapters 2, 3, and 4), reverse(Chapter 3), and strindex and getop(Chapter 4)

Here is my solution:

static char *hidden(int n, char *s) {
    char *p;

    if(n / 10) {
        p = hidden(n / 10, s);
    }
    else {
        p = s;

    }
    *p++ = n % 10 + '0';
    *p = '\0';

    return p;
}

char *itoa(int n, char *s) {
    if(n < 0) {
        *s = '-';
        hidden(-n, s + 1);
    }
    else {
        hidden(n, s);
    }

    return s; /* pointer to first char of s*/
}

itoa is a wrapper for the function hidden. The function hidden returns a pointer to the next free slot in the array s. At the deepest level of recursion it returns a pointer to the first element (the else branch) of the array.


texts:
count = 0

def merge_sort(li):

    if len(li) < 2: return li
    m = len(li) / 2
    return merge(merge_sort(li[:m]), merge_sort(li[m:]))

def merge(l, r):
    global count
    result = []
    i = j = 0
    while i < len(l) and j < len(r):
        if l[i] < r[j]:
            result.append(l[i])
            i += 1
        else:
            result.append(r[j])
            count = count + (len(l) - i)
            j += 1
    result.extend(l[i:])
    result.extend(r[j:])
    return result

unsorted = [10,2,3,22,33,7,4,1,2]
print merge_sort(unsorted)
print count


texts: Calculating difference between cached period and requested

texts:
There is a remote resource containing datasets arranged by time, data is static and doesnt change. Whenever we are going to fetch anything from there we will be saving it in our cache.
User might request a data for a particular time period, lets say from 1st Jan 2019 to 1st Jan 2020. If data is not cached, then we request it from remote resource, in case only part of data is cached, then we need to request what is missing. There is a function which calculates missing intervals, and I think that it looks too verbose. Would be nice to get some suggestions for a better solution. Thanks.
    @SneakyThrows
public static ArrayList<TimeSpan> difference(TimeSpan requested, TimeSpan cached){
    ArrayList<TimeSpan> missingIntervals = new ArrayList<>();
    //requested period is within cached
    if (requested.getFrom().compareTo(cached.getFrom()) >= 0 && requested.getTo().compareTo(cached.getTo()) <= 0){
        missingIntervals = null;
    //requested period is before or after cached
    } else if (requested.getTo().compareTo(cached.getFrom()) <= 0 || requested.getFrom().compareTo(cached.getTo()) >= 0){
        missingIntervals.add(requested);
    // requested start and end dates are outside of cached range
    } else if (requested.getFrom().compareTo(cached.getFrom()) <= 0 && requested.getTo().compareTo(cached.getTo()) >= 0){
        missingIntervals.add(new TimeSpan(requested.getFrom(),cached.getFrom()));
        missingIntervals.add(new TimeSpan(cached.getTo(),requested.getTo()));
    // requested start date is before cached period
    } else if (requested.getFrom().compareTo(cached.getFrom()) < 0
            && requested.getTo().compareTo(cached.getTo()) <= 0
            && requested.getTo().compareTo(cached.getFrom()) > 0){
        missingIntervals.add(new TimeSpan(requested.getFrom(),cached.getFrom()));
    // requested end date is after cached period
    } else if (requested.getTo().compareTo(cached.getTo()) >= 0
            && requested.getFrom().compareTo(cached.getFrom()) >= 0
            && requested.getFrom().compareTo(cached.getTo()) < 0){
        missingIntervals.add(new TimeSpan(cached.getTo(),requested.getTo()));
    }
    return missingIntervals;
}

Here is a TimeSpan class:
public class TimeSpan {

public TimeSpan(Date from, Date to) throws Exception{
    if(from.compareTo(to) >= 0){
        throw new Exception("Start date cannot be greater then end date");
    }
    this.from = from;
    this.to = to;
}

private final Date from;
private final Date to;

}


texts:
Recently I've been fiddling with the idea of sending a text message using C.  Looking at a few options, I thought that using libcurl to send an SMTP email using TLS for some security would be the best and easiest option.  Here's what I would like reviewed:

Method: Is there a better/easier way I could be sending an SMS?
Security: Is my current security enough? How could I add more security to make sure my authentication details aren't being snooped on?
SMS Format: Is there a way I could format my payload to look more like what it would if I sent it off using a normal email client?  The normal email client sends something that looks like the image on the left, with my first name being blacked out; the image on the right is what it looks like sent from my program with my email being censored.

Conversations: With my program, a new conversation is generated each time an SMS is sent, with the numbers at the top (950-9 in this case) being randomly chosen anew each time.  Could an improvement be made to the program so that each new SMS message stays in the same conversation?

#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

typedef struct
{
    int lines_read;
} UploadStatus;

size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp)
{
    if((size == 0) || (nmemb == 0) || ((size * nmemb) < 1)) return 0;

    UploadStatus *upload = (UploadStatus*) userp;
    const char *payload[] =
    {
        "Subject: SMS Test\r\n",
        "\r\n", /* empty line to divide headers from body, see RFC5322 */
        "Test",
        NULL
    };
    const char *data = payload[upload->lines_read];

    if(data)
    {
        size_t len = strlen(data);
        memcpy(ptr, data, len);
        upload->lines_read++;
        return len;
    }
    return 0;
}

int main(void)
{
    CURLcode res = CURLE_OK;
    struct curl_slist *recipients = NULL;
    UploadStatus upload_ctx = {0};
    const char *from = "test@gmail.com";
    const char *to = "UrTxtEmail"; // see http://www.emailtextmessages.com/
    CURL *curl = curl_easy_init();

    if(curl)
    {
        // set username and password
        curl_easy_setopt(curl, CURLOPT_USERNAME, from);
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "password");
        curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:587/");
        // start with normal connection, and upgrade to TLS using STARTTLS
        curl_easy_setopt(curl, CURLOPT_USE_SSL, (long) CURLUSESSL_ALL);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
        curl_easy_setopt(curl, CURLOPT_MAIL_FROM, from);
        recipients = curl_slist_append(recipients, to);
        curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
        curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);
        curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
        // useful for debugging encryped traffic
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        // send the message
        res = curl_easy_perform(curl);
        if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        curl_slist_free_all(recipients);
        curl_easy_cleanup(curl);
    }

    return (int) res;
}


texts: Javascript Slider that controls TinySlider - feels inefficient

texts:
I feel like the main point of inefficiency is how I create "notches" and must loop through all of the created notches every time the value for the slider is changed.

function sliderLoop() {
    for (var i = slideNotchArray.length - 1; i >= 0; i--) {
      if ($(".slider").val() >= slideNotchArray[i].value) {
        console.log(slideNotchArray[i].slide);
        teamSlider.goTo(slideNotchArray[i].slide);
        break;
      }
    }
 }

It's an exponential nightmare as each call can loop through every notch object, and there can be multiple calls a second. This is the only solution I could have thought of though, and I am more than welcome to someone else's suggestions. I attempted to mitigate the severity by including a break once the first notch has been found, as to not loop through the rest, but I feel as though it is still quite heavy.

https://codesandbox.io/s/currying-bush-h3xyz

My major concerns are in relation to

  function sliderLoop() {
    for (var i = slideNotchArray.length - 1; i >= 0; i--) {
      if ($(".slider").val() >= slideNotchArray[i].value) {
        console.log(slideNotchArray[i].slide);
        teamSlider.goTo(slideNotchArray[i].slide);
        break;
      }
    }
  }

  // Fires slider loop every time the value changes, I had to use mousemove as .change() would only fire once the mouse click was relseased.
  $(".slider").on("change mousemove", function() {
    sliderLoop();
  });

The "change mousemove" event listener, calls sliderLoop multiple times a second. sliderLoop() contains a for loop, which could potentially iterate through many (10+) array index's. Calling a for loop which iterates through so many index's multiple times a second makes me believe this is an inefficient method of going about a slider navigation, however, I am at a loss as to how to improve the code while maintaining the functionality. Would you believe this to be an issue worth worrying about? If so, how could I go about improving this?


texts: AngularJS Null coalescing operator filter

texts:
I am relatively new to AngularJS and am coming from a PHP background.

One of the new features for PHP7 was the Null coalescing operator.
In short, it checks if a value is set and if it is then it shows one value, otherwise it shows another.

I wanted to do a similar thing in AngularJS since I was retrieving data from a database using an inner join and so some values are returned as null. As a result of this, I needed a fallback.

Here is the filter code:

app.filter("or", function() {
    return function(input, replace, whatIsNull) {
        //set the defaults
        whatIsNull = typeof whatIsNull == "undefined" ? ["", 0, 0.0, "0", undefined, null, false, []] : whatIsNull;
        replace    = typeof replace == "undefined" ? undefined : replace;

        return whatIsNull.indexOf(input) > -1 ? replace : input;
    }
});

Then I use it in the following:

{{ myStr | or: "N/A" }}

{{ myStr | or: "N/A": [undefined, false] }}

The first example will use the default values of PHP's empty function.
The second example uses a custom array of values that will result in the fallback from or.

Is there a more effective way of setting default values of functions?
The way I would normally do this would be to set it inline in the function declaration (Something that was added in ECMAScript 2015).


texts:
I created 3 different implementations (which produce the same results) using the count_if function from STL. I wish to check the number of elements in the vector which are strictly less than 6.

These are:

C++ lambda function
Global function (no functor)
Using class and creating my own functor

These implementations work, but, how can I improve them into a more efficient and robust solutions?

#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <iostream>

using namespace std;

// GLOBAL function (not FUNCTOR) See below for FUNCTOR implementation!
template <int num>
bool lessThan(int x)
{
    return(x < num); // return TRUE if the value is less than NUM
}

// Paramterized Function with more robust FUNCTOR implementation (written by me) (I know stl has this built in)
class LessThan
{
private:
    int m_x; // the value we wish to be less than
public:
    LessThan(int val) : m_x(val) {} // custom constructor: assign a value to x
    bool operator() (int upper) // all values must be strictly less than the upper bound
    {
        return (m_x < upper);
    }
};

int main()
{
    vector<int> vec = { 2, 7, 4, 5, 7, 7};

    // Using new C++ Lambda function implementation
    int x = count_if(vec.begin(), vec.end(), [](int x) {return x < 6; }); // using C++ Lambda Function (just a function with no name)
    cout <<"There exists " << x << " integers in vec which are strictly less than 6." << endl;

    // Using global lessThan6 implementation (NOT FUNCTOR)
    int y = count_if(vec.begin(), vec.end(), lessThan<6>); // not very robust
    cout << "There exists " << y << " integers in vec which are strictly less than 6." << endl;

    // Using MY OWN FUNCTOR implementation
    int z = count_if(vec.begin(), vec.end(), LessThan(6)); // robust
    cout << "There exists " << z << " integers in vec which are strictly less than 6." << endl;

}


texts:
I am doing a filtered table in react, and I came up with the following code:

import React from 'react';
import { render } from 'react-dom';
import RowFilter from './RowFilter';
import List from './List';
import movieList from './movielist.json';

const data = movieList;
const App = () => (
  <RowFilter data={data}>
    <List/>
  </RowFilter>
);

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

The implementation details are not that important since this is only a rough example, but the general idea is the following:

List normally expects a data array property so that it knows what to render

RowFilter has an input element and keeps track of a list of data. When the value changes, it updates the list of data.

RowFilter also sets the data property for it's child, whatever that child is

The result code works as expected, but I'm wondering about whether this is hard to read or considered a bad practice in general.

Running example


texts: Code to implement the Jaro similarity for fuzzy matching strings

texts:
Problem
This code is meant to solve the problem in this software engineering question. To summarize the issue: given a set of strings that are sort of similar, but not similar enough to use regex upon, how would one get out a set of those "similar strings" amongst the "nonsimilar" strings? This is apparently called fuzzy matching strings, which I personally think is a fabulous name, but moving on. I looked around and hit upon the Jaro similarity as what seemed like a decently simple way to solve the problem. I'm particularly interested in seeing how the functions can be improved. It is written in Python 3.
Approach
First, in the match function, I convert each string into sets and find the intersection of the sets. Then, in the technical_match() function, I calculate the maximum distance to satisfy the requirements of the Jaro similarity, and then find the index of each item in the set of matches in each string, and subtract the two indices to find the distance. If this distance is less than the maximum distance, then it is a "true match" and is appended to a list of these.
Then, I calculate the number of transpositions necessary, i.e., given hello and jello, there are none necessary, because the strings produced when non-matches are stripped out are 'ello' and 'ello'. However, if I have 'cello' and 'ecllo', then it requires a transposition to switch c and e. I calculate this by producing a string from the match letters ordered as per their position in the actual string and then compare each for differences using diff_letters().
With these calculations in hand, I can then calculate the actual Jaro similarity, which is a pretty simple formula.
Finally, I created a fake file, foobar.txt, with some words, and open it, read it, split it by line breaks, and go through each and match to a pattern. If the Jaro similarity is greater than a certain constant, in this case 0.5 (the max, if both strings are the same, being 1, I believe), than that value is added to a list, and the list is printed at the end.
Code
import math

def match(s1, s2):
    set_of_matches = set.intersection(set(s1), set(s2))
    return set_of_matches

def technical_match(s1, s2):
    matches = match(s1, s2)
    max_distance = math.floor(max(len(s1), len(s2)/2)) - 1
    true_list = []
    for i in matches:
        distance = abs(s1.index(i) - s2.index(i))
        if distance <= max_distance:
            true_list.append(i)
    return true_list

def diff_letters(seq1, seq2):
    return sum(1 for a, b in zip(seq1, seq2) if a != b)

def transpositions(s1, s2):
    t = list(technical_match(s1, s2))
    s1_list = []
    s2_list = []
    for i in s1:
        if i in t:
            s1_list.append(i)
    for i in s2:
        if i in t:
            s2_list.append(i)
    s1 = ''.join(s1_list)
    s2 = ''.join(s2_list)
    return diff_letters(s1, s2)

def jaro_similarity(s1, s2):
    matches = len(technical_match(s1, s2))
    if matches == 0:
        return 0
    else:
        return 1/3*(matches/len(s1) + matches/len(s2) + (matches + transpositions(s1, s2))/matches)

match_text = open('foobar.txt', 'r').read().splitlines()
pattern = 'hat'
constant = .5

results = []
for i in match_text:
    if jaro_similarity(i, pattern) > constant:
        results.append(i)

print(results)

Fake text file and output
I used a file called foobar.text which contained
cheat
chat
choose
hat
hot

and ran the code on it (see here if you wish to run it) and received the output ['cheat', 'chat', 'hat', 'hot'].
Review
I'd be glad to accept all comments, as I need all the improvement I can get in my coding style. I am fairly sure this works, as I've tested it on a variety of inputs, but if there's a bug that's slipped through, I apologize; I did my best implementing the Jaro similarity, but the wikipedia article was a tad bit confusing in places.


texts: Find majority element in an array given constant external space

texts:
Given constant external space (yes no HashMap), how would you improve the following code (code-wise or complexity-wise with stress on the latter) to find the majority element in an array?

/**
 * Created by mona on 5/27/16.
 */

import java.util.Arrays;

public class FinaMajority {
    public static int findMajority(int[] a) {
        Arrays.sort(a);
        int maxCount = Integer.MIN_VALUE;
        int maxIdx = Integer.MIN_VALUE;
        for (int i=0; i<a.length; i++) {
            int count = 0;
            while ( (i+count) < a.length && a[i] == a[i+count]) {
                count++;
                if (count == a.length/2) {
                    return a[i];
                }
                if (count > maxCount) {
                    maxCount = count;
                    maxIdx = i;
                }
            }
        }
        return a[maxIdx];
    }

    public static void main(String[] args) {
        int[] a = {3,1,2,2,3,2,2,4,4,3,5,2,3,1,3,4,3,3,3};
        System.out.println(findMajority(a));
    }

}


texts:
This is a typical interview question:

  Given an array that contains both positive and negative elements without 0, find the largest subarray whose sum equals 0.

I am not sure if this will satisfy all the edge case. If someone can comment on that, it would be excellent. I also want to extend this to sum equaling to any ,  not just 0. How should I go about it? And any pointers to optimize this further is also helpful.

from collections import Counter

def sub_array_sum(array,k=0):
    start_index = -1
    hash_sum = {}
    current_sum = 0
    keys = set()
    best_index_hash = Counter()
    for i in array:
        start_index += 1
        current_sum += i
        if current_sum in hash_sum:
            hash_sum[current_sum].append(start_index)
            keys.add(current_sum)
        else:
            if current_sum == 0:
                best_index_hash[start_index] = [(0,start_index)]
            else:
                hash_sum[current_sum] = [start_index]
    if keys:
        for k_1 in keys:
            best_start = hash_sum.get(k_1)[0]
            best_end_list = hash_sum.get(k_1)[1:]
            for best_end in best_end_list:
                if abs(best_start-best_end) in best_index_hash:
                    best_index_hash[abs(best_start-best_end)].append((best_start+1,best_end))
                else:
                    best_index_hash[abs(best_start-best_end)] = [(best_start+1,best_end)]

    if best_index_hash:
        (bs,be) = best_index_hash[max(best_index_hash.keys(),key=int)].pop()
        print array[bs:be+1]
    else:
        print "No sub array with sum equal to 0"

def Main():
    a = [6,-2,8,5,4,-9,8,-2,1,2]
    b = [-8,8]
    c = [7,8,-1,1]
    d = [2200,300,-6,6,5,-9]
    e = [-9,-6,8,6,-14,9,6]
    sub_array_sum(a)
    sub_array_sum(b)
    sub_array_sum(c)
    sub_array_sum(d)
    sub_array_sum(e)

if __name__ == '__main__':
    Main()


texts:
I have made a function for finding the longest common prefix for the challenge on the leetcode site. This is the code:

var longestCommonPrefix = function(strs) {
    let longestPrefix = '';
    if (strs.length > 0) {
      longestPrefix = strs[0];
      for (let i = 1; i < strs.length; i++) {
        for (let j = 0; j < longestPrefix.length; j++) {
          if (strs[i][j] != longestPrefix[j]) {
            longestPrefix = longestPrefix.slice(0, j);
            break;
          }
        }
      }
    }

    return longestPrefix;
};

I am sure there is a way to make this code better, but not sure how to do that. Would appreciate any help.


texts:
Finished
Someone helped me see that i was framenting the output by writing to each file inside
the for loop instead i needed to have one big for loop for each file so that the harddrive
didnt have to move its head everytime

https://stackoverflow.com/questions/9913788/outputing-dictionary-optimally

I have 4 Dictionarys that contain 800k strings with 200 to 6000 characters.
when i load it into memory it takes up about 11 gigs of memory.
it is taking me 2 minutes to parse the data and 2 minutes to output the data.
Is there anyway to output the data faster than what I am using below?
I am only getting 20-31 MB per second disk IO and I know the hard drive can do 800ish

var hash1 = new Dictionary<int, Dictionary<string, string>>(f.Count + 2);
var hash2 = new Dictionary<int, Dictionary<string, string>>(f.Count + 2);
var hash3 = new Dictionary<int, Dictionary<string, string>>(f.Count + 2);
var hash4 = new Dictionary<int, Dictionary<string, string>>(f.Count + 2);

...

foreach (var me in mswithfilenames)
{
    filename = me.Key.ToString();
    string filenamef = filename + "index1";
    string filenameq = filename + "index2";
    string filenamefq = filename + "index3";
    string filenameqq = filename + "index4";

    StreamWriter sw = File.AppendText(filenamef);
    StreamWriter sw2 = File.AppendText(filenameq);
    StreamWriter swq = File.AppendText(filenamefq);
    StreamWriter sw2q = File.AppendText(filenameqq);

    for (i = 0; i <= totalinhash; i++)
    {
        if (hashs1[i].ContainsKey(filenamef))
        {
            sw.Write(hashs1[i][filenamef]);
        }
        if (hashs2[i].ContainsKey(filenameq))
        {
            sw2.Write(hashs2[i][filenameq]);
        }
        if (hashs3[i].ContainsKey(filenamefastaq))
        {
            swq.Write(hash4[i][filenamefastaq]);
        }

        if (hash4[i].ContainsKey(filenameqq))
        {
            sw2q.Write(hash4[i][filenameqq]);
        }
    }
    sw.Close();
    sw2.Close();
    sw3.Close();
    sw4.Close();
    swq.Close();
    sw2q.Close();
}


texts: Get specific properties for all Active Directory groups and all their users, then combine them into CSV

texts:
I've written a script that gets a list of all groups in AD along with a few specific properties for each group (DistinguishedName, CN, Type, and Description). Then it goes through each group and, for each member of type "user" (to exclude computers, servers, etc.), it gets the user's full name, title, and their manager's full name. Finally, it combines the two using a PS Module called Join-Object to join the two lists together and output it as a CSV file.
Getting the AD Groups at the beginning is quick enough; it takes less than a minute to run. Combining all the output at the end likewise is pretty quick; a minute or less and it's done.
The slow part is the middle step of looping through each group. For ~1500 groups and a total of about ~75k to ~85k users across all groups (many users are in multiple AD groups, naturally), it takes 7 hours to run. Is there some way I can improve on that 7 hour runtime (preferably drastically)? Extrapolating from the run-time of the other sections, I would expect the middle section to take an hour or less.
I'm running PowerShell 5.1 on Win10 and querying Active Directory on Windows Server 2016. This script was requested by our security team so they could generally audit AD group membership information in a format familiar to them (a CSV file inside Excel).
Import-Module -Name ActiveDirectory -Force
Import-Module -Name Join-Object -Force

#Get list of AD Groups. Currently ~1500 rows
$ADGroupsList = Get-ADGroup -Filter * -Properties * | Select-Object DistinguishedName,CN,GroupCategory,Description | Sort-Object CN

#Declare ADUsersList object
$ADUsersList = @()

#Declare Record variable and set parameter schema. The [ordered] keyword ensures the data is entered in this order
$Record = [ordered] @{
    "Group Name" = ""
    "Employee Name" = ""
    "Title"= ""
    "Manager" = ""
}

#Loop through each group in the groups list. This is the really, really slow part. If the AD Web Service limit is ever set back to the default (5000), this will fail for any groups that have more than 5,000 users.
foreach ($Group in $ADGroupsList) {
    #Get list of members of the current group in the loop who are of type "user" (excludes servers or other computers, for example)
    $ArrayofMembers = Get-ADGroupMember -Identity $Group.DistinguishedName | Where { $_.objectClass -eq "user" }

    #Loop through each member in the list of members from above
    foreach ($Member in $ArrayofMembers) {
        #Get detailed user info about the current user like title and manager that aren't available from Get-ADGroupMember
        $User = Get-ADUser -Identity $Member -Properties name,title,manager | Select-Object Name, Title, @{Label="Manager";Expression={(Get-ADUser (Get-ADUser $Member -Properties Manager).Manager).Name}}

        #Specifies what values to apply to each property of the $Record object
        $Record."Group Name" = $Group.CN
        $Record."Employee Name" = $Member.Name
        $Record."Title" = $User.Title
        $Record."Manager" = $User.Manager

        #Put all the stored information above in a 'copy' record
        $objRecord = New-Object PSObject -property $Record

        #Append that copy to the existing data in the ADUsersList object
        $ADUsersList += $objRecord
    }
}

#Combines data from the two objects into one. This uses the Join-Object module from https://www.powershellgallery.com/packages/Join-Object/2.0.1
Join-Object -Left $ADGroupsList -Right $ADUsersList -LeftJoinProperty "CN" -RightJoinProperty "Group Name" -Type AllInBoth -LeftMultiMode DuplicateLines -RightMultiMode DuplicateLines -ExcludeLeftProperties DistinguishedName | Export-Csv C:\CombinedADResults.csv -NoTypeInformation


texts: Should Domain objects for a public API be able to save/send themselves?

texts:
My main questions:  FileWithSave handles its saving itself, but delegates it to a repository object.  This allows implementation details to be available without being present in the API when saving (transpose this to a Mail sending API as well, available for send but not public).  Is this OK in terms of OOP practices?  Are there any maintainence gotchas I'm missing?  Does it need reorganization?

Without save:

package com.example.external;

public interface File {
    /**
     * Get the unique identifier.
     *
     * @return unique identifier.
     */
    String getId();

    /**
     * Get the file name.
     *
     * @return file name.
     */
    String getName();

    /**
     * Sets name for the file.
     *
     * @param name file name.
     */
    void setName(String name);

    /**
     * Get the file size.
     *
     * @return file size.
     */
    Long getSize();
}

Without save implementation:

package com.example.internal;

public class FileImpl implements File {
    // I don't want it in my public signature but I want it when I'm saving for some reason :(
    private Something somethingPrivate;
    private final String id;
    private final String name;
    private final Long size;

    public FileImpl(String id, Long size) {
        this.id = id;
        this.size = size;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getSize() {
        return size;
    }
}

Repository for File:

package com.example.external;

public interface FilingCabinet {
    /**
     * Get a file from the cabinet.
     *
     * @param id unique identifier.
     * @return file.
     */
    File get(String id);

    /**
     * Store a file in the cabinet.
     *
     * @param file.
     */
    void store(File file);
}

Without save client sample code:

FilingCabinet cabinet = room.getFilingCabinet();
File file = cabinet.get("my-unique-id");
file.setName("my-new-name");
cabinet.store(file);

With save:

package com.example.external;

public interface FileWithSave extends File {
    /**
     * Save the changes.
     */
    File store();
}

With save implementation:

package com.example.internal;

public class FileWithSaveImpl implements FileWithSave {
    private Something somethingPrivate;
    private final String id;
    private final String name;
    private final Long size;
    private final PrivateFilingCabinet repo;

    public FileWithSaveImpl(String id, Long size, PrivateFilingCabinet repo) {
        this.id = id;
        this.size = size;
        this.repo = repo;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public Long getSize() {
        return size;
    }

    @Override
    public void store() {
        repo.save(this);
    }
}

Wrapper class:

package com.example.external;

/**
 * Wraps PrivateFilingCabinet and injects PrivateFilingCabinet in FileWithSave object.
 */
public interface Secretary {
    /**
     * Get the file for someone.
     *
     * @param unique identifier.
     * @return file.
     */
    FileWithSave getFile(String id);
}

Repository injected in to FileWithSave and not part of the public API package:

package com.example.internal;

public interface PrivateFilingCabinet {
    /**
     * Get a file from the cabinet.
     *
     * @param id unique identifier.
     * @return file.
     */
    FileWithSaveImpl get(String id);

    /**
     * Store a file in the cabinet.
     *
     * @param file.
     */
    void store(FileWithSaveImpl file);
}

With save client sample code:

FileWithSave file = company.getSecretary().getFile("my-unique-id");
file.setName("my-new-name");
file.store();


texts: Getting translated string using reflection and Resource Manager

texts:
I wrote the following code to get the translated string from Resource Manager. The method GetTranslatedString is called more than 50 times in my project.

  public static string GetTranslatedString(string input, string culture)
    {
        if (string.IsNullOrEmpty(input)) return input;
        string retInput = input;
        CultureInfo cultureInfo = new CultureInfo(culture);
        ResourceManager rm = new ResourceManager("Globalization.XYZ", Assembly.GetExecutingAssembly());

        var entry = rm.GetResourceSet(cultureInfo, true, true)
            .OfType<DictionaryEntry>()
            .FirstOrDefault(e => e.Key.ToString().Equals(input, StringComparison.InvariantCultureIgnoreCase));
        if (entry.Value == null) return retInput;
        return entry.Value.ToString();

    }

But I feel it's not perfect code because the ResourceManager class gets new instances many times and since I'm calling GetTranslatedString many times I am sure it will impact on performance.

Second major problem is, I am using reflection inside this code. and it's a costly operation.

It would helpful if I could get review on this.


texts: Length of the longest consecutive run of 1s in its binary representation

texts:
The task

  Given an integer n, return the length of the longest consecutive run
  of 1s in its binary representation.

  For example, given 156, you should return 3

My function solution 1

Style 1

function findMaxNumberOfConsecOnes(dec){
  const countConsecOnes = (acc, x) => [acc[0] < acc[1]
                                       ? acc[1]
                                       : acc[0],
                                       x === "1"
                                       ? acc[1] + 1
                                       : 0 ];

  return [...(dec >>> 0).toString(2)]
      .reduce(countConsecOnes, [0,0]);
}

Style 2

function findMaxNumberOfConsecOnes(dec){
  const countConsecOnes = (acc, x) => [acc[0] < acc[1] ? acc[1] : acc[0],
                                       x === "1" ? acc[1] + 1 : 0 ];

  return [...(dec >>> 0).toString(2)]
      .reduce(countConsecOnes, [0,0]);

Style 1 and Style 2 have the exact same logic, but different style. My first idea was to write it in Style 1. But I then thought what was said to me in this thread about indentation. Therefore I opt for Style 2. But still not sure, whether this is the right way.

Alternatively:

My functional Solution 2

function findMaxNumberOfConsecOnes(dec){
  return [...(dec >>> 0).toString(2)]
    .reduce((acc, x) => {
      const current = x === "1" ? acc[1] + 1 : 0;
      const max = Math.max(acc[0], current);
      return [max, current];
  }, [0,0]);
}

My imperative Solution

function findMaxNumberOfConsecOnes(dec){
  const binStr = (dec >>> 0).toString(2);
  let max = 0, current = 0;
  for (const s of binStr) {
    current = s === "1" ? current + 1 : 0;
    max = Math.max(max, current);
  }
  return max;
}


texts: Creating cover traffic by calling random urls - Javascript loop to decrement float

texts:
This is a for-loop which runs once for each step with i>1 and maybe for 0 <= i <= 1.
var i;
var prob_ = 3.5;
for ( i = prob_; i >= 0; i -= 1 ) {
    if ( i > 1 || withProbability(i) ) {
        loadHttp(randomUrl());
    }
}

with
function withProbability(chance) {
    return Math.random() < chance;
}

JsLint gave me a for-loop error. Is this code ok despite that warning, or should this for-loop be changed to some other looping construct?
Background
prob_ is a ratio between fake actions and real actions. The loop is triggered once for each real action. If prob_ is greater than 1, the fake action is done. If it is in between 0 and 1, it is considered a probability and thus maybe a fake action follows.
This is a case where it was not clear how to replace the for-loop with a forEach, as is often recommended. Maybe ES6 tail recursion could be used...
More context
function loadHttp(toLoad) {
    require("sdk/page-worker").Page({
        contentURL: toLoad
    });
}

The implementation of randomUrl() is rather lengthy and does not relate to the question. It determines a statistically probable length of a HTML (or embedded object like js, img, css, ...) site, then does a lookup for the next bigger URL in a hardcoded list. It is supposed that the randomness will confuse someone who watches for traffic patterns.
Full class coverTraffic.js
This is initialized via
const coverTraffic = require('./coverTraffic.js');
coverTraffic.setLoader(require('./load.js'));

with load.js containing similar to loadHttp as above. It is triggered via
function loads(URL) {
    if ( _.contains(activeHosts, URL.host) ) { // has already started
        coverTraffic.loadNext();
    } else {
        activeHosts.push(URL.host);
        coverTraffic.start();
    }
}
exports.loads = URL => loads(URL);

which is called whenever the browser loads a new URL.
"use strict";

exports.DOC = 'creates cover traffic, up to predetermined parameters';

const { setTimeout } = require("sdk/timers");

const coverUrl = require("./coverUrl.js");
const stats = require("./stats.js");

/** overhead of dummy traffic -1; 1.5 has overhead of 50% */
const FACTOR = 1.5;

var load;

var site_ = {};
var pad_ = {};
var prob_;

function setLoader(load_param) {
    load = load_param;
}
exports.setLoader = (load_param) => setLoader(load_param);

/** a website is loaded by the user. covertraffic determines a target
 * feature vector and adds to the load to approximate the target.
 */
function start() {
    site_ = {};
    pad_ = {};

    site_.html = stats.htmlSize(1); // td: buffer known sites in bloomfilter
    pad_.html = stats.htmlSize(FACTOR) - site_.html;
    site_.num_embedded = stats.numberEmbeddedObjects(1); // td: see above
    pad_.num_embedded = stats.numberEmbeddedObjects(FACTOR) - site_.num_embedded;
    prob_ = pad_.num_embedded / site_.num_embedded;

    //    setTimeout(loadNext, stats.parsingTime());
    load.http(coverUrl.sized(pad_.html));
}
exports.start = start;

function loadNext() {
    var i;
    if ( pad_.num_embedded > 0 ) {
    for ( i = prob_; i >= 0; i -= 1 ) {
        if ( i > 1 || stats.withProbability(i) ) {
        load.http(coverUrl.sized(stats.embeddedObjectSize()));
        pad_.num_embedded -= 1;
        }
    }
    } else {
    console.log("cover traffic empty, num: " + pad_.num_embedded);
    }
}
exports.loadNext = loadNext;

The stats module provides statistical distributions, the load-module just loading a URL as described above.


texts: Makefile for a custom operating system kernel

texts:
I'm now posting the second semi-complete part of my operating system makefile. The kernel itself is currently incomplete, so don't be surprised by the small size of the makefile. When the kernel expands, it will follow suit.

OFLAGS = -Ofast
DEBUGFLAGS = -g -g3 -ggdb3
TARGET = i686-elf
CC = gcc
INCDIR = -I kernel/include/
KERNEL = opal101
CFLAGS = -ffreestanding -Wall -Wextra -fno-exceptions -funsigned-char
LDFLAGS = -T linker.ld -Ofast -nostdlib -lgcc
AS = as
VPATH = kernel/arch/$(TARGET) $(shell find . -type d ! -name "arch"*)
include kernel/arch/$(TARGET)/Makefile
include kernel/drivers/vga/Makefile
include kernel/lib/Makefile
OBJECTS = $(C_OBJECTS) $(ASM_OBJECTS)
.PHONY: help all clean iso run debug
help:
        @echo "make: Usage: make [target]";\
        echo "Targets [run | iso | all | cleani | debug]"
debug: CFLAGS:= $(CFLAGS) $(DEBUGFLAGS)
debug: all
        qemu-system-i386 --kernel $(KERNEL).bin -S -s& \
        gdb-multiarch -s $(KERNEL).bin
run:iso
        qemu-system-i386 -cdrom $(KERNEL).iso
iso: CFLAGS := $(CFLAGS) $(OFLAGS)
iso: all
        mkdir -p $(KERNEL)/boot/grub;\
        cp kernel/arch/i686-elf/stage2_eltorito $(KERNEL)/boot/grub;\
        cp $(KERNEL).bin $(KERNEL)/boot;\
        printf "default 0\n" >>menu.lst;\
        printf "title %s\n" $(KERNEL) >>menu.lst;\
        printf "kernel /boot/%s.bin" $(KERNEL) >>menu.lst;\
        mv menu.lst $(KERNEL)/boot/grub;\
        genisoimage -R -b boot/grub/stage2_eltorito -no-emul-boot \
        -boot-load-size 4 -boot-info-table -o $(KERNEL).iso $(KERNEL)
all: $(KERNEL).bin

$(KERNEL).bin:$(OBJECTS)
        $(TARGET)-$(CC) $(CFLAGS) $(LDFLAGS) $(OBJECTS) -o $(KERNEL).bin
$(C_OBJECTS):%.o:%.c
        $(TARGET)-$(CC) $(CFLAGS) -c $< -o $@ $(INCDIR)
$(ASM_OBJECTS): %.o:%.s
        $(TARGET)-$(AS) $< -o $@
clean:
        rm -rf *.o *.bin *.iso opal101/

I will show the kernel/lib/Makefile. All the rest are almost the same.

C_OBJECTS := $(C_OBJECTS) string.o
string.o:string.h

NOTE: I am not willing to use auto dependency generators because I found them very complex to learn and use, so please don't ask me to use them.


texts: Attributes with special behaviour in Python

texts:
What is the common practice to implement attributes that have side effects in Python? I wrote the following class which supposed to save singletons when a variable is going to get a certain value. The background is that my program had sparse data, meaning that there were a lot of objects having empty sets in their attributes which wasted a lot of memory. (my actual class is slightly more complex). Here is the solution I took:

class DefaultAttr:
    void="Void"

    def __init__(self, var_name, destroy, create):
        self.var_name=var_name
        self.destroy=destroy
        self.create=create

    def __get__(self, obj, owner=None):
        result=getattr(obj, self.var_name)
        if result is DefaultAttr.void:
            result=self.create()
        return result

    def __set__(self, obj, value):
        if value==self.destroy:
            value=DefaultAttr.void
        setattr(obj, self.var_name, value)

class Test:
    a=DefaultAttr("_a", set(), set)

    def __init__(self, a):
        self._a=None
        self.a=a

t=Test(set())
print(t._a, t.a)

Do you see a way to make it neater? I was wondering if I can avoid the hidden attribute _a. Also the "Void" solution seems dodgy. What would you do?


texts:
Recently, I came across this problem on Codility. I am aware there is a bit of similarity to this question and this question, but I am trying to achieve this in C#.

The problem is as follows:

  A non-empty zero-indexed array \$A\$ consisting of \$N\$ integers is
  given. The array contains an odd number of elements, and each element
  of the array can be paired with another element that has the same
  value, except for one element that is left unpaired.

  For example, in array \$A\$ such that:

  \$\begin{align} & A[0] = 9, A[1] = 3, A[2] = 9 \\ & A[3] = 3, A[4] = 9, A[5] = 7 \\ & A[6] = 9 \end{align}\$

  The elements at indexes 0 and 2 have value 9
  The elements at indexes 1 and 3 have value 3
  The elements at indexes 4 and 6 have value 9
  The element at index 5 has value 7 and is unpaired

  Write a function:

class Solution { public int solution(int[] A); }

  that, given an array \$A\$ consisting of \$N\$ integers fulfilling the
  above conditions, returns the value of the unpaired element.

  For example, given array \$A\$ such that:

  \$\begin{align} & A[0] = 9, A[1] = 3, A[2] = 9 \\ & A[3] = 3, A[4] = 9, A[5] = 7 \\ & A[6] = 9 \end{align}\$

  the function should return 7, as explained in the example above.

  Assume that:

  \$N\$ is an odd integer within the range \$[1 \dots 1,000,000]\$
  Each element of array \$A\$ is an integer within the range \$[1 \dots 1,000,000,000]\$
  All but one of the values in \$A\$ occur an even number of times.

  Complexity:

  Expected worst-case time complexity is \$O(N)\$
  Expected worst-case space complexity is \$O(1)\$, beyond input storage (not counting the storage required for input arguments).
  Elements of input arrays can be modified.

I came up with a dictionary with the unique numbers as the key and the frequencies as the value and used Linq to filter the even numbers. Indirectly this means that a number divisible by 2 would have a pair. So far the code performs well, but I believe there is room for improvement as my performance was \$O(N)\$ and also out of curiosity how does Linq achieve better performance than the loops (e.g for).

    public static int OddOccurrencesInArray(int[] A)
    {
        Dictionary<int, int> dictionary = new Dictionary<int, int>();
        foreach(var item in A)
        {
            if (!dictionary.ContainsKey(item))
            {
                dictionary.Add(item, 1);
            }
            else
            {
                dictionary[item]++;
            }
        }
       var query = dictionary.Where(k=>(k.Value % 2) != 0).ToDictionary(k=>k.Key, k=>k.Value);

        foreach(var p in query)
        {
            return p.Key;
        }

        return 0;
    }
    static void Main(string[] args)
    {
        int[] A = { 9, 3, 9, 3, 9, 7, 9};
        Console.WriteLine(OddOccurrencesInArray(A));
        Console.ReadLine();
    }
}


texts: Should methods be inside classes? in Ruby

texts:
I have coded more in Python but I am learning Ruby now. So I am trying to write a solution to create a family_tree and add and get relationships. The code below is of the file that contains the main function which is called from the command line. The below code works and solves the problem but I have written methods without classes. In python it is acceptable. Is is acceptable in ruby? Even though the code works is this how it is written in Ruby? Or does this need refactoring? If yes then please tell how?
#main_file.rb
require_relative 'family'
require_relative 'family_tree'
include FamilyTree
require_relative 'constants'
require_relative 'errors'

def is_valid_input(command)
  #User input Validation
  commands = command.split(' ')
  return false unless (commands && INPUT_FUNCTION_MAPPER.key?(commands[0]))
  return false if (commands[0] == "ADD_CHILD" && commands.length != 4)
  return true
end

def create_family_tree(family_tree)
  #Initializing the family
  family_name = family_tree[:name]
  members = family_tree[:members]

  family = Family.new(family_name)
  members.each do |name, gender, mother_name|
    family.add_member(name, gender, mother_name)
  end
  family
end

def execute_command(command, family)
  result = nil
  unless is_valid_input(command)
    raise InvalidParametersError, "Command is not valid"
  end
  command = command.split(" ")
  if command[0] == "ADD_CHILD"
    mother, name, gender = command[1..]
    result = family.add_member(name, gender, mother)
  end
  result
end

def main_method
  if ARGV.length != 1
    raise InvalidParametersError, "Please provide an input file"
  end
  input_file = ARGV[0]
  unless File.file?(input_file)
    raise InvalidParametersError, "Input file does not exist"
  end

  family = create_family_tree(FAMILYTREE)
  File.readlines(input_file).each do |line|
    line = line.strip
    puts execute_command(line, family)
  end
end

main_method()

This is executed as below:
ruby main_file.rb input.txt