texts: Formatting a price in Swift using an extension vs. a class

texts:
I have a price as a Double, which I should format it as a String.

Should I use an extension instead of classical class to encapsulate "formater", "serializers", etc? Or is there an even better alternative?

Using Class

class PriceFormatter{
    let value:Double

    init(_ value:Double){
        self.value = value
    }

    func format()->String{
        let strValue = "\(value)"
        let subStrings = strValue.split(separator: ".")
        let money = subStrings[0]
        var cents = "00"
        if subStrings.count > 1{
            cents = String(subStrings[1])

            if(cents.count == 1){
                cents = "0\(cents)"
            }
        }

        return "$\(money).\(cents)"
    }
}

Using Extension

extension Double {
    var priceFormatted:String{
        let strValue = "\(self)"
        let subStrings = strValue.split(separator: ".")
        let money = subStrings[0]
        var cents = "00"
        if subStrings.count > 1{
            cents = String(subStrings[1])

            if(cents.count == 1){
                cents = "0\(cents)"
            }
        }

        return "$\(money).\(cents)"
    }
}

Implementation

let input:Double = 5.0
let priceFromClass = PriceFormatter(input).format()
let priceFromExtension = input.priceFormatted


texts: Use of get queryset and using pass to ignore an exception and proceed in my django view

texts:
I wrote a view to update my draft object. Before updating my draft I need to see if any draft exists for package(draft.package) in db or not. If any draft is available, I need to update that draft's fields.

I am using get queryset to look into db to check draft availability. I want to know that using get queryset here is good way or not and using pass into except.

My View

def save_draft(draft, document_list):
    """
    """
    try:
        draft = Draft.objects.get(package=draft.package)
    except Draft.DoesNotExist as exc:
        pass
    except Draft.MultipleObjectsReturned as exc:
        raise CustomException
    else:
        draft.draft_document_list.filter().delete()

    draft.draft_document_list.add(*document_list)
    draft.save()

Extra information:

# models.py

class Package(models.Model):
    name = models.CharField(max_length=100)
    # -- fields

class Document(models.Model):
    # -- fields

Class Draft(models.Model):
    # --- fields
    package = models.ForeignKey(Package)
    draft_document_list = models.ManyToManyField(Document)

My algorithm:

  # first check to see if draft exists for package
  # if exists
      # overwrite draft_document_list with existed draft and save
  # if none exists
      # update passed draft object with draft_document_list

Input variables

save_draft(draft, document_list)
draft --> latest draft object
document_list --> list of documents mapped with Draft as M2M.


texts: Convert minutes portion of time to decimal

texts:
I am making an hours calculator app. It takes a start time, end time and time taken for lunch.
For the start and end time it takes a four-digit hh:mm time. For example: 10:20.
I have made a function which converts the time into a decimal,
so 10:20 = 10.33. The function works, but I feel it looks a little heavy and wondered if anyone has any suggestions of how I could make it better...
const minuteConverter = time => {
    let h = Number(time.split(':')[0]);
    let m = Math.round((1 / 60 * (Number(time.split(':')[1])) + Number.EPSILON) * 100) / 100;
    let mConverted = Number(m.toString().split('.')[1])
    return Number(`${h}.${mConverted}`)
};
console.log(minuteConverter('10:20'))

The time must be output as a number to two decimal places. For example,

'10:20' >> 10.33
'9:45' >> 9.75
'15:33' >> 15.55


texts:
This is a Tic Tac Toe game with a "new game" button. I'm after a general review of the code with some tips on how to make it simpler and tidier.

GitHub

HoboChess.java

package sample;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import java.net.URL;
import java.util.ResourceBundle;

public class HoboChess implements Initializable {

    @FXML Label systemOut;
    @FXML GridPane gridPane;
    final static int ROWS = 3;
    final static int COLUMNS = 3;
    int[][] grid;
    boolean turn;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        grid = new int[COLUMNS][ROWS];
        newVisualField(ROWS, COLUMNS);
    }

    public void newGame(ActionEvent action) {
        grid = new int[COLUMNS][ROWS];
        newVisualField(ROWS, COLUMNS);
    }

    public void WhoWon(int x, int[] zone){
        if (zone[x] == 3){
            systemOut.setText("Os won!");
        }else if (zone[x] == 30){
            systemOut.setText("Xs won!");
        }
    }

    public void winCheck(){
        int[] zone = new int[COLUMNS * ROWS];
        int zoneNumber = 0;

        for (int y = 0; y < 3; y++) {
            for (int x = 0; x < 3; x++) {
                zone[zoneNumber] = grid[y][x];
                zoneNumber++;
            }
        }

        for (int x = 0; x < 3; x++) {
            if (zone[x * 3] == zone[x * 3 + 1] && zone[x * 3] == zone[x * 3 + 2]){
                WhoWon(x * 3, zone);
            }
        }
        for (int x = 0; x < 3; x++) {
            if (zone[x] == zone[x + 3] && zone[x] == zone[x + 6]){
                WhoWon(x, zone);
            }
        }
        if (zone[0] == zone[4] && zone[0] == zone[8]){
            WhoWon(0, zone);
        }else if (zone[2] == zone[4] && zone[2] == zone[6]){
            WhoWon(2, zone);
        }
    }

    public void newVisualField(int rows, int columns){
        gridPane.getChildren().clear();
        for (int y = 0; y < rows; y++) {
            for (int x = 0; x < columns; x++) {
                ButtonCell button = new ButtonCell(grid[x][y], x, y, this);
                gridPane.add(button.aButton, x, y);
            }
        }
    }
}

class ButtonCell {

    public Button aButton;
    boolean buttonPushed;

    ButtonCell(final int button, final int x, final int y, final HoboChess hoboChess) {
        aButton = new Button(String.valueOf(button));
        aButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                if (buttonPushed == false) {
                    if (hoboChess.turn) {
                        hoboChess.grid[y][x] = 3;
                        aButton.setText("O");
                    } else {
                        hoboChess.grid[y][x] = 30;
                        aButton.setText("X");
                    }
                    hoboChess.turn = !hoboChess.turn;
                    buttonPushed = !buttonPushed;
                    hoboChess.winCheck();
                }
            }
        });
    }
}


texts:
I originally made this as a way to use character strings as a base-256 number, but then realized that I could turn it into a method for encryption instead. The only thing is that since I'm using a basic addition algorithm for the encryption process, I'm iterating through a string by one character at a time (which seems kind of slow). Are there any other ways to improve the performance of this process or am I pretty much stuck with simple iteration?

Here's the encryption code:

void encodeStr(string encryptKey, string& inputToEncrypt) {
    assert(minVal < maxVal);
    if (inputToEncrypt.length() == 0) return;

    //preliminary remainder check initialization
    int remainder = minVal; //zero value
    int keyNumCount = 0;
    int keyCount = 0;

    //variables used to determine when to stop counting numbers
    size_t keyPos = 0;
    size_t count = 0;
    size_t countEnd = inputToEncrypt.length();

    //begin numerical addition. stop once the end of both strings is reached
    while (count < countEnd) {
        //convert current characters to unsigned chars
        keyNumCount = encryptKey[keyPos];
        if (keyNumCount < minVal) keyNumCount += minVal;

        keyCount = (count < inputToEncrypt.length()) ? inputToEncrypt[count] : 0;
        if (keyCount < minVal) keyCount += minVal;

        //take advantage of signed-char overflow to calculate current value
        remainder += keyNumCount + keyCount;
        inputToEncrypt[count] = remainder;

        //check if there is a remainder to be tabulated
        remainder = (remainder > maxVal) ? 1 : 0;
        ++count;
        ++keyPos;
        if (keyPos == encryptKey.size()) keyPos = 0;

        //add 1 to the count if there is a remainder at the end of keyNum
        if (count == countEnd && remainder != 0) {
            inputToEncrypt.push_back('\0');
            ++countEnd; //variables used to avoid integer overflow
        }
    }
}

And the decryption function:

void decodeStr(string decryptKey, string& inputToDecrypt) {
    assert(minVal < maxVal);
    if (inputToDecrypt.length() == 0) return;

    //preliminary remainder check initialization
    int remainder = minVal;
    int keyNumCount = 0;
    int keyCount = 0;

    //variables used to determine when to stop counting numbers
    size_t keyPos = 0;
    size_t count = 0;
    size_t countEnd = inputToDecrypt.length();

    //make sure the program exits before the number necomes negative
    while (count < countEnd) {
        //convert current characters to unsigned chars
        keyNumCount = decryptKey[keyPos];
        if (keyNumCount < minVal) keyNumCount += minVal;

        keyCount = inputToDecrypt[count];
        if (keyCount < minVal) keyCount += minVal;

        //take advantage of signed-char overflow to calculate current value
        remainder += keyCount - keyNumCount;
        inputToDecrypt[count] = remainder;

        //check if there is a remainder to be tabulated
        remainder = (remainder > maxVal) ? 1 : 0;
        ++count;
        ++keyPos;
        if (keyPos == decryptKey.size()) keyPos = 0;
    }
}


texts:
I have this code to open an outlook appointment item:

    Public Sub OpenOutlookAppt()
    Set myolApp = CreateObject("Outlook.Application")
    Set objExpCal = Session.GetDefaultFolder(olFolderCalendar).GetExplorer
    Set objNavMod = objExpCal.NavigationPane.Modules.GetNavigationModule(olModuleCalendar)
    Set objNavGroup = objNavMod.NavigationGroups.GetDefaultNavigationGroup(olPeopleFoldersGroup)
    MyCalendar = objNavMod.NavigationGroups.NavigationFolders("Trip Calendar")
    EntryID = Cells(ActiveCell.Row, 22)
    ReDim Newa(1 To MyCalendar.Folder.Items.count)
    r = 1
    For Each Item In MyCalendar.Folder.Items
       Newa(r) = Item.EntryID
       r = r + 1
    Next Item
    For r = 1 To UBound(Newa)
       If Newa(r) = EntryID Then
          MyCalendar.Folder.Items(r).Display
           Exit Sub
       End If
   Next r
   End Sub

This code works, but it is very slow, because it needs to loop through every single appointment item in the calendar folder. So my question is, would there be a faster way of doing this? Is there a way I can just simply reference the item I want to open without having to create a loop? I have the EntryID to reference the item, but I could just as easily store some other data from the item to reference it.


texts:
I have a Scrabble game program which takes two players' words and calculates who has the winning score.
Whichever player has the highest score is the winner; there's a tie if the scores are the same.
It all seems to work how I have written it; however I am sure it can be done better. Just wondering if anyone could give me some ideas on a more efficient way to write this?
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Points assigned to each letter of the alphabet
int points[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};

int compute_score(string word);

int main(void)
{

    // Get input words from both players
    string word1 = get_string("Player 1: ");
    string word2 = get_string("Player 2: ");

    // Score both words
    int score1 = compute_score(word1);
    int score2 = compute_score(word2);

    // TODO: Print the winner
    if (score1 < score2)
    {
        printf("Player 2 wins!...");
    }
    else if (score1 == score2)
    {
        printf("Tie!");
    }
    else
    {
        printf("Player 1 wins!...");
    }
}

