texts: Bubble Sort Implementation | C-ish and Modern C++

texts:
For practice purpose, I wrote bubble sort in C++ two styles: C-ish and modern C++ compliant. I would like to have your comments on any point on these implementations.

Sorting.h

#ifndef SORTING_ALGORITHMS_H
#define SORTING_ALGORITHMS_H

#include <utility>
#include <vector>
//#include <iterator>
#include <algorithm>

namespace etpc
{
    template <class T>
    void sortBubble(T* pArrHead, std::size_t sArrSize)
    {
        for(std::size_t i=0; i<sArrSize-1; i++)
        {
            for(std::size_t j=0; j<sArrSize-i-1; j++)
            {
                if(pArrHead[j]>pArrHead[j+1])
                    std::swap(pArrHead[j], pArrHead[j+1]);
            }
        }
    }

    // May 2, 2020
    // Based on the following link
    // https://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort#C.2B.2B
    // typename vs class
    // https://stackoverflow.com/questions/2023977/difference-of-keywords-typename-and-class-in-templates
    template <class T>
    void sortBubble(std::vector<T>& vArrHead)
    {
        typename std::vector<T>::iterator begin = std::begin(vArrHead);
        typename std::vector<T>::iterator end = std::end(vArrHead);
        while (begin != end--) {
            for (auto it = begin; it != end; ++it) {
                if (*(it + 1) < *it) {
                    std::iter_swap(it, it + 1);
                }
            }
        }
    }
}
#endif // SORTING_ALGORITHMS_H

Main.cpp

#include "Sorting/include/Sorting.h"

#include <iostream>
#include <chrono>
#include <iterator>

