texts: Procedural generation of a general matrix representing a tile map

texts:
The problem is to design an structure which generates "uniformly" the next one in an initially zero matrix. Taking an arbitrary index i in the range [0,m-1] for any j where a[i,j] == 0.
It is, for example:
\begin{gather}
\begin{bmatrix}
0 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 0 & 1\\
0 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix}\\
\to\begin{bmatrix}
1 & 0 & 1\\
1 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 1 & 1\\
1 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 1 & 1\\
1 & 1 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix}\\
\to\begin{bmatrix}
1 & 1 & 1\\
1 & 1 & 0\\
0 & 1 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 1 & 1\\
1 & 1 & 0\\
1 & 1 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 1 & 1\\
1 & 1 & 1\\
1 & 1 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \cdots \to \begin{bmatrix}
1 & 1 & 1\\
1 & 1 & 1\\
1 & 1 & 1\\
1 & 1 & 1\\
\end{bmatrix}
\end{gather}
Where is the utility? This algorithm can be used for procedural generation in any tile game. Now, I'm not a game programmer but I found really annoying the tile generation of Audiosurf 2 so, I want to perhaps provide a better solution.
(Note that the ones can be replaced by a number located by its input order.)
(I know the implications of the player when he doesn't "tap" some tile but there are other alternatives.)
My solution is:
import numpy as np
import numpy.random as rd

class RandomMatrixGenerator():

    def __init__(self, m: int, n: int):
        self.m = m
        self.n = n
        self.matrix = np.zeros(shape=(m,n), dtype='int8')
        self.ones = np.ones(shape=(m,n), dtype='int8')

    def __put_next(self):
        j: int = rd.randint(0, self.n, dtype='int8')

        if self.ones[:,j].all() == self.matrix[:,j].all():
            self.__put_next()

        for i in range(self.m):
            if self.matrix[i, j] == 0:
                self.matrix[i, j] = 1
                return

    def put_next(self):
        if self.ones.all() == self.matrix.all():
            return
        self.__put_next()

# Mini test
gen = RandomMatrixGenerator(4, 5)

for i in range(4 * 5):
    gen.put_next()
    if gen.matrix.all() == gen.ones.all():
        print(i + 1)

I'm learning Python for a class and I want to know if there is a way to optimize this code or reduce syntax, I greatly appreciate it.


texts:
I've written a lambda to perform simple steps to a redshift database. It runs multiple queries with transaction. I use pg-promise.

'use strict';
const config = require('./redshift_config_from_env');
const redshiftConn = `pg://${config.user}:${config.password}@${config.host}/${config.database}`;
const pgp = require('pg-promise')();

var tableCopyQuery = function(tableName) {
  return `
      ALTER TABLE ${tableName}_temp
      RENAME TO ${tableName}_process;
      CREATE TABLE ${tableName}_temp (LIKE ${tableName}_process);`;
};
var insertQuery = function(tableName) {
  return `
      INSERT INTO ${tableName}
      SELECT DISTINCT ${tableName}_process.*
        FROM ${tableName}_process
        LEFT JOIN ${tableName} USING (id)
       WHERE ${tableName}.id IS NULL
       ORDER BY ${tableName}_process.id;
      DROP TABLE ${tableName}_process;`;
};

exports.handler = function(event, context) {
  const client = pgp(redshiftConn);

  client.tx(function (t) {
    return t.batch([
      t.none(tableCopyQuery('active_connections')),
      t.none(insertQuery('active_connections')),
      t.none(tableCopyQuery('active_downloads')),
      t.none(insertQuery('active_downloads'))
    ]);
  })
    .then(function () {
      context.succeed(`Successfully Refreshed.`);
    })
    .catch(function (error) {
      context.fail(`Failed to run queries : ${JSON.stringify(error)}`);
    });
};

I think I may move sql queries into .sql file outside of the function.

Maybe the var could be turned into let because the scope will fit?


texts: C function that emulates string concatenation operator '+' in Python or Go

texts:
I'm working on a project of mine which required multiple calls to strncat(), and it came to me that it'd have been much easier if C also had something like "file://" + getenv("HOME") + filename for string generation. So I built a function that works in a similar fashion, it is a variadic function, the arguments are NULL terminated.
Usage: char *str = mutant_string ("file://", getenv ("HOME"), filename, NULL);
It's obviously up to the user to free the memory str allocated.
The code:-
char *mutant_string (const char *s, ...) {

    va_list argv;
    va_start (argv, s);

    char *return_string = strdup (s);

    size_t realsize, nmemb;

    realsize = strlen (return_string); // Or initial size

    char *c, *ptr;

    while ((c = va_arg(argv, char*)))
    {
        nmemb = strlen (c);
        realsize += nmemb;

        ptr = realloc (return_string, sizeof(char) * (realsize + 1));

        if (!ptr) {
            perror ("realloc");
            free (return_string);
            va_end (argv);
            return NULL;
        }

        return_string = ptr;
        strncat (return_string, c, nmemb);
    }

    return_string[realsize] = 0;

    va_end (argv);

    return return_string;
}

I welcome any kind of observations or opinions. Let me know if there's an external library or function that does exactly this and something that I can read.
Thank you.


texts:
How do I better calculate the definite integral? I am using a function to integrate and another to find the factorial recursively.

I'l like to better the algorithm or the efficiency or even the accuracy for that matter.

    public static double testStatistic(double meanTreatmentSumOfSquares, double meanErrorSumOfSquares)
    {
        return (meanTreatmentSumOfSquares / meanErrorSumOfSquares);
    }

    public static double pValue(double fStatistic, int degreeNum, int degreeDenom)
    {
        double pValue = 0;
        pValue = integrate(0, fStatistic, degreeNum, degreeDenom);

        return pValue;

    }

    public static double integrate(double start, double end, int degreeFreedomT, int degreeFreedomE)
    {
        int iterations = 100000;
        double x, dist, sum = 0, sumT = 0;
        dist = (end - start) / iterations;
        for (int i = 1; i <= iterations; i++)
        {
            x = start + i * dist;
            sumT += integralFunction(x - dist / 2, degreeFreedomT, degreeFreedomE);
            if (i < iterations)
            {
                sum += integralFunction(x, degreeFreedomT, degreeFreedomE);
            }
        }
        sum = (dist / 6) * (integralFunction(start, degreeFreedomT, degreeFreedomE) + integralFunction(end, degreeFreedomT, degreeFreedomE) + 2 * sum + 4 * sumT);
        return sum;
    }

    public static double integralFunction(double x, int degreeFreedomT, int degreeFreedomE)
    {
        double temp=0;
        temp = ((Math.Pow(degreeFreedomE, degreeFreedomE / 2) * Math.Pow(degreeFreedomT, degreeFreedomT / 2)) / (factorial(degreeFreedomE / 2 - 1) * factorial(degreeFreedomT / 2 - 1))) * (factorial(((degreeFreedomT + degreeFreedomE) / 2 - 1)))*((Math.Pow(x, degreeFreedomE / 2 - 1)) / (Math.Pow((degreeFreedomT + degreeFreedomE * x), ((degreeFreedomE + degreeFreedomT) / 2))));
        return temp;
    }

    public static double factorial(double n)
    {
        if (n == 0)
        {
            return 1.0;
        }
        else
        {
            return n * factorial(n - 1);
        }
    }
}
}


texts: Chain of Responsibility Design pattern in C++

texts:
I am learning design patterns from Design pattern for dummies. From that book I have written a chain of responsibility pattern with two programs. Can someone review and let me know which one is proper chain of responsibility design pattern?

A)

#include<iostream>

using std::cout;
using std::endl;

const int FRONT_END_HELP = 0;
const int INTERMEDIATE_LAYER_HELP = 1;
const int GENERAL_HELP = 2;

class HelpInterface
{
public:
    virtual void getHelp(int iHelpConstant) = 0;
};

class FrontEnd : public HelpInterface {
    HelpInterface * Successor;

public:
        FrontEnd(HelpInterface * s){ Successor = s;}
        void getHelp(int iHelpConstant);
};

void FrontEnd::getHelp(int iHelpConstant)
{
    if (FRONT_END_HELP == iHelpConstant)    {
        cout<<"This is the front end, don't you like it ?\n"<<endl;
    } else {
        Successor->getHelp(iHelpConstant);
    }
}

class IntermediateLayer : public HelpInterface{
      HelpInterface * Successor;
public:
    IntermediateLayer(HelpInterface * s) {Successor = s;}
    void getHelp(int iHelpConstant);
};

void IntermediateLayer::getHelp(int iHelpConstant)
{
    if (INTERMEDIATE_LAYER_HELP == iHelpConstant ) {
        cout<<"This is intermediate layer, nice eh?\n"<<endl;
    } else {
        Successor->getHelp(iHelpConstant);
    }
}

class Application : public HelpInterface{

public:
    Application() {}
    void getHelp(int iHelpConstant) {
        cout<<"This the application help\n"<<endl;
    }
};

int main()
{
    Application *app = new Application();
    IntermediateLayer *ilayer = new IntermediateLayer(app);
    FrontEnd * fend = new FrontEnd(ilayer);

    fend->getHelp(GENERAL_HELP);

    fend->getHelp(INTERMEDIATE_LAYER_HELP);

    system("Pause");

}

B)

#include<iostream>

using std::cout;
using std::endl;

const int FRONT_END_HELP = 0;
const int INTERMEDIATE_LAYER_HELP = 1;
const int GENERAL_HELP = 2;

class HelpInterface
{
protected :
    HelpInterface * Successor;
public:
    virtual void getHelp(int iHelpConstant) = 0;
};

class FrontEnd : public HelpInterface {

public:
        FrontEnd(HelpInterface * s){ Successor = s;}
        FrontEnd(){ Successor = NULL;}
        void getHelp(int iHelpConstant);
};

void FrontEnd::getHelp(int iHelpConstant)
{
    if (FRONT_END_HELP == iHelpConstant)    {
        cout<<"This is the front end, don't you like it ?\n"<<endl;
    } else {
        if (Successor != NULL){
            Successor->getHelp(iHelpConstant);
        } else {
            cout<<"No successor\n"<<endl;
        }
    }
}

class IntermediateLayer : public HelpInterface {
public:
    IntermediateLayer(HelpInterface * s) {Successor = s;}
    IntermediateLayer(){ Successor = NULL;}
    void getHelp(int iHelpConstant);
};

void IntermediateLayer::getHelp(int iHelpConstant)
{
    if (INTERMEDIATE_LAYER_HELP == iHelpConstant ) {
        cout<<"This is intermediate layer, nice eh?\n"<<endl;
    } else {
        if (Successor != NULL){
            Successor->getHelp(iHelpConstant);
        } else {
            cout<<"No successor\n"<<endl;
        }
    }
}

class Application : public HelpInterface{

public:
    Application() {Successor = NULL;}
    void getHelp(int iHelpConstant) {
        cout<<"This the application help\n"<<endl;
    }
};

int main()
{
    Application *app = new Application();
    IntermediateLayer *ilayer = new IntermediateLayer(app);
    FrontEnd * fend = new FrontEnd(ilayer);

    fend->getHelp(GENERAL_HELP);

    fend->getHelp(INTERMEDIATE_LAYER_HELP);

    system("Pause");
}