int compute_score(string word)
{
    // TODO: Compute and return score for string
char letters[26];
int asciiletter = 97;
int score = 0;
int i = 0;
int k = 0;

    for (i = 0; i < 26; i++)
    {
        letters[i] = asciiletter + i;

    }

    //Get the chars in the string of word and compare to all letters in alphabet letters[26]
    for(int j= 0, n = strlen(word); j < n; j++)
    {
        //if entered values uppercase, convert to lower as points are the same for either case
        word[j] = tolower(word[j]);
        for(k = 0; k < 26; k++ )
        {
                if (word[j] == letters[k])
                {
                    score = score + points[k];
                }
        }

    }
    return score;
}


texts: Random string generator that 'guesses' user inputted word

texts:
This takes a user inputted string, then tries to randomly 'guess' it. The problem is that whenever the input's length is 6 digits or more, it takes an incredibly long time to process it. Is there a more efficient way of doing this?

import random as rand
import string

def main(word):
    len_word = len(word)
    ntries = 0
    while True:
        letters = []
        for i in range(len_word):
            letters.append(rand.choice(string.ascii_lowercase))

        ntries += 1
        b = ''.join(letters)

        if b==word:
            print('Mission accomplished. It took ' + str(ntries) + ' tries.')
            break

if __name__ == '__main__':
    main(input('input a word: '))

Note: I have tried making the program guess the letters one by one, and then check if said letter was right, but it seemed to make the problem even worse.


texts:
I tried to implement a Python-esque list in C. Having not really used C in anger, I'd like some pointers on style and error handling in particular.

Header

#ifndef __TYPE_LIST_H__
#define __TYPE_LIST_H__

/*  Generic list implementation for holding a set of pointers to a type
    (has to be consistently handled by the element_match and element_delete
    functions)
*/

typedef struct list_s list_t;

#include <stdbool.h>
#include <stdint.h>

extern const uint16_t default_capacity;

list_t* list_create(
    uint16_t    initial_capacity,
    bool        (*element_match )(const void* a, const void* b),
    void        (*element_delete)(void* element));

void list_delete(list_t* list);

bool    list_append(list_t* list, void* element);
void*   list_pop(list_t* list);
bool    list_remove(list_t* list, void* element);
int16_t list_index(list_t* list, void* element);
bool    list_contains(list_t* list, void* element);
bool    list_empty(list_t* list);

#endif

Source

#include <type/list.h>
#include <stdio.h>
#include <stdlib.h>

const uint16_t default_capacity = 256;

struct list_s
{
    uint16_t length;
    uint16_t capacity;
    void**   elements;
    bool     (*element_match )(const void* a, const void* b);
    void     (*element_delete)(void* element);
};

list_t* list_create(
    uint16_t    initial_capacity,
    bool        (*element_match )(const void* a, const void* b),
    void        (*element_delete)(void* element))
{
    list_t* list = (list_t*) malloc(sizeof(list_t));
    if (!list) return NULL;

    if (!initial_capacity) {
        initial_capacity = default_capacity;
    }

    list->elements = (void**) malloc(sizeof(void*) * initial_capacity);
    if (!list->elements) return NULL;

    list->length         = 0;
    list->capacity       = initial_capacity;
    list->element_match  = element_match;
    list->element_delete = element_delete;

    return list;
}

void list_delete(list_t* list)
{
    if (!list) return;

    if (list->element_delete) {
        unsigned i;
        for (i = 0; i< list->length; i++) {
            list->element_delete(list->elements[i]);
        }
    }
    else {
        fprintf(stderr, "WARNING: no element_delete specified");
    }
    free(list);
}

bool list_append(list_t* list, void* element)
{
    if (!list || !element)
        return false;
    if (list->length >= list->capacity) {
        // expand the elements array
        list->capacity *= 2;
        list->elements = realloc(list->elements, sizeof(void*) * list->capacity);
        if (!list->elements) {
            return false;
        }
    }
    list->length += 1;
    list->elements[list->length] = element;
    return true;
}

void* list_pop(list_t* list)
{
    if (!list || list_empty(list)) {
        return NULL;
    }
    void* element = list->elements[list->length];
    list->elements[list->length] = NULL;
    list->length -= 1;
    return element;
}

bool list_remove(list_t* list, void* element)
{
    if (!list || !list->element_match) {
        return false;
    }
    unsigned i;
    bool found = false;
    for (i = 0; i < list->length; i++) {
        if (!found && list->element_match(list->elements[i], element)) {
            found = true;
            list->length -= 1;
        }
        if (found) {
            // shift all subsequent elements back one
            list->elements[i] = list->elements[i + 1];
        }
    }
    return found;
}

int16_t list_index(list_t* list, void* element)
{
    int16_t i;
    for (i = 0; i < list->length; i++) {
        if (list->element_match(list->elements[i], element)) {
            return i;
        }
    }
    return -1;
}

bool list_contains(list_t* list, void* element) {
    return (list_index(list, element) != -1);
}

bool list_empty(list_t* list)
{
    return (list->length == 0);
}


texts:
The code does seem a bit repetitive in places such as the parenturlscraper module and the childurlscraper module.

Does anyone have any recommendations for improving my code and condensing it a little?

In essence, the code scrapes this site and populates a table with details about each crash, geocoding the location data extracted from the site using Google.

__version__ = '0.1'
__author__ = 'antmancoder'

# Importing of modules required for the script to run successfully
import scraperwiki
import lxml.html
import urlparse
import urllib2
import dateutil.parser
from geopy import geocoders

# Introduction of various global variables required throughout the running of the code
urlstem = "http://planecrashinfo.com"
urlyeardb = "database.htm"
yearsource = urlparse.urljoin(urlstem, urlyeardb)
yearlist = []
sourcepageurl = []

def parenturlscraper():
    """Function scrapes all of the parent URLs from 'planecrashinfo.com/database'"""
    html = scraperwiki.scrape(yearsource)
    root = lxml.html.fromstring(html)

    hrefs = root.cssselect('td a')

    for href in hrefs:
        link = href.attrib['href']
        url = urlparse.urljoin(urlstem, link)
        yearlist.append(url)

def childurlscraper():
    """Function scrapes all of the child URLs from those scraped in the parenturlscraper module"""
    for url in yearlist:
        html = scraperwiki.scrape(url)
        root = lxml.html.fromstring(html)
        hrefs = root.cssselect('td a')
        url = url[0:34]
        for href in hrefs:
            linkurl = href.attrib['href']
            url = urlparse.urljoin(url, linkurl)
            sourcepageurl.append(url)

def sourcepagescraper():
    """Function scrapes respective data for each accident and placed it into DB"""
    for url in sourcepageurl:
        try:
            html = scraperwiki.scrape(url)
            root = lxml.html.fromstring(html)
            for tr in root.cssselect("body"):
                tds = tr.cssselect("td")
                location = coorlookup(tds[7].text_content())
                for td in tds:
                    crashinfo = {}
                    crashinfo['url'] = url
                    crashinfo['date'] = dateutil.parser.parse(tds[3].text_content()).date()
                    crashinfo['time'] = tds[5].text_content()
                    crashinfo['location'] = tds[7].text_content()
                    crashinfo['latitude'] = location[1][0]
                    crashinfo['longitude'] = location[1][1]
                    crashinfo['operator'] = tds[9].text_content()
                    crashinfo['flight no'] = tds[11].text_content()
                    crashinfo['route'] = tds[13].text_content()
                    crashinfo['aircraft type'] = tds[15].text_content()
                    crashinfo['registration'] = tds[17].text_content()
                    crashinfo['cn ln'] = tds[19].text_content()
                    crashinfo['aboard'] = tds[21].text_content()
                    crashinfo['fatalities'] = tds[23].text_content()
                    crashinfo['ground'] = tds[25].text_content()
                    crashinfo['summary'] = tds[27].text_content()

                scraperwiki.sqlite.save(unique_keys=['url'], data=crashinfo)
        except urllib2.HTTPError, err:
            if err.code == 404:
                continue

def coorlookup(location):
    """Function is called from the 'sourcepagescraper' function to geolocate locations listed on website for each accident"""
    g = geocoders.Google()
    try:
        loc = g.geocode(location, exactly_one=True)
        return loc
    except:
        return ("",("",""))

parenturlscraper()
childurlscraper()
sourcepagescraper()


texts:
below I have coded a simple configuration manager that loads config elements from a file straight into a dictionary, and also has a function for getting an element by its key in the dictionary. I just wondered if there is anything I can do to improve this..

using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Apple_Server.Application.Base.Core.Config
{
    class ConfigManager
    {
        private readonly Dictionary<string, string> configValues = null;
        private readonly FileInfo configFile = null;
        private readonly ILog _log = null;
        private bool _initialized = false;

        public ConfigManager(string filePath)
        {
            this.configValues = new Dictionary<string, string>();
            this.configFile = new FileInfo(filePath);
            this._log = LogManager.GetLogger(typeof(ConfigManager));
        }

        public void Initialize()
        {
            if (!this._initialized)
            {
                try
                {
                    foreach (string line in File.ReadLines(this.configFile.ToString()).Where(s => !string.IsNullOrWhiteSpace(s) && !s.StartsWith("#") && s.Contains("=")))
                    {
                        this.configValues[line.Split('=')[0]] = line.Split('=')[1];
                    }
                }
                catch (FileNotFoundException)
                {
                    this._log.Error("Unable to find the config file.\nPress any key to exit.");
                    Console.ReadKey(true);

                    Environment.Exit(Environment.ExitCode);
                }
                catch (Exception)
                {
                    Console.WriteLine("opppppps");
                }
            }

            this._initialized = true;
        }

        public string GetConfigElement(string Key)
        {
            return configValues[Key];
        }
    }
}


texts:
I'm trying to create an extensible system for building messages.

I want each style of message to be a unique class. I don't want the client to have to worry about the class type when creating the message (or reading it – but that is not included here).

In the code below, I only use ints and Strings. The final version would wrap ints and Strings in another class with data validation if necessary.

// Run from main
import xx.xxx.StandardFactory.*;
private void standardFactoryTest() {
    StandardFactory standardFactory = new StandardFactory();

    BasePackage testPackage1 = standardFactory.makePackage("Text for One");
    BasePackage testPackage2 = standardFactory.makePackage(999);
    BasePackage testPackage3 = standardFactory.makePackage("Text for Three", 129);

    testPackage1.printData(); // prints “StringPackage value: Text for One”
    testPackage2.printData(); // prints “IntPackage value: 999”
    testPackage3.printData(); // prints “StringIntPackage value: Text for Three, 129”
}

package xx.xxx.StandardFactory;

public class StandardFactory {
    public abstract class BasePackage{
        public abstract void printData();
    }

    public class StringPackage extends BasePackage {
        private final String value;

        StringPackage(String value) {
            this.value = value;
        }

        public void printData() {
            System.out.println("StringPackage value: " + value);
        };
    }

    public class IntPackage extends BasePackage  {
        private final int value;

        IntPackage(int value) {
            this.value = value;
        }

        public void printData() {
            System.out.println("IntPackage value: " + value);
        };
    }

    public class StringIntPackage extends BasePackage  {
        private final String stringValue;
        private final int intValue;

        StringIntPackage(String stringValue, int intValue) {
            this.stringValue = stringValue;
            this.intValue = intValue;
        }