int main()
{
    std::chrono::steady_clock::time_point begin;
    std::chrono::steady_clock::time_point end;
    std::ostream_iterator<int> out_it (std::cout,", ");

    static const int i32Size = 50;
    int arr[i32Size] = {7804, 50398, 14945, 1814, 51383, 63156, 8432, 58103, 28175, 4339, 8361, 37158, 1529, 43066, 62052, 9591, 13168, 332, 55913, 2418, 48066, 46504, 52922, 39523, 36653, 30402, 9373, 56202, 50539, 41187, 42606, 32278, 63902, 41668, 7505, 46534, 25846, 49739, 63411, 45933, 15042, 6544, 35718, 17035, 34647, 15212, 52690, 64299, 61535, 45071};
    begin = std::chrono::steady_clock::now();
    etpc::sortBubble<int>(arr, i32Size);
    end = std::chrono::steady_clock::now();
    std::cout << "Time difference impArray = " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() << "[ns]" << std::endl;
    std::copy(std::begin(arr), std::end(arr), out_it);
    std::cout << '\n';

    std::vector<int> v = {7804, 50398, 14945, 1814, 51383, 63156, 8432, 58103, 28175, 4339, 8361, 37158, 1529, 43066, 62052, 9591, 13168, 332, 55913, 2418, 48066, 46504, 52922, 39523, 36653, 30402, 9373, 56202, 50539, 41187, 42606, 32278, 63902, 41668, 7505, 46534, 25846, 49739, 63411, 45933, 15042, 6544, 35718, 17035, 34647, 15212, 52690, 64299, 61535, 45071};
    begin = std::chrono::steady_clock::now();
    etpc::sortBubble<int>(v);
    end = std::chrono::steady_clock::now();
    std::cout << "Time difference impVector = " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() << "[ns]" << std::endl;
    std::copy(std::begin(v), std::end(v), out_it);
    std::cout << '\n';

    return 0;
}
```


texts:
I am new to Qt and am trying to understand object destruction and where I need to explicitly destroy objects using delete.

class MainDialog: public QWidget {
        Q_OBJECT
    public: MainDialog(QWidget *parent=0);
    private:
        QPushButton *m_newClick;
          QPushButton *m_editClick;
         MainContact *m_contact;
    }

MainDialog::MainDialog(QWidget *parent):QWidget(parent) {
    QWidget *container= new QWidget();

    QPushButton *m_newClick =new QPushButton("New", container);
    QPushButton *m_editClick= new QPushButton("Edit", container);

    QLineEdit *m_text=new QLineEdit(container);

    QVBoxLayout *vlayout=new QVBoxLayout();
    QHBoxLayout *hlayout=new QHBoxLayout();
    hlayout->addWidget(m_newClick);
    hlayout->addWidget(m_editClick);
    vlayout->addLayout(hlayout);

    connect(m_viewClick,SIGNAL(clicked()),this,SLOT(viewClick()) );
    connect(m_newClick,SIGNAL(clicked()),this,SLOT(newClick()) );

    setWindowTitle("Welcome");

    setLayout(vlayout);

}

My queries:

Will the Pushbuttons and lineEdits get destroyed once container is destroyed?
Do I need to destroy m_contact separately as it is not part of the container?

I would like a small explanation on the parent child object destruction as well.


texts: Calculate the movement required to get from one angle to another angle on a compass

texts:
The goal of the function is to find out how to get from one angle to another angle. Two things are involved: the amount to move by and the direction (+ means turn right, - means turn left). The most the angle will have to move by is 180deg. The function is rather short. I wanted to avoid using and trig functions or pi. I want this as fast as I can while maintaining readability.

import pandas as pd
import numpy as np

def get_wind_dir_difd(dir_1, dir_2):
    """
    Figures out the shortest way to get from dir_1 to dir_2. Positive nunber go clockwise, negative numbers go counter clockwise.
    NOTE: The direction 0 and 360 are the same.
    :param dir_1: int. The direction of the first wind.
    :param dir_2: The direction of the second wind.
    :return: int. The what to add (can be a negative number too) to the first wind dir to get to the second wind dir.
    """
    diff = dir_2 - dir_1

    if diff > 180:  # the highest diff can be is 180
        diff = 360 - diff

    elif diff < -180:  # the lowest diff can be is -180
        diff = 360 + diff

    if dir_2 > dir_1 and (dir_2 - dir_1 > 180):  # ensures the correct sign is used when dir_2 is larger and the difference betwene the two is more than 180, EX 10, 310 or 40, 360
        diff = -diff

    return diff

# IGNORE WHAT IS BELOW, THAT IS JUST TO TEST

get_wind_dir_dif_vec = np.vectorize(get_wind_dir_difd)

df = pd.read_csv('test.csv')

df['diff'] = get_wind_dir_dif_vec(df['val1'], df['val2'])

for i in range(len(df)):
    row = df.iloc[i]
    correct_or_not = row['diff'] == row['what_diff_should_be']
    if correct_or_not:
        correct_or_not = ''
    else:
        correct_or_not = 'X'
    df.set_value(i, ' bad_answer ', correct_or_not)

print(df)

To give you a better idea of the program

    val1  val2  diff  what_diff_should_be  bad_answer
0    120    30   -90                  -90
1    340    20    40                   40
2     20   340   -40                  -40
3    310    10    60                   60
4     10   310   -60                  -60
5      0   300   -60                  -60
6    300     0    60                   60
7    190   180   -10                  -10
8    180   190    10                   10
9    200   220    20                   20
10   220   200   -20                  -20
11    10   190   180                  180
12   360     0     0                    0
13     0   360     0                    0
14   340    20    40                   40
15   350     0    10                   10
16   350   360    10                   10
17    40   360   -40                  -40
18   180     0  -180                 -180
19     0   180   180                  180

This is the csv I tested it on.

val1,val2,diff,what_diff_should_be
120,30,,-90
340,20,,40
20,340,,-40
310,10,,60
10,310,,-60
0,300,,-60
300,0,,60
190,180,,-10
180,190,,10
200,220,,20
220,200,,-20
10,190,,180
360,0,,0
0,360,,0
340,20,,40
350,0,,10
350,360,,10
40,360,,-40
180,0,,-180
0,180,,180


texts: Build process for compiling client JS modules into one script

texts:
I am currently writing a rather large client-side JS application which is made of of multiple modules, each in different files (before compiling). I am using Node.js to build the final script based on all the individual modules.

For the script to work properly all modules must be added in the proper order, so they can access any modules they depend on. One way to solve this is by maintaining an array of all the modules in the correct order to be inserted. I find that limiting though, having to add each file manually and in the correct position.

I have come up with a different solution to this, and would love to get some feedback on it.

First I have one wrapper file, which is wraped around all the modules. Looks like this:

(function( ns ){

var module = window[ns] = {

    _modules: window[ns] && window[ns]._modules || {},

    exports: function( name, mod ){
        this._modules[name] = mod;
    },

    require: function( name ){
        var mod = this._modules[name];
        if(!mod) throw new Error(name + ' module not found');
        return mod;
    }
};

MODULES_INSERT

})( '_myCoolApp' );

Where it says "MODULES_INSERT" is where the modules get inserted.

Now inside the individual modules it looks something like this:

// export this module
module.exports('view', View);

function View(){ etc.. }

// import other module
var util = module.require('util');

And finally I have my build script (node.js) which adds all the modules/files, and orders them based on any module.requires they contain in their code, ensuring that all dependencies are loaded before they are required:

for(i in srcFiles){
    file = srcFiles[i];
    var content = fs.readFileSync(file.src);
    content = '(function(){\n' + content;
    content = content + '})();\n';

    // find any module dependencies
    var match, requires = [], regex = /module.require\(['"]([^'"]+)/g;
    while(match = regex.exec(content)){
        requires.push(match[1]);
    }

    file.requires = requires;
    file.content = content;
}

for(i in srcFiles){
    file = srcFiles[i];
    recurse(file);
}

function recurse(file){
    if(!file) return;

    if(file.requires.length > 0) {
        file.requires.forEach(function(req){
            recurse(srcFiles[req]);
        });
    }
    if(!file.added) results.push(file.content);
    file.added = true;
}

code = results.join('');
code = wrapper.replace('MODULES_INSERT', code);

Is this solution way overkill? One downside I see to this, is what happens when two files require each other, which gets loaded first? Is there a more effective solution for this?


texts: Extract left text outside the parenthesis if any

texts:
Im trying to extract the text on the left, outside the parenthesis ():

import re
clean_title = re.match(r'(.*)\(.*\)', title.lower())
if clean_title:
   return clean_title.group(1).rstrip()

Any suggestions to improve it, maybe without regex?

Expected results:

>>'Alone in the Dark (The Cincinnati Series Book 2)'
>>'alone in the dark'


texts: Annotate a class's important string value via an attribute

texts:
I have some Field objects that need to be serialized. Their primary string identifier is called a Tag and starts with a number, so it's not suitable for use as a class name. Thus, for a field bearing tag 32A, I am using the name Field32A. However, during serialization, I need access to the literal string value "32A".

I don't think it's a good idea to convert the name of the class to a string and substring the 32A off the end (though I'm open to hearing argument). And, instead of hard-coding this string in the serialization logic somewhere deep in the class, I thought of putting the string in an attribute that can decorate the class itself, in close proximity to the class name in the source code, so future developers who (say) copy this class to a new one won't miss the need to change the class name and the string representing the tag value.

Note: the FieldTag attribute on the FieldBase class is just there to prove that we’re getting the right fieldtag (and in some cases I did incorrectly get the base class field tag, such as when it was omitted on the derived class, until I put the inherit: false in there).

The magic here is occurring inside the Field32A.ToString method where it refers to FieldTag, which goes to the property on the base class and gets the value from the attribute. Do you think this is a good idea?

Run the following code live in a DotNetFiddle

[FieldTag("Base")]
public abstract class FieldBase {
    public string FieldTag {
        get {
            FieldTagAttribute fieldTagAttribute = (FieldTagAttribute) (
                GetType().GetCustomAttribute(typeof(FieldTagAttribute), inherit: false)
            );

            if (fieldTagAttribute == null) {
            throw new InvalidOperationException(String.Format(
               "Class {0} has no attribute [FieldTag]. "
               + "Please add the attribute to this class.", GetType()));
            }

            return fieldTagAttribute.FieldTag;
        }
    }
}

public class FieldTagAttribute : Attribute {
   public FieldTagAttribute(string fieldTag) {
       FieldTag = fieldTag;
   }

   public string FieldTag { get; set; }
}

[FieldTag("32A")]
public class Field32A : FieldBase {
    public string Value{ get; set; }
    public override string ToString() {
        return ":" + FieldTag + ":" + Value;
    }
}

void Main() {
    Field32A field32A = new Field32A { Value = "12345" };
    field32A.ToString().Dump(); // :32A:12345
}


texts:
I'm trying to solve the Code Jam Dice Straight problem. My Python solution seems to produce the correct output for the first few test cases but then it becomes too slow. How can I possibly optimize it?

from operator import itemgetter
from itertools import groupby

def get_straight(chunk: list, idx: int, straight: int, dice: set) -> int:
    """Get max straight starting at index idx."""
    if idx == len(chunk) - 1:
        return straight

    item = chunk[idx]

    return max((get_straight(chunk, idx+1, straight+1, dice-{x})
                for x in item[1] if x in dice), default=straight)

def main():
    T = int(input())

    for i in range(T):
        ndice = int(input())
        integers = []

        for j in range(ndice):
            integers.extend((int(x), j) for x in input().split())

        integers.sort(key=itemgetter(0))

        grouped = [(k, [x[1] for x in g])
                   for k, g in groupby(integers, itemgetter(0))]
        chunks = []

        # find runs of consecutive numbers
        for k, g in groupby(enumerate(grouped), lambda x: x[0]-x[1][0]):
            g = list(g)
            if len(g) > 1:
                chunks.append(list(map(itemgetter(1), g)))

        chunks.sort(key=len, reverse=True)

        max_straight = 1

        for chunk in chunks:
            if len(chunk) <= max_straight:
                break

            for k in range(len(chunk)-1):
                if len(chunk) - k < max_straight:
                    break
                dice = set(range(ndice))
                straight = get_straight(chunk, k, 0, dice)
                if straight > max_straight:
                    max_straight = straight

        print("Case #{}: {}".format(i+1, max_straight))

main()


texts: Python common file operations generalization

texts:
Functions with common and simple file operations have started to repeat in my code. Many like this one, but with subtle differences for example:

def do_something_with_file(file_name, access_mode, data):
    with open(file_name, access_mode) as f:
        f.do_something(data)

This is my solution so far:

import pickle
from functools import partial

def _open_file(func, access_mode, file_name, *args, **kwargs):
    with open(file_name, access_mode) as f:
        return func(f, *args, **kwargs)

open_file = partial(_open_file, lambda f: f, 'r')

read_lines = partial(_open_file, lambda f: list(f), 'r')

write_lines = partial(_open_file, lambda f, d: f.writelines(d), 'w')

load_pickle = partial(_open_file, lambda f: pickle.load(f), 'rb')

save_pickle = partial(_open_file, lambda f, d: pickle.dump(d, f), 'wb')

Example usage:

write_lines('file.txt', data)
pickle = load_pickle('file.pickle')

It seems readable enough for simple tasks and more complicated function definitions could also be passed to partial instead of simple anonymous functions like above.

Does anyone see any drawbacks of using this or has suggestions on how it could be improved?


texts:
I have this currently working code, but it's extremely slow. I'm talking almost an hour to execute, if it executes at all (our server isn't all that great to start with). Is there a better way to write this?

Basically, I am wanting to return the Top 5 parts, that match a distinct pattern code within the same table. So, if there were 100 distinct pattern codes in my [PartNumber] table, I would end up with 500 records.

ORIGINAL at time of question posting (Executes in 32 minutes):

DECLARE @PartInfo TABLE(
    [PartNumber] [varchar](64) NOT NULL,
    [PatternCode] [varchar](64) NOT NULL,
    [LanguageCode] [varchar](24) NOT NULL);

DECLARE @PatternCode nvarchar(64);
DECLARE pattern_Cursor CURSOR LOCAL SCROLL STATIC
    FOR
    SELECT TOP 1000 [PartNumber].[PatternCode]
    FROM [Web_Service].[dbo].[PartNumber] [PartNumber]
    WHERE PatternCode NOT LIKE 'NOT FOUND'
    GROUP BY [PartNumber].[PatternCode]

    OPEN pattern_Cursor;

    FETCH NEXT FROM pattern_Cursor
    INTO @PatternCode;

    WHILE @@FETCH_STATUS = 0
        BEGIN
            INSERT INTO @PartInfo
            SELECT TOP 5 [PartNumberInfo].*
            FROM [Web_Service].[dbo].[PartNumber] [PartNumber]
            WHERE [PartNumber].[PatternCode] = @PatternCode;

            FETCH NEXT FROM pattern_Cursor
            INTO @PatternCode;
        END
CLOSE pattern_Cursor;
DEALLOCATE pattern_Cursor;

SELECT *
FROM @PartInfo
ORDER BY [@PartInfo].[PatternCode]

First revision (Executes in 24 minutes):

CREATE TABLE #PartInfo ([PartNumber] [varchar](64) NOT NULL,
                        [PatternCode] [varchar](64) NOT NULL,
                        [LanguageCode] [varchar](24));

DECLARE @PatternCode nvarchar(64);

DECLARE pattern_Cursor CURSOR FAST_FORWARD
    FOR
    SELECT [PartNumber].[PatternCode]
    FROM [Web_Service].[dbo].[PartNumber] [PartNumber]
    WHERE PatternCode <> 'NOT FOUND'
    GROUP BY [PartNumber].[PatternCode]

    OPEN pattern_Cursor;

    FETCH NEXT FROM pattern_Cursor
    INTO @PatternCode;

    WHILE @@FETCH_STATUS = 0
        BEGIN
            INSERT INTO #PartInfo
            SELECT TOP 5 [PartNumber].*
            FROM [Web_Service].[dbo].[PartNumber] [PartNumber]
            WHERE [PartNumber].[PatternCode] = @PatternCode
            ORDER BY [PartNumber].[DateTimeValidated] DESC;

            FETCH NEXT FROM pattern_Cursor
            INTO @PatternCode;
        END

CLOSE pattern_Cursor;

DEALLOCATE pattern_Cursor;

SELECT *
FROM #PartInfo
ORDER BY [#PartInfo].[PatternCode]

FINAL COMPLETED AND WORKING CODE (executes in 15 seconds):

SET NOCOUNT ON
GO
SET ARITHABORT ON
GO
SET ANSI_PADDING ON
GO

DECLARE @TopCount int = 5;

SELECT [DistinctTop].[PartNumber]
      ,[DistinctTop].[PatternCode]
      ,[DistinctTop].[LanguageCode]

FROM (SELECT [PartNumber]
            ,[PatternCode]
            ,[LanguageCode]
            ,RANK() OVER
                (PARTITION BY [PatternCode] ORDER BY [PartNumber]) AS RowRank
     FROM PartNumberInfo) AS [DistinctTop]

WHERE [DistinctTop].[RowRank] <= @TopCount

ORDER BY [DistinctTop].[PatternCode];


texts: Is it normal to have a base type for Entities and Value Objects?

texts:
Please see the code below, which I am currently using in a production application. :

public abstract class Entity
{
    public virtual long Id { get; protected set; }

    public override bool Equals(object obj)
    {
        var compareTo = obj as Entity;

        if (ReferenceEquals(compareTo, null))
            return false;

        if (ReferenceEquals(this, compareTo))
            return true;

        if (GetRealType() != compareTo.GetRealType())
            return false;

        if (!IsTransient() && !compareTo.IsTransient() && Id == compareTo.Id)
            return true;

        return false;
    }

    public static bool operator ==(Entity a, Entity b)
    {
        if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
            return true;

        if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
            return false;

        return a.Equals(b);
    }

    public static bool operator !=(Entity a, Entity b)
    {
        return !(a == b);
    }

    public override int GetHashCode()
    {
        return (GetRealType().ToString() + Id).GetHashCode();
    }

    public virtual bool IsTransient()
    {
        return Id == 0;
    }

    public virtual Type GetRealType()
    {
        return NHibernateUtil.GetClass(this);
    }
}

Every Entity class inherits from it.

It is a slight variation of the code here: https://github.com/vkhorikov/DddInAction/blob/master/DddInPractice.Logic/Common/Entity.cs

I am trying to decide whether to remove this base entity type from my application because of the feedback I have received when talking about it.

Is it normal to have a base Entity type (and base ValueObject) that has a base implementation for comparisons e.g. Object.Equals, IEquality.Equals etc?

It seems logical to me.  Say I have the following entities:

Customer
Supplier
Product
Production
etc

Why is it a bad idea for them all to be compared by ID by default?

I have a separate domain model and data model if that has any bearing.


texts:
I wrote this piece of code to mimic the *nix tree utility, however, I am not happy with the pad_info=[] part. It's used to make padding according to whether the parents were last child of their parents or not. Is there any alternate (and a more elegant) way to do this?

def tree(path, depth=1, max_depth=100, print_hidden=False, pad_info=[]):
    '''Print contents of directories in a tree-like format
    By default, it prints upto a depth of 100 and doesn't print hidden files,
    ie, files whose name begin with a '.'

    returns number of files, number of directories it encountered
    '''

    fileCount, dirCount = 0, 0
    files = sorted(os.listdir(path), key=lambda s: s.lower())
    if not print_hidden:
        files = [os.path.join(path, x) for x in files if not x.startswith('.')]

    for i, file in enumerate(files):
        padding = ['|   ' if x == 'nl' else '    ' for x in pad_info]
        padding = ''.join(padding)
        filename = os.path.basename(file)
        is_last = i == len(files) - 1
        prefix = '`-- ' if is_last else '|-- '

        print '%s%s%s' % (padding, prefix, filename)

        if os.path.isdir(file):
            dirCount += 1
            new_pad_info = pad_info + (['l'] if is_last else ['nl'])
            fc, dc = tree(os.path.join(path, file), depth=depth+1,
                          max_depth=max_depth, print_hidden=print_hidden,
                          pad_info=new_pad_info)
            fileCount += fc
            dirCount += dc
        else:
            fileCount += 1

    return fileCount, dirCount


texts:
I got a mixture of two languages C and C ++

The code finds the folder my documents and creates additional folders in it when the program starts, I found no other way to implement this better.
I also did not find any ready-made example where all this has already been implemented so as not to make a bicycle, I like when the code looks compact, but it looks bad for me.

template <typename T1, typename T2>
void knownFolder(T1& setKnownFolderID, T2& getDisplayName)
{
    PWSTR pszFolderPath;

    for (;;) // !!!>
    {
        if (FAILED(SHGetKnownFolderPath(setKnownFolderID, 0, nullptr, &pszFolderPath)))
            continue;

        getDisplayName = pszFolderPath;
        CoTaskMemFree(pszFolderPath);

        break;  // <!!
    }
}