texts: Is this an efficient implementation of the Roman Numeral Converter?

texts:
Is this an efficient way to implement the Roman Numeral Converter ?

So first, I put all the digits of the parameter number into an array.

Then I loop through this array, and multiply a 10 power based number to the current digit.

I use the resulted number in multiple statements, to compare it with special cases or numbers bigger or smaller than those cases.

For each if statement, when it is true, I concatenate a corresponding roman numeral to the whole.

At the end I return the final Roman Numeral as a string.

function convertToRoman(num) {

  var digitArr = []; // 2

  while(num !== 0){
    digitArr.push(num % 10); // 2
    num = Math.floor(num / 10); // num = 0
  }

  var len = digitArr.length;
  var romanNumber = "";
  var numb;
  var number;

  for(var i = len-1;i >= 0;i--){ // 1 0
    number = Math.pow(10, i) * digitArr[i]; // 3

    if(number >= 1000){
      for(var j = 0;j < digitArr[i];j++)romanNumber += "M";
    }else if(number === 900){
      romanNumber += "CM";
    }else if(number > 500){
      numb = number / 100 - 5;
        romanNumber += "D";
        for(var k = 0;k < numb;k++)romanNumber += "C";
    }else if(number === 500){
      romanNumber += "D";
    }else if(number === 400){
      romanNumber += "CD";
    }else if(number < 400 && number >= 100){
      numb = number / 100;
        for(var l = 0;l < numb;l++)romanNumber += "C";
    }else if(number === 90){
      romanNumber += "XC";
    }else if(number >= 60 && number < 90){
      numb = number / 10 - 5;
      romanNumber += "L";
      for(var z = 0;z < numb;z++)romanNumber += "X";
    }else if(number === 50){
      romanNumber += "L";
    }else if(number === 40){
      romanNumber += "XL";
    }else if(number < 40 && number >= 10){
      numb = number / 10;
      for(var x = 0;x < numb;x++)romanNumber += "X";
    }else if(number === 9){
      romanNumber += "IX";
    }else if(number < 9 && number >= 6){
      numb = number - 5;
      romanNumber += "V";
      for(var y = 0;y < numb;y++)romanNumber += "I";
    }else if(number === 5){
      romanNumber += "V";
    }else if(number === 4){
      romanNumber += "IV";
    }else if(number < 4){
      for(var p = 0;p < number;p++){
        romanNumber += "I";
      }
    }
  }

  return romanNumber;
}


texts: Cloud Function: Deleting from both Firestorage and Firestore in a kind of "batch"

texts:
I've written code that deletes a "post" the user has sent with my Android app. A "post" is made of an image (stored in Firestorage) named A, of a Firestore document named B which is the user UID (this document contains a field that is the sum of all the posts' number of likes), and of another Firestore document named C which is the post that is going to be deleted.

So, if a user deleted a post:

A must be deleted
AND B must be updated (by decreasing the number of likes of the user by the number of likes of the post that is going to be deleted)
AND C must be deleted

If at least one of these changes can't complete, nothing must be deleted or updated and an error or an exception must be thrown to the Android app.

Problem: you would think it'd be very simple; I would have to simply use a batch write, put these 3 operations in it and then commit the batch. However... A is a Firestorage document, not a Firestore document, while B and C are Firestore documents. Thus, it's simply technically impossible to do that.

Question

I would want to know if the workaround I've found is correct or not, and if there is a way to correct it or improve it.