        public void printData() {
            System.out.println("StringIntPackage value: " + stringValue + ", " + intValue);
        };
    }

    public StringPackage makePackage(String value) {
        return new StringPackage(value);
    }

    public IntPackage makePackage(int value) {
        return new IntPackage(value);
    }

    public StringIntPackage makePackage(String stringValue, int intValue) {
        return new StringIntPackage(stringValue, intValue);
    }
}

Potential problems:
    If I add new classes I need to add them to the factory. I don't see this as too much work.
    Messages could take arguments in a different order. I will not need to make every different     combination of input for my purposes so this should not be a problem.
    Large packages may need five or six different arguments. This goes against the principle of     using few arguments in a function, but it would be the exception not the rule.

I am interested specifically in the following:

Is this a common design
pattern (is it a version of the factory pattern)?
Are there more
suitable design pattern options available?
Are there any obvious
improvements?
Is it possible to have the factory static so I don't
need a factory object?

I am not interested in the following (with reasons):

Naming – This has been done as example code
Comments – I have not attempted to comment this code
Data validation – Not required at this point

Everything else is fair game.


texts:
I am trying to optimize the following code:

    private void Screen_Paint(object sender, PaintEventArgs e)
    {
        Graphics bmpGraphics = Graphics.FromImage(_screenBitmap);

        int xLoc = 0;
        int yLoc = 0;

        bmpGraphics.Clear(Color.Black);
        _resetInvoked = true;

        for (int i = 0; i < 4000; i += 2)
        {
            var bgBit = (byte) ((_screenMemory[i + 1]) & 112);
            var fgBit = (byte)((_screenMemory[i + 1]) & 15);
            SolidBrush bgBrush = _backgroundBrushesArray[bgBit/16];
            SolidBrush fgBrush = _foregroundBrushesArray[fgBit];

            if (((xLoc % 640) == 0) && (xLoc != 0))
            {
                yLoc += 12;
                xLoc = 0;
            }
            if (_resetInvoked)
            {
                string s = System.Text.Encoding.ASCII.GetString(_screenMemory, i, 1);
                var pf = new PointF(xLoc, yLoc);

                bmpGraphics.FillRectangle(bgBrush, xLoc + 2, yLoc + 3, 8f, 11f);
                bmpGraphics.DrawString(s, _renderFont, fgBrush, pf);

            }
            xLoc += 8;
        }

        _resetInvoked = false;

        e.Graphics.DrawImage(_screenBitmap, new Point(0, 0));
        bmpGraphics.Dispose();
    }

This is a Winforms User Control that mimics a console like screen. Its working just fine, but I'd like to speed it up. Running it through Telerik's JustCode performance monitor, the slowest performance seems to come from the FillRectangle and DrawString methods. Is there anyway to speed this up?


texts: Project Euler Problem #6 - sum square difference

texts:
The sum of the squares of the first ten natural numbers is:

  \$1^2 + 2^2 + ... + 10^2 = 385\$

  The square of the sum of the first ten natural numbers is:

  \$(1 + 2 + ... + 10)^2 = 55^2 = 3025\$

  Hence the difference between the sum of the squares of the first ten
  natural numbers and the square of the sum is \$3025 − 385 = 2640\$.

  Find the difference between the sum of the squares of the first one
  hundred natural numbers and the square of the sum.

//Project euler problem 6

#include <iostream>
#include <cmath>
using namespace std;

unsigned int sum(int);
unsigned int sqsum(int);

int main()
{
    cout << sum(100)*sum(100) - sqsum(100);
}

unsigned int sum(int n) // function for finding sum of n numbers
{
    return (n*(n+1))/2;
}

unsigned int sqsum(int n) // function for finding sum of squares
{
     return ((n)*(n+1)*(2*n +1 ))/6 ;
}


texts: Replacing a For Each loop with something faster

texts:
I'm a very inexperienced VBA user, I've just created my first "For Each" loop but it's very slow.  I'm happy that it works but eager to know if there is a alternative method that is quicker.  Any advice would be appreciated but please bear in mind my inexperience!

My routine takes two variables "UserSelectionMin" and "UserSelectionMax" and uses them in conjunction with the RandBetween function to place a value in every cell in the selected range (all the selected cells will be empty).

Sub RandomScores()

Dim addr As String
addr = Selection.Address

' opens a userform and collects the min value, assigned to UserSelectionMin (which is declared as an integer)
MinScore
' opens a userform and collects the max value, assigned to UserSelectionMax (which is declared as an integer)
MaxScore

For Each c In Worksheets("matches").Range(addr).Cells
If Abs(c.Value) = 0 Then c.Value = WorksheetFunction.RandBetween(UserSelectionMin, UserSelectionMax)
Next

Unload RandomScoreFormMin
Unload RandomScoreFormMax

End Sub

The MinScore and MaxScore procedures are below although these bits seem to be working OK.

Sub MinScore()
With RandomScoreFormMin.ListBoxMin
.AddItem "0"
.AddItem "1"
End With
RandomScoreFormMin.Show vbModal
End Sub

Sub MaxScore()
With RandomScoreFormMax.ListBoxMax
    .AddItem "1"
    .AddItem "2"
    .AddItem "3"
End With
RandomScoreFormMax.Show vbModal
MsgBox "You selected " & UserSelectionMin & " as your min score and " & UserSelectionMax & " as your max score"
End Sub


texts:
The question is about printing alphabets in a rangoli pattern of size/dimension input by the user.
Example:
size 3

----c----
--c-b-c--
c-b-a-b-c
--c-b-c--
----c----

The picture contains details about the challenge
OR
https://www.hackerrank.com/challenges/alphabet-rangoli/problem
Sample Code:
n = int(input('Enter a size: '))

alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

for j in range(0, n-1):
    ls_1 = str(''.join(alpha[n-1:abs(n-(j+2)):-1]))
    ls_1 = ls_1 + ls_1[-2::-1]
    ls = str('-'.join(ls_1))
    print('-' * (((n - j) * 2) - 2) + ls + '-' * (((n - j) * 2) - 2))

ls_1 = str(''.join(alpha[n-1::-1]))
ls_1 = ls_1 + ls_1[-2::-1]
ls = str('-'.join(ls_1))
print(ls)

for j in range(n-2, -1, -1):
    ls_2 = str(''.join(alpha[n-1:abs(n-(j+2)):-1]))
    ls_2 = ls_2 + ls_2[-2::-1]
    ls_s = str('-'.join(ls_2))
    print('-' * (((n - j) * 2) - 2) + ls_s + '-' * (((n - j) * 2) - 2))

Sample Output:
Enter a size: 5
--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------

Is the above code that I have done...is it a good code to say?
Also, I couldn't find any other way to solve the problem.
(I am a beginner in Python)


texts: Implementation of `ulp` and `nextAfter` for platforms where these are missing

texts:
I need the ulp method in Codename ONE, and since it isn't available there, I tried to come up with my own version. The code is completely written from scratch, based solely on the documentation of the java.lang.Math class.

Please ignore the @Override annotations. This is from a utility class I wrote to be able to use the same code for Java SE and Codename ONE development (this obviously is the Codename ONE version).

private static final double MAX_ULP = com.codename1.util.MathUtil.pow(2.0, 971);

@Override
public double ulp(double d) {
    if (Double.isNaN(d)) {
        // If the argument is NaN, then the result is NaN.
        return Double.NaN;
    } else if (Double.isInfinite(d)) {
        // If the argument is positive or negative infinity, then the
        // result is positive infinity.
        return Double.POSITIVE_INFINITY;
    } else if (d == 0.0) {
        // If the argument is positive or negative zero, then the result is Double.MIN_VALUE.
        return Double.MIN_VALUE;
    } else if (d == Double.MAX_VALUE || d == -Double.MAX_VALUE) {
        //If the argument is ±Double.MAX_VALUE, then the result is equal to 2^971.
        return MAX_ULP;
    } else {
        d = Math.abs(d);
        return nextAfter(d, Double.MAX_VALUE) - d;
    }
}

@Override
public double copySign(double x, double y) {
    return com.codename1.util.MathUtil.copysign(x, y);
}

private boolean isSameSign(double x, double y) {
    return copySign(x, y) == x;
}

@Override
public double nextAfter(double start, double direction) {
    if (Double.isNaN(start) || Double.isNaN(direction)) {
        // If either argument is a NaN, then NaN is returned.
        return Double.NaN;
    } else if (start == direction) {
        // If both arguments compare as equal the second argument is returned.
        return direction;
    } else if ((start == Double.MIN_VALUE || start == -Double.MIN_VALUE)
            && (!isSameSign(start, direction) || Math.abs(direction) < Math.abs(start))) {
        // If start is ±Double.MIN_VALUE and direction has a value such that
        // the result should have a smaller magnitude, then a zero with
        // the same sign as start is returned.
        return copySign(0.0, start);
    } else if (Double.isInfinite(start) && !Double.isInfinite(direction)) {
        // If start is infinite and direction has a value such that the
        // result should have a smaller magnitude, Double.MAX_VALUE with
        // the same sign as start is returned.
        return copySign(Double.MAX_VALUE, start);
    } else if ((start == Double.MAX_VALUE || start == -Double.MAX_VALUE)
            && (Double.isInfinite(direction) && isSameSign(start, direction))) {
        // If start is equal to ± Double.MAX_VALUE and direction has a
        // value such that the result should have a larger magnitude, an
        // infinity with same sign as start is returned.
        return start > 0.0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
    } else if (start==0.0) {
        return copySign(Double.MIN_VALUE, direction);
    } else {
        long d = ((direction > start) == (start>=0)) ? 1L : -1L;
        long x = Double.doubleToLongBits(start) + d;
        return Double.longBitsToDouble(x);
    }

}

PS: I wrote this code from scratch (for licence reasons), so if anybody has a use for this, feel free to use and modify it in your own projects.

EDIT: The code I originally posted still had an error I found after checking all corner cases against the JDK version. I had to introduce another check for start==0.0 in nextAfter to get all unit tests pass. Also, the condition for setting d was flawed.


texts: Scheme/Racket: idiomatic infix math evaluator

texts:
Inspired by xkcd and a couple of praising blog posts, I decided to try out Lisp. It seemed that the best-supported dialect was Racket, itself a variant of Scheme, so I went with that and wrote an infix mathematical expression parser to get familiar with the basic concepts.

That was a mind-bending experience considering I never did functional programming. Not having mutable variables (or not using them, anyways) and having to use recursion instead of loops was a little hard for my imperative mind.

Anyways, I came up with this. My goal was to parse infix mathematical expressions with correct precedence and parentheses. It supports additions, subtractions, multiplications and divisions. It works, but it's probably full of hints that I'm new at this, and I would like to know which parts could have been made more idiomatic.

#lang racket

;; usage: (reduce (tokenize))