/

template <typename T2>
void folderLink(T2& setDisplayName, T2& getDisplayName)
{
    getDisplayName = setDisplayName + L"\\" + getDisplayName;

    for (;;) // !!!>
    {
        if (!filesystem::exists(getDisplayName))
            if (!filesystem::create_directory(getDisplayName))
                continue;

        break; // <!!
    }
}

/

wstring folder_Documents,                    // C:\ ... \Documents
        folder_Microsoft = L"Microsoft",     // C:\ ... \Documents\Microsoft

        folder_XP = L"XP",
        folder_XP_Alpha = L"Alpha",
        folder_XP_Beta = L"Beta",

        folder_Win7 = L"Win7",
        folder_Win7_Alpha = L"Alpha",
        folder_Win7_Beta = L"Beta";

/

void foldersystem()
{
    knownFolder(FOLDERID_Documents, folder_Documents); // Documents

    folderLink(folder_Documents,
        folder_Microsoft); // Microsoft

        folderLink(folder_Microsoft,
            folder_XP); // XP

            folderLink(folder_XP, folder_XP_Alpha);
            folderLink(folder_XP, folder_XP_Beta);

        folderLink(folder_Microsoft,
            folder_Win7); // Win7

            folderLink(folder_Win7, folder_Win7_Alpha);
            folderLink(folder_Win7, folder_Win7_Beta);

}


texts: Simulates flipping a coin repeatedly and continues until however many consecutive heads are tossed

texts:
This program simulates flipping a coin repeatedly and continues until however many consecutive heads are tossed.

I'm wondering if there are any issues when initializing a variable in a for loop the way I did. Also I assume assigning -1 to i was an appropriate move as well because after a loop cycle it will iterate (i++) causing i to become 1 if I had not, resulting in one less loop.

/*
 * File: ConsecutiveHeads.java
 * ---------------------------
 * This program simulates flipping a coin
 * repeatedly and continues until however many
 * consecutive heads are tossed.
 */

/* Library packages */
import acm.program.*;
import acm.util.RandomGenerator;

public class ConsecutiveHeads extends ConsoleProgram {

    public void run() {
        int flips = 0;
        for (int i = 0; i < CONSECUTIVE_HEADS; i++) {
            String coinSide = flipCoin();
            println(coinSide);
            flips++;
            if (coinSide.equals("Tails")) {
                i = -1;
            }
        }
        println("It took " + flips + " flips to "
                + "get " + CONSECUTIVE_HEADS + " consecutive heads.");
    }

    /* Returns true 50% of the time */
    private String flipCoin() {
        return rgen.nextBoolean() ? "Tails" : "Heads";
    }

    /* Create an instance variable for the random number generator */
    private RandomGenerator rgen = RandomGenerator.getInstance();

    /* Private constant */
    private static final int CONSECUTIVE_HEADS = 3;
}


texts: Is there any loss in performance converting a 'where' clause to a lambda?

texts:
Is there any different in performance for the following 2 queries.
I'm just wondering what is the better of the two:

var res1 = (from a in _ctx.DataContext.Actions
            join e in _ctx.DataContext.Events on a.EventId equals e.EventId
            select a).Single(a => a.ActionId == actionId);

or

var res2 = (from a in _ctx.DataContext.Actions
            join e in _ctx.DataContext.Events on a.EventId equals e.EventId
            where a.ActionId == actionId
            select a).Single();


texts:
I'm just getting started with Python -- completing a simple exercise from a practice website.  My code works -- just looking for feedback on better ways to achieve the goal.

Goal:

  Find the original (unscrambled) words, which were randomly taken from
  a wordlist. Send a comma separated list of the original words, in the
  same order as in the list below.

I stored the scrambled words in words.txt and the wordlist in wordlist.txt

#!/usr/bin/env python3

# open word files
wordlist = open("wordlist.txt", "r").read().split()
words = open("words.txt", "r").read().split()

s = list()

# loop through scrambled words
for word in words:
    # break scrambled word into characters
    chars = list(word)
    # loop through comparison list
    for compare in wordlist:
        # break compare word into characters
        compare_chars = list(compare)
        # make copy of scrambled characters
        char_list = chars[:]
        # loop through scrambled word characters
        for char in chars:
            # if character not in compare word go to next compare word
            if not char in compare_chars:
                break
            # if character found remove it (in case character exists more than once)
            compare_chars.remove(char)
            char_list.remove(char)
        # if all compare characters exhausted we *may* have found the word
        if not compare_chars:
            # if all scrambled characters are utilized then we have the right word
            if not char_list:
                s.append(compare)
            else:
                s.append('???')
            break

# create comma separated list of words
print(",".join(s))


texts:
My implementation in Progress 4GL of the Luhn Algorithm. Any suggestions on improving it?

FUNCTION fnLuhnAlgorithm RETURNS LOGICAL
  (INPUT pcNumber AS CHARACTER):
/*------------------------------------------------------------------------------
  Purpose:  Applies Luhn Algorithm to check a Number
    Notes:  Returns True/False Validation based on check digit

    From the rightmost digit, which is the check digit, moving left, double the value
    of every second digit;
    if product of this doubling operation is greater than 9 (e.g., 7 * 2 = 14).
        Sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5) together
    Compute the sum of the digits.
    Multiply by 9.
    The last digit, is the check digit.
------------------------------------------------------------------------------*/
    DEFINE VARIABLE cNum        AS CHARACTER NO-UNDO.
    DEFINE VARIABLE iCheck      AS INTEGER   NO-UNDO.
    DEFINE VARIABLE iLength     AS INTEGER   NO-UNDO.
    DEFINE VARIABLE iLoopCnt    AS INTEGER   NO-UNDO.
    DEFINE VARIABLE iNum        AS INTEGER   NO-UNDO.
    DEFINE VARIABLE iNum1       AS INTEGER   NO-UNDO.
    DEFINE VARIABLE iNum2       AS INTEGER   NO-UNDO.
    DEFINE VARIABLE iTestLength AS INTEGER   NO-UNDO.

    ASSIGN
      iLength     = LENGTH(pcNumber)
      iTestLength = iLength - 1
        iCheck = 1. /* 1 for the check digit we skip */

    DO iLoopCnt = iTestLength TO 1 BY -1:
      ASSIGN
          iNum = INTEGER(SUBSTR(pcNumber,iLoopCnt,1))
          iCheck = iCheck + 1.

      IF iCheck MODULO 2 = 1 THEN
          ASSIGN iNum1 = iNum1 + iNum.
      ELSE
      DO:
          ASSIGN iNum2 = iNum * 2.
          IF iNum2 < 10 THEN
              ASSIGN iNum1 = iNum1 + iNum2.
          ELSE
              ASSIGN
                cNum  = STRING(iNum2)
                iNum1 = iNum1 + INTEGER(SUBSTR(cNum,1,1)) + INTEGER(SUBSTR(cNum,2,1)).
      END.
    END.

    ASSIGN
        iNum2 = iNum1 * 9
        iNum = iNum2 MODULO 10.

    IF iNum = INTEGER(SUBSTR(pcNumber,iLength,1)) THEN
      RETURN TRUE.
    ELSE
      RETURN FALSE.

END FUNCTION. /* fnLuhnAlgorithm  */


texts: Making a list of customers who buy the top N items from a supplier

texts:
I have a method that works perfectly well and does what it's supposed to, albeit a little slow (30 - 40 seconds).  I would like to be able to speed it up or at least make it more efficient, any ideas please?

The purpose is to generate a list of which customers are buying the top requested (topN) lines from a supplier. The first part gets a list of products from the requested supplier, the second part works out which products are the best selling by distribution and then sales and then adds those products to an array and they form the column names for the datatable.  The last part loops all of the customer accounts and puts yes or no in the column if they have bought it in the last 3 months.  I hope that makes sense.

private void CustomersBuyingRange(string supplier, int topN)
{
    // Get a list of products from a supplier.
    string[] products = productDetails
                        .Where(x => x.SupplierID == supplier.ToUpper())
                        .Select(x => x.ProductCode).ToArray();

    // Rank the products by distribution and then by sales,
    // then add the required amount to an array.
    string[] topSellers = detailedOrderLines
                            .Where(x => products.Contains(x.ProductCode))
                            .GroupBy(x => x.ProductCode)
                            .Select(x => new
                            {
                                x.FirstOrDefault().ProductCode,
                                DeliveredQty = x.Sum(p => p.DeliveredQty),
                                Distribution = x.Select(c => c.CustomerID).Distinct().Count()
                            })
                            .OrderByDescending(x => x.Distribution)
                            .ThenByDescending(x => x.DeliveredQty)
                            .Take(topN)
                            .Select(a => a.ProductCode).ToArray();

    DataTable table = new DataTable("Customers");
    table.Columns.Add("CustomerID", typeof(string));
    table.Columns.Add("Customer", typeof(string));
    table.Columns.Add("AccountManager", typeof(string));
    // Add the columns with the products.
    foreach (string product in topSellers)
    {
        table.Columns.Add(product, typeof(string));
    }

    // We only want customers that have had an order in the last 3 months.
    var customers = customerDetails
        .Where(x => x.LastInvoiceDate > DateTime.Now.AddMonths(-3).Date)
        .OrderBy(x => x.CustomerName)
        .ToList();

    foreach (var customer in customers)
    {
        DataRow row = table.NewRow();
        row["CustomerID"] = customer.CustomerID;
        row["Customer"] = customer.CustomerName;
        row["AccountManager"] = customer.AccountManager;
        for (int i = 0; i < topN; i++)
        {
            row[topSellers[i]] = detailedOrderLines
                .Any(x => x.CustomerID == customer.CustomerID &&
                     x.ProductCode == topSellers[i] &&
                     x.InvoiceDate > DateTime.Now.AddMonths(-3).Date
                     ) ? "Yes" : "No";
        }

        table.Rows.Add(row);
    }
    Export.ExportToExcel(table, true);
}

There are roughly 3000 customers.
Any advise would be greatly appreciated.


texts: Manage connection without 'using' statement

texts:
I replace this common statement:

using (var connection = new MySqlConnection(connectionString))
{
     connection.Open();
     // Do work here; connection closed on following line.
}

With this connection manager class that I made:

public class ConnectionBase : IConnectionBase
{
    private static readonly string ConnString =
        ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

    private static readonly Lazy<MySqlConnection> ConnectionString =
        new Lazy<MySqlConnection>(() => new MySqlConnection(ConnString));

    private IDbConnection _db;

    public IDbConnection Db
    {
        get
        {
            if (_db != null) return _db;

            _db = ConnectionString.Value;
            if (_db.State == ConnectionState.Closed) _db.Open();
            return _db;
        }
    }

    public void Dispose()
    {
        if (_db != null)
            _db.Dispose();
    }
}

And wired up to my repository like this:

public abstract class BaseRepository
{
    protected readonly IDbConnection _repository;

    public BaseRepository(IConnectionBase connection)
    {
        _repository = connection.Db;
    }
}

Then I use it on top of the dapper method (since it contains connection.close() at the end of every method that it used).

public class MyTableRepository : BaseRepository
{
    public MyTableRepository(IConnectionBase connection) : base(connection) {}

    public List<MyTable> GetAllMyTable()
    {
        return _repository.Query("SELECT * FROM MyTable").ToList();
    }

}

It's been working great thus far for quite some time in production.

Are there any side effects for this implementation since it doesn't explicitly state to dispose the IDbConnection object?