I would also want to know if the exceptions mechanism I use is correct (these exceptions are thrown if the client doesn't send values that are expected by the Cloud Functions script, or if the post could not be deleted): will my Android app be able to handle these exceptions and is it the way to do it? In other words: should I throw exceptions or return values likes -1, -2 (i.e.: error codes) for example?

The code

exports.deletePost = functions.https.onCall((data, context) => {

    if(!context.auth) {
        throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated.');
    }

    if(data.the_post === null || data.the_post === '') {
        throw new functions.https.HttpsError('invalid-argument', 'The function must be called with an adequat post.');
    }

    if(data.stored_image_name === null || data.stored_image_name === '') {
        throw new functions.https.HttpsError('invalid-argument', 'The function must be called with an adequat post.');
    }

    const the_post = data.the_post;
    const deleteDbEntry = admin_firestore.collection('list_of_slots').doc(the_post);
    const promise = deleteDbEntry.get().then(function(doc) {

        const stored_image_name = data.stored_image_name;
        const filePath = context.auth.uid + '/posts/' + stored_image_name;

        const batch = admin.firestore().batch();
        batch.delete(deleteDbEntry);
        if(doc.data().number_of_likes > 0) {
            const updateUserLikes = admin_firestore.collection("users").doc(context.auth.uid);
            batch.update(updateUserLikes, "likes", FieldValue.increment(-doc.data().number_of_likes));
        }
        const batch_commit = batch.commit();
        const deleteFile = storage.bucket('andr0d-XYZ-fXXXX.appspot.com').file(filePath).delete();

        return Promise.all([deleteFile, batch_commit]).then(function() {
            return 1;
        }).catch(function(error) {
            console.log(error);
            throw new functions.https.HttpsError('unknown', 'Unable to delete the post. (2)');
        });

    }).catch(function(error) {
        console.log(error);
        throw new functions.https.HttpsError('unknown', 'Unable to delete the post. (1)');
    });

    return promise;
});


texts: Fade and slide animatable elements on window scroll

texts:
I wrote a simple JavaScript function to animate objects on my webpage to fade and slide in from the bottom of the screen when the user scrolls them into view.  I did this by using JavaScript to add and remove a CSS class that animates the element to every element with the showOnScroll class.

Example element:

<content-card class="animated showOnScroll" data="[[item]]"></content-card>

JavaScript function:

window.onscroll = function(e) {
  var toShow =  document.querySelectorAll('.showOnScroll');
  for(var i = 0; i < toShow.length; i++) {
    if(window.innerHeight - toShow[i].getBoundingClientRect().top - 100 > 0) {
      toShow[i].classList.remove('fadeOutDown');
      toShow[i].classList.add('fadeInUp');
    } else {
      toShow[i].classList.remove('fadeInUp');
      toShow[i].classList.add('fadeOutDown');
    }
  }
}

The fadeInUp and fadeInDown classes use CSS to animate the elements.  See a work in progress here (may not work on mobile).  The app is written using Polymer.

I'm mostly concerned about performance—if I have around 50 of these elements on a page, can that noticeably impact most browsers?  If so, I have a couple of ideas to optimize already:

Remove the showOnScroll class once an element has been scrolled in (only animate each element once instead of fading in and out)
Append elements to the DOM as the user scrolls down
Only run the loop if the user scrolls at least 50px

Are these going in the right direction?  Is there anything else I should consider?


texts: Rendering content conditional on the authentication state of the user

texts:
During a code review the following approach of delivering content conditionally dependent upon the state of the user was rejected as adverse to performance due to its multiple use of RenderAction, and instead the approach of RenderPartial was preferred. In order to take this approach it would be necessary to include conditional logic in the view, thus violating separation of concern.

What would you advise as the optimum approach for conditionally including a partial view without including logic in the view?

Header.cshtml

@Model HeaderModel

Some markup

@Html.RenderAction("AuthenticatedUserPanel", Model.SubModel)
@Html.RenderAction("UnauthenticatedUserPanel", Model.SubModel)

Controller.cs

Controller(IContext context)
{
     _context = context;
}

public ActionResult AuthenticatedUserPanel(Model model)
{
    if(_context.IsAuthenticated())
    {
        return View("AuthenticatedUserPanel.cshtml", model)
    }

    return EmptyContentResult();
}

public ActionResult UnauthenticatedUserPanel(Model model)
{
    if(!_context.IsAuthenticated())
    {
        return View("UnauthenticatedUserPanel.cshtml", model)
    }

    return EmptyContentResult();
}

I could possibly include the name of the target view to render in my model e.g. So that my logic for determining which view to use is contained within my ModelAdapter, but this approach feels temperamental and more error prone?

Header.cshtml

@Model HeaderModel

Some markup

@Html.RenderAction(Model.TheViewToRender, Model.SubModel)


texts:
I've implemented a factorial function in a more "Ruby" way. I would like to get feedback on the algorithm.

def factorial_of n
  (1..n).inject :*
end

factorial_of 5
=> 120


texts: Word list scrapper Merger and parse for duplicate entries trying too optimize and convert to python

texts:
#!/bin/bash
reset

echo "Creating output folder to Desktop/CombinedText and final passwordlist will show up as Final0Duplicates.txt"

##Functions##

##output file detection and creation##

function Dependency_Check
{
    file2='~/Desktop/backupwordlist'
    if [ ! -f "$file2" ]
        touch "$file2"
    file2='~/Desktop/CombinedText'
    if [ ! -f "$file3" ]
        touch "$file3"
}
## sort and merge .txt files and list files##

function Combined_Sort
{
##checks if file1 is not in directory##
 file1='Final.list'
 if [ ! -f "$file1" ]
    then
        echo "$file1 is not present"
        echo -e "\e[41m\e[5m[+]-------------------creating $file1 and adding all .txt files to it-----------[+]\e[0m"
        cat *.txt > Final.txt
        reset
        ##text_Troll
        sleep 2s
        echo -e "\e[42m\e[5m[+]-------------------Working on Final List-------------------------------------[+]\e[0m"
        cat Final.txt > Final.list
        reset
        echo -e "\e[42m\e[5m[+]--------final list finished removing 1.list-------[+]\e[0m"
        echo -e "\e[41m\e[5mremoving Duplicates from Final list\e[0m"
        sleep 10s
        reset
        sort -u Final.list > Final0Duplicates.txt
        find . -name Final0Duplicates.txt -exec cp {} ~/Desktop/backupwordlist \;
        sleep 10s
 else
        echo "$file1 is present"
        echo "combining list files to 2.txt"
        cat *.list > 2.txt
        sleep 30s
        reset
        sleep 20s
        echo "Working on Final List"
        cat *.txt > Final.list
        echo "final list finished removing 1.list"
        echo "removing Duplicates from Final list"
        sort -u Final.list > Final0Duplicates.txt
        find . -name Final0Duplicates.txt -exec cp {} ~/Desktop/backupwordlist \;
        sleep 10s

 fi
}

##Crawls all subdirectories and extracts txt documents to desktop folder##

function crawl
{

    find . -name \*.txt -exec cp {} ~/Desktop/CombinedText \;
}

reset
crawl
reset
echo "crawling"
Dependency_Check
echo "Creating Dependency Folder on desktop "
Combined_Sort
echo "All Text Documents have been Combined and sorted."
sleep 6

Okay so a break down of this project started as a pseudo code project out of boredom. but I was looking to see how this can be preformed in python. There are several functions in this code as a break down.

Functions

Dependency_Check
checks to see if the output folders are on the Desktop if not it creates it to be honest this is probably an unnecessary function
Combined_Sort
This takes all of the text documents and merges them into one text document than removes duplicate entries and outputs a file Final0Duplicates.txt to ~/Desktop/backupwordlist
Crawler
This function crawls all subdirectories of the working folder and grabs all files with .txt extension copies them to ~/Desktop/CombinedText
GOAL
My Goal with this program is to possibly create this as a powershell script to work with windows or a batch file using system variables instead of importing a ton of libraries with python. any help would be greatly appriciated, Later this will be released on github as a tool for pentesters to build a master dictionary attack file. Feel free to use this code it is fully fuctional as of 4/9/2019 on 64 bit kali linux latest build and patch.


texts: Code to create and check a numeric password

texts:
I am very new to coding and I have created this relatively simple code to do with my basic knowledge of the language. However I have had to do with some unwanted code including shutting it down if password is too long. so could anybody help me with any improvements to this?

import time

passwordx = float(input('create your password'))
def password():
    passwordx
    if passwordx>9999:
        print('password is wrong\n innitiating shutdown')

        x=5
        time.sleep(1)
        print(x)
        x-=1
        time.sleep(1)
        print(x)
        x-=1
        time.sleep(1)
        print(x)
        x-=1
        time.sleep(1)
        print(x)
        x-=1
        time.sleep(1)
        print(x)
        x-=1
        time.sleep(1)
        print(x)
        x-=1
        quit()

    else:
        print('code saved')
        x=1
        while x <1000:
            print('###############')
            x+=1

def login():
    passwordguess = float(input('please enter password'))

    if passwordguess == passwordx:
        print('access granted')

    else:
        print('wrong')
        print('here\'s a clue', (passwordx-passwordguess)**2)
        login()

password()

login()


texts: Asks the user to input 10 integers, and then prints the largest odd number

texts:
I have written a piece of python code in response to the following question and I need to know if it can be "tidied up" in any way. I am a beginner programmer and am starting a bachelor of computer science.

  Question: Write a piece of code that asks the user to input 10 integers, and then prints the largest odd number that was entered. if no odd number was entered, it should print a message to that effect.

My solution:

a = input('Enter a value: ')
b = input('Enter a value: ')
c = input('Enter a value: ')
d = input('Enter a value: ')
e = input('Enter a value: ')
f = input('Enter a value: ')
g = input('Enter a value: ')
h = input('Enter a value: ')
i = input('Enter a value: ')
j = input('Enter a value: ')

list1 = [a, b, c, d, e, f, g, h, i, j]
list2 = [] # used to sort the ODD values into
list3 = (a+b+c+d+e+f+g+h+i+j) # used this bc all 10 values could have used     value'3'
                          # and had the total value become an EVEN value

 if (list3 % 2 == 0): # does list 3 mod 2 have no remainder
    if (a % 2 == 0): # and if so then by checking if 'a' has an EVEN value     it rules out
                 # the possibility of all values having an ODD value entered
        print('All declared variables have even values')
    else:
        for odd in list1: # my FOR loop to loop through and pick out the     ODD values
            if (odd % 2 == 1):# if each value tested has a  remainder of one to mod 2
                list2.append(odd) # then append that value into list 2
        odd = str(max(list2)) # created the variable 'odd' for the highest ODD value   from list 2 so i can concatenate it with a string.
        print ('The largest ODD value is ' + odd)


texts: Function to get current value or default from a string of two values

texts:
I have SQL scripts that I want to be executable directly in the editor (like DataGrip or SSMS) and also in automated integration tests. However, in each use-case they require different environment and version parameters. I cannot use string_split because we use an ancient SQL Server 2012.

In order to differentiate between them, I created the GetCurrentOrDefault function that can either use the first or the second value.

I start by finding the index of the | that I use as a separator. Then I get the string before and after this character. Finally, I check whether the string has the format '{%}|%' and if yes, then I use the default version, otherwise the current one. (All magic-numbers are arbitrary primes.)

if object_id('dbo.GetCurrentOrDefault') is not null drop function GetCurrentOrDefault

go

create function GetCurrentOrDefault(@valueOrDefault nvarchar(59)) returns nvarchar(17)
begin
    declare @current_value as nvarchar(17);
    declare @default_value as nvarchar(17);
    declare @value_separator_index as int

    select @value_separator_index = charindex('|', @valueOrDefault)

    if @value_separator_index = 0 return null

    select @current_value = substring(@valueOrDefault, 0, @value_separator_index)
    select @default_value = substring(@valueOrDefault, @value_separator_index + 1, len(@valueOrDefault) - @value_separator_index + 1)
    return iif(@valueOrDefault like '{%}|%', @default_value, @current_value)
end

go

Usage example:

declare @env as nvarchar(51) = N'{Environment}|production'
declare @ver as nvarchar(59) = N'{Version}|3.9.0'

select @env = dbo.GetCurrentOrDefault(@env)
select @ver = dbo.GetCurrentOrDefault(@ver)

if @env is null raiserror ('Invalid environment: ' + @env, 16, 1)
if @ver is null raiserror ('Invalid version: ' + @ver, 16, 1)

-- many many inserts with settings ...

Tests replace the placeholders with their custom values like:

.GetSql().Format(new { Environment = "test", Version = "4.0.0" }) // C#

What do you think? Is there a more clever solution?


texts:
Implementation for a relatively basic programming challenge:

  Find the first unique character in a string

So evaluating the string ABCA would return B.

My implementation does the following:

Initialize a boolean array that is the size of the input string - note that the default initialization value is false
The boolean array's values correspond to whether or not the input string character that shares the same index value is unique or not.
Compare each character in the input string against all the characters to the right of it
If there is a match, set the values in the boolean array to true for each character index value.
Iterate through the boolean array and return the first value that is false.
If iteration completes, throw a NoUniqueCharacters Exception

Is there a better approach?

I briefly considered using some sort of Ordered Map (if such a thing exists) that maps characters to their counts where the character key values are ordered by their index in the string

public Character identifyFirstUniqueCharacterInString(final String string) throws NoUniqueCharactersException {
        final char[] chars = string.toCharArray();
        final boolean[] repeatedCharacterIndices = new boolean[chars.length];
        for (int candidateCharacterIndex = 0; candidateCharacterIndex < chars.length; candidateCharacterIndex++) {
            for (int comparisonCharacterIndex = candidateCharacterIndex + 1; comparisonCharacterIndex < chars.length; comparisonCharacterIndex++) {
                if (chars[candidateCharacterIndex] == chars[comparisonCharacterIndex]) {
                    repeatedCharacterIndices[candidateCharacterIndex] = true;
                    repeatedCharacterIndices[comparisonCharacterIndex] = true;
                }
            }
        }
        for (int repeatedCharacterIndex = 0; repeatedCharacterIndex < repeatedCharacterIndices.length; repeatedCharacterIndex++) {
            if (!repeatedCharacterIndices[repeatedCharacterIndex]) {
                return chars[repeatedCharacterIndex];
            }
        }

        throw new NoUniqueCharactersException();
    }


texts: How do I refactor this responsive background images code?

texts:
In my latest project I am using fullscreen background images for each page. I decided to write some code to fetch the different thumbnail sizes and then use it as a background for the appropriate viewport size using media queries. I also made sure that in the case of big screens the smallest image loads first so that the visitor is mostly never greeted with a blank or loading background. I set the image as the featured image of the page and then call it using this code-

$args = array(
            'post_type' => 'attachment',
            'numberposts' => 1,
            'post_status' => null,
            'post_parent' => $post->ID,
            'post_mime_type' => 'image'
            );

            $attachments = get_posts( $args );

            if ( $attachments ) :
                foreach ( $attachments as $attachment ) :
                    $img_thelargeArr = wp_get_attachment_image_src( $attachment->ID, "full");
                    $img_medArr = wp_get_attachment_image_src( $attachment->ID, "med");
                    $img_mediumArr = wp_get_attachment_image_src( $attachment->ID, "medium");

                    $img_thelarge = $img_thelargeArr[0];
                    $img_med = $img_medArr[0];
                    $img_medium = $img_mediumArr[0];
                endforeach;
            endif;

And then in the page.php (or whichever template file with full background) itself I added the following style tag to display images providing fallback for bigger screen sizes so that the background loads progressively.

<style media="screen">
 @media (min-width: 1800px) {
body { background: url(<?php echo $img_thelarge; ?>) no-repeat center center fixed;
background-size: cover; }
html.multiplebgs body { background: url(<?php echo $img_thelarge; ?>), url(<?php echo    $img_med; ?>), url(<?php echo $img_medium; ?>);
background-size: cover;
background-repeat: no-repeat; }
}

@media (min-width: 1000px) and (max-width: 1799px) {
body { background: url(<?php echo $img_thelarge; ?>) no-repeat center center fixed;
background-size: cover; }
html.multiplebgs body { background: url(<?php echo $img_thelarge; ?>), url(<?php echo $img_med; ?>), url(<?php echo $img_medium; ?>);
background-size: cover;
background-repeat: no-repeat; }

}

@media (min-width: 400px) and (max-width: 999px) {
body { background: url(<?php echo $img_med; ?>) no-repeat center center fixed;
background-size: cover; }
html.multiplebgs body { background: url(<?php echo $img_med; ?>), url(<?php echo $img_medium; ?>);
background-size: cover;
background-repeat: no-repeat; }
}

@media (max-width: 399px) {
body { background: url(<?php echo $img_medium; ?>) no-repeat center center fixed;
background-size: cover; }
}
</style>

This works as expected but I am using this for a bunch of other page templates as well and was wondering if I can move this code to a single PHP file and reference it from each of these templates. I don't know OOP so need help to figure this out. There is only one variation in one of the templates I am using $post->ID instead of $attachment->ID.

How do I set this up as a function that can be referenced from an external PHP file in the theme folder itself?  Is it possible to use JavaScript to add inline styles instead of a style tag on the pages?  How do I go about this?


texts: Cast an object to Decimal? or Int? etc but leave it as null if it is null

texts:
In a case like this:

object A1 = null;
Decimal? B = Convert.ToDecimal(A1);
object A2 = null;
int? C = Convert.ToInt32(A2);

Note that in case where A1 or A2 have values, they appear to be of type double.

B and C will be 0 instead of null. A1 actually comes from Excel via the interop and (Decimal?)A1 throws an error: Specified cast is not valid. yet Convert.ToDecimal(A1) works. The problem is that if A1 is null, I want B to also be null

So at the moment I'm solving it like this:

Func<object, Decimal?> convertOrNullDecimal = x => x == null ? (Decimal?)null : Convert.ToDecimal(x);
Func<object, int?> convertOrNullInt32 = x => x == null ? (int?)null : Convert.ToInt32(x);

B = convertOrNullDecimal(A1);
C = convertOrNullDecimal(A2);

Is this a reasonable way to go? Or can I refactor that into a single function? It's possible I'll have to add other numeric data types later on...

I tried it like this:

public static Decimal? convertOrNull(object x)
{
    return x == null ? (Decimal?)null : Convert.ToDecimal(x);
}
public static int? convertOrNull(object x)
{
    return x == null ? (int?)null : Convert.ToInt32(x);
}

but then the calls become ambiguous. I guess you can't overload based on output variable type...

Also note that if I try B = A1 as Decimal?, then if A1 had a numerical value, B is still null because it looks like Excel passed numeric cells as doubles and empty cells as null


texts: Refactoring from .. in .. select to more compact one

texts:
Is it possible to write the two following lines of code in a more compact one?

IEnumerable<int> collection = from partnerNumbers in contract.Contact.PartnerNumbers select partnerNumbers.Pnr;
var response = this.otherClass.SomeMethod(collection, DateTime.Now.Date);

Additional information:

public int SomeMethod(IEnumerable<int> partnerNumbers, DateTime startDate)
{
    ...
}

...

[Table("Conracts")]
public class Contract
{
    public virtual Contact contact
    {
        get;
        set;
    }
}

...

public class Contact
{
    public virtual Collection<PartnerNumbers> PartnerNumbers
    {
        get;
        private set;
    }
}

...

public class PartnerNumbers
{
    public int Id { get; set; }
    public virtual int Pnr { get; set; }
    public string Information { get; set; }
    public virtual Contact contact { get; set; }
}


texts: Iterators in JavaScript and remembering position

texts:
This is an attempt to write a function link that creates a linked list from an array:

function link(list) {
    let next = tail = null;

    for(let i = list.length-1; i >= 0; i--) {
      const value = list[i];
      next = { value, next };
    }

    let cursor = head = next;

    function* iterator() {
      while(cursor.next) {
        yield cursor;
        cursor = cursor.next
      }
      yield cursor;
    }

    return {
      [Symbol.iterator]: iterator,
      head,
      tail,
    };
}

console.log(...link([1,2,3,4]));

The iterator maintains a cursor to remember its position in the iteration.

This feels wrong and brittle.

Is it?

If so, how should the iterator be implemented here.


texts:
I'm kind of new to C++ and was just wondering if anyone could give me tips on how I could make my code more efficient (I added some comments to the code to help you understand it better).

Is it a good idea to use switch cases? Is there a way I can use more functions/arrays/pointers?

Source code

Here is some of the code:

case 1:
        //Asks for number to place bet on
        cout << endl << "Please choose a number to place your bet on: ";
        cin >> betNumber;

        //Checks if number is valid (between 1 and 36)
        while (betNumber < 1 || betNumber > 36) {
            cout << endl << "You must choose a valid number between 1 and 36, inclusive!" << endl;
            cout << "Please choose a number to place your bet on: ";
            cin >> betNumber;
        }

        //Asks for amount to bet on that number
        cout << endl << "How much would you like to bet on the number " << betNumber << "? $";
        cin >> betAmount;

        //Checks if minimum amount is $1 and if the player has enough money in their account
        while (betAmount < 1 || betAmount > bankAccount) {
            cout << endl << "You have $" << bankAccount << " in your bank account: $";
            cin >> betAmount;
        }

        //Seeds random number to the generator
        srand(time(0));

        //Generates a random number
        randomNumber = 1 + (rand() % 36);

        cout << endl << "The ball landed on the number " << randomNumber << ".";

        //Checks if player won or lost their bet
        if (betNumber == randomNumber) {
            bankAccount = win(betAmount, betOdds, bankAccount);
            cout << endl << "Congratulations, you won! You now have $" << bankAccount << " in your account." << endl;
        } else {
            bankAccount = lose(betAmount, bankAccount);
            cout << endl << "Bad luck, you lost! You now have $" << bankAccount << " in your account." << endl;
        }

        break;


texts:
The code uses SQLAlchemy Core. However, what I want to know is if writing code in this pattern is recommendable.

def saveUser(self, user):
    """
    Inserts or updates a user in database.
    The method first checks if the provided user's id already exists. If no, then the user will be inserted. Otherwise, the stored values are updated.

    Args:
        user (User)
    Returns:
        User object with inserted id
    """
    result = self._engine.execute(self._userTable.select().where(self._userTable.c.Id == user._id))
    if not result.first():
        # user doesn't exist in database.
        result = self._engine.execute(self._userTable.insert(), Email=user.email, PasswordHash=user.passwordHash,
                                      DisplayName=user.displayName, Active=user.active)
        user._id = result.inserted_primary_key[0]
    else:
        # user already exists in database.
        result = self._engine.execute(self._userTable.update().where(self._userTable.c.Id == user._id),
                                      Email=user.email, PasswordHash=user.passwordHash, DisplayName=user.displayName, Active=user.active)
    return user

def deleteUser(self, userId=None, email=None):
    """
    Deletes a user.
    Either userId or email can be passed. If both are passed, then a user containing both userId and email will be deleted.
    If none of the arguments are provided, then the method call will have not effect.
    Args:
        userId (int): If this is None, only email will be used to delete the user.
        email (str): If this is None, only userId will be used to delete the user.
    """
    if not userId and not email:
        return # Because an empty and_ clause generated later on will raise OperationalError.
    idClause = self._userTable.c.Id == userId if userId else None
    emailClause = self._userTable.c.Email == email if email else None
    finalClause = and_(idClause, emailClause)
    deleteQuery = self._userTable.delete().where(finalClause)
    result = self._engine.execute(deleteQuery)


texts:
Problem: Remove duplicates from a given array of integers.

I want this method to work without using data sets except an array.

My code is currently \$O(n^2 + n) = O(n^2)\$. How do I shorten this? My main goal in writing this code was in the mindset that I am in an interview and that I am given only 20 minutes to solve this problem. Thus, I tried to find the quickest way of solving the problem. Advice on how better to approach these problems would also be very helpful!

public int[] removeDuplicate(int[] arr)
{
    int temp[] = new int[arr.length];
    boolean[] check = new boolean[arr.length];
    int index = 0;
    for(int i = 0; i < arr.length; i++)
    {
        if(check[i] != true)
            temp[index++] = arr[i];
        else
            continue;

        int var = arr[i];
        for(int j = i+1; j < arr.length; j++)
        {
            if(var == arr[j])
                check[j] = true;
        }
    }
    int returnArray[] = new int[index];

    for(int i = 0; i < returnArray.length; i++)
        returnArray[i] = temp[i];

    return returnArray;
}


texts: Program efficiency vs user experience. Python Ancestor app

texts:
Bit of a basic question but I was creating a ancestor/family tree app thingy (haven't really worked out the details) and I wrote a small start-up program (seen below) which checks the AppData directory exists and the config file exist (consisting of the number of tree and their respective names).
I was wondering if it's better to include the code that updates the config file at the beginning of runtime EVERY TIME or not since its only there in case the user accidently changes something:
import json
import os

AncestoryDir = os.getenv("APPDATA") + "\Ancestry"
ConfigFile = AncestoryDir + "\CONFIG.ini"

# Make Ancestory Directory
if not os.path.exists(AncestoryDir):
    os.makedirs(AncestoryDir)

# Update Config.ini File
CONFIGTree = {"Tree Count": None, "Tree's": []}
for File in os.scandir(AncestoryDir):
    if File.is_file():
        Tree, Suffix = File.name.split(".")
        if Suffix == "json":
            CONFIGTree["Tree's"].append(Tree)
CONFIGTree["Tree Count"] = len(CONFIGTree["Tree's"])
with open(ConfigFile, "w") as JSON:
    json.dump(CONFIGTree, JSON, indent = 4)

Main File:
import os

os.system("python Ancestory.py")
#Other Stuff

As you can see it updates the config file EVERY TIME and im not sure if its worth it. Any thoughts or suggestions are appreciated.
Note:
Please don't tell me about PEP-8, I'm well aware of it and I choose to ignore it out of pure idiocy (my choice)


texts:
My take on a binary search algorithm without research or knowledge of an efficient one. It would be appreciated if one could show me an efficient way to do it using recursion or a more pythonic approach.

from math import *

numList = [i for i in range(11)]

while True:
     try:
           beginning = 0
           end = len(numList) - 1
           mid = floor(((end-beginning)/2) + beginning)

           value = int(input("What value would you like to search for?: "))

           notFound = True

           while notFound:
               if value > end or value < beginning:
                   print("The value is not in the list")
                   break
               elif value == mid:
                   print("The value is in the list")
                   print("The index is " + str(mid))
                   notFound = False
               elif value == end:
                   print("The value is in the list")
                   print("The index is " + str(end))
                   notFound = False
               elif value > mid:
                  beginning = mid
                  mid = floor(((end-beginning)/2) + beginning)
               elif value < mid:
                  end = mid
                  mid = floor(((end-beginning)/2) + beginning)
     except ValueError:
          print("Invalid characters")

```


texts: Writing a generic casting extension-method

texts:
I'm writing a C# extension-method that converts any object to a type. E.g. the method shall convert a string with value "y" to a true-boolean - so there will be some specific castings like bools, chars, DateTimes,...

Here are some examples of my target:

int number = 3;
string stringNumber = number.To<string>();

stringNumber now should be a string with value equals to "3". (Yeah, there's already the ToString(), it's just an example)
another one:

string myDateString = "Mon, 27 Jun 2007 12:34:56 CET";
DateTime myDate = myDateString.To<DateTime>();

myDate now should be a DateTime-object with value equals to a Date on 27th June of 2007 on time 12:34:56.

So, what I did is, I wrote following method:

public static T To<T>(this object @this)
{
    CastTo castedValue = null;

    if (typeof(T) == typeof(DateTime) || typeof(T) == typeof(DateTime?))
    {
        DateTime? result = null;

        if (@this is string actualStringValue)
            result = _tryCastStringToDateTime(actualStringValue);

        if (result != null)
            castedValue = new CastTo<DateTime> {Value = result.Value};
    }

    else if (typeof(T) == typeof(bool) || typeof(T) == typeof(bool?))
    {
        bool? result = null;

        if (@this is string actualStringValue)
            result = _tryCastStringToBoolean(actualStringValue);

        else if (@this is int actualIntegerValue)
            result = _tryCastIntegerToBoolean(actualIntegerValue);

        if (result != null)
            castedValue = new CastTo<bool> {Value = result.Value};
    }

    if (castedValue == null || castedValue.IsInitial)
        return (T) Convert.ChangeType(@this, typeof(T));

    return ((CastTo<T>) castedValue).Value;
}

those _tryCast....-methods simply cast an object to the specific type.

Here are my classes CastTo and CastTo<T>.

internal abstract class CastTo
{
    public abstract bool IsInitial { get; }

    public object Value { get; set; }
}

internal class CastTo<T> : CastTo
{
    private T _value;

    public override bool IsInitial => EqualityComparer<T>.Default.Equals(Value, default(T));

    public new T Value
    {
        get => _value;
        set
        {
            if (!EqualityComparer<T>.Default.Equals(value, default(T)))
                _value = value;
        }
    }
}

Are there any issues you'd suggest me to change?

Code-Style?
Performance?
Bad Practice?
Someone said, this is a misuse of generics. Is it really?


texts: Constructor function, prototype and making a modal

texts:
I'm playing around with prototypes, constructor functions and javascript - I'm not really a Javascript developer but am interested in this.

Am I on the right track with this code? I'm looking for a code review from a JS developer. I know the codes a bit funky.

I created an example of it working here.

function modal( width, height, backgroundColor, overlayColor, showOverlay, url )
{
    this.width = width; // a percentage based number %
    this.height = height; // optional, usually needs not to be set
    this.backgroundColor = backgroundColor; // set the background colour to the modal
    this.overlayColor = overlayColor; // as hex, to be converted to rgba
    this.url = url;
    this.showOverlay = showOverlay;
    this.createModal = function()
    {
        // create elements to add classes to and insert in to dom
        var modalOverlay = document.createElement('div')
        ,   modalContent = document.createElement('div')
        ,   modalInner = document.createElement('div');

        // build html structure
        modalOverlay.className = "modalOverlay";
        modalContent.className = "modalContent";
        modalOverlay.appendChild(modalContent);
        modalInner.className = "modalInner";
        modalContent.appendChild(modalInner);

        // add new html structure to body
        document.body.appendChild(modalOverlay);

        // Theme model
        this.themeModel();
    }
    this.themeModel = function() {

        // is there a background color?
        var overlayBgColor = this.showOverlay ? this.convertHext(this.overlayColor,50) : "transparent";

        $('.modalOverlay').css({
            'background-color': overlayBgColor
        });

        $('.modalContent').css({
            'background-color': this.backgroundColor,
            'width': this.width,
            'height': this.height
        });

        // load content
        this.loadContent();
    }
    this.loadContent = function(){
        if( url )
        {
            $('.modalInner').load(url);
        }
        else
        {
            $('.modalInner').html("please provide a url to load! close");
        }

    }
    this.showModal = function(){
        this.createModal();
        $('.modalOverlay').fadeIn(50);
        $('body').addClass('modalShow');
    }
    this.hideModal = function(){
        $('.modalOverlay').fadeOut(300, function(){
           $('.modalOverlay').remove();
        })
        $('body').removeClass('modalShow');
    }
    this.convertHext = function(hex,opacity)
    {
        hex = hex.replace('#','');
        r = parseInt(hex.substring(0,2), 16);
        g = parseInt(hex.substring(2,4), 16);
        b = parseInt(hex.substring(4,6), 16);
        result = 'rgba('+r+','+g+','+b+','+opacity/100+')';
        return result;
    }
}
body
{
    position: relative;
    margin: 0; /* reset margin */
    padding: 0; /* reset padding */
}

.modalShow .modalContent
{
    opacity: 1;
   overflow':'hidden';
  -webkit-transition: all .3s ease-out;
          transition: all .3s ease-out;
margin-top: 30px;
}

.modalOverlay
{
    display: none;
    overflow: auto;
    overflow-y: scroll;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 9999;
    -webkit-overflow-scrolling: touch;
    outline: 0;
    background-color: #2d2d2d;
    background-color: rgba(45,45,45,0.2);

}
.modalContent
{
    width: 50%;
    height: auto;
    background-color: #FFFFFF;

    margin-top: 0;
    margin-bottom: 30px;
    margin-left: auto;
    margin-right: auto;
    opacity: 0;
  -webkit-transition: all .3s ease-out;
          transition: all .3s ease-out;
}

.modalInner
{
    padding: 20px;
}

    show modal


texts: Basic arithmetic calculator in JavaScript

texts:
Task is basically:

"Write a function which takes two number as the first two parameter. The third parameter is one of the arithmetic operators (+ , - , * , /). Execute the arithmetic operation (number1 operator number2) and return the result of it."

Here's the first idea I've had:

function calculate(num1, num2, operator) {
  num1 = parseFloat(num1);

  if (isNaN(num1)) {
    throw Error('First parameter invalid. Must be a number.');
  }

  num2 = parseFloat(num2);

  if (isNaN(num2)) {
    throw Error('Second parameter invalid. Must be a number.');
  }

  operator = operator.trim();

  if (!/^\+$|^\-$|^\*$|^\/$/.test(operator)) {
    throw Error('Third parameter invalid. Valid are + | - | * | /');
  }

  return eval(num1 + operator + num2);
}

Then I've had another idea for the implementation which uses the ES6-syntax:

function calculate2(num1, num2, operator) {
  num1 = parseFloat(num1);

  if (isNaN(num1)) {
    throw Error('First parameter invalid. Must be a number.');
  }

  num2 = parseFloat(num2);

  if (isNaN(num2)) {
    throw Error('Second parameter invalid. Must be a number.');
  }

  operator = operator.trim();

  if (!/^\+$|^\-$|^\*$|^\/$/.test(operator)) {
    throw Error('Third parameter invalid. Valid are + | - | * | /');
  }

  var calculations = {
    '+' : (numb1, numb2) => numb1 + numb2,
    '-' : (numb1, numb2) => numb1 - numb2,
    '*' : (numb1, numb2) => numb1 * numb2,
    '/' : (numb1, numb2) => numb1 / numb2
  }

  return calculations[operator](num1, num2);
}

I still like the eval-version a bit better.

Can't see any harm which eval should create here because it's controlled via regular expression what is passed until that point.

What's your opinion?

Which implementation is better one?

Looking forward reading your answers.


texts:
This is my solution to the codercharts problem http://codercharts.com/puzzle/word-swap but if keeps failing when I submit the solution because of the cpu_excess_time. Please suggest possible optimisations for this problem, I believe my solution is correct but not optimal.

#!/usr/bin/python

def swap_words(first_word,second_word,word_dict):
    wd = word_dict
    #if the first word is equal to second ,
    # we have got the target word
    if first_word == second_word:
        return [first_word]
    for word in word_dict:
        if len(word) == len(first_word) and \
           sum([x != y for x,y in zip(list(first_word),list(word))]) == 1:
            wd.remove(word)
            ret = swap_words(word,second_word,wd)
            if ret != False:
                ret.append(first_word)
                return ret
    return False

if __name__ == '__main__':
    import sys
    filename = sys.argv[1]
    first_word = sys.argv[2]
    second_word = sys.argv[3]
    text = open(filename).read()
    word_dict = text.split('\n')
    word_list = swap_words(first_word,second_word,word_dict)
    for word in reversed(word_list):
        print word


texts: Listing skills for role-playing characters

texts:
After I completed writing this code, I started to wonder if the switches should be replaced with a more OOP approach. I originally picked the switch approach because there will never be anymore skill groups, only the 5 listed. It also made it a bit easier on the GUI side of things to associate a selection index to one of the enum values.

I figure the KISS rule applies since the structure of the data is going to be concrete, but I'm always open to broadening my view.

public class SkillsComponent
{
    private List<AttackSkillData> strikeSkills = new List<AttackSkillData>();
    private List<AttackSkillData> magicSkills = new List<AttackSkillData>();
    private List<AttackSkillData> techSkills = new List<AttackSkillData>();
    private List<AttackSkillData> dualTechSkills = new List<AttackSkillData>();
    private List<AttackSkillData> triTechSkills = new List<AttackSkillData>();

    public SkillsComponent(List<AttackSkillData> strikeSkills, List<AttackSkillData> magicSkills, List<AttackSkillData> techSkills, List<AttackSkillData> dualTechSkills, List<AttackSkillData> triTechSkills)
    {
        this.strikeSkills = strikeSkills;
        this.magicSkills = magicSkills;
        this.techSkills = techSkills;
        this.dualTechSkills = dualTechSkills;
        this.triTechSkills = triTechSkills;
    }

    public void AddNewSkill(SkillAttackType skillAttackType, AttackSkillData data)
    {
        switch (skillAttackType)
        {
            case SkillAttackType.Strike: { strikeSkills.Add(data); } break;
            case SkillAttackType.Magic: { magicSkills.Add(data); } break;
            case SkillAttackType.Tech: { techSkills.Add(data); } break;
            case SkillAttackType.DualTech: { dualTechSkills.Add(data); } break;
            case SkillAttackType.TriTech: { triTechSkills.Add(data); } break;
        }
    }

    public List<AttackSkillData> GetListOfLearnedSkills(SkillAttackType skillAttackType)
    {
        List<AttackSkillData> listToUse = null;
        switch(skillAttackType)
        {
            case SkillAttackType.Strike: { listToUse = strikeSkills; } break;
            case SkillAttackType.Magic: { listToUse = magicSkills; } break;
            case SkillAttackType.Tech: { listToUse = techSkills; } break;
            case SkillAttackType.DualTech: { listToUse = dualTechSkills; } break;
            case SkillAttackType.TriTech: { listToUse = triTechSkills; } break;
        }
        return listToUse;
    }
}


texts: Printing even and odd using two concurrent threads

texts:
Please review the code below where thread Odd prints all odd numbers from 1 to 9 and thread Even prints all even numbers from 2 to 8. I tested it and it works but can we improve it from design or performance perspective?

To print odd

public class Odd implements Runnable{

private Monitor sharedObject;

public Odd(Monitor monitor){
    this.sharedObject = monitor;
}

@Override
public void run() {

    try {
        printOdd();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void printOdd() throws InterruptedException {
    synchronized(sharedObject){
        for(int i=1; i< 10; i++){
            if(i%2!=0){
                while(!sharedObject.isOdd()){
                    sharedObject.wait();
                }
                System.out.println("Odd: "+ i);
                sharedObject.setOdd(false);
                sharedObject.notifyAll();
            }
        }
    }

}

To print even

public class Even  implements Runnable{

private Monitor sharedObject;

public Even(Monitor monitor){
    this.sharedObject = monitor;
}

@Override
public void run() {

    try {
        printEven();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void printEven() throws InterruptedException {
    synchronized(sharedObject){
        for(int i=1; i< 10; i++){
            if(i%2==0){
                while(sharedObject.isOdd()){
                    sharedObject.wait();
                }
                System.out.println("Even: "+ i);
                sharedObject.setOdd(true);
                sharedObject.notifyAll();
            }
        }
    }

}

Monitor class

public class Monitor {

    private volatile boolean isOdd;

    public boolean isOdd() {
      return isOdd;
    }

    public void setOdd(boolean isOdd) {
      this.isOdd = isOdd;
    }

}


texts: Laravel - Repetitive code in store and update functions

texts:
I am working on a system and I can see myself using repetitive code that does not look right. I want to clean up my code but I don't really know many ways to do so. I have 2 methods (store and update). They both look like this

store

public function store(Request $request)
    {
        $user = Auth::user();

        $validatedData = $request->validate([
            'street' => ['required', 'string'],
            'number' => ['required', 'string'],
            'city' => ['required', 'string'],
            'state' => ['required', 'string'],
            'postal_code' => ['required', 'string'],
            'country' => ['required', 'string'],
            'phone' => ['required', 'string']
        ]);

        $addresses = Address::all();

        $billing = 0;
        if($request->is_billing) {
            $billing = $request->is_billing;
            foreach($addresses as $address) {
                if($address->is_billing == 1) {
                    $address->is_billing = 0;
                    $address->save();
                }
            }
        }

        $address = Address::create([
            'user_id' => $user->id,
            'token' => Str::random(32),
            'street_name' => $request->street,
            'house_number' => $request->number,
            'postal_code' => $request->postal_code,
            'state' => $request->state,
            'city' => $request->city,
            'country_id' => $request->country,
            'phone' => $request->phone,
            'is_billing' => $billing
        ]);

        return redirect('/dashboard/user/' . $user->user_token . '/addresses');
    }

update

public function update(Request $request, $id)
    {
        $addresses = Address::all();
        $address = Address::where('token', $id)->firstOrFail();
        $user = Auth::user();

        $billing = 0;
        if($request->is_billing) {
            $billing = $request->is_billing;
            foreach($addresses as $item) {
                if($item->is_billing == 1) {
                    $item->is_billing = 0;
                    $item->save();
                }
            }
        }

        $address->user_id = $user->id;
        $address->street_name = $request->street;
        $address->house_number = $request->number;
        $address->postal_code = $request->postal_code;
        $address->state = $request->state;
        $address->city = $request->city;
        $address->country_id = $request->country;
        $address->phone = $request->phone;
        $address->is_billing = $billing;

        $address->save();

        return redirect('/dashboard/user/' . $user->user_token . '/addresses');
    }

Currently, the code looks messy and I have a feeling it can be done much more efficiently. Can someone give me tips on how to clean this up?


texts:
I currently use this method to count unread messages for a user (self here):

def unread_messages_count
  number = 0
  conversations = Conversation.where {|conversation| conversation.user1 == self || conversation.user2 == self }
  conversations.each do |conversation|
    number += conversation.messages.select{|message| !message.read && (message.user != self) }.count
  end
  number
end

However, this seems highly inefficient to me since I'm iterating on every conversation found to look for unread messages.

Any input on how to make this method smarter will be much appreciated !


texts:
Stumbled upon this interview question:

  Given a morse encoded sentence with no spaces or separation between letters or words and a list of words contained in the message, decode it.

This was my solution (and a test case with the jack and jill sentence):

 static String[] alpha = {"a","b","c","d","e","f","g","h","i","j","k",
        "l","m","n","o","p","q","r","s","t","u","v",
        "w","x","y","z"};
static String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",
        ".--","-..-","-.--","--.."};

private static HashMap<Character, String> letters = new HashMap<>();

public static void main(String[] args) {
    for (int i = 0; i < alpha.length; i++) {
        letters.put(alpha[i].charAt(0), morse[i]);
    }

    String[] words = {"hill","jack","went","and","jill","the","up"};
    System.out.println(
            decode(".---.--.-.-.-.--.-...---...-...-...--.-.-..-.--.-............-...-..",
                    words)
    );
}

private static String decode(String code, String[] words){
    String[] encodedWords = new String[words.length];
    for (int i = 0; i < words.length; i++) {
        encodedWords[i] = encodeWord(words[i]);
    }

    return decodePossibility(code, words, encodedWords, new StringBuilder());
}

private static String decodePossibility(String code, String[] words, String[] encodedWords, StringBuilder current){
    if(code.length() == 0) return current.toString();
    for (int i = 0; i < encodedWords.length; i++) {
        if(code.length() >= encodedWords[i].length()){
            if(code.substring(0, encodedWords[i].length()).equals(encodedWords[i])){
                String result = decodePossibility(code.substring(encodedWords[i].length()), words, encodedWords, current.append(words[i]).append(' '));
                if(result != null){
                    return result;
                }
            }
        }
    }
    return null;
}

private static String encodeWord(String word){
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < word.length(); i++) {
        stringBuilder.append(letters.get(word.charAt(i)));
    }
    return stringBuilder.toString();
}

Any tips on how to improve the code? Any alternative solution?
To back track to a correct solution I would prefer throwing an exception, but sadly I'am not allowed to do so.


texts:
How can this solution be improved?

#include <limits.h>

void itoa(int n, char s[])
{
    int min_int = 0;
    int i, sign;
    if (INT_MIN == n) {
        min_int = 1;
        n++;
    }

    if ((sign = n) < 0)
        n = -n;
    i = 0;
    do {
        s[i++] = n % 10 + '0';
    } while ((n /= 10) > 0);

    if (sign < 0)
        s[i++] = '-';

    s[i] = '\0';

    if (min_int)
        s[0]++;

    reverse(s);
}


texts: Update dictionary in constant time in Python

texts:
Consider a large list of 4 character strings.

For example: ['P0BH', 'LF3J', 'MA1Y', 'STSM', '8Y74', 'JWBD']

I want to add a new string in the following precise manner:

If the new string already exists in the given list, delete the old value from the list and prepend the new string to the front of the list. For example, if the string 'MA1Y' was added, then the output list would look like this:
['MA1Y', 'P0BH', 'LF3J', 'STSM', '8Y74', 'JWBD']. If the new string does not exist in the list, then just prepend the new string to the front. For example, if the string 'FSH7' was added, then the output list would look like this: ['FSH7', 'P0BH', 'LF3J', 'MA1Y', 'STSM', '8Y74', 'JWBD'].

There is one other caveat: the algorithm must run in constant time complexity. I don't care about space complexity.

Naturally, I have already implemented a solution, which is given below. I believe it runs in constant time complexity, but I would like that we improve it or redesign something better. My understanding is that a map has constant time deletion, membership testing and assignment.

Does the addTicker method in my tickerMap class run in constant time?

If my algorithm is poor, please let me know.

import random
import string

class tickersMap:
    def __init__(self, tickersList):
        self.Map = {t:i for i, t in enumerate(tickersList)}
        self.firstIndex = 0

    def addTicker(self, newTicker):
        if newTicker in self.Map:
            print('exists')
            del self.Map[newTicker]
            self.Map[newTicker] = self.firstIndex - 1
            self.firstIndex -= 1
        else:
            self.Map[newTicker] = self.firstIndex - 1
            self.firstIndex -= 1

    def listTickers(self):
        # This is O(n) but is only required for printing
        return sorted(self.Map, key=self.Map.get)

if __name__ == "__main__":

    tickersList = [''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(4)) for __ in range(6)]

    newTickers = [''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(4)) for __ in range(3)]

    newTickers.insert(0,tickersList[3])
    newTickers.insert(3,tickersList[2])

    print('Starting ticker list:', tickersList)
    tMap = tickersMap(tickersList)

    for newTicker in newTickers:

        print('\nCurrent map:', tMap.Map)

        print('Want to add:', newTicker)

        tMap.addTicker(newTicker)

        print('New map', tMap.Map)

        newTickersList = tMap.listTickers()

        print('New ticker list:', newTickersList)


texts: SPOJ "SBANK - Sorting Bank Accounts" TLE

texts:
I am new tro programming and have chosen python 2.7 to begin with. But, I often have to deal with a TLE while competitive coding like in the problem below, where my code runs fine on all test cases but runs out of the given time bound.

My code runs fine on Ideone.com for all the given test cases, but gives a TLE on SPOJ.

This is the SBANK problem at SPOJ.

  In one of the internet banks thousands of operations are being performed every day. Since certain customers do business more actively than others, some of the bank accounts occur many times in the list of operations. Your task is to sort the bank account numbers in ascending order. If an account appears twice or more in the list, write the number of repetitions just after the account number. The format of accounts is as follows: 2 control digits, an 8-digit code of the bank, 16 digits identifying the owner (written in groups of four digits), for example (at the end of each line there is exactly one space):

  30 10103538 2222 1233 6160 0142

  Banks are real-time institutions and they need FAST solutions. If you feel you can meet the challenge within a very stringent time limit, go ahead! A well designed sorting algorithm in a fast language is likely to succeed.

My code as follows :

def neww(k):
    neww=sorted(set(x+"%d"%(k.count(x)) for x in k))
    for each in neww:
        print each
for _ in range(int(raw_input())):
    p=raw_input()
    if p=='':
        p=raw_input()
    k=[raw_input() for _ in xrange(int(p))]
    neww(k)
    print ""


texts:
The following code is taken from an archived course. Although my answer to the assignment passes  the tests, I'm not sure if it is actually the correct way to write golang code. Primarily because in my solution, there is one extra channel left at the end when the master node is done distributing map/reduce tasks. If it helps, the link to my code is https://github.com/tushar00jain/distribute/blob/master/mapreduce/master.go#L29

Although the code should be self explanatory, other definitions are in the same folder.

I have 2 solutions and I've provided one of them that uses channels below.

The submitJob function is responsible for making the map/reduce RPC call on the workers. If I interchange the lines marked as replace, the code does not work anymore, because there is no channel waiting for mr.registerChannel after the worker from the last job becomes available.

mr.registerChannel basically registers a worker (by sending the ip address) and indicates that it is available, so that a task waiting for this channel can execute. Once the task is done, it makes this channel available again. One thing to be noted is that, I other code will be sending on the mr.registerChannel as well (because there needs to be a worker to begin with).

The code after that just launches goroutines for all the map tasks, which wait for a worker to become available. Then I place blocking code with the done channel so that reduce only starts after all the maps are done. The code for reduce is also similar.

package mapreduce

import "container/list"
import "fmt"

func (mr *MapReduce) RunMaster() *list.List {
    // Your code here
    mr.Workers = make(map[string]*WorkerInfo)
    done := make(chan bool)

    var submitJob func(args *DoJobArgs)
    submitJob = func(args *DoJobArgs) {
        worker := <-mr.registerChannel
        if _, ok := mr.Workers[worker]; !ok {
            mr.Workers[worker] = &WorkerInfo{worker}
        }

        var res DoJobReply
        ok := call(worker, "Worker.DoJob", args, &res)
        if ok {
            done <- true                     // replace
            mr.registerChannel <- worker     // replace
        } else {
            fmt.Printf("DoJob: RPC %s Job error\n", worker)
            delete(mr.Workers, worker)
            // recursively keep trying with a different worker
            submitJob(args)
        }
    }

    go func() {
        for i := 0; i < mr.nMap; i++ {
            args := &DoJobArgs{mr.file, Map, i, mr.nReduce}
            go func(args *DoJobArgs) {
                submitJob(args)
            }(args)
        }
    }()

    for i := 0; i < mr.nMap; i++ {
        <-done
    }

    go func() {
        for i := 0; i < mr.nReduce; i++ {
            args := &DoJobArgs{mr.file, Reduce, i, mr.nMap}
            go func(args *DoJobArgs) {
                submitJob(args)
            }(args)
        }
    }()

    for i := 0; i < mr.nReduce; i++ {
        <-done
    }

    close(done)
    return mr.KillWorkers()
}


texts: Finding acronyms with >=1 letters at the start of each consecutive word

texts:
Problem
I'm seeking a clean and efficient way to determine whether one string is an initialism/acronym of another.
Example: IBM => International Business Machines
However, a key condition for my use case is that an initialism might be constructed using more than one letter from each consecutive word.
Example: ANEXAIST = An Example Is This
Working solution
My solution works, though only returns a single answer (even when multiple might exist - this is fine for my use case). I wonder if there's a cleaner and more efficient implementation?
s1 = 'anexithi'
s2 = 'an example is this'

def recursive_split(s1, s2, mapping=[]):
    for s1_sub in [s1[:i] for i in range(4)]:
        if s1_sub!='' and s1_sub == s2[:len(s1_sub)]:
            mapping_ = mapping + [(s1_sub, s2.split()[0])]
            if s1_sub == s1:
                return mapping_
            rec = recursive_split(s1[len(s1_sub):], ' '.join(s2.split()[1:]), mapping_)
            if rec is not None:
                return rec

recursive_split(s1, s2)

Output
[('an', 'an'), ('ex', 'example'), ('i', 'is'), ('thi', 'this')]


texts:
I have a data table with 7 columns. The first column is the index that increases from 1 to N and is considered to be in ascending order by default. The remaining columns are unsorted. I need to be able to show icons on the table depending on the type of sorting performed, an up arrow for a column in ascending order, a down arrow for a column in descending order and no arrows in unsorted mode.

I assume that when a person sorts column 2, column 1 enters the unsorted state while column 2 can be in an ascending or descending sorted state. I need a 3 way switch where 1 variable at a given time can be toggled ascending or descending and the rest of them are reset back to their initial values.

I wrote a class to handle this and would love to know your opinion on the same. Would this be the RIGHT way to handle 3 way switch between a group of variables? Are there any better approaches for the same.

class SortState {
    constructor(options = {}) {
        this.unsorted = 0
        this.ascending = -1
        this.descending = 1
        this.state = []
        this.initialValues = []
        if (options.keys && options.keys.length && options.values && options.values.length) {

            for (let i = 0, j = 0; i < options.keys.length && j < options.values.length; i++ , j++) {
                this.state.push({
                    key: options.keys[i],
                    value: options.values[j]
                })
            }

            this.initialValues = options.values
        }
    }

    toggle(key) {
        let found = this.state.find(i => i.key === key)
        if (found) {
            let length = this.state.length, current
            for (let i = 0; i < length; i++) {
                current = this.state[i]
                if (current.key === key) {
                    if (current.value === this.ascending) {
                        current.value = this.descending
                    }
                    else if (current.value === this.descending) {
                        current.value = this.ascending
                    }
                    else {
                        current.value = this.initialValues[i]
                    }
                }
                else {
                    current.value = this.unsorted
                }
            }
        }
    }

    getKey(key) {
        let found = this.state.find(i => i.key === key)
        return found ? found : null
    }
}


texts: Word count and most frequent words from input text, excluding stop words

texts:
# Program will display a welcome message to the user
print("Welcome! This program will analyze your file to provide a word count, the top 30 words and remove the following stopwords.")

s = open('Obama 2009.txt','r').read()  # Open the input file

# Program will count the characters in text file
num_chars = len(s)

# Program will count the lines in the text file
num_lines = s.count('\n')

# Program will call split with no arguments
words = s.split()
d = {}
for w in words:
    if w in d:
        d[w] += 1
    else:
        d[w] = 1

num_words = sum(d[w] for w in d)

lst = [(d[w],w) for w in d]
lst.sort()
lst.reverse()

# Program assumes user has downloaded an imported stopwords from NLTK
from nltk.corpus import stopwords # Import the stop word list
from nltk.tokenize import wordpunct_tokenize

stop_words = set(stopwords.words('english')) # creating a set makes the searching faster
print ([word for word in lst if word not in stop_words])

# Program will print the results
print('Your input file has characters = '+str(num_chars))
print('Your input file has lines = '+str(num_lines))
print('Your input file has the following words = '+str(num_words))

print('\n The 30 most frequent words are /n')

i = 1
for count, word in lst[:50]:
    print('%2s. %4s %s' %(i,count,word))
    i+= 1

print("Thank You! Goodbye.")


texts:
I have made a program to calculate the amount of flour, eggs, sugar and butter required for making lemon cakes and cupcakes.

import math

cupcake = [4, 0.1, 12, 14]
#[Butter, egg, flour, sugar]
lemon = [80, 4.5, 240, 300]
#[Butter, egg, flour, sugar]

cup_in = int(input('How many cupcakes would you like? '))
lem_in = int(input('How much lemon cake would you like? '))

amount_cup = []
amount_cup = [x*cup_in for x in cupcake]

amount_lemon = []
amount_lemon = [(x * lem_in) for x in lemon]

print(amount_cup)
print(amount_lemon)

total = []
total = [x + y for x, y in zip(amount_cup, amount_lemon)]

print(total)

amt_butter = total[0]
amt_egg = total[1]
amt_flour = total[2]
amt_sugar = total[3]

bag_but_large = 0
bag_but_medium = 0
bag_but_small = 0

bag_flr_large = 0
bag_flr_medium = 0
bag_flr_small = 0

bag_egg_large = 0
bag_egg_medium = 0
bag_egg_small = 0

bag_sgr_large = 0
bag_sgr_medium = 0
bag_sgr_small = 0

#Calculates the amount of butter bags needed
while amt_butter > 0:

    if amt_butter > 500:
        amt_butter -= 500
        bag_but_large += 1

    elif amt_butter > 250:
        amt_butter -= 250
        bag_but_medium += 1

    elif amt_butter > 125:
        amt_butter -= 125
        bag_but_small += 1

    else:
        bag_but_small += 1
        amt_butter = 0

#Flour
while amt_flour > 0:

    if amt_flour > 750:
        amt_flour -= 750
        bag_flr_large += 1

    elif amt_flour > 500:
        amt_flour -= 500
        bag_flr_medium += 1

    elif amt_flour > 250:
        amt_flour -= 250
        bag_flr_small += 1

    else:
        bag_flr_small += 1
        amt_flour = 0

#Egg
    while amt_egg > 0:

        if amt_egg > 12:
            amt_egg -= 12
            bag_egg_large += 1

        elif amt_egg > 10:
            amt_egg -= 10
            bag_egg_medium += 1

        elif amt_egg > 6:
            amt_egg -= 6
            bag_egg_small += 1

        else:
            bag_egg_small += 1
            amt_egg = 0

#Sugar
while amt_sugar > 0:

        if amt_sugar > 600:
            amt_sugar -= 600
            bag_sgr_large += 1

        elif amt_sugar > 400:
            amt_sugar -= 400
            bag_sgr_medium += 1

        elif amt_sugar > 200:
            amt_sugar -= 200
            bag_sgr_small += 1

        else:
            bag_sgr_small += 1
            amt_sugar = 0

print("*" * 80)
print("Purchases needed: ")
print(bag_but_large, "large bags of butter needed.")
print(bag_but_medium, "medium bags of butter needed.")
print(bag_but_small, "small bags of butter needed.")
print("*" * 80)
print(bag_flr_large, "large bags of flour needed.")
print(bag_flr_medium, "medium bags of flour needed.")
print(bag_flr_small, "small bags of flour needed.")
print("*" * 80)
print(bag_sgr_large, "large bags of sugar needed.")
print(bag_sgr_medium, "medium bags of sugar needed.")
print(bag_sgr_small, "small bags of sugar needed.")
print("*" * 80)
print(bag_egg_large, "large boxes of eggs needed.")
print(bag_egg_medium, "medium boxes of eggs needed.")
print(bag_egg_small, "small boxes of eggs needed.")


texts: Simple/Naive Implementation of Identity and Maybe Monad in Elixir

texts:
This is my first crack at a identity monad and a maybe monad in Elixir:

defmodule Monad do
  @doc "v is value to be wrapped as monadic value"
  def return(v), do: fn -> v end
  @doc "m is monad function, mv is monadic value"
  def bind(m, mv), do: m.(mv.())
end

#Simple identity monad
id = fn s -> s end
h = Monad.return(:ok)
r = Monad.bind(id, h)

#Maybe monad
maybe = fn s -> if is_nil(s), do: :error, else: s end
r = Monad.bind(maybe, h)

I'd like to see if there is a way to make the monad into a protocol since the return and bind seem to be common to all monads.


texts: Monitor webserver accessibility inconsistencies

texts:
I have written a simple application to monitor whether a couple of Java EE 6 web applications deployed to Glassfish 3.1.2.2 are accessible. My intent is to demonstrate to our operations team that the applications are intermittently inaccessible.

package monitoring;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Monitoring {

    private static final Logger logger = Logger.getLogger("MonitoringLogger");

    public static void main(String[] args) throws MalformedURLException, IOException, InterruptedException {
        configureLogger();
        URL[] urls = {
            new URL("http://alpha:11480/AlphaApplication-war/"),
            new URL("http://beta:11680/BetaApplication-war/")
        };
        while (true) {
            for (URL url : urls) {
                URLConnection connection = url.openConnection();
                connection.setReadTimeout(5000);
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    while (reader.ready()) {
                        logger.info(reader.readLine());
                    }
                } catch (SocketTimeoutException exception) {
                    logger.log(Level.SEVERE, "Read timed out to {0}", url);
                }
            }
            Thread.sleep(TimeUnit.MINUTES.toMillis(5));
        }
    }

    private static void configureLogger() throws IOException {
        FileHandler fh;
        fh = new FileHandler("logfile.log");
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
        logger.info("Logger initialized");
    }
}

When the connection is successful, the reply is logged. When the connection times-out, the timeout is logged.

A Windows batch file runs this application on start-up:

java -jar "C:\Users\Me\Monitoring\dist\Monitoring.jar"
pause

I'm satisfied with the behaviour of this application, but I'm using unfamiliar APIs to accomplish an unfamiliar task, so I'm looking for broad advice.


texts:
I have written a simple wrapper for WinSCP in C#. I have written it to simplify SFTP connections I will needing to perform.

public class WinSCPConn : IDisposable
{
        //private fields
        private SessionOptions sessionOptions;
        private TransferOptions transferOptions;
        private Session session;

        //public properties
        public bool IsSessionOpen { get { return session.Opened; } }

        public WinSCPConn(string hostname, string username, string password)
        {
            sessionOptions = new SessionOptions();
            sessionOptions.Protocol = Protocol.Sftp;
            sessionOptions.HostName = hostname;
            sessionOptions.PortNumber = 22;
            sessionOptions.Password = password;
            sessionOptions.UserName = username;
            sessionOptions.Timeout = new TimeSpan(0, 3, 0);
            sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = true;

            transferOptions = new TransferOptions();
            transferOptions.TransferMode = TransferMode.Binary;

            try
            {
                session = new Session();
                session.ExecutablePath = Properties.Settings.Default.WinSCPPath;
            }
            catch (SessionLocalException)
            {
                throw;
            }

        }

        public void Open()
        {
            try
            {
                if (session.Opened == false)
                {
                    session.Open(sessionOptions);
                }
            }
            catch (SessionRemoteException)
            {
                throw;
            }
        }

        public TransferOperationResult SendFile(string SourceFile, string DestFile)
        {
            TransferOperationResult result;
            try
            {
                 result = session.PutFiles(SourceFile, DestFile, false, transferOptions);
                 return result;
            }
            catch (SessionRemoteException)
            {
                 throw;
            }
        }

        public void CreateDirectory(string FolderPath)
        {
            try
            {
                if (!session.FileExists(FolderPath))
                {
                    session.CreateDirectory(FolderPath);
                }
            }
            catch (SessionRemoteException)
            {
                throw;
            }
        }

        public void Close()
        {
            if (session.Opened == true)
            {
                session.Dispose();
            }
        }

        public void Dispose()
        {
            Close();
        }
 }

It would be used as follows:

 using (WinSCPConn conn = new WinSCPConn("host", "username", "password"))
 {
      conn.Open();
      conn.CreateDirectory("/path/");
      conn.SendFile(@"C:\file.txt","/path/file.txt");
 }

My questions are as follows:

How is my exception handling?
Is there too much going on in the constructor?


texts:
This is my first implementation of MongoDB, much much more to come. This sheds light on some things like how I've structured my collection. I hope to gain feedback and insight from the community on best practices as well as do's and don'ts.

Givens

I have a website with multiple apps.
Each user can at one point signup / login for an app.
There is one MongoDB collection called users that will store all the information.
I want a log for each app that tracks users actions (signup, login, logout).

Example User Document

{
  "_id": ObjectId("5035b9fc0000005eed000002"),
  "apps": {
    "app0": {
      "log": [
        {
          "status": "signup",
          "created_at": ISODate("2012-08-23T05:05:00.872Z")
        },
        {
          "status": "login",
          "created_at": ISODate("2012-08-23T05:05:04.012Z")
        },
        {
          "status": "login",
          "created_at": ISODate("2012-08-23T05:05:06.236Z")
        }
      ]
    }
  },
  "user": "reggi"
}

This code is the first interaction with the user they put a small piece of information in and I have to determine whether they are already in the database or not. They can initiate the signup process more than once, so both the initial and update need to write the same log.

users.findOne({"username":req.query.user},function(err, post){
  if(typeof(post) == "undefined"){
    //username does not exist in users create it with this app instance
    users.save((function(){
      var object = {
        "username":req.query.user,
        "apps":{},
      };
      object.apps[appAlias] = {};
      object.apps[appAlias].log = [];
      object.apps[appAlias].log.push({
        status: "initiated-signup",
        created_at: new Date(),
      });
      return object;
    }()));
  }else{
    //username does exist in users create new apps object
    users.update({"_id":post._id},(function(){
      var object = {};
      object.$push = {};
      object.$push["apps."+appAlias+".log"] = {
        status: "initiated-signup",
        created_at: new Date()
      };
      return object;
    })())
  }
});

This is my first dabble with MongoDB. I'm using Mongolian.


texts:
This is a Python module I made to search the Rotten Tomatoes movie API.  It caches the search results in a SQLite database.

What improvements can I make to the cache system?  Is there a better way to store the results of the API search?

Is there a better way to communicate with the API?

import urllib2
import json
import sqlite3
import time

# sqlite database file
cache_database = "movies.db"
# how many seconds before the entry expires
cache_expiration = 60*60  # one hour

class Cache:
    def get_conn(self):
        """
        connect with the sqlite database
        """
        conn = sqlite3.connect(cache_database)
        c = conn.cursor()
        c.execute(""" CREATE TABLE IF NOT EXISTS movies(
                        search_query TEXT PRIMARY KEY,
                        page_number INT,
                        timestamp INTEGER,
                        search_results BLOB); """)
        return conn

    def get(self, search_query, page_number):
        """
        get the search results from the database
        """
        with self.get_conn() as conn:
            c = conn.cursor()
            query = """SELECT search_results FROM movies WHERE
                       search_query = \"{search_query}\" AND
                       page_number = {page_number} AND
                      (strftime('%s', 'now') - timestamp) < {cache_expiration}"""

            query = query.format(search_query = search_query,
                                 page_number = page_number,
                                 cache_expiration = cache_expiration)
            results = ""
            for a in c.execute(query):
                results = a
            return results

    def put(self, search_query, page_number, search_results):
        """
        put the results into the database
        """
        timestamp = int( time.time() )
        with self.get_conn() as conn:
            c = conn.cursor()
            insert = """ INSERT OR REPLACE INTO movies
                         (search_query, page_number, timestamp, search_results) VALUES
                        (\"{search_query}\", {page_number}, {timestamp}, ?); """

            insert = insert.format(search_query = search_query,
                                   page_number = page_number,
                                   timestamp = timestamp)
            c.execute(insert, (search_results,))
            conn.commit()

class Movie:

    api_key = ""
    userAgent = "MovieInfoBot/1.0"

    def search(self, query, results_per_page=25, page_number=1):
        """
        searches for movies: movie name, result limit, page number
        """
        cache = Cache()
        result = cache.get(query, page_number)
        if result != "":
            print "using cache"
            movie_json = result[0]
        else:
            print "using web"
            #format the url
            base_url = "http://api.rottentomatoes.com/api/public/v1.0/movies.json"
            url = "{base_url}?apikey={api_key}&q={search_term}&page_limit={results_per_page}&page={page_number}"
            param = {}
            param["base_url"] = base_url
            param["api_key"] = self.api_key
            param["search_term"] = urllib2.quote(query.encode("utf8"))
            param["results_per_page"] = results_per_page
            param["page_number"] = page_number
            url = url.format(**param)
            req = urllib2.Request(url, headers={ 'User-Agent': self.userAgent })
            movie_json = urllib2.urlopen(req).read()

            # put the results into the movie cache
            cache.put(query, page_number, movie_json)

        movie_dict = json.loads(movie_json)
        return movie_dict

movie = Movie()
movie.api_key = "xua5v8mbvermd2t9v5gyeaua"
data = movie.search("the wizard of oz")

print json.dumps(data, indent=4)

Here is the module on GitHub https://github.com/kylelk/Rotten-Tomatoes


texts:
I implemented a multistep form with the method described by Ryan Bates in ep217 but I had some weird behavior when refreshing or moving between the steps Acts_as_good_style (old but still good) has a tip redirect when moving on that lead me to the change in the code that follows.

In a nutshell, it says that if you're in the create action you should not render new (as I was doing).

This solved the problem. But I had to manage the case of errors in the form, so I ended up with this code.

#profiles_controller.rb

def create
  # [...] save etc [...]

  # render
  if @profile.new_record?
    # render 'new' # OLD
    session[:profile_valid] = @profile.errors.blank?  # NEW
    redirect_to new_profile_path # NEW
  else
    # [...]
  end
end

def new
  @profile = Profile.new(session[:profile_params])
  # [...]

  # rebuild errors (see create)
  # check false because first time is nil and no error have to be displayed
  @profile.valid? if session[:profile_valid] == false
  session[:profile_valid] = true
end

Where in the new action I reload the errors otherwise lost depending on session[:profile_valid], that works fine.

BUT this way doesn't look very good to me and I would appreciate to have your opinion, OR how do you manage your controllers in multispets forms?

What was the strange behavior? Refreshing or going back and forth through the steps sometimes you jump to the wrong page, not clear what the logic is, probably depends on the validations in the model and the params hash.


texts: Inserting a DBNull value into a database

texts:
I have code which works pretty well. I just need some of your opinions on how to write it better with fewer line of code. I want to use a ternary operator but I couldn't make it work so I did an if else instead.

Basically, I want to insert a price on my database. The price column is a nullable decimal. Even in my C# code, it's a nullable decimal as well.

if (items.Price == null)
{
    SqlParameter[] p =
    {
        new SqlParameter("@purchaseorder", items.PurchaseOrderItems),
        new SqlParameter("@modelnumber", items.ModelNumber),
        new SqlParameter("@quantity", items.Quantity),
        new SqlParameter("@Price",  DBNull.Value),
        new SqlParameter("@Description", items.Description),
        new SqlParameter("@OrderNumber", items.OrderNumber),
        new SqlParameter("@Unit", items.Unit)
    };

    i = Dal.ExecuteNonQuery(sql,p);
}
else
{
    SqlParameter[] p =
    {
        new SqlParameter("@purchaseorder", items.PurchaseOrderItems),
        new SqlParameter("@modelnumber", items.ModelNumber),
        new SqlParameter("@quantity", items.Quantity),
        new SqlParameter("@Price",  items.Price),
        new SqlParameter("@Description", items.Description),
        new SqlParameter("@OrderNumber", items.OrderNumber),
        new SqlParameter("@Unit", items.Unit)
    };

    i = Dal.ExecuteNonQuery(sql,p);
}
return i;

Can this be written without the else block?


texts:
I wrote this if statement event listener to add and remove a class to a couple links based on changed.owl.carousel. However, I know this is not the most DRY method in writing the code and often find myself writing more than is needed. Is there a cleaner way to write this code?

owl.on('changed.owl.carousel', function(event) {
  if ($('.owl-item.active>.item.slide3').length>0) {
    $('#link3').addClass('hover');
  } else if (jQuery('.owl-item.active>.item.slide4').length>0) {
    $('.link').removeClass('hover');
    $('#link4').addClass('hover');
  } else {
    $('.link').removeClass('hover');
  }
})


texts: Deleting a node from Binary Tree in OCaml

texts:
I am currently exploring OCaml and wrote the following implementation of deleting a node from a binary tree

let rec deleteNode tree' value =
  match tree' with
  | Empty -> Empty
  | Node(left, nodeValue, right) ->
      if value < nodeValue then
        Node((deleteNode left value), nodeValue, right)
      else if value > nodeValue then
        Node(left, nodeValue, (deleteNode right value))
      else if left = Empty && right = Empty then
        Empty
      else if left = Empty then
        right
      else if right = Empty then
        left
      else
        let newValue = minValue right in
        Node(left, newValue, (deleteNode right newValue))

Where my tree type is

type tree =
  | Empty
  | Node of tree * int * tree

I am looking for a review of my code so that I can improve my OCaml and functional skills.


texts: Decomposing bitfield with Haskell: is recursion the only way to do this?

texts:
Here's a program to take a bitfield like 7 and decompose it into the flags [1,2,4].
Ignore that the algorithm for doing this doesn't use bit shifting/is stupid.

Problems: it seems like I have to have the bithelp function for the sole purpose of calling the other ones, since getFlags and findPower both need to be given given a "starter value" as their second argument (since I can't find a good way to make the argument optional on the first try).

Is there any other way to do what they're doing without recursion? Is recursion like this the standard way to "loop" in FP?

I'll be pleased to be shown anything else I'm doing stupidly here:

-- Algorithm:
-- * given any integer:
-- * find largest power of 2 that fits inside the integer
-- * going from largest to smallest powers of 2, progressively substract any power of 2 that can be subtracted until you get to zero
-- * collect these powers and return them as a list
--
-- These represent the bits that are set within the bitfield
-- E.g. bithelp of 51 = [32,16,2,1]

-- process bitfield
bithelp :: Int -> [Int]
bithelp bitfield = getFlags bitfield $ findPower bitfield 0

-- find starting number: largest power of 2 to fit within bits
findPower :: Int -> Int -> Int
findPower bitfield power
    | 2^power > bitfield = 2^last -- when overshoot bitfield, return last power
    | otherwise = findPower bitfield next
    where next = power + 1
          last = power - 1

-- starting with flag, subtracts down the list of flags, returning list of matches
getFlags :: Int -> Int -> [Int]
getFlags currentBits flag
    | currentBits == flag = [flag] -- only one flag left, last item
    | found = [flag] ++ getFlags remainingBits nextFlag
    | not found = getFlags currentBits nextFlag
    where remainingBits = currentBits - flag
          nextFlag = flag `div` 2
          found = currentBits >= flag -- means bits could be substracted

-- get user input and print list of matched bits
main = do
    putStrLn "Bitfield:"
    line <- getLine
    let bitfield = read line :: Int
    let flags = bithelp bitfield
    putStrLn "List of flags:"
    print flags