;; tokenizing function
(define (tokenize)
  (define (-tokenize-operator first)
    (cond
      ([equal? first #\+] (list + (read-char)))
      ([equal? first #\-] (list - (read-char)))
      ([equal? first #\*] (list * (read-char)))
      ([equal? first #\/] (list / (read-char)))))

  (define (-tokenize-number first)
    (define (--char->number char)
      (let ([ascii-zero (char->integer #\0)])
        (- (char->integer char) ascii-zero)))

    (define (--read-number initial)
      (let ([char (read-char)])
        (if (char-numeric? char)
            (--read-number (+ (--char->number char) (* initial 10)))
            (list initial char))))

    (if (char-numeric? first)
        (--read-number (--char->number first))
        '()))

  (define (-tokenize-openparen first)
    (if (equal? first #\()
        (list #\( (read-char))
        '()))

  (define (-tokenize first endchar)
    (if (equal? first endchar)
        '()
        (let ([operator (-tokenize-operator first)]
              [number (-tokenize-number first)]
              [openparen (-tokenize-openparen first)])
          (cond
            ([pair? operator] (cons (car operator) (-tokenize (cadr operator) endchar)))
            ([pair? number] (cons (car number) (-tokenize (cadr number) endchar)))
            ([pair? openparen] (list (-tokenize (cadr openparen) #\))))
            (else (tokenize))))))

  (let ([first (read-char)])
    (-tokenize first #\newline)))

;; parsing and evaluation function
(define (reduce tokens)
  (define (-operator-priority op)
    (cond
      ([ormap (lambda (p) (equal? p op)) (list + -)] 1)
      ([ormap (lambda (p) (equal? p op)) (list * /)] 2)))

  (define (-rvalue list max-priority)
    (define (--lower-parentheses parenthesed-expression next-tokens)
          (let ([paren-result (car (-rvalue parenthesed-expression 0))])
            (-rvalue (cons paren-result next-tokens) max-priority)))

    (define (--reduce-rvalue lvalue next-tokens)
      (let* ([operator (car next-tokens)]
             [priority (-operator-priority operator)]
             [then (cdr next-tokens)])
        (if (> priority max-priority)
            (let* ([rvalue (-rvalue then priority)]
                   [value (operator lvalue (car rvalue))])
              (-rvalue (cons value (cdr rvalue)) max-priority))
            list)))

    (let ([lvalue (car list)]
          [next-tokens (cdr list)])
      (if (pair? lvalue)
          (--lower-parentheses lvalue next-tokens)
          (if (pair? next-tokens)
              (--reduce-rvalue lvalue next-tokens)
              list))))

  (car (-rvalue tokens 0)))

Thanks!


texts: Pre-calculate the winning combinations for an n-sized tic tac toe board using C++ functional programming

texts:
This code pre-calculates the winning combinations for an n-sized tic tac toe board.

I first created my function using an imperative approach.  This is just how I naturally write code most of the time.  I then tried to think about the problem using a "What I want to accomplish?" approach, rather than "What do I want it to do?"  In the end I think I still ended up with an imperative approach, just using STL algorithms as loops.

Imperative approach:

std::vector<std::vector<int>> rules3(const int x){
    using namespace std;

    vector<vector<int>> seqs;
    for(int n=0; n<x; ++n){
        vector<int> seq;
        for(int m=0; m<x; ++m){
            seq.push_back(n*x+m);
        }
        seqs.push_back(seq);
    }
    for(int n=0; n<x; ++n){
        vector<int> seq;
        for(int m=0; m<x; ++m){
            seq.push_back(n+x*m);
        }
        seqs.push_back(seq);
    }
    vector<int> seq;
    for(int n=0; n<x; ++n){
        seq.push_back(n*x+n);
    }
    seqs.push_back(seq);
    seq.clear();
    for(int n=0; n<x; ++n){
        seq.push_back(x-1+n*(x-1));
    }
    seqs.push_back(seq);

    return seqs;
}

Getting more functional:

std::vector<std::vector<int>> rules2(const int x){
    using namespace std;

    vector<vector<int>> seqs;
    vector<int> iter(x);
    iota(iter.begin(), iter.end(), 0);

    for(auto n: iter){
        vector<int> seq;
        for(auto m: iter){
            seq.push_back(n*x+m);
        }
        seqs.push_back(seq);
    }
    for(auto n: iter){
        vector<int> seq;
        for(auto m: iter){
            seq.push_back(n+x*m);
        }
        seqs.push_back(seq);
    }
    vector<int> seq;
    seq.clear();
    for(auto n: iter){
        seq.push_back(n*x+n);
    }
    seqs.push_back(seq);
    seq.clear();
    for(auto n: iter){
        seq.push_back(x-1+n*(x-1));
    }
    seqs.push_back(seq);

    return seqs;
}

Functional approach? (still feels imperative):

std::vector<std::vector<int>> rules1(const int x){
    using namespace std;

    vector<vector<int>> seqs;
    vector<int> iter(x);
    iota(iter.begin(), iter.end(), 0);

    transform(iter.begin(), iter.end(), back_inserter(seqs), [&](const int& n){
        vector<int> seq;
        transform(iter.begin(), iter.end(), back_inserter(seq), [&](const int& m){
            return n*x+m;
        });
        return seq;
    });
    transform(iter.begin(), iter.end(), back_inserter(seqs), [&](const int& n){
        vector<int> seq;
        transform(iter.begin(), iter.end(), back_inserter(seq), [&](const int& m){
            return n+x*m;
        });
        return seq;
    });
    vector<int> seq;
    transform(iter.begin(), iter.end(), back_inserter(seq), [&](const int& n){
        return n*x+n;
    });
    seqs.push_back(seq);
    seq.clear();
    transform(iter.begin(), iter.end(), back_inserter(seq), [&](const int& n){
        //return (x-n-1)*x+n; // 6,4,2
        return x-1+n*(x-1); // 2,4,6
    });
    seqs.push_back(seq);

    return seqs;
}

Output when printing:

rules3
std::vector(0, 1, 2)
std::vector(3, 4, 5)
std::vector(6, 7, 8)
std::vector(0, 3, 6)
std::vector(1, 4, 7)
std::vector(2, 5, 8)
std::vector(0, 4, 8)
std::vector(2, 4, 6)
rules2
std::vector(0, 1, 2)
std::vector(3, 4, 5)
std::vector(6, 7, 8)
std::vector(0, 3, 6)
std::vector(1, 4, 7)
std::vector(2, 5, 8)
std::vector(0, 4, 8)
std::vector(2, 4, 6)
rules1
std::vector(0, 1, 2)
std::vector(3, 4, 5)
std::vector(6, 7, 8)
std::vector(0, 3, 6)
std::vector(1, 4, 7)
std::vector(2, 5, 8)
std::vector(0, 4, 8)
std::vector(2, 4, 6)


texts:
I want to abstract away differences between zipfile and rarfile modules. In my code i want to call ZipFile or RarFile constructors depending on file format. Currently i do it like that.

def extract(dir, f, archive_type):
    '''
    archive_type should be 'rar' or 'zip'
    '''
    images = []

    if archive_type == 'zip':
        constructor = zipfile.ZipFile
    else:
        constructor = rarfile.RarFile

    with directory(dir):
        with constructor(encode(f)) as archive:
            archive.extractall()
        os.remove(f)
        images = glob_recursive('*')

    return images

Is there any more elegant way for dynamic object calling?


texts: Is it fine to use my domain model as DTO (Entity Framework Core)?

texts:
I was reading about anemic data models and rich domain models in DDD. I don't want to follow DDD completely but take rather pragmatic approach and just take some concepts out of it because clean ddd seems like an overkill. What I'm building is Web API (using ASP.NET Core and Entity Framework Core).

I don't want to maintain separate DTOs just for serializing and deserializing my models.

And I want to make most of the things like service layer and my controllers generic. Because it's mostly CRUD and logic is repeating - a lot of boilerplate.

I'm not planning to use any other ORM other than EF Core.

EF Core allows mapping to backing fields:

https://ardalis.com/encapsulated-collections-in-entity-framework-core
https://technet.microsoft.com/en-us/mt842503.aspx

Is it fine if I will design my models like this and at the same time use them as my DTOs for serialization and deserialization?

public class Player
{
    [JsonIgnore]
    public int Id { get; set; }

    [NotMapped, Required]
    public PlayerInfo ActiveInfo { get; set; } // setter must be public to allow deserialization (or use custom resolver for json net)

    [JsonIgnore]
    public ICollection<PlayerInfo> PlayerInfos { get; set; } = new HashSet<PlayerInfo>();

    private Player()
    {
    }

    public Player(PlayerInfo info)
    {
        info.IsActive = true;
        PlayerInfos.Add(info);
    }

    public void SetActiveInfo(PlayerInfo playerInfo)
    {
        var currentlyActiveInfo = PlayerInfos.SingleOrDefault(info => info.IsActive);
        if (currentlyActiveInfo != null)
        {
            currentlyActiveInfo.IsActive = false;
        }
        playerInfo.IsActive = true;
        PlayerInfos.Add(playerInfo);

        ActiveInfo = playerInfo;
    }
}

This is controller:

public class PlayerController
{
    private readonly DbContext _dbContext { get; set; }
    private readonly DbSet<Player> _players { get; set; }

    public PlayerController(DbContext dbContext)
    {
        _dbContext = dbContext;
        _players = dbContext.Set<Player>();
    }

    // Create new player
    [HttpPost]
    public ActionResult<Player> Post([FromBody] Player player)
    {
        if (!ModelState.IsValid)
        {
           //Handle validation error
        }
        // No service layer for the sake of simplicity.
        player.SetActiveInfo(player.ActiveInfo); // will use _activeInfo
        _players.Add(player); // begins tracking entity
        if (_dbContext.Save() == 0)
        {
            // handle error

        }
        return player;
    }
}


texts: Finding optimal mapping patterns that transform relational data into a linear format

texts:
I'm trying to upgrade my javascript to be more functional. I have used function composition and curry successful on less complicated code but i'm now running into a point where i'm not sure on how to approach it.

Given the below relational data structures.

// Contains all node types and its property definitions. Including any additional information like readable descriptions etc..

const nodes = [{
  id: '0ec7deff-91af-e911-812a-00155d0a5146',
  description: 'Airplanes',
  properties: [{
    id: '0fc7deff-91af-e911-812a-00155d0a5146',
    description: 'Weight'
  }, {
    id: '06c7deff-91af-e911-812a-00155d0a5146',
    description: 'Color'
  }]
}, {
  id: '278182d0-4ba2-4813-b74e-277a2296e864',
  description: 'Manufacturers',
  properties: [{
    id: '003e14d7-c11a-41e1-ad08-ab8896a3cb55',
    description: 'Boeing'
  }]
}]

// Contains only the to be used nodes and there relations(defined through children nodes) in the eventual output. The above definitions can be used to pull in additional data.

const rootNode = {
  id: '0ec7deff-91af-e911-812a-00155d0a5146',
  properties: [{
   id: '0fc7deff-91af-e911-812a-00155d0a5146',
  }],
  children: [{
    id: '278182d0-4ba2-4813-b74e-277a2296e864',
    properties: [{
      id: '003e14d7-c11a-41e1-ad08-ab8896a3cb55',
    }]
  }],
}

The rootNode is the starting point. It can contain an infinite amount of children including properties that need to be displayed. Each node needs to be checked for child nodes and be added to the eventual result. For example a linear set to be displayed on the x axis where the properties will be shown on a next row also on the x axis.

[{
  id: '0ec7deff-91af-e911-812a-00155d0a5146',
  description: 'Airplanes',
  properties: [{
    id: '0fc7deff-91af-e911-812a-00155d0a5146',
    description: 'Weight'
  }]
 }, {
   id: '278182d0-4ba2-4813-b74e-277a2296e864',
   description: 'Manufacturers',
   properties: [{
     id: '003e14d7-c11a-41e1-ad08-ab8896a3cb55',
     description: 'Boeing'
   }]
 }]

The eventual output will be shown in a 2 dimensional grid or table.

Airplanes     Manufacturers
Weight        Boeing

Or in a more elaborate example if i would provide more data and a larger query.

Airplanes                       Manufacturers
Weight    Color    Type         Boeing    Lockhead

I build a function that works and uses recursion but it just doesn't feel right. I want to pull it apart into smaller units. Note that lodash is used here, hence the shorthands etc.

function initializeNodeMapper(nodes) {
  const result = []

  return function mapNodes(node) {
    const usedPropertyIds = map(node.properties, 'id')
    const currentNode = find(nodes, ['id', node.id])
    const nodeWithReducedProperties = reduce(currentNode, (acc, value) => ({
        ...acc,
        properties: filter(value, property => indexOf(usedPropertyIds, property.id) !== -1),
    }), currentNode)

    result.push(nodeWithReducedProperties)

    if (node.children && node.children.length > 0) {
      forEach(node.children, mapNodes)
    }

    return result
  }
}

const mapData = initializeNodeMapper(nodes)
const mappedData = mapData(initialNode)

Using functional patterns i want to find a more optimal pattern of mapping and testing the code.


texts:
just wanted to check with you could this be done better:

awk -F"\t" '{
    for (i = 1; i <= NF; i++) {
        if ($i != "NULL") {
            printf("%s%s", $i, FS);
        }
    }

    printf("\n");
}' file1

The goal is to print only non-NULL fields. For example:

echo "TestRecord001 NULL    NULL    Age 29  NULL    NULL    Name    John" | awk -F"\t" '{
    for (i = 1; i <= NF; i++) {
        if ($i != "NULL") {
            printf("%s%s", $i, FS);
        }
    }

    printf("\n");
}'

will print out: TestRecord001  Age 29  Name    John


texts:
I did a working CRUD abstracted class, and I am not sure that this is a good way for it, so I would like to hear your opinion.

protected function properties(){
    $properties = array();
    foreach (self::$table_fields as $db_field){
        if(property_exists($this, $db_field)){
            $properties[$db_field] = $this->$db_field;
        }
    }
    return $properties;
}

public function create(){
    $db = db::getConnection()->conn;
    $properties = $this->properties();

    $key = implode(",",array_keys($properties));
    $value = implode(",:",array_keys($properties));

    $sql = "INSERT INTO ".self::$table."(" . $key . ") ";
    $sql.= "VALUES (:" . $value . ")";
    $stmt = $db->prepare($sql);
    foreach($properties as $key=>$value){
        $stmt->bindParam($key,$value);
    }
    if($stmt->execute()){
        print_r($stmt);
        $this->id = db::the_insert_id();
        return true;
    }else{
        print_r($stmt);
        return false;
    }
    return $stmt;
}

This is working well: I am getting TRUE as response and it creates a user in database, but I am just not sure about it.


texts:
I'd like this code to be improved

package com.array.demo;

public class BinarySearchMethod {

public static void main(String[] args) {

    int[] arr = { 2, 4, 5, 6, 8, 9, 11, 15, 17, 19, 22, 111, 117, 234, 543 };

    int search = 2;
    BinarySearchMethod b = new BinarySearchMethod();
    int size = arr.length;

    int searchPos = b.binarySearch(arr, size, search);

    if (searchPos == -1) {
        System.out.println("Element not found");
    } else {
        System.out.println("Element found in the position " + searchPos);
    }

}

public int binarySearch(int[] arr, int size, int search) {
    int start = 0;
    int end = size - 1;

    while (start <= end) {
        int mid = (start + end) / 2;
        if (arr[mid] == search) {
            return mid;
        } else if (arr[mid] < search) {
            end = mid - 1;

        } else {
            start = mid + 1;
        }
    }

    return -1;

}

}


texts:
Often I need to clean a file name using Path.GetInvalidFileNameChars(), however I do not know of a way to search for any of the invalid letters (except by using Regex) in one pass.

public string LoopMethod()
{
    StringBuilder sb = new StringBuilder(fileName);
    foreach(var invalidChar in Path.GetInvalidFileNameChars())
    {
        sb.Replace(invalidChar, '_');
    }
    return sb.ToString();
}

Regex invalidCharsRegex;
public void RegexMethodInit()
{
    var invalidChars = Path.GetInvalidPathChars().Select(c => Regex.Escape(c.ToString())).ToString();
    invalidCharsRegex = new Regex(string.Join("|", invalidChars));
}

public string RegexMethod(string fileName)
{
    return invalidCharsRegex.Replace(fileName, "_");
}

Is one of those ways the "correct" way to to this or is there a better function I am missing?


texts: Koch snowflake in Python with numpy and pygame

texts:
I've drawn a Koch snowflake with Python 3. I'm new to the Python world and would appreciate all feedback on how to make the code more Pythonic as I'm not used to these idioms, styles and modules. All other feedback is of course also greatly appreciated.

The snowflake is constantly redrawn in preparation for the future. This main loop is based on the pygame.draw example but feels a bit clunky with done=False;while not done etc.

import pygame
import numpy
from math import pi, sin, cos

# some constants
FPS = 10
WINDOW_SIZE = [400,400]
LINE_WIDTH = 1
MIN_LINE_LENGTH = 1 # when to terminate recursion

# main loop
def main():
    # init pygame and window
    pygame.init()
    screen = pygame.display.set_mode(WINDOW_SIZE)
    # loop until user exits
    done = False
    clock = pygame.time.Clock()
    while not done:
        # limit frame rate
        clock.tick(FPS)
        # check if user exited
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done=True
        # clear screen
        screen.fill([255,255,255])
        # calculate the three corners of the snowflake,
        # an equilateral triangle centered on the screen
        screen_center = numpy.array([ WINDOW_SIZE[0]/2, WINDOW_SIZE[1]/2 ])
        radius = WINDOW_SIZE[1]/2 # not really radius? but distance from center to corner
        snowflake_top   = screen_center + vector_from_polar( radius, pi/2 )
        snowflake_left  = screen_center + vector_from_polar( radius, pi/2 + 2*pi/3 )
        snowflake_right = screen_center + vector_from_polar( radius, pi/2 + 4*pi/3 )
        # draw the snowflake
        draw_koch_line( screen, snowflake_top,   snowflake_left  )
        draw_koch_line( screen, snowflake_left,  snowflake_right )
        draw_koch_line( screen, snowflake_right, snowflake_top   )
        # flip buffers
        pygame.display.flip()

# vector_from_polar: constructs a vector from its angle and mangitude
def vector_from_polar( magnitude, angle ):
    return magnitude * numpy.array( [ numpy.cos( angle ), numpy.sin( angle ) ] )

# draw_koch_line: (approximately) draws a Koch line between the points specified
def draw_koch_line(screen, line_start, line_end ):
    if numpy.linalg.norm( line_end - line_start ) / 3 < MIN_LINE_LENGTH:
        # last iteration: draw the line
        pygame.draw.line(screen, [0,0,0], line_start, line_end, LINE_WIDTH )
    else:
        # find the normal to this line
        line_normal = numpy.array([
                line_end[1]-line_start[1],
                line_start[0]-line_end[0] ])
        # find the three points of the "triangle" used to define the segments
        triangle_left  = 2/3*line_start + 1/3*line_end # 1/3 of this line
        triangle_right = 1/3*line_start + 2/3*line_end # 2/3 of this line
        triangle_top   = 1/2*line_start + 1/2*line_end + \
                         numpy.sqrt(3)/2/3 * line_normal # point "above" the line
        # recurse for each segments
        draw_koch_line(screen, line_start,     triangle_left)
        draw_koch_line(screen, triangle_left,  triangle_top)
        draw_koch_line(screen, triangle_top,   triangle_right)
        draw_koch_line(screen, triangle_right, line_end)

main()


texts:
I wrote / modified two scripts to count Facebook and Twitter reactions. Anything I can do to improve these?

Count Facebook Reactions

 class FacebookReactions
 {
    public $url;

    function __construct($url)
    {
        $query  = 'SELECT like_count, total_count FROM link_stat WHERE url="'.$url.'"';
        $apifql="https://api.facebook.com/method/fql.query?format=json&query=".urlencode($query);

        $json=file_get_contents($apifql);
        $fb_obj=json_decode($json);
        $fb_array=object_2_array($fb_obj);

        $this->total = $fb_array[0]['total_count'];
        $this->like = $fb_array[0]['like_count'];
    }
 }

Count Twitter Reactions

 class TwitterReactions
 {
    public $url = '';
    public $output = array();
    public $count = 0;
    public $total = 100;

    function __construct($url,$total)
    {
        $this->url = $url;

        $query = 'http://search.twitter.com/search.json?q='.$url.'&result_type=mixed&rpp='.$total;
        $reactions=file_get_contents($query);
        $reactions_array=json_decode($reactions, TRUE);

        foreach($reactions_array as $key => $results)
        {
            if(is_array($results)){
                foreach($results as $key => $result){
                    $this->output[$key]['user'] = $result['from_user'];
                    $this->output[$key]['image'] = $result['profile_image_url'];
                    $this->output[$key]['message'] = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","\\0", $result['text']);
                    $this->output[$key]['date'] =  date('m.d.y',strtotime($result['created_at']));
                }
            }
        }
        $this->count = count($this->output);
    }
 }


texts:
I haven't done much Python in the past, so I was wondering if you could look over my code and make sure everything is up to snuff?

I know programs that do this exist already, but I am having a challenge with my friend on who can build a simple backup system for our college files.

I have run the code through Pylint and a PEP8 code checker, and fixed the errors it produced.

"""
Basic Python Backup
Nat Zimmermann
"""

# SETTINGS
TIME_FORMAT = '%d-%m-%Y-%H:%M:%S'
MAX_DIRS = 5

import shutil
from datetime import datetime
from os import walk

def get_dirs(dirs):
    """Get all immidiate directories in the current directory"""

    converted_dirs = []

    if len(dirs) > MAX_DIRS:
        test_dir = None

        for test_dir in dirs:
            try:
                app_dir = datetime.strptime(test_dir, TIME_FORMAT)
                converted_dirs.append(app_dir)

            except ValueError:
                print("Directory %s does not match date format, ignoring..."
                      % test_dir)

    return converted_dirs

def remove_dirs():
    """Remove the oldest directories"""

    dirs = walk('.').__next__()[1]
    converted_dirs = get_dirs(dirs)

    if converted_dirs:
        try:
            oldest_dir = datetime.strftime(min(converted_dirs), TIME_FORMAT)
            shutil.rmtree(oldest_dir)

            print("Removed old directory %s" % oldest_dir)

            remove_dirs()

        except IOError as error:
            print(error)

def copy_directory():
    """Copiy a given directory to a new directory with the current date"""

    old_directory = input("Directory to copy: ")
    new_directory = datetime.now().strftime(TIME_FORMAT)

    print("Copying...")

    try:
        shutil.copytree(old_directory, new_directory)
        print("Successfully copied files to directory %s" % new_directory)

    except IOError as error:
        print(error)
        copy_directory()

copy_directory()
remove_dirs()


texts: Establishing parameters for a sales report, with default boolean and date values

texts:
The idea is that I am getting the params from a GET request in the form of a Hash (symbol→str) and I want to transform them into dates and booleans. For that reason, I created two private methods to_date and to_b.

class Report
  include ActiveModel::Model

  attr_accessor :start_date, :end_date, :show_sales, :show_daily_active_users,
                :show_registered_cc, :show_all_time_registered_cc, :show_users

  def initialize(params)
    params ||= {}
    @start_date = to_date(params, :start_date, Time.zone.today - 7.days)
    @end_date = to_date params, :end_date, Time.zone.today
    @show_sales = to_b params, :show_sales, true
    @show_daily_active_users = to_b params, :show_daily_active_users, true
    @show_registered_cc = to_b params, :show_registered_cc
    @show_all_time_registered_cc = to_b params, :show_all_time_registered_cc
    @show_users = to_b params, :show_users
  end

  def sales
     (...)
  end

  (...)

  private

  def to_date(params, key, default_val)
    if params.key?(key)
      Date.parse(params[key])
    else
      default_val
    end
  end

  def to_b(params, key, default_true = false)
    default_val = '1' if default_true
    params.fetch(key, default_val) == '1'
  end
end

The problem is that Rubocop says that the Assignment Branch Condition size for the method initialize is too high (15.81 over a limit of 15).

Is there anything I could change to fix that? I don't think that creating a new class just to do that is worth it.


texts:
I have just started reading the GO4 book to learn the OOD concepts.
In order to practice the Prototype pattern, I implemented a small example (the idea for colored shapes was taken from "refactoring.guru"). Following is my code with some questions beneath.
Prototype definition:
enum class Shape
{
    Circle,
    Rectangle,
};

class ColoredShapePrototype
{
protected:
    std::string color_;
public:
    ColoredShapePrototype() {}
    ColoredShapePrototype(std::string color) : color_(color) {}
    virtual ~ColoredShapePrototype() {}
    virtual ColoredShapePrototype* Clone() const = 0;
    virtual void ShapeDetails() { std::cout << "Color: " << color_ << "\n"; }
    virtual void UpdateColor(int color) { color_ = color; }
};

class ColoredCirclePrototype : public ColoredShapePrototype
{
private:
    int radius_;
public:
    ColoredCirclePrototype(std::string color, int raduis) : ColoredShapePrototype(color), radius_(raduis) {}
    ColoredShapePrototype* Clone() const override { return new ColoredCirclePrototype(*this); }
    void ShapeDetails() { ColoredShapePrototype::ShapeDetails(); std::cout << "Radius: " << radius_ << "\n"; }
};

class ColoredRectanglePrototype : public ColoredShapePrototype
{
private:
    int height_;
    int width_;
public:
    ColoredRectanglePrototype(std::string color, int height, int width) : ColoredShapePrototype(color), height_(height), width_(width) {}
    ColoredShapePrototype* Clone() const override { return new ColoredRectanglePrototype(*this); }
    void ShapeDetails() { ColoredShapePrototype::ShapeDetails(); std::cout << "Height: " << height_ << "\nWidth:" << width_ << "\n"; }
};

class ShapesPrototypeFactory
{
private:
    std::unordered_map<Shape, ColoredShapePrototype*> prototypes_;
public:
    ShapesPrototypeFactory() {
        prototypes_[Shape::Circle] = new ColoredCirclePrototype("White", 5);
        prototypes_[Shape::Rectangle] = new ColoredRectanglePrototype("White", 2, 3);
    }
    ~ShapesPrototypeFactory() {
        delete prototypes_[Shape::Circle];
        delete prototypes_[Shape::Rectangle];
    }
    ColoredShapePrototype* CreatePrototype(Shape shape) { return prototypes_[shape]->Clone(); }
};

Usage in main:
ShapesPrototypeFactory prototype_factory;
ColoredShapePrototype* circ = prototype_factory.CreatePrototype(Shape::Circle);
circ->ShapeDetails();
ColoredShapePrototype* rect = prototype_factory.CreatePrototype(Shape::Rectangle);
rect->ShapeDetails();
delete circ;
delete rect;

Questions:

Interfaces in general - pure virtual functions and other variables are declared, and derived classes should implement those. Suppose I want to add a specific capability (with unique data member and member function) to the derived - Does it contradict the interface idea? (Because, if I have a pointer from base to derived, this pointer will not recognize the specific method...). If it is OK, Is there a way to execute a derived function through the interface(who doesnt have this function..)?

while debugging and watching circ variable, I can see the variable in the memory window, and I see "white" color, but I cant find the radius there. Is there a way i can see specific data member address in the memory? (I have tried circ->radius_ etc. none was working..)

I have seen that most implementations are using "unique_ptr". I know its basic usage, but how critical it is? and why not use it all the times rather than a regular pointer actually? and where are the places I should use it in the prototype pattern?

Implementing Copy Constructor in case of non-stack variables (shallow/deep copying) for the clone operation - Is a CCtor in the base class is sufficient or the derived is required as well?

Code review - better syntax/design/ideas/improvements?

Thanks in advance, I will highly appreciate your help!


texts: Optimize K-Mean for large number of clusters

texts:
I am writing a Python code for KMeans clustering.
The aim of this post is to find out how I can make my below mentioned code optimal when the number of clusters is very large. I am dealing with data with tens of millions of samples and scores of features. The number of clusters that I am talking about is of the order of 500000. I have checked the correctness of the code by comparing that with results from scikit-learn's implementation of KMeans clustering.
I am aware that I can use sckit learn for KMeans clustering. But, I am writing my own custom Python code for a few purposes which include but are not limited to the below reasons.

To be able to change distance functions for my specific work assignments : from Euclidean distance to Huang distance.
To use this custom code for various other tasks like anomaly detection.

Below is my code:
class KMeans:
    def __init__(self, arr, k):
        self.arr = arr
        self.k = k

    # Main driver function
    def loop_over_centers(self, max_iter):

        # Choose random centroids.
        random_centers = np.random.choice(len(self.arr), self.k, replace=False)

        # Iterate till a certain max number of iterations.
        for iteration in range(0, max_iter, 1):
            cluster_dict = defaultdict(list)

            if iteration == 0:
                chosen_centers = random_centers

            # Assign samples to cluster centers based on minimum distance
            for i in range(len(self.arr)):
                distance_list = []
                for center in chosen_centers:
                    distance_list += [self.distance(self.arr[center], self.arr[i])]

                cluster_dict[chosen_centers[np.argmin(distance_list)]] += [i]

            chosen_centers = self.update_center(cluster_dict)

        return cluster_dict

    # Distance between two arrays
    def distance(self, arr1, arr2):
        return np.sqrt(np.sum(np.subtract(arr1, arr2) ** 2))

    # Gives new centroids with each new iteration
    def update_center(self, cluster_dict):
        cluster_center = []

        for cluster in list(cluster_dict.keys()):
            cluster_list = []

            # Find samples corresponding to each cluster.
            for sample in cluster_dict[cluster]:
                cluster_list += [self.arr[sample]]

            # Mean of samples in a given cluster.
            cluster_mean = np.mean(np.array(cluster_list), axis=0).tolist()

            distance_from_mean = []

            # Find which sample is closest to mean of cluster.
            for sample in cluster_dict[cluster]:
                distance_from_mean += [self.distance(cluster_mean, self.arr[sample])]

            # Build an updated list of cluster centers.
            cluster_center += [cluster_dict[cluster][np.argmin(distance_from_mean)]]

        return cluster_center

arr = [[12, 3, 5], [1, 6, 7], [8, 92, 1], [6, 98, 2], [5, 90, 3], [29, 5, 6], [11,4,4], [30, 6, 5],]

testKMeans = KMeans(arr, 3)
testKMeans.loop_over_centers(1000)

In a real world case, arr will have tens of millions of samples and I would like to have about 500000 cluster centroids. At present the performance of code is okay when arr has tens of millions of samples and number of cluster centroids is small (10-20). But is very slow when the number of clusters is very large (hundreds of thousands).
How can I improve the runtime performance of this code for large number of cluster centers?.


texts:
I created a small sample project using caliban, akka-persistence and ZIO. I'm not really happy with the wiring code:

    implicit val defaultRuntime: DefaultRuntime = new DefaultRuntime {}

    val counter = context.spawn(Counter("counter"), "counter")
    val service: CounterService = defaultRuntime.unsafeRun(CounterService.make(counter, scheduler, timeout))

    val graphQl = GraphQlApi(service)
    val routes = HttpRoutes(context.system, graphQl.interpreter)

    val serverBinding: Future[Http.ServerBinding] = Http()(untypedSystem).bindAndHandle(routes.counterRoutes(ec, defaultRuntime), "localhost", port)

The CounterService is wrapping the ask-calls to the persistent actor in a zio.Task:

class CounterService(counter: ActorRef[Counter.Command], scheduler: Scheduler, timeout: Timeout) {

  implicit val s: Scheduler = scheduler
  implicit val t: Timeout = timeout

  def getCounter: Task[Counter.Count] = {
    ZIO.fromFuture { ec =>
      counter ? GetCount
    }
  }
}

object CounterService {
  def make(countManager: ActorRef[Counter.Command], scheduler: Scheduler, timeout: Timeout): UIO[CounterService] = {
    for {
      manager <- ZIO.succeed(countManager)
    } yield new CounterService(manager, scheduler, timeout)
  }
}

For creating the Routes I need to pass the GraphQLInterpreter, the ExecutionContext and the zio.Runtime:

case class HttpRoutes(system: ActorSystem[Nothing], interpreter: GraphQLInterpreter[zio.ZEnv, _]) {

  def counterRoutes(ec: ExecutionContext, runtime: Runtime[zio.ZEnv]): Route = {
    path("graphql") {
      AkkaHttpAdapter.makeHttpService(interpreter)(ec, runtime)
    }
  }

}

The project compiles and I can execute graphql requests just fine. But I'm not satisfied (nor experienced) with wiring these libraries together. To me it feels like there is space for improvement on how to wire up these libraries but I'm kinda stuck.

Does anyone has some input on this vague question? Any other advice/feedback to my code is much appreciated as well :)

Full project source code can be found here: link to github project


texts: Share data between controllers with service

texts:
I have to share data between controllers. In this example I'm using an aside. This has the exact same functionality as a modal from Angular Bootstrap.

I put the aside in my service so I can close it from another controller.

The problem is that I have to share the complete scope / object in the service so i can share the data between the controllers. In my real example, there are many lists in this object so it seems like it's a bit of overkill if I put the complete object in my service.

Is there a better way to do this?

I have to change the value from the scope on my page (= input field) but also in the aside. But the aside must have a different controller. Or can I use the same controller (MainController) for the aside? If I add the MainController to the aside, it instantiate the MainController again and the binding is lost. (See code example below)

Plunker

AsideService.initAside($aside.open({
    placement: 'right',
    templateUrl: 'PropertiesSidebar.html',
    size: 'lg',
    controller: 'MainController'
  }));


texts:
I'm making my own script editor (in this case for Arma: Cold War Assault) because I want to learn and this is challenging enough.

Let me just get this out of the way: please don't tell me that I should do easier things. I want to do this anyway.

So, basically I have the simple GUI for now with a working new/open/save file menu.

I've managed to highlight certain words with different colors (because I want to tackle the hardest part first) but it's not efficient.

I've come up with several ideas for the algorithm (didn't implement them all), but I want to know what you'do, if there's a certain way and what I am doing wrong.

This all happens inside a JTextPane class.

The arrays containing the reserved words:

Collections.addAll(keywords, "private", "public", "if", "not", "then", "else", "else if");
Collections.addAll(operators, "+", "-", "=", "==", "?", "!","(", ")","{", "}", "_", "-", "^", "<", ">");

ArrayList<String> keywords = new ArrayList<String>();
ArrayList<String> operators = new ArrayList<String>();

Everytime the user makes an update to the document, it get's updated:

@Override
public void insertUpdate(DocumentEvent e) {
    update();
}

@Override
public void removeUpdate(DocumentEvent e) {
    update();
}

When the user stops typing, it waits 500 ms to update the screen:

Timer t;

/**
 * Updates the text when user stops typing
 */
public void update(){

    if (t != null) {
        if (t.isRunning())
            t.stop();
    }

    t = new Timer(250, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            long start = System.currentTimeMillis();

            String text = getText();

            SimpleAttributeSet attrs = new SimpleAttributeSet();
            StyleConstants.setForeground(attrs, Color.BLACK);
            StyledDocument doc = getStyledDocument();
            doc.setCharacterAttributes(0, text.length(), attrs, true);

            int index = 0, carriage = 0;

            while ((index < text.length())) {

                if (text.codePointAt(index) == 10) {
                    carriage += 1;
                }

                for (String s : Keywords.listKeywords()) {
                    if (text.startsWith(s, index)){
                        changeColor(doc, reserved.get(s), index, carriage, s.length(), false);
                        index += s.length();
                        break;
                    }
                }

                for (String s : Keywords.listOperators()) {
                    if (text.startsWith(s, index)){
                        changeColor(doc, reserved.get(s), index, carriage, s.length(), false);
                        index += s.length();
                        break;
                    }
                }

                index++;
            }
            wordCount.setText("word count: " + index);
            System.out.println("Iterations took: "
                    + (System.currentTimeMillis() - start) + " ms");

            t.stop();
        }
    });
    t.start();
}

private void changeColor(StyledDocument doc, Color color, int index, int carriage, int length, boolean replace) {
    SimpleAttributeSet attrs = new SimpleAttributeSet();
    StyleConstants.setForeground(attrs, color);
    doc.setCharacterAttributes(index - carriage, length, attrs, replace);
}

How would I go about doing this more efficiently?

As of right now, with almost 145.000 words i have a delay of about 400 ms with 12 keywords and other words.


texts: Simple gas station calculator for Windows

texts:
After reading some beginner textbooks on C++ programming, I decided to write a trivial unit conversion program. Since I am working on Windows, the console windows still use codepage 850 by default, and I wanted to output the Euro currency sign. I also wanted to get the error handling right, since that's one of the topics beginner books often ignore. And, since I'm German, I wanted to use the appropriate decimal separators.

Now my "trivial" program has become quite large. Does it have to be that large? Is there some way to make it smaller, without giving up one of its features?

#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <locale>
#include <string>

#include <Windows.h>

class SwitchToUtf8 {
private:
    UINT in;
    UINT out;
public:
    SwitchToUtf8() {
        in = GetConsoleCP();
        out = GetConsoleOutputCP();
        SetConsoleCP(65001);
        SetConsoleOutputCP(65001);
    }
    ~SwitchToUtf8() {
        SetConsoleCP(in);
        SetConsoleOutputCP(out);
    }
};

int main() {
    SwitchToUtf8 temporarily;

    std::locale::global(std::locale(""));
    std::wcin.imbue(std::locale());
    std::wcout.imbue(std::locale());
    std::wcerr.imbue(std::locale());

    const double price_per_liter = 1.31;

    std::wcout << "How much gas did you refuel? ";
    std::wcin.sync();

    double liter;
    if (std::wcin >> liter) {
        double price = liter * price_per_liter;
        std::ios::fmtflags saved_flags(std::wcout.flags());
        std::wcout << "That sums up to " << std::fixed << std::setprecision(2) << price << " €.\n" << saved_flags;
        std::wcout << price << "\n";
    }
    else {
        std::wcin.clear();

        std::wstring line;
        if (std::getline(std::wcin, line)) {
            std::wcerr << "Input error: " << line << "\n";
        }
        else {
            std::wcerr << "Other error\n";
        }
    }
}


texts:
When checking for existence of a substring I have been doing this:

var that = "ok hello cool";
if( that.indexOf('hello') + 1 ) {
}

Instead of:

if( that.indexOf('hello') != -1 ) {
}

Am I overlooking something or is there a reason not to do this.

Update:

Yes, I was indeed unaware of the even simpler method of:

if ( ~that.indexOf( 'hello' ) ) {

}

You can read about the ~ bitwise operator and the other queer bitwise operators here:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators


texts:
I'm trying to remove the duplicate from the list and count the list after removing the duplicates

seq = [[1,2,3], [1,2,3], [2,3,4], [4,5,6]]
new_seq = [[1,2,3], [2,3,4], [4,5,6]]
count = 3

My code takes around 23 seconds for around 66,000 lists in a list

How can I make my code faster?

def unique(seq):
    new_seq = []
    count = 0
    for i in seq:
        if i not in new_seq:
            new_seq.append(i)
            count += 1
    return count


texts: Cumulative transition matrix Markov Chain simulation

texts:
I have a cumulative transition matrix with probabilities for all the possible states from 1 to 5. Now the algorithm for simulating future states is following: the initial state is selected randomly, and a random value between 0 and 1 is then produced by uniform random number generator.To determine the next state in the Markov process the value of the random number is is compared with the elements of of the *i-*th row of the cumulative transition matrix determined from the preceding state. If the value of the random number is greater than the cumulative probability of the preceding state but less then or equal to the cumulative probability of the succeeding state, the succeeding state is chosen to represent the next state.

cum_trans <- matrix(c(0.1686747,0.4337349,0.6265060,0.7289157,1,
              0.2765957,0.5053191,0.6648936,0.7659574,1,
              0.2518519,0.4740741,0.6518519,0.7407407,1,
              0.1911765,0.4705882,0.6617647,0.7941176,1,
              0.2096774,0.4892473,0.6827957,0.7419355,1
              ), nrow = 5, ncol = 5, byrow = TRUE)

       [,1]      [,2]      [,3]      [,4]      [,5]
 [1,] 0.1686747 0.4337349 0.6265060 0.7289157    1
 [2,] 0.2765957 0.5053191 0.6648936 0.7659574    1
 [3,] 0.2518519 0.4740741 0.6518519 0.7407407    1
 [4,] 0.1911765 0.4705882 0.6617647 0.7941176    1
 [5,] 0.2096774 0.4892473 0.6827957 0.7419355    1

state<-matrix(NA, nrow=1,ncol=25)
i<-sample(1:5,1)
state[1]<-i
for (k in 2:25){
 rr<-runif(1)
 state[k]<-findInterval(rr,cum_trans[i,])+1
 i<-state[k]
 }
 state

So I'm not sure if I implemented the algorithm correctly. Can someone suggest modifications or improvements.


texts: Search suggestion box with jQuery and AJAX

texts:
var searchUser = function(searchQuery){
    var request = $.ajax({
        url:"search.php",
        type: "POST",
        data: { search:searchQuery},
        success: function(reply){
            $("#search-box").css("display", "block");
            $("#search-box").html(reply);
        }
    });
}

I know this is a terrible way of doing it, right? How else would I best go about outputting the search result to my #search-box? Right now, I send an AJAX request to my search.php file which returns all the HTML of the search. Surely this wouldn't be good from a performance perspective?


texts: Validating Shift class through builder pattern

texts:
I have a Shift class that looks like this:

public class Shift
{
    public string Name { get; private set; }
    public TimeSpan StartHour { get; private set; }
    public TimeSpan EndHour { get; private set; }

    public TimeSpan Duration => EndHour - StartHour;

    private Shift()
    {
    }
}

Since there are some limitations and restrictions to what StartHour && EndHour can be I needed some way to validate the input of the class and if it fails - prevent the creation of the object or at least not return it to the user, without throwing an exception because I want to allow the user to re-enter the arguments if some of them were invalid.

Than I created an interface and some derived classes to be injected during the construction of the object:

public interface IShiftValidator
{
    Exception FailedValidationException { get; }
    string FailedValidationMessage { get; }
    bool IsValid(Shift shiftToValidate);
}

public class ShiftRangeValidator : IShiftValidator
{
    public Exception FailedValidationException { get; private set; }
    public string FailedValidationMessage { get; private set; } = string.Empty;

    public bool IsValid(Shift shiftToValidate)
    {
        if (shiftToValidate.Duration.TotalMinutes <= 0)
        {
            FailedValidationException = new ArgumentOutOfRangeException(nameof(shiftToValidate.Duration));
            FailedValidationMessage = "Shift's duration cant be less than 1 minute.";
            return false;
        }
        if (shiftToValidate.Duration.TotalHours > SharedSettings.MaximumShiftHours)
        {
            FailedValidationException =
                new ArgumentOutOfRangeException(nameof(shiftToValidate.Duration));
            FailedValidationMessage = "Shift's duration cant be longer than the maximum allowed hours.";
            return false;
        }
        return true;
    }
}

After that I implemented the builder pattern as a nested class in the Shift class, so I can make the constructor of the class private and construct the object fully in the builder class:

public class ShiftBuilder
{
    private Shift _shift;

    public ShiftBuilder()
    {
        _shift = new Shift();
    }

    public ShiftBuilder WithName(string name)
    {
        _shift.Name = name;
        return this;
    }

    public ShiftBuilder WithStartHour(TimeSpan startHour)
    {
        _shift.StartHour = startHour;
        return this;
    }

    public ShiftBuilder WithEndHour(TimeSpan endHour)
    {
        _shift.EndHour = endHour;
        return this;
    }

    public Shift Build(IEnumerable<IShiftValidator> validators)
    {
        if (validators != null)
        {
            foreach (var shiftValidator in validators)
            {
                if (!shiftValidator.IsValid(_shift))
                {
                    if (!string.IsNullOrEmpty(shiftValidator.FailedValidationMessage))
                    {
                        MessageBox.Show(shiftValidator.FailedValidationMessage);
                    }
                    throw shiftValidator.FailedValidationException;
                }
            }
        }
        Shift shift = _shift;
        _shift = null;
        return shift;
    }
}

Here's an example usage:

Shift.ShiftBuilder shiftBuilder = new Shift.ShiftBuilder();
var a = shiftBuilder.WithName("Test")
    .WithStartHour(new TimeSpan(12, 0, 0))
    .WithEndHour(new TimeSpan(24, 0, 0))
    .Build(new[] { new ShiftRangeValidator() });

var b = shiftBuilder.Build(null); // null
var c = shiftBuilder.Build(new[] {new ShiftRangeValidator()}); // crash

I have few concerns:

Is it clear that you're unable to reuse the same ShiftBuilder twice?
Is IShiftValidator good as it is or should I separate it in few smaller interfaces?


texts:
I wrote this program to match square brackets as part of a Brainf**k interpreter. I'm aware that it gets caught in an infinite loop if brackets are entered like this: ][.

Are there any performance improvements I can make?
Should I change any variable names?
Are there other syntax errors that will break the code?
How can I fix said errors?
Anything else I did wrong?

//Matches an opening or closing bracket to a corresponding opening or closing bracket
int getMatchingBraceIndex(unsigned int braceIndex, char* str) {
    //Current nesting level
    int level = 0;
    //Matching brace's nesting level
    //(Matching braces have to be at the same level)
    int returnLvl = -1;

    /*******************************************************************************\
     * Note:                                                                       *
     * If brace given is open brace, iterate through string from beginning to end  *
     * If brace given is close brace, iterate through string from end to beginning *
    \*******************************************************************************/
    //If brace given is open brace
    if (str[braceIndex] == '[') {
        //Iterator
        int i = 0;

        //Iterate through given string
        for (i; i < strlen(str); i++) {
            //If current character of string is open brace
            if (str[i] == '[') {
                //Increment nesting level
                level++;
                //If current character is given brace, assume that matching brace is on the same nesting level
                if (i == braceIndex) {
                    returnLvl = level;
                }
            //If current character of string is close brace
            } else if (str[i] == ']') {
                //If currnet nesting level is nesting level of matching brace, return current index
                if (level == returnLvl) {
                    return i;
                //Otherwise, decrement nesting level and keep going through the string
                } else {
                    level--;
                }
            }
        }
    //If brace given is close brace
    } else if (str[braceIndex] == ']') {
        //Iterator
        int i = strlen(str) - 1;

        //Iterate through given string
        for (i; i >= 0; i--) {
            //If current character of string is close brace
            if (str[i] == ']') {
                //Increment nesting level
                level++;
                //If current character is given brace, assume that matching brace is on the same nesting level
                if (i == braceIndex) {
                    returnLvl = level;
                }
            //If current character of string is open brace
            } else if (str[i] == '[') {
                //If nesting level is nesting level of matching brace, return current index
                if (level == returnLvl) {
                    return i;
                //Otherwise, decrement nesting level and keep going through the string
                } else {
                    level--;
                }
            }
        }
    } else {
        //Error
        setColor(RED, BLACK);
        printf("Unable to match brace at index %i\n", braceIndex);
        setColor(DEFAULT, BLACK);
        return -1;
    }

    return -1;
}


texts: Convert int64 to custom base64 number string

texts:
I want to convert int64 to custom base 64 number string, with this specification:

0..9   -> 0..9
10..35 -> a..z
36..61 -> A..Z
62     -> _
63     -> -

Is this implementation correct/efficient?

func EncodeLogKey(id int64) string {
  str := make([]byte,0,12)
  if id == 0 { return "0" }
  for id>0 {
    var ch rune
    mod := rune(id % 64)
    if mod <= 10 {
      ch = '0' + mod
    } else if mod <= 10+26 {
      ch = 'a' + (mod - 10)
    } else if mod <= 10+26+26 {
      ch = 'A' + (mod - 10 - 26)
    } else if mod % 2 == 0 {
      ch = '_'
    } else {
      ch = '-'
    }
    str = append(str,byte(ch))
    id /= 64
  }
  return string(str)
}

func DecodeLogKey(logKey string) (int64, error) {
  res := int64(0)
  for ch := range logKey {
    res *= 64
    mod := int64(ch)
    if ch >= '0' && ch <= '9' {
      res += (mod - '0')
    } else if ch >= 'a' && ch <= 'z' {
      res += 10 + (mod - 'a')
    } else if ch >= 'A' && ch <= 'Z' {
      res += 10 + 26 + (mod - 'A')
    } else if ch == '_' {
      res += 10 + 26 + 26
    } else if ch == '-' {
      res += 10 + 26 + 26 + 1
    } else {
      return res, fmt.Errorf("Invalid logKey character: '%c'", res)
    }
  }
  return res, nil
}


texts: Serializing types with a common superclass

texts:
I have written code responsible for saving data to a file using Serialization. I think that a natural way to avoid repetition is to use inheritance but I'm not sure if it would work because of generics.

How can I remove all the repetition in the below code?

Some general information:

There is a class StoredItem and classes PipeCable, Element, ValveMotor which extend StoredItem.
There is Data class in which are ObservableLists of PipeCable, Element, ValveMotor

The code that I'd like to improve but I don't know how:

private void savePipeCableList(Data data) {
    try {
        Path path = Paths.get(Strings.dataPipeCableFileName);
        OutputStream fos = Files.newOutputStream(path);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(new ArrayList<PipeCable>(data.getPipeCableList()));
        oos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void saveElementList(Data data) {
    try {
        Path path = Paths.get(Strings.dataElementFileName);
        OutputStream fos = Files.newOutputStream(path);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(new ArrayList<Element>(data.getElementList()));
        oos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void saveValveMotorList(Data data) {
    try {
        Path path = Paths.get(Strings.dataValveMotorFileName);
        OutputStream fos = Files.newOutputStream(path);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(new ArrayList<ValveMotor>(data.getValveMotorList()));
        oos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I will appreciate any suggestions.


texts:
The question is taken for a coding interview I had, it is also in geeks for geeks,  https://www.geeksforgeeks.org/zigzag-tree-traversal/

you are given a binary tree and you need to print it in a ZigZag/Snake order
for level one from left to right and the next level from right to left and so on.

I was asked only to come up with a solution I used a queue and a stack in the real interview, when I coded it now I tried using 2 stacks.

Please review the code as if it was a real interview, complexity, coding style, assume I have 20-30 minutes to code. you can ignore the test case.

Thanks.

using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TreeQuestions
{
    [TestClass]
    public class PrintBinaryTreeZigZag
    {

        [TestMethod]
        public void PrintBinaryTreeZigZagTest()
        {
            BinaryTree root = new BinaryTree
            {
                Value = 1,
                Left = new BinaryTree { Value = 2 },
                Right = new BinaryTree { Value = 3 }
            };
            root.Left.Left = new BinaryTree { Value = 7 };
            root.Left.Right = new BinaryTree { Value = 6 };
            root.Right.Left = new BinaryTree { Value = 5 };
            root.Right.Right = new BinaryTree { Value = 4 };
            List<int> res = PrintBinaryZigZag(root);
            List<int> expected = new List<int> { 1, 3, 2, 7, 6, 5, 4 };
            CollectionAssert.AreEqual(expected, res);

        }

        public List<int> PrintBinaryZigZag(BinaryTree root)
        {
            if (root == null)
            {
                return null;
            }
            Stack<BinaryTree> currentLevel = new Stack<BinaryTree>();
            Stack<BinaryTree> nextLevel = new Stack<BinaryTree>();
            List<int> result = new List<int>();
            currentLevel.Push(root);
            bool leftToRight = true;
            while (currentLevel.Count > 0)
            {
                BinaryTree temp = currentLevel.Peek();
                currentLevel.Pop();
                if (temp != null)
                {
                    //same as print
                    result.Add(temp.Value);

                    if (leftToRight)
                    {
                        if (temp.Left != null)
                        {
                            nextLevel.Push(temp.Left);
                        }
                        if (temp.Right != null)
                        {
                            nextLevel.Push(temp.Right);
                        }
                    }
                    else
                    {
                        if (temp.Right != null)
                        {
                            nextLevel.Push(temp.Right);
                        }
                        if (temp.Left != null)
                        {
                            nextLevel.Push(temp.Left);
                        }
                    }
                }
                if (currentLevel.Count == 0)
                {
                    leftToRight = !leftToRight;
                    Stack<BinaryTree> tempStack = currentLevel;
                    currentLevel = nextLevel;
                    nextLevel = tempStack;
                }
            }
            return result;
        }
    }
    public class BinaryTree
    {
        public BinaryTree Left { get; set; }
        public BinaryTree Right { get; set; }
        public int Value { get; set; }
    }
}


texts: Return office details from multiple tables

texts:
The function itself is just returning as void. But, the point of the posted code is not about what the function is returning. It is the code related to using T-SQL and C# to return data from a SQL database that I would like reviewed. Especially the way the using statements are structured.

    public void GetOffice(int syncID)
    {
        string strQry = @"
Select so.SyncID,
   so.title
From Offices o
Left Outer Join SyncOffices so On so.id = o.SyncID
Where o.SyncID = @syncID
";

        using (SqlConnection conn = new SqlConnection(Settings.ConnectionString))
        {
            using (SqlCommand objCommand = new SqlCommand(strQry, conn))
            {
                objCommand.CommandType = CommandType.Text;
                objCommand.Parameters.AddWithValue("@syncID", syncID);
                conn.Open();
                SqlDataReader rdr = objCommand.ExecuteReader();

                if (rdr.Read())
                {
                    this.OfficeName= rdr.GetString(1);
                }

                rdr.Close();
            }
        }
    }


texts: Create a program that will take user input, reverse it, and then check if it is a palindrome

texts:
Assuming there is no punctuation. It should remove spaces and bring all characters down to lowercase.

My aim was to write code that directly represented my idea of how I would have done things.
This is relevant because there were many ways I could have implemented the cleanString() method and what you see below is not the first way. This is the way that I actually found logical and understand the code for. The other way was to use #include <algorithm> and transform which did not make sense to me despite working.

Here is my solution:

#include <iostream>
#include <vector>
#include <locale>

  std::vector <char> stringToVec(std::string inputString) {
    std::vector <char> letters;
    for (int a = 0; a < inputString.size(); a++) {
      letters.push_back(inputString.at(a));
    }
    return letters;
  }

std::string vecToString(std::vector <char> inputVec) {
  std::string reversedString("");
  for (int a = 0; a < inputVec.size(); a++) {
    reversedString.push_back(inputVec.at(a));
  }
  return reversedString;
}

std::string cleanString(std::string inputString) {
  std::locale loc;
  for (std::string::size_type i = 0; i < inputString.length(); i++) {
    inputString[i] = std::tolower(inputString[i], loc);
  }
  for (std::string::size_type i = 0; i < inputString.length(); i++) {
    if (inputString[i] == ' ') {
      inputString.erase(i, 1);
    }
  }
  return inputString;
}

std::string checkPalindrome(std::string reversedString, std::string originalString) {
  if (cleanString(originalString) == cleanString(reversedString)) {
    return "Yes";
  }
  return "No";
}

std::vector <char> reverseVec(std::vector <char> inputVec) {
  std::vector <char> reversedReturn;
  for (int a = inputVec.size() - 1; a >= 0; a--) {
    reversedReturn.push_back(inputVec.at(a));
  }
  return reversedReturn;
}

int main() {
  std::cout << "Enter the string you would like reversed: ";
  std::string userInput("");
  std::getline(std::cin, userInput, '\n');
  std::string reversedInput(vecToString(reverseVec(stringToVec(userInput))));
  std::cout << "Reversed: " << reversedInput << std::endl;
  std::cout << "Palindrome: " << checkPalindrome(reversedInput, userInput) << std::endl;
  return 0;
}