texts:
Here is a little encryptor I wrote, I'm just asking for people to tell me what is good practice and what's not. Also, I mean the code, not the actual encryption (because it's just a dumb thing).

#include "stdafx.h"
#include <iostream>
#include <stdexcept>

using namespace std;

int encrypter(int input);
int decrypter(int input);
bool whatToDoFunc();

int main()
{
    try
    {
        bool keepGoing = true;

        while (keepGoing)
        {
            bool success = whatToDoFunc(); char redo;
            cout << "Press 'y' to redo or anykey to exit" << endl;
            cin >> redo;
            if (success == true && (redo == 'y' || redo == 'Y'))
                keepGoing == true;
            else
                keepGoing = false;
        }
        }
    catch (runtime_error err)
    {
        cout << err.what() << endl;
        char exitCon;
        cout << "Enter anykey to exit" << endl;
        cin >> exitCon;
        return -1;
    }

    return 0;
}

bool whatToDoFunc()
{
    int input;
    char whatToDo;
    cout << "Welcome to the JeGo encrypter what do you want to do encrypt or     decrypy? Enter E or D\n" << endl;
    cin >> whatToDo;
    if (whatToDo == 'e' || whatToDo == 'E')
    {
        cout << "Enter the number you want to encrypt" << endl;
        cin >> input;
        int inputEncrypted = encrypter(input);
        cout << "Your number encrypted is " << inputEncrypted << endl;
    }

    else
    {
        if (whatToDo == 'd' || whatToDo == 'D')
        {
            cout << "Enter the already encrypted number" << endl;
            cin >> input;
            int numDecrypted = decrypter(input);
            cout << "Your number decrypted is " << numDecrypted << endl;
        }
        else
        {
            cerr << "Error" << endl;
            throw runtime_error("Your input was invalid");
        }
    }

return true;
}

int encrypter(int input)
{
    int inputEncrypted;
    inputEncrypted = ((((input * 2) + 7) + 5) + 8);
    if (inputEncrypted % 2 == 0)
        ++inputEncrypted;
    else
        inputEncrypted = inputEncrypted + (13 + 13) + (11 + 11);
    return inputEncrypted;
}

int decrypter(int inputEncrypted)
{
    int decryptedNum = 0;
    if (inputEncrypted % 2 == 1)
        --inputEncrypted;
    else
    {
        (11 - 11) - (13 - 13) - inputEncrypted;
    }
    decryptedNum = ((((inputEncrypted - 8) - 5) - 7) / 2);
    return decryptedNum;
}

Please tell me what I could do to make it better or just nicer design! :)


texts: Singleton handler for reading and writing configuration.json

texts:
In a current project of I have multiple modules that need to read from and write to a config.json file, where the settings are saved as nested dictionaries. I chose json here, because I want the config file to be human-readable.
Simplified example config.json:
{
  "server_data": {
    "email_address": "something@somewhere.com",
    "server_address": "imap.server.com",
    "server_port": 993
  },
  "handle_emails": {
    "output_directory": "C:\\Users\\riskypenguin\\some_directory",
    "mark_read": false,
    "write_to_file": true,
    "folders": ["inbox"]
  },
  "output": {
    "output_directory": "C:\\Users\\riskypenguin\\some_other_directory",
    "print_timeinfo": true,
    "print_form_counts": true
  }
}

My config_handler.py provides standardised access to the file via get_setting and set_setting. For different use cases throughout the project I need to be able to access the configuration settings at varying depths. For example: Some boolean settings are read and written directly, but the dict at server_data will be read and processed as a whole. Concurrency is not relevant for this project, so there are no collisions regarding read and write access.
config_handler.py
import os
import json
from functools import reduce

from definitions import CONFIG_DIR, CONFIG_FILE, DEFAULT_CONFIG_FILE

__all__ = ["get_setting", "set_setting"]

# Helper functions

def _save_config_data(content):
    if not os.path.exists(CONFIG_DIR):
        os.makedirs(CONFIG_DIR)

    with open(CONFIG_FILE, 'w') as f:
        json.dump(obj=content, fp=f, indent=2)

def _load_config_data():
    file = CONFIG_FILE if os.path.exists(CONFIG_FILE) else DEFAULT_CONFIG_FILE

    with open(file, 'r') as f:
        return json.load(f)

_config_data = _load_config_data()

# Exported functions

# Old version of get_setting, currently not in use
def get_setting_old(*args, default=None):
    current_value = _config_data

    for key in args:
        if isinstance(current_value, dict):
            current_value = current_value.get(key, default)
        else:
            return default

    return current_value

def get_setting(*config_keys, default=None):
    drill_down = lambda x, y: dict.get(x, y, default) if isinstance(x, dict) else default
    return reduce(drill_down, config_keys, _config_data)

def set_setting(*config_keys, value):
    current_value = _config_data

    for key in config_keys[:-1]:
        if isinstance(current_value, dict):
            current_value = current_value.get(key)
        else:
            return False

    last_key = config_keys[-1]
    if isinstance(current_value, dict):
        current_value[last_key] = value
    else:
        return False

    _save_config_data(_config_data)

    return True

As this is my first shot at handling configurations in a central way like this I am grateful for all feedback. I'm particularly interested in feedback about:

General approach
Comparison between the haskell-like approach of get_setting vs. the simpler and more readable approach of get_setting_old
set_setting seems rather unelegant to me. As the types of a setting can be either mutable or immutable I don't see a better solution though. I've thought about wrapper classes for primitive types, but that feels rather unpythonic and creates some unnecessary overhead when reading from and before writing to json. Maybe I'm missing something here.
I've been thinking about creating a simple class for a path of config_keys, to be able to pass a ConfigKeyPath object instead of a bunch of separated string arguments. I'm not sure which of the two approaches is better.


texts: Basic event stopPropagation() example - a better way of doing so?

texts:
I've got a very very basic demo here that uses the .stopPropagation method. I want to just make it so that clicking on the parent element only runs the function, so I assumed I could use e.stopPropagation() as in the commented out line in the example below. However, that fails, which meant I had to apply the stopPropagation() method to the child element to prevent clicking on the child activating the initial click function.
Is this really the right way of doing this, or is there a better way? Something doesn't feel right here. Thanks for any help - the code is below

var test = document.getElementById('test'),
    child = document.getElementById('child');

test.addEventListener('click', function (e) {
  //e.stopPropagation();
  console.log('click');
});

child.addEventListener('click', function (e) {
  e.stopPropagation();
  console.log('clicked child - is there a better way of using e.stopPropagation() ?');
});
#test {
  background: red;
  display: flex;
  position: relative;
  height: 30px;
  width: 100%;
}
#child {
  background: pink;
  margin-top: 5em;
  position: absolute;
}

child

CodePen: https://codepen.io/ns91/pen/wvayqaE


texts:
Attempting to see whether using 196 as a respectively in my program will have a result or not, I made a simple function to test it. Now the 196-Algorithm requires this:

Take any positive integer with at least two digits, a
Take a and reverse it (for example 23 becomes 32)
Now add the new number to a
Repeat the process until the a is a palindrome (when reversed, a palindrome's value should still be the same)

This is my function:

def one_nine_six_algorithm(a):
    b = a
    if a > 9:
        while str(b)[::-1] != str(b):
            c = str(b)[::-1]
            b += int(c)
        return b

In this program, I literally did how do the algorithm. The integer, a, is taken in and checked that it is a positive, two-digit number. Then, the algorithm is run in the while loop, where b is the new/current value of a and c is basically b reversed but as a string  in able to use [::-1]. Then c as an integer (int(c)) is added to b and is continued until b is a palindrome (checked in the while line). Then it returns b, which is used for whatever reason I need it for.

Now for complicated integers, this might go through a lot of loops and take a lot of time to finish. Is there a more efficient way to improve my program in terms of speed and readability?


texts:
As usual I'm wondering if there is a better way to do:

(The code extends a angular service)

(function(window, angular, undefined) {
        'use strict';
        angular.module('api.base', ['restangular'])
            .factory('Base', function(Restangular) {
                return function(route){
                    var elements = Restangular.all(route);
                    return {
                        one : function (id) {
                            return Restangular.one(route, id).get();
                        },
                        all : function (id) {
                            return elements.getList();
                        },
                        store : function(data) {
                            return elements.post(data);
                        },
                        copy : function(original) {
                            return Restangular.copy(original);
                        }
                    }
                }
            })
    })(window, angular);

    (function(window, angular, undefined) {
        'use strict';
        angular.module('api.post', ['api.base'])
            .factory('Post', function(Base) {
                function ngPost() {
                    this.prop = ['publish','draft'];
                    this.myMethod = function(){}
                };
                return angular.extend(Base('post'), new ngPost());
            })
    })(window, angular);


texts:
I wrote a simple program to encode a local text file with password and decode it back. There is one text file and it is either encoded with a password or is in plain text.

I had a version in Python for this, but nim compiles to an executable, so I gave it a try.

I'm not perfectly happy with command line argument handling, as well as with some repeated code in case statement, but maybe there are other things to improve too.

import os
import system
import strutils
import terminal

import xxtea

const FILENAME = "passwords.txt"
const USAGE = """Encrypt and decrypt a file using a password.

Usage:
    vault open [file]
    vault close [file]

Default file:
    passwords.txt

WARNING: this program may overwrite or delete file content without
a possibilty of recovery. Passwords cannot be recovered. Information
can be destroyed by repeated attempts of encryption/decryption. Use
at you own risk.
"""

proc getpass(message: string = "Password: "): string =
   return terminal.readPasswordFromStdin(message)

proc getpass2(): string =
    let key = getpass()
    let key2 = getpass("Repeat password: ")
    if key == key2:
        return key
    else:
        quitWithMessage("Passwords do not match")

proc write(content: string): void =
    writeFile(filepath(), content)

proc notify(message: string): void =
    echo message, " ", filepath()

# cli args helpers

proc filepath(): string =
    try:
       return paramStr(2)
    except IndexError:
       return FILENAME

proc command(): string =
    try:
       return paramStr(1).toLowerAscii()
    except IndexError:
       quitWithMessage(USAGE)

# flow control

proc quitWithMessage(message: string): void =
    echo message
    quit(1)

# main

if command() notin ["open", "close", "help"]:
    quitWithMessage(USAGE)

let existingContent = readFile(filepath())

case command()
    of "open":
        let key = getpass()
        let newContent = xxtea.decrypt(existingContent, key)
        write(newContent)
        notify("Decoded")
    of "close":
        let key = getpass2()
        let newContent = xxtea.encrypt(existingContent, key)
        write(newContent)
        notify("Encoded")
    of "help":
        quitWithMessage(USAGE)


texts:
This is how I imagine my project's layering:

BLL

Should be independent and contain only pure business logic and properties
Sample Domain Model:

public class Role
{
    private UnitOfWork uow { get; set; }

    public Role()
    {
        uow = new UnitOfWork();
    }

    public int RoleId { get; set; }
    public string Name { get; set; }
    public string ID { get; set; }
    public string Description { get; set; }

    public int AddRole()
    {
        //Mapping from Business 'Role' type to Data Model 'Role' type
        AutoMapper.Mapper.CreateMap<SoC.BLL.Role, SoC.DAL.Role>();
        var model = AutoMapper.Mapper.Map<SoC.DAL.Role>(this);
        return uow.Roles.Add(model);
    }
}

DAL

Contain generic repository and Unit of work and data model meaning model that will reflect the database.
Sample Data Model:

public class Role
{
    [Key]
    public int RoleId { get; set; }

    [Required]
    [StringLength(50, ErrorMessage = "Name Cannot Be More Than 50 Characters")]
    public string Name { get; set; }

    [Required]
    [StringLength(6, ErrorMessage = "ID Cannot Be More Than 6 Characters")]
    public string ID { get; set; }

    [Required]
    [StringLength(250, ErrorMessage = "Description Cannot Be More Than 250 Characters")]
    public string Description { get; set; }
}

Web

This will be ASP.NET MVC app that will use BLL. (Should or should not be aware of DAL?)
Sample Controller Action:

public ActionResult Index()
{
    var role = new Role { RoleId = 1, ID = "ADMIN", Name = "Administrator", Description = "Hello World"  };
    int check = role.AddRole();

    return View();
}

So, from app I am communicating with the Domain Model which has a AddRole() method that will first map using automapper to the equivalent Data Model and then call Add() of repo method to persist the record.

This way my BLL is becoming a little dependent on AutoMapper and DAL but my DAL seems independent. I am trying to create just a simple layering for a simple yet well maintained project. Please suggest on its problems and improvements.


texts:
I am sure there are better ways to do things but this is part of my first JavaScript project and I'm slowly getting accustomed with how things work in JavaScript. This is also why I ask for a code review, to find what I could not see.

Suggestions on idiomatic JavaScript would be welcome.

/* Circular buffer used to add values in blocks of constant size */
function IndexOutOfBounds(maxIndex, requestedIndex, method) {

  this.maxIndex       = maxIndex;
  this.requestedIndex = requestedIndex;
  this.method         = method;

  this.toString = function () {
    return "Invalid index in method ['" + this.method + "']\n" +
           "Requested index    : " + this.requestedIndex + "\n" +
           "Valid _buffer index : " + "[0.." + this.maxIndex + "]";
  };
}

function ImproperBlockLength(ringBlockLength, givenBlockLength) {
  this.ringBlockLength  = ringBlockLength;
  this.givenBlockLength = givenBlockLength;

  this.toString = function () {
    return "Block length mismatch.\n" +
           "Requeste block length : " + this.givenBlockLength  + "\n" +
           "Valid block length    : " + this.ringBlockLength;
  };
}

function Ring(length, blockLength) {
  this.length    = length;
  this._maxIndex = this.length - 1;
  this._start    = 0;
  this._buffer   = new Float32Array(this.length);

  /* blockLength should always be a factor of size.
   * An exception is thrown if it's not;
   */
  this._blockLength = 0;

  if (blockLength) {

    if (length % blockLength != 0) {
      throw "Block length must be a factor of length.";
    } else {
      this._blockLength = blockLength;
    }

  }
}

Ring.prototype.checkBounds = function (requested, callerName) {

  if (requested < 0 || requested > this._maxIndex)
    throw new IndexOutOfBounds(this._maxIndex, requested, callerName);
};

Ring.prototype.relativeIndex = function(index) {
  return (this._start + index) % this.length;
};

/* Should not be used when there is a set _blockLength */
Ring.prototype.push = function (element) {

  this._buffer[this._start] = element;

  var newStart = this._start + 1;
  this._start = newStart > this._maxIndex ? 0 : newStart;
};

Ring.prototype.get = function (index) {

  this.checkBounds(index, 'get');

  return this._buffer[this.relativeIndex(index)];
};

Ring.prototype.set = function (index, value) {

  this.checkBounds(index, 'set');

  this._buffer[this.relativeIndex(index)] = value;

};

Ring.prototype.concat = function(arr) {

  var alen = arr.length;
  var blen = this._blockLength;

  if (alen != blen) {
    throw new ImproperBlockLength(blen, alen);
  }

  this._buffer.set(arr, this._start);
  this._start = (this._start + alen) % this.length;

};

Ring.prototype.map = function (callback) {

  var relativeIndex;
  var value;

  for(var i = 0 ; i < this.length ; i++) {
    relativeIndex = this.relativeIndex(i);
    value = this._buffer[relativeIndex];

    this._buffer[relativeIndex] = callback(value, i, this.length);
  }
};


texts: Find if some words in array value are in same array php

texts:
I have to find where a given string is in my multidimensional array.
So this is my array

$input = array(array('time' => '18:31:00', 'artist' => 'LUIS RODRIGUEZ & DEN HARROW'), array('time' => '18:32:00', 'artist' => 'J BALVIN'), array('time' => '18:33:00', 'artist' => 'THE BLACK EYED PEAS FT J BALVIN'), array('time' => '18:34:00', 'artist' => 'THE BLACK EYED PEAS FT J BALVIN'), array('time' => '18:35:00', 'artist' => 'J BALVIN'));

I have to find at what time I can find this

$artista_inserito = 'THE BLACK EYED PEAS FT J BALVIN';

So I use a function to delimiter my array and even string

function multiexplode($delimiters, $string)
{

    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

// array with string delimeter
$array_delimiter_artisti = array(' FEAT ', ' feat ', ' FT ', ' ft ', ' + ', ' AND ', ' and ', ' E ', ' e ', ' VS ', ' vs ', ' FEAT. ', ' feat. ', ' FT. ', ' ft. ', ' VS. ', ' vs. ', ' , ', ' & ');

// I split the current artist
$artisti_inseriti = multiexplode($array_delimiter_artisti, $artista_inserito);

So I search the given string un my array

foreach ($input as $split) {
    $time = $split['time'];
    $artist = $split['artist'];
    $lista_artisti = multiexplode($array_delimiter_artisti, $artist);

    foreach ($lista_artisti as $nuovo) {
        $artista_split = $nuovo;

        // copy all new data in new array
        $nuovo_array_dati[] = array('time' => $time, 'artist' => $artista_split);
    }
}

foreach ($nuovo_array_dati as $controllo) {
    $time = $controllo['time'];
    $artist = $controllo['artist'];

    foreach ($artisti_inseriti as $trova_artista) {
        $artista_singolo = $trova_artista;

        foreach ($controllo as $index => $a) {
            if (strstr($a, $artista_singolo)) {
                // now I can print where I found the given string $artista_inserito
                echo "$artista_singolo  is at $time ";

            }
        }
    }
}

So this is my output

J BALVIN is at 18:32:00
THE BLACK EYED PEAS is at 18:33:00
J BALVIN is at 18:33:00
THE BLACK EYED PEAS is at 18:34:00
J BALVIN is at 18:34:00
J BALVIN is at 18:35:00

Can I improve this?
Thanks


texts: Sorting the array of strings on their lengths in Java , Using Maps, ascending order....

texts:
I wrote the java method to answer this question :
Write a Program to sort String on their length in Java? Your method should accept  an array of String and return a sorted array based upon the length of String

So my questions:
1. Is my method efficient enough?
2. Can it be improved somehow?

 private static String[] sort(String [] string) {
    /*Local variables*/
    Map<String, Integer> map=new LinkedHashMap<String, Integer>();
    Map<String, Integer> mapCopy=new LinkedHashMap<String, Integer>();
    int [] lengthsArray=new int[string.length];
    String [] sortedStrings=new String[string.length];
    int counter1=0;
    int counter2=0;

    /* Store all the pairs <key,value>
     * i.e <string[i],string[i].length>
     */
    for(String s:string){
        map.put(s, s.length());
        lengthsArray[counter1]=s.length();//store all the lengths
        counter1++;

    }
    mapCopy=new LinkedHashMap<String, Integer>(map);//make a copy of map
    Arrays.sort(lengthsArray);//sort the array of lengths

    /*
     * Sort array according to the array of lengths
     * by finding the matching value from the map
     * then add it to the final string array,and then remove it from the map
     */
    for(int item:lengthsArray){

        for(Map.Entry<String, Integer> e:map.entrySet()){
            if(item==e.getValue()){
                sortedStrings[counter2]=e.getKey();
                counter2++;
                map.remove(e.getKey());
                break;
            }
        }
    }

    map=mapCopy;
    System.out.println(map);//print map
    return sortedStrings;
}


texts: Is there a way to simple Haskell class instance?

texts:
I define a Pixel data with different size like this.

data Pixel = RGB8 Word8 Word8 Word8
           | RGBA8 Word8 Word8 Word8 Word8
           | RGB16 Word16 Word16 Word16
           | RGBA16 Word16 Word16 Word16 Word16
           | Empty
           deriving (Eq)

and Num instance

instance Num Pixel where
  x + Empty = x
  Empty + x = x
  (RGB8 ru gu bu) + (RGB8 rv gv bv) = RGB8 (ru + rv) (gu + gv) (bu + bv)
  (RGBA8 ru gu bu au) + (RGBA8 rv gv bv av) = RGBA8 (ru + rv) (gu + gv) (bu + bv) (au + av)
  (RGB16 ru gu bu) + (RGB16 rv gv bv) = RGB16 (ru + rv) (gu + gv) (bu + bv)
  (RGBA16 ru gu bu au) + (RGBA16 rv gv bv av) = RGBA16 (ru + rv) (gu + gv) (bu + bv) (au + av)
  x - Empty = x
  Empty - x = x
  (RGB8 ru gu bu) - (RGB8 rv gv bv) = RGB8 (ru - rv) (gu - gv) (bu - bv)
  (RGB16 ru gu bu) - (RGB16 rv gv bv) = RGB16 (ru - rv) (gu - gv) (bu - bv)
  (RGBA8 ru gu bu au) - (RGBA8 rv gv bv av) = RGBA8 (ru - rv) (gu - gv) (bu - bv) (au - av)
  (RGBA16 ru gu bu au) - (RGBA16 rv gv bv av) = RGBA16 (ru - rv) (gu - gv) (bu - bv) (au - av)
  _ * _ = error "Not support multiply"
  abs  = id
  signum _ = error "Not support signum"
  fromInteger _ = error "Not support fromInteger"

It's very ugly and bored. I think Haskell is a Elegant language, so can I have a better style to write this?


texts:
I write this session helper class to use it inside my projects for managing the $_SESSION variables setup after an user login or logout. It's very simple and after some tests it seems to work smoothly and fine.

The class doesn't have a constructor, this because the needed parameters that are the username and the user id are passed directly to the setSession method.

The sessionCode method is instead only a code who is used to check if the user is logged in or not, this to limit the access to certain pages if needed.

<?php
namespace library;

class SessionHelper{

private $username;
private $id;
private $ip;

public function setSession(string $email,int $id){
    session_regenerate_id();
    $_SESSION['session_code'] = $this->sessionCode();
    $_SESSION['user_ip'] = $_SERVER['REMOTE_ADDR'];
    $_SESSION['user_id'] = $id;
    $_SESSION['username'] = $email;

    return true;
}

public function sessionStatus(){
    if(isset($_SESSION['session_code'])){
        if(hash_equals($_SESSION['session_code'], $this->sessionCode())){
          return true;
        } else {
          return false;
        }
    }
}

public function unsetSession(){
    session_unset();
    session_destroy();
    return true;
}

private function sessionCode(){
    return hash('sha256', session_id());
}

}

?>

USAGE EXAMPLE AFTER A LOGIN SCRIPT:

<?php
require_once 'SessionHelper.php';

use library\SessionHelper as SessionHelper;

$session = new SessionHelper;

$session->setSession('user1', '4');

?>

USAGE ON RESTRICTED ACCESS PAGES

<?php
session_start();

require_once 'library/Autoloader.php';

use library\SessionHelper as SessionHelper;

$session = new SessionHelper;

if($session->sessionStatus() != true){
  header('Location: index');
  die();
}
?>


texts: Evaluating two functions according to their performance

texts:
//Function-A
        function duplicatesNumber(text) {
            var counts = {};
            let textLowered = text.toLowerCase();
            textLowered.split("").forEach(function (x) {
                counts[x] = (counts[x] || 0) + 1;
            });
            return Object.entries(counts).filter(arr => arr[1] > 1).length
        }

        //Function-B
        function duplicateCount(text) {
            return text.toLowerCase().split('').filter(function (val, i, arr) {
                return arr.indexOf(val) !== i && arr.lastIndexOf(val) === i;
            }).length;
        }

       //Function-B
         let start = performance.now();
        console.log(duplicateCount("aaBBcDDcefgheeaas"))
        let end = performance.now();
        console.log("Function-B: "+ (end-start));

         //Function-A
         let start1 = performance.now();
        console.log(duplicatesNumber("aaBBcDDcefgheeaas"))
        let end1 = performance.now();
        console.log("Function-A: "+ (end1-start1))

I have two functions they both do the same thing. Return the number of duplicates.
My question is about their performances. I have just started to learn data structures and algorithms in javascript. I covered Big O'Notation. But I didn't get it correctly I guess.
Since Function-A has for each method which means it is O(n) clearly. Isn't that mean Function-A should be slower than the second one? How can be Function-A is faster than Function-B?


texts: Generic Template implementation of merge sort in C++

texts:
A few month ago I wrote several basic sort algorithm for educational purposes as generic as possible in C++. In a few days time I want to present some of that stuff in my class but before that I thought I show my implementation to you and listen to your comments of what do you find confusing or very readable.

Mergesort

template <typename I>
    void merge(I first, I mid, I last) {
        while (first != mid && mid != last) {
            auto iter = mid;
            first = std::upper_bound(first, mid, *mid);
            mid = std::upper_bound(mid, last, *first);
            std::rotate(first, iter, mid);
        }
    }

What did I do here? Very simple; I want to avoid to allocate any new memory actively myself and try to write readable algorithm with as few loops as possible.

Obviously, I could not use the 'standard' way implementing merge not very readable. I also needed an in-place looking variant. So I started at looking what I actually do if I try to merge something in itself, what mergesort does in the end.

According to the STL documentation, std::upper_bound does the following:

  Returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found.
  The range [first, last) must be at least partially ordered, i.e. partitioned with respect to the expression !(value < element) or !comp(value, element). A fully-sorted range meets this criterion.
  The first version uses operator< to compare the elements, the second version uses the given comparison function comp.

I call this function twice, first to receive an Iterator of the first part of my array which is greater than the Item in the middle and then for my middle part which is greater than the Item behind my first Iterator of my array. Then I rotate those two "newly build" ranges.

According to the documentation, std::rotate does the following:

  Performs a left rotation on a range of elements.
   Specifically, std::rotate swaps the elements in the range [first, last) in such a way that the element n_first becomes the first element of the new range and n_first - 1 becomes the last element.
   A precondition of this function is that [first, n_first) and [n_first, last) are valid ranges.

template< class ForwardIt >
void rotate( ForwardIt first, ForwardIt n_first, ForwardIt last );

The precondition is always fulfilled because our ranges are within the array we want to merge stuff. This will be repeated as long first is not mid and mid is not equal to last, otherwise we merged our ranges.

What follows is simply the the algo for merge sort using the above implementation of merge:

template <typename I>
    void mergesort(I first, I last) {
        auto&& size = std::distance(first, last);
        if (size < 2) {
            return;
        }

        auto&& mid = first + size / 2 + size % 2;

        mergesort(first, mid);
        mergesort(mid, last);
        merge(first, mid, last);
    }


texts: Efficiently update matrix calculations in Python

texts:
I'm trying to create functions in Python that would update calculations for a matrix only for new entries. These functions are created within a Design class, where users would submit a design into an existing database of designs. The distance between each design should be calculated, but ideally not by brute force every time so as to optimize for larger sized matrices (e.g. if there were 100+ designs). Here's what I have so far:

def compute_matrix(self, all_design, new_design):
    M = {}
    count = 0
    #Does the design already exist?
    existing_design = None
    #Do not calculate every time
    update_distance = None
    for i in self.designs:
        for j in self.designs:
            if i not in M:
                M[i] = {}
                current_design = M[i]
                count += 1
            if i == j:
                continue
    #need to test - only update based on new entries
    for current_design in all_design:
        update_distance = self._distance(new_design, current_design)
        #Is calculation exactly the same?
        if update_distance is None or current_distance == update_distance:
            continue
    ##M[i][j] = self._distance(i, j)
    return current_distance

def _distance(self, i, j):
    p1 = self.designs[i].values()
    p2 = self.designs[j].values()
    ##Using pdist to calculate distance matrix
    dm = pdist(M, reduce(lambda a,x: (x[1]-x[0])**2 + a, zip(p1,p2), 0))
    return dm

Designs are of 3D models where displacement forces are calculated on each model. Distances would evaluate how similar or dissimilar each collection of measured forces are from one another. So in a matrix of collected information of 100+ designs, a user would ideally be able to determine the top 5 most similar or dissimilar designs from a submitted one based on the distance between stored values within each design.

M is a matrix defined within compute_matrix and is the initialized matrix where submitted designs with their values will be stored. Time would probably be the primary concern with these calculations. E.g. if a row is added into a matrix of 100*100 designs, I would not want a 101*101 calculation to be done - rather just the distance between the 101st design and the rest of the designs to be updated instead of iterating through all the designs again.

How could I think about formatting the code properly? And might something like scipy.spatial.cKDTree be usable for a scenario like this? Or would that be more appropriate for finding the nearest vector in a matrix, and not the distance between each and every vector in a matrix?


texts: Are all these steps necessary with prepared statement?

texts:
Are all these steps correct and necessary?

<?php
if (isset($_SESSION['userID'])) {
    $userID = $_SESSION['userID'];
    $stmt = $mysqli->prepare(
       "SELECT usergroup, firstname FROM tbl_users WHERE userID = ? ");
    $stmt->bind_param('i', $userID);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($usergroup, $firstname);
    $stmt->fetch();
    $_SESSION['usergroup'] = $usergroup;
    $_SESSION['firstname'] = $firstname;
    $stmt->close();
}
?>


texts:
I'm trying to learn the process of defining/calling a (somewhat) complex function.

I understand the main idea, and can do it on a small (simple) scale.

A simple example:

def multiply(x, y):
     return x*y

numb1 = 2
numb2 = 3

print(multiply(numb1, numb2))

Now what I'm trying to do is clean up my Vigenere cipher by defining the functions, and what's stumping me is what parameters to use and why. I don't want to change the (possibly poorly-written) code, however I just want to see how it would look after making use of defined functions.

message = input("Enter a message to encrypt:\n").upper().replace(" ", "")
print("Enter your encryption key ("+str(len(message)),"or less letters.): ")
key = input().upper().replace(" ", "")
div_times = int(int(len(message))/int(len(key)))
remainder = int(len(message))%int(len(key))
key_ring = (((key)*(div_times+1))[:-(len(key)-remainder)])
alph = 26

print("-------\n"
      "Message:  ",message,"\n"
      "Key:      ",key_ring,
      "\n-------")
mvalues = [0]*len(message)
kvalues = [0]*len(key_ring)
m_position = 0
k_position = 0

for letter in message:
    mvalues[m_position] = ord(letter)
    m_position += 1

for key in key_ring:
    num = alph - (int(ord("Z")) - int(ord(key)))
    kvalues[k_position] = num - 1
    k_position += 1

m_position = 0
k_position = 0
print("\nEncrypted message: ", end="")
for character in message:
    newletter_v = (mvalues[m_position] + kvalues[k_position])
    if newletter_v > ord("Z"):
        newletter_v -= 26
    elif newletter_v < ord("A"):
        newletter_v += 26
    print(chr(newletter_v)+"", end="")
    m_position += 1
    k_position += 1


texts: Controller action to process orders and payments

texts:
I'm trying to reduce the if statements and simplify this create action.

def create
@order = Order.create_from_result(JSON.parse(params['order']), JSON.parse(params['customer']))

# Ensure order saves before processing payment
if @order.persisted?

  # Braintree transaction
  result = @order.make_payment(params[:payment_method_nonce])

  if result.success?
    @order.paid!
    @order.process!
    render :json => { :status => 200 }
  else
    p "#Error: #{result.message}"
    render :json => { :error => "#{result.message}" }
  end

else
  p "Error: Order did not save successfully"
  render :json => { :error => "Something went wrong. Don't worry, no transaction was made." }
end
end

I thought about moving most of this logic to a single @order.process! call, but then I'm not sure of the best way to handle the Braintree transaction result & return any errors.

Basically, three things take place in this action for an @order:

Order is created from JSON result
Order payment is made
Order is processed (order data is crunched and sent to supplier)


texts: Remove item from a list, which (of the 2) methods is better?

texts:
I have a List, and I have to delete one item from the list when I find it. I am using the code below to do that:

Iterator<MyClass> iter = flist.iterator();
while (iter.hasNext()) {
    Long deletedFiId = iter.next().getId();
    if (deletedFiId.equals(fiId)) {
         iter.remove();
         break;
     }
}

One of my co-workers suggested I should hold the object to be removed and remove it once we get out of the for loop, like this:

MyClass deletedFiId = null;
for (MyClass dto: flist) {
  if (dto.getId().equals(fiId)) {
    deletedFiId = dto;
    break;
  }
if (deletedFiId != null)
  fiList.remove(deletedFiId);

Which one of the above is a good-to-have in the code?


texts: Structure of inheritance between Animal classes and methods

texts:
I'm trying to do some basic inheritance between the 3 classes and use some simple methods, and I'm looking to learn what should be the correct structure between them and what can be improved.

class Animal:
    def __init__(self, kind, place):
        self.kind = kind
        self.place = place

#This class inherits kind and place arguments from Animal class (which can work for any animal)
#Initiates a Dog object with name, gender and breed parameters.

class Dog(Animal):
    def __init__(self, name, gender, breed):
        self.name = name
        self.gender = gender
        self.breed = breed
        Animal.__init__(self, 'Dog', 'Ground')

    #woof method, just prints an action for the Dog object with his name.
    def woof(self, *args):
        print("%s just did a %s woof" % (self.name, *args))

    #getallinfo method, get's all the parametrs of both classes.
    def getallinfo(self):
        print("%s is a %s %s %s, sitting on the %s" % (self.name, self.gender, self.breed, self.kind, self.place))

#Cat class inherits the paramets of use for a Cat (similar things) like name, gender and breed, which they both share, also the getallinfo method and initiate them.
class Cat(Dog):
    def __init__(self, name, gender, breed):
        Dog.__init__(self, name, gender, breed)
        Animal.__init__(self, 'Cat', 'Ground')

#Speak method, returns a print for a cat "meow" with him name.
    def speak(self, *args):
        print("%s just did a %s meow" % (self.name, *args))

#Here I create 3 objects, 2 dogs and 1 cat with selected arguments.
#And check for some methods on the objects.
Mickey = Dog('Mickey', 'Male', 'Bulldog')
Flora = Dog('Flora','Female','Pug')
Tina = Cat('Tina','Female','Persian')
Tina.getallinfo()
Tina.speak('soft')
Dog.getallinfo(Flora)
Dog.woof(Mickey, 'loud')


texts: Ruby implementation for Hacker Rank connected cells in a grid

texts:
https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem

problem statement:

  Consider a matrix where each cell contains either a 1 or a 0.  Any
  cell containing a 1 is called a filled cell.  Two cells are said to be
  connected if they are adjacent to each other horizontally,
  vertically, or diagonally. In the following grid,  all cells marked X
  are connected to the cell marked Y.

  XXX
  XYX
  XXX
  If one or more filled cells are also connected, they
  form a region. Note that each cell in a region  is connected to zero
  or more cells in the region but  is not necessarily directly connected
  to all the other cells in the region.

  Given an  matrix, find and print the number of cells in the largest
  region  in the matrix. Note that there may be more than one region in
  the matrix.

  For example, there are two regions in the following  matrix.  The
  larger region at the top left contains  cells.  The smaller one at the
  bottom right contains .

  110
  100
  001

my solution:

# Complete the connectedCell function below.
def connectedCell(matrix)
    highest_count = 0
    visited = {}

    (0...matrix.length).each do |i|
        (0...matrix[0].length).each do |j|
        next if visited[[i,j]]
            if matrix[i][j] == 1
                res = get_area_count([i,j], matrix)
                if res[0] > highest_count
                    highest_count = res[0]
                end

                visited = visited.merge(res[1])
            end
        end
    end

    highest_count
end

def get_area_count(pos, matrix)
    q = [pos]
    visited = {}
    count = 0
    while q.length > 0
        tile_pos = q.shift
        if !visited[tile_pos]
            count += 1
            visited[tile_pos] = true
            q += nbrs(tile_pos, matrix)
        end
    end

    return [count, visited]
end

def nbrs(pos, matrix)
    right = [pos[0], pos[1] + 1]
    left = [pos[0], pos[1] - 1]
    top = [pos[0] + 1, pos[1]]
    bottom = [pos[0] - 1, pos[1]]
    top_right = [top[0], right[1]]
    bottom_right = [bottom[0], right[1]]
    top_left = [top[0], left[1]]
    bottom_left = [bottom[0], left[1]]
    positions = [right, left, top, bottom, top_right, bottom_right, top_left, bottom_left]
    positions.select{|npos| in_bounds?(npos, matrix.length, matrix[0].length) && matrix[npos[0]][npos[1]] == 1}
end

def in_bounds?(pos, m, n)
    pos[0] >= 0 && pos[0] < m && pos[1] >= 0 && pos[1] < n
end

thought process:
My thought was to iterate through each cell in the matrix and then if it was a 1 I would do a depth-first traversal to find all other cells that had a 1and were connected to the parent cell. then I would add 1 to the count whenever I visited a cell and add it to the visited hash so that it wouldn't be added to the count. I added helper methods for in_bounds? and nbrsmostly for better readability in the get_area_count method(which is the dfs implementation). The nbrs method is pretty verbose, but I kept it that on purpose because I'm preparing for technical interviews, where accuracy is important, and I thought actually listing out each direction would help in debugging / explaining it to the interviewer.


texts: Unity Gravity script lowering FPS because of overlap sphere checking collision

texts:
What are some ideas or ways that I can increase the efficiency of this gravity script because it is way to depending for what i want it for.
The game has a target at the center and there are objects far away all around the target and when gravity script is enabled I create an overlap sphere check which objects have a rigidbody and collision and pull them to target at a constant speed, but my FPS drops to the floor.
Would it be more efficient to have a script in each of these objects with a AddForce and direction towards target? Or any other ideas? Maybe something to change in this current script?
Am I right on the gravity script being too demanding because of the distance the gravity script is checking?
[RequireComponent(typeof(Rigidbody))]
public class Gravity : MonoBehaviour
{
private Rigidbody ownBody;
[HideInInspector]
public float maxVelocityOfInfluence;
private float rangeOfInfluence = 7000.0f;

private void OnEnable()
{
    if (ownBody == null)
    {
        ownBody = GetComponent<Rigidbody>();
    }
}

private void FixedUpdate()
{
    Collider[] cols = Physics.OverlapSphere(transform.position, rangeOfInfluence);
    List<Rigidbody> rbs = new List<Rigidbody>();

    foreach (Collider c in cols)
    {
        Rigidbody otherBody = c.attachedRigidbody;
        if (otherBody != null && otherBody != ownBody && !rbs.Contains(otherBody) &&
HasTagDownHierarchy(otherBody.transform, "Boat"))
        {
            rbs.Add(otherBody);

            Vector3 offset = transform.position - c.transform.position;
            otherBody.velocity = (offset.normalized * maxVelocityOfInfluence);
        }
    }
}

private static bool HasTagDownHierarchy(Transform transform, string tag)
{
    if (!transform)
    {
        return false;
    }

    if (transform.CompareTag(tag))
    {
        return true;
    }

    foreach (Transform child in transform)
    {
        if (HasTagDownHierarchy(child, tag))
        {
            return true;
        }
    }

    return false;
}


texts: Replacing the second word of some matching lines in a file

texts:
I have a file that at some point contains a line of the following form:

OutputFilename output.root

I want to write a Python function that replaces the text after "OutputFilename" and saves to a new file.

I have made the following attempt, which works, but I'm sure there must be a more efficient, Pythonic way to do this.

def set_cuts_configuration_output_filename_configuration(
    cuts_filename                 = "cuts.txt",
    output_filename_configuration = "output_new.root",
    output_cuts_filename          = "cuts_new.txt"
    ):
    # Access the cuts configuration.
    with open (cuts_filename, "r") as input_file:
        cuts_file = input_file.readlines()
    # Find the output filename line.
    modified_file = []
    for line in cuts_file:
        if "OutputFilename" in line:
            modified_file.append(line.split(" ")[0] + " " + output_filename_configuration + "\n")
        else:
            modified_file.append(line)
    # Save the new file content.
    output_cuts_file = open(output_cuts_filename, "w")
    for line in modified_file:
        output_cuts_file.write(line)
    output_cuts_file.close()


texts:
Background

I've come across a puzzle (Problem 10 from this list of sample interview questions):

  One day, an alien comes to Earth. Every day, each alien does one of four things, each with equal probability to:

  Kill himself
  Do nothing
  Split himself into two aliens (while killing himself)
  split himself into three aliens (while killing himself)

  What is the probability that the alien species eventually dies out entirely?

Unfortunately, I haven't been able to solve the problem theoretically. Then I moved on to simulate it with a basic Markov Chain and Monte Carlo simulation in mind.

This was not asked to me in an interview. I learned the problem from a friend, then found the link above while searching for mathematical solutions.

Reinterpreting the question

We start with the number of aliens n = 1. n has a chance to not change, be decremented by 1, be incremented by 1, and be incremented by 2, %25 for each. If n is incremented, i.e. aliens multiplied, we repeat this procedure for n times again. This corresponds to each alien will do its thing again. I have to put an upper limit though, so that we stop simulating and avoid a crash. n is likely to increase and we're looping n times again and again.

If aliens somehow go extinct, we stop simulating again since there's nothing left to simulate.

After n reaches zero or the upper limit, we also record the population (it will be either zero or some number >= max_pop).

I repeat this many times and record every result. At the end, number of zeros divided by total number of results should give me an approximation.

The code

from random import randint
import numpy as np

pop_max = 100
iter_max = 100000

results = np.zeros(iter_max, dtype=int)

for i in range(iter_max):
    n = 1
    while n > 0 and n < pop_max:
        for j in range(n):
            x = randint(1, 4)
            if x == 1:
                n = n - 1
            elif x == 2:
                continue
            elif x == 3:
                n = n + 1
            elif x == 4:
                n = n + 2
    results[i] = n

print( np.bincount(results)[0] / iter_max )

iter_max and pop_max can be changed indeed, but I thought if there is 100 aliens, the probability that they go extinct would be negligibly low. This is just a guess though, I haven't done anything to calculate a (more) proper upper limit for population.

This code gives promising results, fairly close to the real answer which is approximately %41.4.

Some outputs

> python aliens.py
0.41393
> python aliens.py
0.41808
> python aliens.py
0.41574
> python aliens.py
0.4149
> python aliens.py
0.41505
> python aliens.py
0.41277
> python aliens.py
0.41428
> python aliens.py
0.41407
> python aliens.py
0.41676

Aftermath

I'm okay with the results but I can't say the same for the time this code takes. It takes around 16-17 seconds :)

How can I improve the speed? How can I optimize loops (especially the while loop)? Maybe there's a much better approach or better models?


texts: Enabling/Disabling button on a certain condition

texts:
I am using a Telerik Datetime control. On onBlur event of input box I am checking if the date is valid/in-valid, based upon that I am enabling or disabling the submit button (anchor tag actually).

var embedUrl = null;
function onBlur(sender) {
    var constants = {
        classDisabled: 'button-disabled',
        emptyHref: "javascript:void(0)"
    };
    if (sender) {
        var jqueryButton = window.jQuery('.button-submit');
        if (!embedUrl) {
            embedUrl = jqueryButton.href;
        }
        // Check if the string is valid date.
        // As it's being triggerd from Telerik so we use _invalid
        if (sender._invalid) {
            // Date is in-valid, add the class disabled if it does not exists.
            if (!jqueryButton.hasClass(constants.classDisabled)) {
                jqueryButton.attr('href', constants.emptyHref);
                jqueryButton.addClass(constants.classDisabled);
            }
        } else {
            // Date is valid, remove the class disabled if already exists.
            if (jqueryButton.hasClass(constants.classDisabled)) {
                jqueryButton.attr('href', embedUrl);
                jqueryButton.removeClass(constants.classDisabled);
            }
        }
    }
}

I have an anchor tag which has some href which I need to persist.

I want to know how I can write this code a little cleaner.


texts:
Recently I have learned about singleton design pattern. I have tried to implement Redis connection following singleton design pattern.

conn/redis.go

package conn

import (
    "sync"

    "github.com/go-redis/redis"
)

// Redis client
type Redis struct {
    *redis.Client
}

var redisInstance *Redis
var once sync.Once

func GetRedis() *Redis {
    once.Do(func() {
        cfg := config.Redis()

        redisInstance = &Redis{
            Client: redis.NewClient(&redis.Options{
                Addr:     cfg.Address,
                Password: cfg.Password,
                DB:       cfg.DB,
            }),
        }
    })

    return redisInstance
}


texts: Find all integral coordinates given top left corner and bottom right corner of a rectangle

texts:
Here is the problem I am working on -

  There is an \$N \times N\$ field on which missiles are being bombarded. Initially,
  all the cells in this field have the value \$0\$. There will be \$M\$ missiles
  bombarded on this field. The \$i\$th missile will have power \$P_i\$ and it will
  affect all the cells in region with \$(A_i,B_i)\$ as top-left corner and
  \$(C_i,D_i)\$ as bottom-right corner. Because of missile, value of all the
  cells in this rectangle will get XORed with \$P_i\$.

  After all the missiles have been bombarded, you have to find out
  values in each cell of this field.

Here is what I have tried -

N = 3
M = 3
missiles = [[3,3,1,3,2],
[2,2,1,2,2],
[3,1,1,2,3]]

from itertools import product
# Logic
coords = {}
for i in missiles:
    Pi, Ai, Bi, Ci, Di = i
    for j in product(*[range(Ai-1, Ci), range(Bi-1, Di)]):
        if coords.get(j):
            coords[j] ^= Pi
            #[NxN[i[0]][i[1]] ^= Pi
        else:
            coords[j] = 0 ^ Pi

def print_grid(coords, N):
    count = 0
    for i in product(*[range(N), range(N)]):
        if i in coords:
            print(coords[i], "",end="")
        else:
            print(0, "",end="")
        count+=1
        if count%N==0:
            print()

print_grid(coords, N)

Output -

3 3 3
1 1 3
3 3 0

Exactly does what I want, but I was wondering is there a way to optimize it for large inputs. Any help appreciated.


texts: Showing items and categories after clicking on a subcategory

texts:
How can I speed up my app?  It's very slow if I click on a button and open a new page. All data in time is local. I'm not sure if the problem is in my code or xamarinu.

foreach (var category in avm.Categories)
    {
        ToolbarItem ItemCategory = new ToolbarItem();
        ItemCategory.Name = category.Name;
        ToolbarItems.Add (ItemCategory);
        ItemCategory.Activated += (object sender, EventArgs e) =>
        {
            SubCategoryStack.Children.Clear();
            this.IsPresented = true;
            foreach (var Subcategory in category.SubCategories)
            {
                Button btn_subcategory = new Button();
                btn_subcategory.Text = Subcategory.Name;
                SubCategoryStack.Children.Add(btn_subcategory);

                btn_subcategory.Clicked += (object senderr, EventArgs d) =>
                {
                    this.IsPresented= false;
                    stackIbro2.Children.Clear();
                    stackIbro.Children.Clear();
                    Array array = Array.CreateInstance(typeof(Article), Subcategory.Articles.Count);
                    for(int i = 0; i< Subcategory.Articles.Count; i++)
                    {
                        StackLayout articlesH = new StackLayout()
                        {Orientation = StackOrientation.Horizontal};
                        Button btn_article = new Button();
                        Label btn_Quantity = new Label();
                        array.SetValue(Subcategory.Articles[i], i);
                        btn_article.Text = Subcategory.Articles[i].Name;
                        btn_Quantity.Text = Subcategory.Articles[i].Quantity.ToString();

                        btn_article.HorizontalOptions = LayoutOptions.StartAndExpand;
                        btn_Quantity.HorizontalOptions = LayoutOptions.End;
                        articlesH.Children.Add(btn_article);
                        articlesH.Children.Add(btn_Quantity);
                        stackIbro2.Children.Add(articlesH);
                    }

                    //btn_article.Text = new System.Collections.ObjectModel.ObservableCollection<Article> ((Article[])array).ToString();

                };

            }
        };
    }


texts:
Problem
A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
For example, consider array A such that:
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3

We can split this tape in four places:
P = 1, difference = |3 − 10| = 7
P = 2, difference = |4 − 9| = 5
P = 3, difference = |6 − 7| = 1
P = 4, difference = |10 − 3| = 7

Write a function:
function solution(A);
that, given a non-empty array A of N integers, returns the minimal difference that can be achieved.
For example, given:

  A[0] = 3
  A[1] = 1
  A[2] = 2
  A[3] = 4
  A[4] = 3
the function should return 1, as explained above.

Write an efficient algorithm for the following assumptions:
N is an integer within the range [2..100,000];
each element of array A is an integer within the range [−1,000..1,000].
My solution:

A = []
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3

function solution(A) {
  // write your code in JavaScript (Node.js 8.9.4)

  if (A.length > 0) {
    let defArr = [];
    let l = [];
    let all = A.reduce((a, b) => {
      l.push(a)
      return a + b
    })

    l.forEach((item) => {
      defArr.push(Math.abs(all - (item + item)))
    })
    return Math.min(...defArr)
  }

  return 0;

}
console.log(solution(A))


texts:
This code works by taking my user input and correctly pulling the information I'm giving it.

I'm having difficulty understanding the implementation of methods in classes. I'm pretty sure I'm not doing this the correct way. Can anyone show me the way it should be done?

class prog_setup:

 def __init__(self):
  """Initiates the below modules/variables."""

  self.get_starlist()
  self.get_InputKey()
  self.define_listsANDarrays()
  self.determine_normalizationpoint()
  self.create_fobs_fobserr()
  #self.calculate_taumag()
  self.search_DUSTYmodels()
  self.calculate_chi2()
  self.delete_null_components()
  self.dust_whittet_sub()

 def get_starlist(self):
  """Imports the list of stars that you would like information on."""

  self.star_list=np.array([])

  try:
   get_star_list=raw_input('Input pathname of the list of stars to be studied: ')
   incoming_stars=open(get_star_list,'rb')
   for line in incoming_stars:
     x=line.split()
     self.star_list=np.append(self.star_list,x) #Appends the individual star-IDs to the empty array star_list.
   print 'Stars imported successfully.'
  except IOError:
   print 'Star import unsuccessful. Check that the star catalog file-path is correct. Program exiting now.'
   sys.exit()
  self.indices_of_star_list=range(len(self.star_list))

def get_InputKey(self):
 """Imports the Input (.inp) file. Historically, InputUttenthaler.inp. Allows for definition
 of parameters which are utilized later in the script."""

 input_script=raw_input('Pathname of .inp file: ')
 InputKey=[]
 self.band=''
 self.Ak_scalefactor=''
 try:
  with open(input_script) as input_key:
    for line in input_key.readlines():
     x=[item for item in line.split()]
     InputKey.append(x)
    if InputKey[0][0]=='1' or InputKey[0][0]=='2':  #Checks to see if .inp file is valid or not by checking the first row/column which should be 1 or 2.
     print 'Your .inp file was successfully imported'
    else:
     print 'Your .inp file import failed. Check the validity of your file.\n Program exiting now.'
     sys.exit()
 except IOError:
  print 'The .inp file import was unsuccessful. Check that your file-path is valid.\n Program exiting now.'
  sys.exit()

The entire code is longer; I just put in the first two methods to give an example of what my structure looks like.


texts:
I am new to Python (and coding in general) and after about a week of reading "Thinking Like a Computer Scientist: Learning with Python" I decided to try and build a version the classic "guessing game". I added some extra features such as counting the number of guesses the user takes, and playing against a simulated "computer" player to make the program slightly more interesting. Also, the number of guesses the computer takes is based on the mean number of guesses needed to guess a number in a given range (which is logarithmic of base 2 for range n) and varies according to standard deviation.

Any feedback on the structure of my code or the way I generate the number of guesses the computer takes would be much appreciated!

# Number guessing game in Python
# Taylor Wright
# July 27 2016

import random

def get_number(level):                  #selects a random number in range depending on difficulty selected
    if level == "e":
        number = random.randint(1,20)
    if level == "m":
        number = random.randint(1,100)
    if level == "h":
        number = random.randint(1,1000)
    elif level != "e" and level != "m" and level != "h":
        print ("Invalid input!")
        get_number()
    return number

def select_level():    #prompts the user to select a difficulty to play on
    while True:
        level = str(input("Would you like to play on easy, medium, or hard? \n"
                      "Type 'e' for easy, 'm' for medium, or 'h' for hard!\n"))
        if level != "e" and level != "m" and level != "h":
            print("Invalid input!\n")
        if level == "e" or level == "m" or level == "h":
            break
    return level

def guess_number(level):        #function that prompts the user to guess within range depending on chosen difficulty
    if level == "e":
        guess = int(input("Guess a number between 1 and 20:\n"))
    if level == "m":
        guess = int(input("Guess a number between 1 and 100:\n"))
    if level == "h":
        guess = int(input("Guess a number between 1 and 1000:\n"))
    return guess

def check_guess(guess,number):         #processes the guess and tells the user if it is too high, too low, or bang on
    if guess > number:
        print ("your guess is too high! Try again! \n")
    if guess < number:
        print ("your guess is too low! Try again! \n")
    if guess == number:
        print("\n{0} was the number!".format(number))

def com_num_guesses(level):          #function to get the number of guesses taken by the computer
    if level == "e":
        com_guesses = round(random.normalvariate(3.7,1.1))
    if level == "m":
        com_guesses = round(random.normalvariate(5.8,1.319))
    if level == "h":
        com_guesses = round(random.normalvariate(8.99,1.37474))
    print("The computer guessed the number in {0} guesses! Can you beat that?".format(com_guesses))
    return com_guesses

def mainloop():
    level = select_level()
    number = get_number(level)
    com_guesses = com_num_guesses(level)
    num_guesses = 0
    while True:                 #tells program how to handle guesses after the first guess
        guess = guess_number(level)
        check_guess(guess,number)
        num_guesses += 1
        if guess == number:
            print( "You got it in {0} guesses.".format(num_guesses))
            if num_guesses == com_guesses:
                print("It took the computer {0} guesses too!\nIt's a tie!\n".format(com_guesses))
            if num_guesses > com_guesses:
                print("It took the computer {0} guesses.\nThe computer wins!\n".format((com_guesses)))
            if num_guesses < com_guesses:
                print("It took the computer {0} guesses.\nYou win!\n".format(com_guesses))
            play_again = str(input("To play again type 'yes'. To exit type 'no'. \n"))
            if play_again == "yes":
                mainloop()
            if play_again == "no":
                raise SystemExit(0)
            break

mainloop()


texts:
I have this regex:

(\d?)[A-Za-z](?=(\d?)(.*))(?=(.* ){5})

It would be used by me for Chess FEN strings.

I wonder if regex [A-Za-z] is faster than [RNBQKrnbqk]? I only need to check the given letters (but no other letters will appear).

My thoughts are:

[A-Za-z] - the regex engine can match if a char is 65 <= c <= 90 or 97 <= c <= 122. Worst case is 4 comparisons.
[RNBQKrnbqk] - the engine checks if the inspected char equals every given character in the group. Worst case is 10 comparisons.

Am I understanding regex correctly?


texts:
This program is basically a rhyming dictionary. It makes use of Sphinx's groups phonemic dictionary of English which includes a lot of words broken into their respective phonemes, and if we assume that, at least for most cases, anytime the two last phonemes match, the two words rhyme, then it's very easy to whip up a program that does so. Here's my try at this:

import requests
import os
import re

def load_library():
    with open('library.txt', 'r') as library:
        lines = library.readlines()

    return [x for x in lines if not x.startswith(';;;')]

def rhyme(string):

    if os.path.isfile('library.txt'):
        library = load_library()
    else:
        url = "http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict-0.7b"
        response = requests.get(url, stream=True)

        if not response.ok:
            print("Error loading library")

        with open('library.txt', 'wb+') as library:
            for block in response.iter_content(32):
                library.write(block)

    library = load_library()
    string = string.upper()

    phonemes = [y for y in library if y.startswith(string)][0][len(string):]
    phonemes_split = str.strip(phonemes).split(' ')

    matches = [z for z in library if z.endswith(phonemes_split[-2] + ' ' + phonemes_split[-1] + '\n')]
    matches = [z.strip().split(' ') for z in matches]

    return matches

Of course it's naive to assume that EVERYTIME the last two phonemes of two different words match, they rhyme, but most of the times, they do.

This program returns a list of matching words broken into their respective phonemes.

I spent two years studying English literature before I dropped out in favor of pursuing computer programming so I'm qualified to say that I barely know what a phoneme is.