texts:
I've been playing with COM lately and while getting to understand the mechanism of how class methods/properties are called an idea came to mind: what if we can have a global instance of a class that exposes a Factory for creating new instances of that class but the Initializer method is Private. Is that possible? The answer is YES. We can make use of the Me special variable to find and replace the instance pointer so that we can redirect calls to the desired instance.
Consider Class1 which has the VB_PredeclaredId set to True:
VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "Class1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'@PredeclaredId
Option Explicit

#If Mac Then
    #If VBA7 Then
        Private Declare PtrSafe Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr
    #Else
        Private Declare Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As Long) As Long
    #End If
#Else 'Windows
    'https://msdn.microsoft.com/en-us/library/mt723419(v=vs.85).aspx
    #If VBA7 Then
        Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
    #Else
        Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    #End If
#End If

#If Win64 Then
    Private Const PTR_SIZE As Long = 8
#Else
    Private Const PTR_SIZE As Long = 4
#End If

Private m_name As String
Private m_id As Long

Public Function Factory(ByVal newName As String, ByVal newID As Long) As Class1
    Dim newClass1 As Class1
    Set newClass1 = New Class1
    '
    #If VBA7 Then
        Dim mePtr As LongPtr
        Dim swapAddr As LongPtr
    #Else
        Dim mePtr As Long
        Dim swapAddr As Long
    #End If
    '
    'Find the address where the swap must happen
    'Note we cannot save ObjPtr(Me) to a variable because
    '   we could get the position of that variable instead
    swapAddr = VarPtr(Me)
    Do
        swapAddr = swapAddr + PTR_SIZE
        CopyMemory mePtr, ByVal swapAddr, PTR_SIZE
    Loop Until mePtr = ObjPtr(Me)
    'Debug.Print swapAddr - VarPtr(Me) '56 on x64 and 168 on x32
    '
    CopyMemory ByVal swapAddr, ObjPtr(newClass1), PTR_SIZE
    Init newName, newID
    CopyMemory ByVal swapAddr, mePtr, PTR_SIZE
    '
    Set Factory = newClass1
 End Function

Private Sub Init(ByVal newName As String, ByVal newID As Long)
    m_name = newName
    m_id = newID
End Sub

Public Property Get Name() As String
    Name = m_name
End Property

Public Property Get ID() As Long
    ID = m_id
End Property

Now we could create and use new instances like this:
Sub TestFactory()
    With Class1.Factory("Test", 4)
        Debug.Print .Name
        Debug.Print .ID
    End With
End Sub

even if the Init method is Private.
I don't really understand why the offset is 56 bytes on x64 and 168 bytes on x32 (at least on my computers). Would be nice if somebody could figure this out so that the loop used in finding the swap address is not needed anymore.

EDIT 1
Apparently on x64 it is sufficient to get the swap address like this:
    #If Win64 Then
        swapAddr = VarPtr(Factory) + PTR_SIZE
        mePtr = ObjPtr(Me)
    #End If

so no loop would be needed.
Edit 2
I've decided to create a new follow-up question with a new improved code, instead of answering this question because the code here is slower and less safer. Go to: Private VBA Class Initializer called from Factory #2


texts: Python 3: Why is my prime sieve so slow?

texts:
I've implemented the sieve of Eratosthenes in Python 3 as follows:

def sieve_of_eratosthenes(n):
    is_prime = [True] * (n+1)
    is_prime[0] = False
    is_prime[1] = False
    p = 0

    while True:
        for i, prime in enumerate(is_prime):
            if prime and i > p:
                p = i
                break
        else:
            break

        multiple = p + p

        while multiple <= n:
            is_prime[multiple]= False
            multiple = multiple + p

    r = []
    for i, prime in enumerate(is_prime):
        if prime: r.append(i)
    return r

Running this to 100,000 takes ~25 seconds.

I felt that was on the slow side, so I decided to take a different approach. The Sieve works prospectivly: it works ahead to clear out all multiples. I made a retrospective function, trial-dividing everything lower than the current prime-candidate:

def retrospect(n):
    primes = [2, 3]
    i = 5

    while i <= n:
        isprime = True
        lim = math.sqrt(n)+1
        for p in primes:
            if p > lim:
                break
            if i % p == 0:
                isprime = False
                break
        if isprime:
            primes.append(i)
        i += 2

    return primes

This is way faster!

Questions:

Are there any obvious shortcomings to the Sieve implementation?
Is there a point where the retrospect gets slower than the sieve?


texts: Extracting all-caps variables from string expressions

texts:
I'm extracting variables from user entered mathematical expressions, so that I can enter them into the expression evaluator exprtk. For now, the condition is given that variable names will be composed of consecutive capital letters. Any mathematical constants or function names will be lowercase. Some hypothetical inputs and expected outputs:

Input: "(A + B) - 2"
Expected Output: { A, B }

Input: "pow(AC,E) * ( E * F )"
Expected Output: { AC, E, F }

The code I have right now seems to work, but I would love a critique. I add a space to the end of the string to make my algorithm catch cases at the end of the string, which seems a bit hacky(?).

template<class T>
std::vector<std::string> MapEvaluator<T>::extractVariables(std::string expression) {

    expression = expression + " ";
    std::vector<std::string> variables = {};
    std::string substring;
    size_t consecutiveCharsCaps = 0;
    bool previousCharCaps = false;

    for (size_t i = 0; i < expression.length(); i++)
    {
        if (isCapital(expression[i]))
        {
            consecutiveCharsCaps++;
            previousCharCaps = true;
        }
        else {
            if(previousCharCaps) {
                substring = expression.substr(i - consecutiveCharsCaps, consecutiveCharsCaps);
                variables.push_back(substring);
                consecutiveCharsCaps = 0;
                previousCharCaps = false;
            }
        }
    }

    unique(variables);
    return variables;
}

template <class T>
void MapEvaluator<T>::unique(std::vector<std::string> &vec)
{
    auto end = vec.end();
    for (auto it = vec.begin(); it != end; ++it) {
        end = std::remove(it + 1, end, *it);
    }
    vec.erase(end, vec.end());
}

template<class T>
bool MapEvaluator<T>::isCapital(char c) {
    return (c >='A' && c <= 'Z');
}


texts: Print worksheets depending on checkbox. Slower than before

texts:
I have an userform that has check boxes where user can decide which worksheets to print.

Code in userform:

Sub PrintOK_Click()

PrintSelection = Summary.value + _
CCSummary.value + _
DivSalaries.value + _
CCSalaries.value + _
PrintAll.value _

' Displays warning box if no report is selected
If PrintSelection = 0 Then
    MsgBox "No Report(s) selected. Please select Report(s) to print.", 0 + vbExclamation, "Incomplete Request"
End If

' Check to see which worksheets have been selected and
' Run print modules for selected worksheets
    If Summary.value = -1 Then
        Call setup("Summary")
    End If

    If CCSummary.value = -1 Then
        Call setup("Monthly CC Sum")
    End If

    If DivSalaries.value = -1 Then
        Call setup("Div Sal Sum")
    End If

    If CCSalaries.value = -1 Then
        Call setup("CC Sal Sum")
    End If

    If PrintAll.value = -1 Then
        Call setup("PrintAll")
    End If

' Close Form box
End
End Sub

Userform selection is passed into the following. Takes the worksheet(s) selected and stores into array.

Sub setup(Optional tabs As String)
'store sheets into array

Dim arr() As Variant

'called from printer icon on activesheet
If tabs = "" Then
    arr = Array(ActiveSheet.Name)

'called via checkbox from print menu
ElseIf tabs = "PrintAll" Then
    arr = Array("Summary", "Monthly CC Sum", "Div Sal Sum", "CC Sal Sum")
Else
    arr = Array(tabs)
End If

Call goPrint(arr)

End Sub

Which then passes the array to another sub to do the printing

Sub goPrint(tabArr As Variant)

Dim ws As Worksheet
Dim area As String
Dim title As String

'loop through array to print each sheet
For i = 0 To UBound(tabArr)

    Set ws = Worksheets(tabArr(i))

    With ws

        If .Name = "Summary" Then
            area = "PRNSUMMARY"
            title = "$1:$9"
        ElseIf .Name = "Monthly CC Sum" Then
            area = "PRNMONTHLYCCSUM"
            title = "$2:$16"
        ElseIf .Name = "Div Sal Sum" Then
            area = "PRNDIVSALSUM"
            title = ""
        ElseIf .Name = "CC Sal Sum" Then
            area = "PRNCCSALSUM"
            title = "$2:$16"
        End If

        With .PageSetup
            .PrintArea = area
            .PrintTitleRows = title
            .PrintTitleColumns = ""
            .LeftHeader = ""
            .CenterHeader = ""
            .RightHeader = ""
            .LeftFooter = Year(Now()) & " Budget:   &F"
            .CenterFooter = "Page &P of &N"
            .RightFooter = "&D:   &T"
            .LeftMargin = Application.InchesToPoints(0.25)
            .RightMargin = Application.InchesToPoints(0.25)
            .TopMargin = Application.InchesToPoints(0.5)
            .BottomMargin = Application.InchesToPoints(0.5)
            .HeaderMargin = Application.InchesToPoints(0)
            .FooterMargin = Application.InchesToPoints(0.25)
            .PrintHeadings = False
            .PrintGridlines = False
            .PrintComments = xlPrintNoComments
            '.PrintQuality = 600
            .CenterHorizontally = False
            .CenterVertically = False
            .Orientation = xlLandscape
            .Draft = False
            .PaperSize = xlPaperLetter
            .FirstPageNumber = xlAutomatic
            .Order = xlDownThenOver
            .BlackAndWhite = False
            .Zoom = False
            .FitToPagesWide = 1
            .FitToPagesTall = False
        End With

        'Debug.Print tabArr(i)
        'Debug.Print area
        .PrintOut Copies:=1, Collate:=True

    End With

Next

End Sub

There's a delay of maybe two seconds after pressing OK before the printer starts to print. The previous (much longer) code had no discernible delay. How to improve speed?

(Previous code had a different sub for each worksheet thus repeating the pagesetup code block multiple times.)


texts: Getting the list of people who RT'd a particular Twitter account (using Twitter4J)

texts:
I'm looking for feedback (both general Java, and Twitter specific) on how I'm getting the Twitter handles of everyone who retweeted me over the last 200 Tweets.  Comments welcome.

package twitone;

import java.util.ArrayList;
import twitone.structure.BaseTwitterClass;
import twitone.structure.TwitApplicationFactory;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;

public class getmyretweeters extends BaseTwitterClass {

    public static void main(String[] args) throws TwitterException {

        Twitter twitter = TwitApplicationFactory.getjoereddingtonTwitter();
        String temp[] = getRetweeters(twitter);
        for (String string : temp) {
            System.out.println(string);
        }
    }

    public static String[] getRetweeters(Twitter twitter) {
        ArrayList<String> names = new ArrayList<String>();
        try {
            for (Status status : twitter.getUserTimeline(new Paging(1, 200))) {
                System.out.println(status.getText());
                if (status.getRetweetCount() > 0) {
                    Thread.sleep(120000);// Because I don't want to breach
                                        // Twitter's rate limits
                    for (Status rt : twitter.getRetweets(status.getId())) {
                        names.add(rt.getUser().getScreenName());
                    }
                }
            }
        } catch (TwitterException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return names.toArray(new String[names.size()]);
    }
}


texts:
I'm working in my project with the following script:

;(function($, doc, win) {
"use strict";

 // cache the window object
 var jQuerywindow = $(window);

 $('section[data-type="background"]').each(function(){

   // declare the variable to affect the defined data-type
   var jQueryscroll = $(this);

    $(window).scroll(function() {

      // HTML5 proves useful for helping with creating JS functions!
      // also, negative value because we're scrolling upwards
      var yPos = -(jQuerywindow.scrollTop() / jQueryscroll.data('speed'));

      // background position
      var coords = '50% '+ yPos + 'px';

      // move the background
      jQueryscroll.css({ backgroundPosition: coords });
    }); // end window scroll
 });  // end section function

})(jQuery, document, window);

The script allows me to have several sections with parallax background effect.  So, I can have one or ten in a page. I'm a bit concern about performance. Can the script be improved?


texts: Concatenating multiple strings from a JSON response

texts:
I would like to concatenate a series of strings populated from an XHR response. So, I've chosen to do it like this:

$.post('/API',null,'json')
    .done(function(response){
        if (response.status === 'success') {
            location = response.data.city + ', ' + response.data.state;
        }
    })
    .fail(function(){
        location = previousLocation;
    })
    .always(function(){
        $("#location").text(location);
    });

This feels clunky. Should I be more defensive in assuming a response from the API? Would this be more elegantly handled by some kind of templating function?


texts: Golang execute several go routine in loop and then wait

texts:
I'm new in Go and excited with its easy-to-use concurrency implementation. However I'm not sure if I'm doing it right in Golang way.
Consider the code where I spawn process(i int, ch chan int) every loop as separate goroutine. Then the result which comes from the channel will be consumed by consume(ch chan int, wg *sync.WaitGroup).
I know that the channel is blocking, so let's implement buffered channel. And of course I don't want the process terminated before every goroutine finished the operation, so I add WaitGroup.

func main() {
    var wg sync.WaitGroup
    n := 5
    ch := make(chan int, n)
    for i := 0; i < n; i++ {
        println("Processing ", i)
        go process(i, ch)
        go consume(ch, &wg)
    }
    println("Finished the process")
    wg.Wait()
}

func consume(ch chan int, wg *sync.WaitGroup) {
    wg.Add(1)
    defer wg.Done()
    println("Result ", <-ch)
}

func process(i int, ch chan int) {
    ch <- (i * 5)
}

Am I doing it right? Or there are better way to do this?
Many thanks!


texts: Apache reverse proxy security configuration

texts:
Could someone share some light and check if this is okay for apache httpd security/good standards? I'm using apache httpd to call my Node.js app that is running with Express and also configuring SSL.

apache2.conf:

DefaultRuntimeDir ${APACHE_RUN_DIR}

PidFile ${APACHE_PID_FILE}

Timeout 300

KeepAlive On

MaxKeepAliveRequests 100

KeepAliveTimeout 5

User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

HostnameLookups Off

ErrorLog ${APACHE_LOG_DIR}/error.log

LogLevel warn

IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

Include ports.conf

LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

IncludeOptional sites-enabled/*.conf

Protocols h2 http/1.1

KeepAlive Off

<IfModule mpm_prefork_module>
  StartServers 4
  MinSpareServers 20
  MaxSpareServers 40
  MaxClients 200
  MaxRequestsPerChild 4500
</IfModule>

ServerTokens Prod
ServerSignature Off

FileETag None
TraceEnable off

site-name.conf:

<VirtualHost *:80>

  ServerName www.site-name.com
  ProxyRequests Off

  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined

  Redirect permanent / https://site-name.com

</VirtualHost>

site-name-ssl.conf:

<IfModule       mod_ssl.c>
  <VirtualHost  _default_:443>
      ServerName site-name.com

      ErrorLog ${APACHE_LOG_DIR}/error.log
      CustomLog ${APACHE_LOG_DIR}/access.log combined

      SSLEngine on
      ProxyRequests Off

      SSLCertificateFile /etc/letsencrypt/live/site-name.com/fullchain.pem
      SSLCertificateKeyFile /etc/letsencrypt/live/site-name.com/privkey.pem
      Include   /etc/letsencrypt/options-ssl-apache.conf

      ProxyPass /api http://site-name.com:3000/api
      ProxyPassReverse /api http://site-name.com:3000/api

      ProxyPass / http://site-name.com:4226/
      ProxyPassReverse / http://site-name.com:4226/

  </VirtualHost>
</IfModule>


texts: Understanding exceptions in a constructor (by the conversion C-string to long example)

texts:
I myself is a Java-developer and now I'm trying to understand how to do it in the most efficient way in C++. After reading that answer I decided to write the following:

//Headers omitted
class integer_validator
{
public:
    integer_validator(const char* const str);
    bool is_valid();
    long get_number();
private:
    bool valid;
    long result;
};

integer_validator::integer_validator(const char* const str)
{
    char *endptr;
    result = strtol(str, &endptr, 10);
    if(*endptr == '\0') valid = true;
    else valid = false;
}

bool integer_validator::is_valid()
{
    return valid;
}

long integer_validator::get_number()
{
    if(!valid)
        throw std::exception();
    return result;
}
int main ()
{
    integer_validator vv("123123");
    integer_validator v("123123a");
    std::cout << vv.get_number() << std::endl; //prints the number
    std::cout << v.get_number() << std::endl;  //throws the exception
}

DEMO

And it works perfectly fine. But I'm not sure about some things I did. Is it considered good to put any piece of logic into a constructor? I actually do the validation within the constructor's body and I use only the C-functions.

So should I be afraid of throwing an exception during the construction in that case?


texts: Unique nucleotide permutations, Python itertools product

texts:
I'm searching for all the unique possible permutations of nucleotide given a defined length. By unique, I mean the reverse complement would not be counted.

  ACGT

For example, permutations of length 1 would be:

A:T
C:G
G:C
T:A

But the last two wouldn't be included because they would already be seen.

Length 2 would be:

AA:TT
AC:GT
AG:CT
AT:AT
CA:TG
CC:GG
CG:CG
CT:AG
GA:TC
GC:GC
GG:CC
GT:AC
TA:TA
TC:GA
TG:CA
TT:AA

So, 8, 11, 12, 14, 15, 16 wouldn't be included for the same reason, and so on.

def data_count(n, trantab):
    nn = int(n)
    count = 0
    seen = set()

    with open('file.txt','w') as f:
        for number in range(1, nn+1):
            for p in itertools.product('ACGT', repeat=number):
                print(''.join(p)+':'+''.join(p)[::-1].translate(trantab))
                if ''.join(p) in seen:
                    pass
                else:
                    seen.add(''.join(p)[::-1].translate(trantab))
                    count += 1
            #print(x)
            f.write(str(number)+' = '+str(count)+'\n')
            count = 0

It does the job pretty well until 10 or 12, but beyond that it takes a lot of time to output results.

n is the length of the search and trantab is:

intab = 'ACGT'
outtab = 'TGCA'
trantab = str.maketrans(intab, outtab)

to get the reverse complement of the nucleotide.

Is there any way to improve this one?


texts: Subclassing Flask for Permissions with Google App Engine

texts:
I'm trying to set up a very lightweight permission system using Google App Engine and Flask.

The end result I am hoping for is that each individual view is its own permission, and in an admin panel you can assign the views each user is allowed to see.

How would I set this up better? It works fine, but I'm going to be querying ndb on operator for each and every view everytime a page loads.

from google.appengine.api import users
from google.appengine.ext import ndb
import logging
from flask import Flask, redirect, make_response, request

def user_authorized(rule):
    user = users.get_current_user()
    username = str(user)
    user_info = Operators.query(Operators.username == username).get()
    if not user_info:
        return False
    if rule in user_info.permissions:
        return True
    else:
        return False

def forbidden_view():
    return make_response(
        'You do not have permission or this user does not exist. Login'.format(users.create_login_url(request.url)),
        403
    )

class FlaskWithPermissions(Flask):
    def route(self, rule, **options):
        def decorator(f):
            endpoint = options.pop('endpoint', f.__name__)
            if user_authorized(rule):
                self.add_url_rule(rule, endpoint, f, **options)
                return f
            else:
                self.add_url_rule(rule, endpoint, forbidden_view, **options)
        return decorator

app = FlaskWithPermissions(__name__)

class Operators(ndb.Model):
    username = ndb.StringProperty()
    permissions = ndb.StringProperty(repeated=True)

@app.route('/')
def index():
    return 'OK /'

@app.route('/test')
def test():
   return 'OK /test'

@app.route('/testfail')
def testfail():
    return 'OK /testfail'

The test data I have in the database is:

Operators(username='test@example.com', permissions=['/', '/test']).put()

And then log in as test@example.com, of course.


texts:
Could you provide feedback for this code? For arrays of length 2, is it more efficient not to use a sorting algorithm?

package insertion.sort;

import java.util.Arrays;

public class InsertionSort {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int[] testArr = {-10, -5, 100, 51, 6, 50};
        insertionSort(testArr);
        System.out.println(Arrays.toString(testArr));
    }

    public static void insertionSort(int[] arr) {
        for(int i = 1; i < arr.length; i++) {
            int temp = arr[i];
            int j;
            for(j = i; j > 0 && arr[j-1] > temp; j--)
                arr[j] = arr[j-1];
            arr[j] = temp;
        }
    }

}

By the way, I've noticed "quicksort" is spelt all as one word, but "insertion sort" is spelt as two. Is that right? Would anyone ever say "quicksort sort"?


texts: Inspectors & Deconstruction on Unions in a list

texts:
I am still new to functional programming and found myself trying to filter and map a list of discriminating unions.  I could be wrong, but it started to feel very unnatural to do this.  I just couldn't figure out how else to get the workflow that I wanted in the CreateThing method.

The IsTrue/False and Value/Error methods are very useful, but their implementations seem awkward.  But they are what allows me to work with DUs in list form.

Is there a more elegant/natural solution to this?

module Test

open System.Collections.Generic

// some borrowed finaglery from s.o.
module Seq =
    // borrowed from: https://stackoverflow.com/a/12564899
    // takes until the condition is true plus one more
    let takeUntil predicate (s:seq<_>) =
        let rec loop (en:IEnumerator<_>) = seq {
            if en.MoveNext() then
                yield en.Current
            if predicate en.Current then
                yield! loop en
            }

        seq { use en = s.GetEnumerator()
            yield! loop en
            }

// the union in question
type Valid<'a> =
    | Valid of 'a
    | Invalid of string

// the inspectors and destructors in question
module Valid =

    let IsTrue v = match v with |Valid _-> true |_-> false
    let IsFalse v = match v with |Valid _-> false |_-> true
    let Value v = match v with |Valid v -> v | Invalid _ -> failwith "no value"
    let Error v = match v with |Valid _ -> failwith "no error" | Invalid i -> i

module UseCase =

    type Thing = {
        Values : int list
    }

    let ValidateNumber (i : int) : Valid<int> =
        if i = 3 then Invalid "no threes yo" else Valid i

    let CreateThing (inputs : int seq) : Valid<Thing> =
        // pull items through the seq until i hit a problem
        let worked = inputs |> Seq.map ValidateNumber |> Seq.takeUntil Valid.IsFalse |> Seq.toList

        // see if it all worked out or not
        let success = List.last worked |> Valid.IsTrue

        if success then
            // deconstruct my 'valids' back to primitive ints
            Valid {Thing.Values = worked |> List.map Valid.Value}
        else
            // deconstruct my last error into a new error
            Invalid (List.last worked |> Valid.Error)


texts: Refactor method by removing else condition

texts:
Given the below code is there a way to eliminate the else clause from the below method?
In my workplace else clause is considered evil because it somehow decreases the readability of the code.
public boolean validateAndSetDateRelatedSessionAttributes(String startDateFromParam, String endDateFromParam, HttpSession session) throws ParseException {
    boolean isDateRangeValid = true;
    final boolean requestContainsCustomDate = requestContainsCustomDate(startDateFromParam, endDateFromParam);

    if(requestContainsCustomDate || sessionContainsCustomDate(session)) {
        if(requestContainsCustomDate) {
            if(!isDateRangeValid(startDateFromParam, endDateFromParam)) {
                isDateRangeValid = false;
                startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();
                endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();
            }
        } else {
            startDateFromParam = session.getAttribute(BACalendarConstant.START_DATE).toString();
            endDateFromParam = session.getAttribute(BACalendarConstant.END_DATE).toString();
        }
        setSessionAttributes(startDateFromParam, endDateFromParam, session);
    }
    return isDateRangeValid;
}


texts:
I've had some help designing my field boxes and I was hoping to get feedback on the code. The fields will increase in complexity which is why I thought to structure it this way (image upload fields, textbox with WYSIWYG controls etc.

CSS

.error { height: 27px; background-color: red; margin-bottom: 4px;}
.lft { float: left; }
ul, li { list-style-type: none; vertical-align:middle; }
.ts3 { font-size: 15px; }
.dc3 { background-color: #808080; }
.tc5 { color: #333333;}
.p4 { padding: 4px; }
.r2 { border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; }
.r6 { border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; }
.field { line-height:27px; font-family:arial, sans-serif; border-color: #d9d9d9; border-top:solid 1px #c0c0c0; }
input.field{width:100%}
.fieldwrapper{ padding: 0 5px 0 0; overflow: hidden;}
label{width:200px; display:inline-block; float:left}

HTML

Error!

Sender email address

<input class="field r2" placeholder="Email" type="text" value="">

This is just me explaining how to use this particular field. It is very interesting, don't you know...

JSfiddle link
LNIK


texts: Interface design to have multiple implementations of network call libraries (Retrofit or Volley)

texts:
I am learning design patterns from Head First Design Patterns and a principle I came across is to "code to interface". Now I want to apply this principle in my Android app, which includes lots of API calls. I am using Retrofit for network calls.

I have applied this principle considering some scenario something like this:

Suppose in the future I need to shift from Retrofit to Volley or any other networking library.
I created an interface with a method to getData from the server and created a class which implements that interface. The implemented method includes the Retrofit code to getData from the server.
Now in the future, if I want to use Volley, I'll create a new class implementing the interface and with Volley code to retrieve data from the server.

Interface

public interface NetworkCallsApi {
    String getDataFromServer(Activity activity,String url,String Callback);
}

Retrofit Implementation

public class NetworkCallsRetrofitImpl implements NetworkCallsApi{

private Retrofit retrofit;

@Override
public String getDataFromServer(Activity activity, String url, String Callback) {

retrofit = new Retrofit.Builder()
        .baseUrl(StringConstants.ROOT_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

RetrofitApi apiCalls = retrofit.create(RetrofitApi.class);

Call<ResponseBody> call = apiCalls.getDataFromServer(url);

call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {

    }
});
return null;
}
}

ServiceCalls.java

public class ServiceCalls {

    public static ServiceCalls serviceCalls;
    public NetworkCallsApi networkCallsimpl;

    public static ServiceCalls getInstance(){

        if(serviceCalls == null){
            serviceCalls = new ServiceCalls();
        }
        return serviceCalls;
    }

    public void setNetworkCallsimpl(NetworkCallsApi networkCallsimpl) {
        this.networkCallsimpl = networkCallsimpl;
    }

    public String getDataFromServer(Activity activity, String url, String callback){
        networkCallsimpl.getDataFromServer(activity,url,callback);
        return null;
     }
 }

MainFragment:

public class StatusFragment extends Fragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Setting the implementation
        ServiceCalls.getInstance().setNetworkCallsimpl(new NetworkCallsRetrofitImpl());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_pnr_status,container,false);

        try{
          init();
        }catch(Exception e){}
        return view;
   }

    private void init() {

        ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            setUrlKeysAndValues();
            ServiceCalls.getInstance().getDataFromServer(getActivity()
                ,Utils.getInstance().buildUrl(urlKeys,urlValues),"onResponse");
        }
        });

    }
}

Have I correctly applied that principle? If not, what changes do I need to make? In onCreate of MainFragment, I am hardcoding the implementation. How can the interface design pattern be better applied in this scenario?


texts:
I've been working on Bill of Materials mini schema for a while. At first I had single Part table where I've referenced itself. I was told it would be better to have separate table because we'd need to have info like quantity and that quantity is not part of Part itself. Here's the script...

CREATE TABLE Part
(
    ID INT NOT NULL PRIMARY KEY IDENTITY,
    PartNumber NVARCHAR(50) NULL,
    [Description] NVARCHAR(MAX) NULL,
    ListPrice DECIMAL(12,2) NULL
)

CREATE TABLE BOM
(
    ID INT NOT NULL PRIMARY KEY IDENTITY,
    PartId INT NOT NULL,
    ParentId INT NULL,
    Quantity INT NULL
)

ALTER TABLE BOM ADD CONSTRAINT BOM_PartId_FK
FOREIGN KEY (PartId) REFERENCES Part(ID)

ALTER TABLE BOM ADD CONSTRAINT BOM_ParentId_FK
FOREIGN KEY (ParentId) REFERENCES Part(ID)

insert into Part (PartNumber, Description, ListPrice) values ('AAA', 'A', 250.00)
insert into Part (PartNumber, Description, ListPrice) values ('AA', 'A', 100.00)
insert into Part (PartNumber, Description, ListPrice) values ('BBB', 'B', 250.00)
insert into Part (PartNumber, Description, ListPrice) values ('BB', 'B', 90.00)
insert into Part (PartNumber, Description, ListPrice) values ('B', 'B', 40.00)

insert into BOM (PartId) values (1)
insert into BOM (PartId, ParentId, Quantity) values (2, 1, 5)
insert into BOM (PartId, ParentId, Quantity) values (4, 3, 10)
insert into BOM (PartId, ParentId, Quantity) values (5, 4, 50)
insert into BOM (PartId, ParentId, Quantity) values (4, 1, 50)

Would this be ok as beginner BOM schema?

I've tested with the below query, this gets immediate children of BOM with ID of 1.

select e.*
from BOM b
join BOM e on b.PartId = e.ParentId
where b.ID = 1

I will recursively call this from c# to populate children from any level in the BOM, but usually top most level.


texts: Exercism assignment for word-count in Clojure

texts:
I would appreciate some insights / comments from Clojure regulars out there about my submission here.

(ns phrase)
(require '[clojure.string :as s])

(defn word-array
  [phrase]
  (-> (s/lower-case phrase)
      (s/split #"\W+")))

(defn word-count
  [phrase]
  (-> (word-array phrase)
      (frequencies)))


texts: Basic Javascript algorithm for time implementation (morning, afternoon, etc.)

texts:
I have a small JavaScript time detection module that detects what time it is now, like morning, afternoon, evening, or night.

How can I make the following code less redundant? Is my code already clean? It would also be great if I could get some comments on the style of the code. I really want to know what the best coding practices are.

var now = new Date(),
    hour = now.getHours();

var morning   = (hour >= 4  && hour <= 11),
    afternoon = (hour >= 12 && hour <= 16),
    evening   = (hour >= 17 && hour <= 20),
    night     = (hour >= 21 || hour <= 3);

if(morning) {

  console.log("It's morning");

} else if(afternoon){

  console.log("It's afternoon");

} else if(evening) {

  console.log("It's evening");

} else if(night) {

  console.log("It's night");

}


texts: Seemingly complicated way of displaying page views

texts:
I have this code

//TRIGGER MULTIPLE VIEWS, WALL AND FORUM
if(isset($_COOKIE["projects-sorting"])) {
    $_SESSION['projectsDisplayMode'] = $_COOKIE["projects-sorting"];
}
if(isSet($_GET['mode'])) {
    $_SESSION['projectsDisplayMode'] = $_GET['mode'];
}
if(!isSet($_SESSION['projectsDisplayMode'])) {
    $_SESSION['projectsDisplayMode'] = "wall"; //default is wall mode
}
$mode = $_SESSION['projectsDisplayMode'];
setcookie("projects-sorting", $mode, time() + (86400 * 30), "/"); // 86400 = 1 day

Which to me looks overly complicated, but it does work.

What it does:

Checks  if a specific cookie exists, if it does, set session variable projectsDisplayMode to whatever that cookie's content is.
Check if _GET variable mode exists, if it does, set projectsDisplayMode to whatever that variable is (Would overwrite the last variable set if both exist)
Last check if the session variable is set at all, if it's not set it to "wall", as that is the default.
Now set $mode (A specific page variable) to be processed a bit more to show the page properly.

I'm not concerned with the afterwards processing, I just want to see if there is a better way that I can do the first bit that may be faster or more standard, or more pleasant to look at.


texts: Generating and finding parent nodes in a post-order tree

texts:
Given a height h and list q of integers, list the parent node of
  each element in q, if nodes are read in post-order sequence starting
  at 1. The tree could be read like this if h=3.

    7
  3   6
 1 2 4 5

  If h = 3 and q = [1,3,7] the output would be the list [3, 6, -1] where
  the parent of the root is always -1.

How can I make this code faster? It does okay until h=10, then it slows down since it has to check \$2^h-1\$ nodes.

#Generate a perfect binary tree of height h
#Find the parent nodes of the values in list g, return negative 1 for the
#root

node_list = []
solution = {}

class Node:
    def __init__(self):
        self.left = None
        self.right = None
        self.data = None
        self.parent = -1
        self.left_edge = True
        self.depth = 0

def answer(h, q):
    global node_list
    global solution
    final_answer = []
    root = int(pow(2, h))-1
    solution.update({root: -1})
    node_list = (list(range(root+1)))
    node_list.reverse()
    node_list.pop()
    node = Node()
    node.data = root
    node.left = left_branch(h, node)
    node.right = right_branch(h, node)
    for i in q:
        for key in solution:
            if i == key:
                final_answer.append(solution[key])
        return final_answer

def left_branch(h, parent: Node):
    global node_list
    global solution
    new_node = Node()
    new_node.depth = parent.depth + 1
    new_node.parent = parent.data

    try:
        if parent.left_edge:
            new_node.data = parent.data//2
        node_list.remove(new_node.data)
    else:
        new_node.left_edge = False
        new_node.data = parent.data - int(pow(2, h - new_node.depth))
        print(new_node.data)
        node_list.remove(new_node.data)

    except ValueError:
        if not(new_node.data in node_list):
            return new_node

    solution.update({new_node.data: parent.data})
    left = left_branch(h, new_node)
    right = right_branch(h, new_node)
    new_node.left = left
    new_node.right = right
    return new_node

def right_branch(h, parent: Node):
    global node_list
    global solution
    new_node = Node()
    new_node.left_edge = False
    new_node.depth = parent.depth + 1
    new_node.parent = parent.data
    new_node.data = parent.data - 1
    try:
        node_list.remove(new_node.data)
    except ValueError:
        return new_node
    left = left_branch(h, new_node)
    right = right_branch(h, new_node)
    new_node.left = left.data
    new_node.right = right.data

    solution.update({new_node.data: parent.data})

    return new_node

This was a challenge given by Google Foobar. The time window has expired. My code took too long to run. I'm wondering about the optimal way to solve this problem.


texts: Finding a string whose MD5 starts like the digits of π

texts:
I tried to make a program to find a string whose MD5-hash starts like the digits of pi, where dot is omitted. Is there a faster way to do it than this:

import hashlib
import random
import string
n = 1
while True:
    word = ''.join(random.choice(string.ascii_lowercase) for _ in range(20))
    if (str(hashlib.md5(word.encode('utf-8')).hexdigest()))[:n] == '31415926535897932384626433832795'[0:n]:
        print('n='+str(n)+", "+word)
        n = n + 1


texts: Checking whether a string ends with one of a list of suffixes

texts:
I want to check if some line ends with any substring defined in some list. Is there a better way than following one?

endsA = ['foo', 'bar', 'fur', 'beer']
endsB = ['door', ... ]

def checkEnds(line, ends):
    for end in ends:
        if line.endswith(end):
            return True

....

if checkEnds(line, endsA):
    do_something()


texts: All permutations of the pairs that add to squares

texts:
Given a number, this program would find "all permutations of the pairs that add to squares" from 1 to number.

  E.g: Given an input number of 16, one of the possible answers would be:

8:1:15:10:6:3:13:12:4:5:11:14:2:7:9:16

  and its reverse.

Note that the function called hasIntegerRoot has been commented out for a purpose. I would appreciate if reviewer would chose me to use hasIntegerRoot over currently used List<Integer> squareList.

I'm looking for code review, best practices, optimizations etc.

Verifying Complexity (where \$n\$ is the input number):

Time: \$O(n!)\$
Space: \$O(n!)\$

public final class PairSquare {

    private PairSquare() {};

    /**
     *  Given a number, this program would find "all permutations of the pairs that add to squares" from 1 to number"
     *
     * @param num        The number upto which adjacent numbers should sum to a sqaure
     * @return           A List of all the lists/chains of integers such that adjacent numbers sum upto a square.
     */
    public static List<List<Integer>> pairSquare (int num) {
        if (num <= 0) throw new IllegalArgumentException("The input number " + num + " should be less than equal to zero.");

        final List<List<Integer>> pairSquaresList = new ArrayList<List<Integer>>();
        final List<Integer> squareList = squareList(num);
        final LinkedHashSet<Integer> elements = new LinkedHashSet<Integer>();
        for (int i = 1; i <= num; i++) {
            elements.add(i);
            getSqaureLists(i, num, elements, pairSquaresList, squareList);
            elements.remove(i);
        }
        return pairSquaresList;
    }

    private static List<Integer> squareList(int num) {
        int limit = num + (num  - 1);
        int n = 2;
        final List<Integer> sqaureList = new ArrayList<Integer>();
        int square;
        while ((square = n * n) <= limit) {
            sqaureList.add(square);
            n++;
        }
        return sqaureList;
    }

//    private static boolean hasIntegerRoot(int x) {
//        double root = Math.sqrt(x);
//        return  root == (int)root;
//    }

    private static void getSqaureLists(int currNum, int num, LinkedHashSet<Integer> elements, List<List<Integer>> pairSquareList, List<Integer> squareList) {
        if (elements.size() == num) {
            pairSquareList.add(new ArrayList<Integer>(elements));
            return;
        }

        for (int i = 1; i <= num; i++) {
            // a number has already been added in the list. deduping.
            if (elements.contains(i))  continue;

//            // checking if the adjacent numbers add up to a square of an int.
//            if (hasIntegerRoot(i + currNum)) {
//                elements.add(i);
//                getSqaureLists(i, num, elements, pairSquareList, squareList);
//            }

            if (squareList.contains(i + currNum)) {
                elements.add(i);
                getSqaureLists(i, num, elements, pairSquareList, squareList);
            }

            elements.remove(i);
        }
        return;
    }

    public static void main(String[] args) {
        List<Integer> list1 = Arrays.asList(8, 1, 15, 10, 6, 3, 13, 12, 4, 5, 11, 14, 2, 7, 9, 16);
        List<Integer> list2 = Arrays.asList(16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8);

        List<List<Integer>> listOfLists = new ArrayList<List<Integer>>();
        listOfLists.add(list1);
        listOfLists.add(list2);

        Assert.assertEquals(listOfLists, pairSquare(16));
    }
}


texts:
Here's a little script that enters text into a document when activated.

tell application "TextEdit"
  activate
end tell
delay 0.2
tell application "System Events"
  keystroke "Hello World!"
  keystroke return
end tell

I stuck the delay in there because otherwise the first few keystrokes tend to trigger before the window is done activating, so I end up with "lo World!" in the document and "Hel" in whatever other window had focus when the script was activated. Is that the proper use of delay, or is there a better way to circumvent that problem?


texts:
I have been using $_SESSION, $_POST, $_GET, $_SERVER globals directly without ever knowing there was a concept/practice called, "Wrapping globals in classes" until, yesterday. As I did, I was able to immediately understand its effective benefit / usefulness. But I searched for a good wrapper, for $_SESSION, $_GET and $_POST but could not find anything simple/good. So, as a test I made this for the session global.

<?php

/**
 * A SESSION Wrapper class.
 *
 * @category Session
 * @version  1.0.0
 * @Nile
 */

namespace Nile\Lib;

class Session
{
    protected static $sessionLife = 1200;

    public static function start()
    {
        if(!headers_sent() && !session_id()){
            if(session_start()){
                session_regenerate_id();
                return true;
            }
        }
        return false;
    }

    public static function set($Key, $value)
    {
        $_SESSION[$Key] = $value;
    }

    public static function has($Key)
    {
        return (bool)(isset($_SESSION[$Key])) ? $_SESSION[$Key] : false;
    }

    public static function get($Key)
    {
        return (isset($_SESSION[$Key])) ? $_SESSION[$Key] : false;
    }

    public static function del($Key)
    {
        if(isset($_SESSION[$Key])){
            unset($_SESSION[$Key]);
            return false;
        }

    }

    public static function destroy()
    {
        if(isset($_SESSION)){
            session_destroy();
        }
    }

    public static function dump()
    {
        if(isset($_SESSION))
        {
            print_r($_SESSION);
            return ;
        }

        throw new \Exception("Session is not initialized");
    }

}

And this is the simple session initialization.

Session::start(); // does session_start();
Session::set('user', 'isLogedIn'); //does $_SESSION['user'] = 'isLoggedIn';

Considering this is my first wrapper, I would like a review and what I could add next. Something that is not very complicated, just easy to understand and a useful feature for this class.


texts:
I am using the following script to fuzzy search almost similar book names for duplicate:
import re
from nltk.util import ngrams

OriginalBooksList = list()
booksAfterRemovingStopWords = list()
booksWithNGrams = list()
duplicatesSorted = list()

stopWords = ['I', 'a', 'about', 'an', 'are', 'as', 'at', 'be', 'by', 'com', 'for', 'from', 'how', 'in', 'is', 'it', 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'the',
             'and', 'A', 'About', 'An', 'Are', 'As', 'At', 'Be', 'By', 'Com', 'For', 'From', 'How', 'In', 'Is', 'It', 'Of', 'On', 'Or', 'That', 'The', 'This', 'To', 'Was', 'The', 'And']

with open('UnifiedBookList.txt') as fin:
    for line_no, line in enumerate(fin):
        OriginalBooksList.append(line)
        line = re.sub(r'[^\w\s]', ' ', line)  # replace punctuation with space
        line = re.sub(' +', ' ', line)  # replace multiple space with one
        line = line.lower()  # to lower case
        if line.strip() and len(line.split()) > 2:  # line can not be empty and line must have more than 2 words
            booksAfterRemovingStopWords.append(' '.join([i for i in line.split(
            ) if i not in stopWords]))  # Remove Stop Words And Make Sentence

for line_no, line in enumerate(booksAfterRemovingStopWords):
    tokens = line.split(" ")
    output = list(ngrams(tokens, 3))
    temp = list()

    temp.append(OriginalBooksList[line_no])  # Adding original line
    for x in output:  # Adding n-grams
        temp.append(' '.join(x))
    booksWithNGrams.append(temp)

while booksWithNGrams:
    first_element = booksWithNGrams.pop(0)
    x = 0
    for mylist in booksWithNGrams:
        if set(first_element) & set(mylist):
            if x == 0:
                duplicatesSorted.append(first_element[0])
                x = 1
            duplicatesSorted.append(mylist[0])
            booksWithNGrams.remove(mylist)
    x = 0

with open('DuplicatesSorted.txt', 'w') as f:
    for item in duplicatesSorted:
        f.write("%s\n" % item)

The input is:
A Course of Pure Mathematics by G. H. Hardy
Agile Software Development, Principles, Patterns, and Practices by Robert C. Martin
Advanced Programming in the UNIX Environment, 3rd Edition
Advanced Selling Strategies: Brian Tracy
Advanced Programming in the UNIX(R) Environment
Alex's Adventures in Numberland: Dispatches from the Wonderful World of Mathematics by Alex Bellos, Andy Riley
Advertising Secrets of the Written Word: The Ultimate Resource on How to Write Powerful Advertising
Agile Software Development, Principles, Patterns, and Practices
A Course of Pure Mathematics (Cambridge Mathematical Library) 10th Edition by G. H. Hardy
Alex’s Adventures in Numberland
Advertising Secrets of the Written Word
Alex's Adventures in Numberland Paperback by Alex Bellos

The output is:
A Course of Pure Mathematics by G. H. Hardy

A Course of Pure Mathematics (Cambridge Mathematical Library) 10th Edition by G. H. Hardy

Agile Software Development, Principles, Patterns, and Practices by Robert C. Martin

Agile Software Development, Principles, Patterns, and Practices

Advanced Programming in the UNIX Environment, 3rd Edition

Advanced Programming in the UNIX(R) Environment

Alex's Adventures in Numberland: Dispatches from the Wonderful World of Mathematics by Alex Bellos, Andy Riley

Alex’s Adventures in Numberland

Alex's Adventures in Numberland Paperback by Alex Bellos

Advertising Secrets of the Written Word: The Ultimate Resource on How to Write Powerful Advertising

Advertising Secrets of the Written Word

By looking at the script, it seems to me that I have over complicated things. Please give some suggestion on how I can make this code better.


texts:
I recently started learning Python, and made a simple text based Hangman game. I wanted to know if there could be anything done to make the code cleaner or more efficient.

import random
import os
import sys

def main():
    pickword()

def start(word, twoplayer):
    wordarray = ''
    userguess = []
    guessright = 0
    lettersright = 0
    if len(word) < 5:
        tries = 6
    else:
        tries = 10
    usedletters = []

    if twoplayer == False:
        print(word)
        print("Welcome to hangman")
        print("I will think of a word and you will have to guess it, are you ready!")
        input("Press enter to continue")
    else:
        print("Welcome to hangman")
        print("Player 1 has already thought of a word, let's begin")
        input("Press enter to continue")

    lengthword = len(word)

    if twoplayer == False:
        for i in range(1, lengthword):                  #creates a new variable, all underscores
            userguess.append("_ ")
    else:
         for i in range(1, lengthword):                  #creates a new variable, all underscores
            userguess.append("_ ")

    wordarray = (list(word))

    if twoplayer == False:
        for i in range(0, lengthword):                  #removes \n from end of word
            if wordarray[i] == "\n":
                wordarray.remove(wordarray[i])
                break

    usedletters = []
    getuserguess(wordarray, userguess, tries, usedletters, word)

def pickword():
    word = 0
    twoplayer = input("Do you want to play 2 player[Y/N]")
    if twoplayer.lower() == "y":
        word = input("Player 1, enter the word you want player 2 to guess, don't let them see! ")

        if len(word) < 3:
            print("That word is too short")
            pickword()

        print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
        print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
        print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")

        word = word.lower()
        twoplayer = True
        start(word, twoplayer)
    else:
        try:
            word = random.choice(open('hangman.txt').readlines())
            twoplayer = False
            start(word, twoplayer)

        except:
            input("Error, no word list found, press enter to exit")
            sys.exit()

def getuserguess(wordarray, userguess, tries, usedletters, word):

    print(' '.join(userguess))
    guess1 = input("Enter your guess: ")

    if len(guess1) < 1 or len(guess1) > 1 or guess1.isdigit():
        print("Invalid input")
        getuserguess(wordarray, userguess, tries, usedletters, word)
    else:
        checkuserguess(wordarray, userguess, guess1, usedletters, tries, word)

def lose(word):
    again = input("Sorry, you lost, the word was {}Would you like to play again[Y/N]".format(word))
    if again.lower() ==  "y":
        pickword()
    else:
        sys.exit()

def win():
    again = input("Congrats, you won hangman, do you want to play again?[Y/N]")
    if again == "Y" or "y":
        pickword()
    else:
        sys.exit()

def checkuserguess(wordarray, userguess, guess1, usedletters, tries, word):

    guess1list = (list(guess1))

    if guess1list[0] in usedletters:
        print("You already used that letter")
        getuserguess(wordarray, userguess, tries, usedletters, word)

    if guess1 in wordarray:
        usedletters.append(guess1)
        for i in range(0, len(wordarray)):
            if wordarray[i] == guess1list[0]:
                userguess[i] = guess1list[0]
                usedletters.append(guess1list[0])

        if "_ " not in userguess:
            print(' '.join(userguess))
            win()
        else:
            getuserguess(wordarray, userguess, tries, usedletters, word)

    else:
        if tries > 0:
            print("Sorry, that letter is not in the word, you have ", tries, " remaining")
            tries -= 1
            getuserguess(wordarray, userguess, tries, usedletters, word)
        else:
            lose(word)

main()


texts: Using Grand Central Dispatch to fetch data from Parse.com and update UI asynchronously

texts:
This works, and the UI is snappy in the simulator, but since this is my first time really using GCD, I'd just like this code to be reviewed before I start using it everywhere.  Note that this is inside a PFQueryTableViewController.

My function:

  func tableRefresh() {

        // get quality of service (high level)
        let qos = Int(QOS_CLASS_USER_INITIATED.value)

        // get global queue
        dispatch_async(dispatch_get_global_queue(qos, 0)) { () -> Void in

            //execute slow task
            self.queryForTable()

        // get main queue, do UI update
            dispatch_async(dispatch_get_main_queue()) {
                self.loadObjects()
            }

        }

    }

My function in action:

@IBAction func done(segue: UIStoryboardSegue) {

        let addPersonViewController = segue.sourceViewController as! AddPersonViewController

        // If I get a person back from APVC
        if let person = addPersonViewController.person {

            // If that person has a name
            if let name = person.name {

            // Note: the reference to current user creates the pointer
            let newPerson = Person(name: name, user: PFUser.currentUser()!)

            // Save
            newPerson.saveInBackgroundWithBlock() { succeeded, error in
                if succeeded {

                    println("\(newPerson) was Saved")

                    self.tableRefresh()

                } else {

                    if let errorMessage = error?.userInfo?["error"] as? String {
                        self.showErrorView(error!)
                        }
                    }
                }
            }

        }

    }


texts: Fastest C++ code to get common prefix length

texts:
In a C++ program, I have the following function to find the length of the longest common prefix between to char arrays a and b. String b is guaranteed to be shorter than string a.

Is there a faster char array comparison code (for example, with some library function)? I wish to optimize this code for speed.

long len_common_prefix(char a[], char b[]) {
    char* p = a;
    char* q = b;
    while ((*p == *q) && (*q)) {
        p++;
        q++;
    };
    return p-a;
}

I've found the following code to be about 10 times faster that the original one I gave.  Is there an even faster alternative?

long long int len_common_prefix(char a[], char b[]) {
    long long int* p = (long long int*)a;
    long long int* q = (long long int*)b;
    int ratio = sizeof(long long int) / sizeof(char);
    while (*p == *q) {
        p++;
        q++;
    }
    long long int long_long_diff = p-(long long int*)a;
    char* p2 = (char*)p;
    char* q2 = (char*)q;
    while (*p2 == *q2) {
        p2++;
        q2++;
    }
    return long_long_diff * ratio + (p2 - (char*)p);
}


texts:
Consider the following:

#include <iostream>

struct State { virtual ~State() = default; };

struct Drunk : State {
    void singWhileDrunk() {std::cout << "Singing while drunk.\n";}
};

struct Person {
    State* state;
    void singWhileDrunk() {dynamic_cast<Drunk*>(state)->singWhileDrunk();}  // Is this good?
};

int main() {
    Person bob;
    bob.state = new Drunk;
    bob.singWhileDrunk();
    // dynamic_cast<Drunk*>(bob.state)->singWhileDrunk();  // Using this is better?
}

What I wonder is if Person::singWhileDrunk() should really be defined in Person or not.  singWhileDrunk() only has true meaning if the person is drunk, so to define it in Person seems wrong to me. However, it does simplify the code in main(), especially if it is to be used a lot.

(dynamic_cast<Drunk*>(bob.state)->singWhileDrunk();

is clearly more typing (and may run into difficulties if I want to redefine it everywhere it is used, e.g. change dynamic_cast to static_cast).  Another issue I have is that in my program I have many different types of states, each with their own special functions, and to define them all in Person will really bloat the Person class with MANY, MANY functions that don't even seem to belong in Person.  So there seems to be pros and cons to both choices and would like to hear what others have to say about this.

This is just an example of course. In reality, I have states like FlySpellState, with the function flies(), which also seems to have no place in Person (since people cannot fly normally), though it could be.


texts:
Reason for script:

dir="auto" is an attribute value from the HTML 5 spec with current poor support in IE and Opera browsers.  The project I am working on only cares about IE, Firefox and Safari browsers and handles text in both left to right LTR and right to left RTL languages.  For cases where the directionality of the text coming from the data source is unkown, I would like to use dir="auto" to handle most cases of directionality. For IE, I would like to simulate this functionality using JavaScript.

Goal of review:

I am hopeful that a review of my work will identify areas where I can improve the code to be more in line with its stated purpose as well as aligning the code to best practices and identifying any bugs that may exist.

Implementation:

An isLTR function was used as I figured most use cases would be against LTR text as opposed to RTL.
In my research, I wandered across a script by Nicholas Zakas which I thought would be useful and have integrated it into my solution.
The project uses Dojo 1.8.1.

XHTML:

Script call in head tag after call to Dojo library:

<!--[if IE]><script type="text/javascript" src="./PatternsTools/PatternsBidi.js"></script><![endif]-->

JavaScript:

window.Patterns = window.Patterns || {};
window.Patterns.Bidi = window.Patterns.Bidi || {};
window.Patterns.Bidi.Strings = window.Patterns.Bidi.Strings || {};
window.Patterns.Bidi.Strings.LTRcharacters = "\u0041-\u005A\u0061-\u007A\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u202A\u202D\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF";
window.Patterns.Bidi.Strings.RTLcharacters = "\u0591-\u07FF\u200F\u202B\u202E\uFB1D-\uFDFD\uFE70-\uFEFC";
window.Patterns.Bidi.Strings.NeutralWeakCharacters = "\u0000-\u0040\u005B-\u0060\u007B-\u00BF\u00D7\u00F7\u02B9-\u02FF\u2000-\u2BFF\u2010-\u2029\u202C\u202F-\u2BFF";

(function(/*Class Object*/ Bidi){
    function getDirection(/*HTML Element*/ element) {
    /*Copyright 2010 Nicholas C. Zakas. All rights reserved.*/
    /*MIT Licensed*/
        var result = null;
        if (element){
            if (window.getComputedStyle){
                result = window.getComputedStyle(element,null).direction;
            } else if (element.currentStyle){
                result = element.currentStyle.direction;
            }
        }

        return result;
    }

    function prependOverride(/*HTML Element*/ element, /*Boolean*/ isLTR) {
        var direction = getDirection(element) === "ltr";
        if (isLTR !== direction) {
            element.innerHTML = (isLTR ? "&#8237;" : "&#8238;") + element.innerHTML + "&#8236;";
        }
    }

    function isLTR(/*String*/ s) {
        var ltrDirCheck = new RegExp("^[" + Bidi.Strings.NeutralWeakCharacters + "]*?[" + Bidi.Strings.LTRcharacters + "]");
        return ltrDirCheck.test(s);
    };

    (function init() {
        require(["dojo/ready", "dojo/_base/array"], function(/*Function*/ ready, /*Object*/ array) {
            ready(function() {
                array.forEach(dojo.query("[dir=auto]"), function(/*HTML Element*/ element, /*Integer*/ i) {
                    prependOverride(element, isLTR(element.innerHTML));
                });
            });
        });
    })();
})(window.Patterns.Bidi);


texts:
Recently, I've been making and refining installer and rescue images to boot from USB media, in the form of CD-ROM or hard disk images.  After a few occasions where I re-ran the command after removing the media (and ending up with a large file in /dev/disk/by-id/ instead of writing to a device), I wrote a small wrapper to check that the target is a block device.

Since then, it's grown features - notably to take input direct from network sources (e.g. a build server) to save making a local copy first.  In these cases, I want to be able to sudo write-image but still make the network connection as non-root user (partly as good practice, but also so that I can use my ~/.ssh/config and private keys in the normal way).

The usage() function ought to explain how it's intended to be used; if I need to explain further, then it's a sign that my documentation needs improving.

The reason that this needs Bash rather than POSIX shell is to use command substitution process substitution.  The use of a shell function in process substitution seems to be particularly non-portable, but it works for me with Bash 4.4.

#!/bin/bash

set -eu

die() { echo "$@" >&2; exit 1; }

usage() {
    cat <<END
usage: $0 [source] <usb-device>
The source can be
  * a filename
  * a URL
  * ssh:[user@]<host>:<file>  (must be passwordless)
  * '-' or absent (for piping from standard input)
END
}

as_real_user() {
    exec ${SUDO_USER+sudo -n -H -u "$SUDO_USER" }"$@"
}

case $# in
    1)
        case "$1" in
            --help|-h)
                usage
                exit 0
                ;;
        esac
        ;;
    2)
        case "$1" in
            ssh:*)
                file="${1#*:}"
                host="${file%%:*}"
                file="${file#*:}"
                exec < <(as_real_user ssh "$host" cat "$file")
                ;;
            *://*)
                exec < <(as_real_user wget -q -O - "$url")
                ;;
            -)
                # standard input is already connected
                ;;
            *)
                test -e "$1" || die "$1: not found"
                test -f "$1" || die "$1: not a plain file"
                test -r "$1" || die "$1: not readable"
                exec < "$1"
                ;;
        esac
        shift
        ;;
    *)
        usage
        exit 1;
esac

test -b "$1" || die "$1: not a block device"
test -w "$1" || die "$1: not writable"
cut -d' ' -f1 /proc/mounts | grep -Fxq $(realpath "$1") && die "$1: is mounted"
outfile="of=$1"

# Explanation
# * nocreat - just checking, given above tests of destination
# * fsync - don't return until image is fully written
# * dsync,bs,status - show update every 1 MB written
ddflags="conv=nocreat,fsync oflag=dsync bs=1M status=progress"

exec dd $ddflags $outfile


texts:
I am building a simple login page which will check for username before navigating to another screen and here is how I am doing the binding now. I would like to know if I am doing it right and if I am not, what is the recommended way of doing the binding. Moreover, I creating the UI programmatically.

ViewModel.swift

// Inputs
private let usernameSubject = PublishSubject<String>()
private let nextButtonDidTapSubject = PublishSubject<Void>()

// Outputs
private let validUsernameSubject = PublishSubject<Bool>()
private let invalidUsernameSubject = PublishSubject<String>()

// MARK: - Init

init() {

    input = Input(username: usernameSubject.asObserver(),
                  nextButtonDidTap: nextButtonDidTapSubject.asObserver())

    output = Output(validUsername: validUsernameSubject.asObservable(),
                    invalidUsername: invalidUsernameSubject.asObservable())

    nextButtonDidTapSubject
        .withLatestFrom(usernameSubject.asObservable())
        .subscribe(onNext: { [unowned self] text in
            if text.count >= self.minUsernameLength {
                self.validUsernameSubject.onNext(true)
            } else {
                let message = text.count > 0 ?
                    "Please enter a valid username" :
                    "Please enter a username"
                self.invalidUsernameSubject.onNext(message)
            }
        })
        .disposed(by: disposeBag)

}

ViewController.swift

private func configureBinding() {

    loginLandingView.usernameTextField.rx.text.orEmpty
        .subscribe(viewModel.input.username)
        .disposed(by: disposeBag)

    loginLandingView.nextButton.rx.tap
        .subscribe(viewModel.input.nextButtonDidTap)
        .disposed(by: disposeBag)

    viewModel.output.validUsername
        .subscribe(onNext: { [unowned self] _ in
            print("Valid username - Navigate...")
            self.navigate()
        })
        .disposed(by: disposeBag)

    viewModel.output.invalidUsername
        .subscribe(onNext: { [unowned self] message in
            self.showAlert(with: message)
        })
        .disposed(by: disposeBag)

}


texts:
Background

I'm writing user input validation for a client-side JavaScript web application. Users enter numerals representing an integer into an <input>. As part of validation, the application must check that parseInt(input.value, 10) will result in the integer represented by the user's input.

In JavaScript, all numbers are floating-points. Within the interval [-253, 253], all integers have exact representations. The challenge is to guarantee that the user has provided a number within the interval. parseInt() doesn't work:

// Yields true
parseInt('9007199254740993', 10) === 9007199254740992;

I'm looking for any feedback. Firstly, correctness, then performance.

Current Solution

var isSafeIntegerString = function() {
  'use strict';

  // The digits of the greatest and least safe integers, 2**53 and
  // -2**53 respectively.
  var limDigits = [9, 0, 0, 7, 1, 9, 9, 2, 5, 4, 7, 4, 0, 9, 9, 2];

  // The number digits in the safe integer limits.
  var limLength = limDigits.length;

  // The structure of safe integers.
  //
  //   ^...$  The entire string must match the structure
  //
  //   [-+]?  May be preceded by either a '-' or a '+'
  //
  //   0*     May have leading zeros
  //
  //   (\d{1, limLength}) Must contains between 1 and limLength digits

  var safeIntegerStructure = new RegExp('^[-+]?0*(\\d{1,' + limLength + '})$');

  return function(str) {
    // If str is not a string, it cannot be a safe integer string.
    if (Object.prototype.toString.call(str) !== '[object String]') {
      return false;
    }

    // If str doesn't have the structure of a safe integer string, it
    // can't be one.
    var match = str.match(safeIntegerStructure);
    if (match === void 0) {
      return false;
    }

    // str has a safe integer structure. The RE captured the
    // significant digits (i.e., without the sign or leading zeros).
    var numerals = match[1];
    var numeralsLength = numerals.length;

    // If str contains less significant digits than the limit, it is
    // less and therefore is safe.
    if (numeralsLength < limLength) {
      return true;
    }

    // If str contains more significant digits than the limit, it is
    // greater and therefore is not safe.
    if (numeralsLength > limLength) {
      return false;
    }

    // str and the limit contain the same number of digits. So, compare
    // each digit, starting from the most significant.
    for (var i = 0; i < numeralsLength; ++i) {
      var digit = parseInt(numerals.charAt(i), 10);
      var limDigit = limDigits[i];
      if (digit < limDigit) {
        return true;
      }
      if (digit > limDigit) {
        return false;
      }
    }

    // str is equal to a safe integer limit.
    return true;
  };
}();

Tests

(function() {
  var test = function(str, isSafe) {
    console.log(str, isSafe, isSafeIntegerString(str));
  };

  var schemata = [
    [                 '0', true ],
    [                '-0', true ],
    [                 '1', true ],
    [                '-1', true ],
    [   '900719925474099', true ],
    [   '900719925474099', true ],
    [  '9007199254740991', true ],
    [  '9007199254740991', true ],
    [  '9007199254740992', true ],
    [ '-9007199254740992', true ],
    [ '09007199254740992', true ],
    ['-09007199254740992', true ],
    [  '9007199254740993', false],
    [ '-9007199254740993', false],
  ];

  for (var i = 0; i < schemata.length; ++i) {
    var schema = schemata[i];
    test(schema[0], schema[1]);
  }
}());


texts:
I am attempting the matched brackets problem. I have written a Python program which seems to do the job but is very slow and thus exceeds the time limit. Please help me making this code more efficient. I have explained my code in the comments.

length = int(input())
inp = input().split(' ')
inp = [ int(x) for x in inp ]
position = 0 ##where our cursor is.
highest_depth =0
buffer = 0
stretch = 0 ##max distance b/w two matched brackets.
bar = 0 ## jst a buffer for calculating max distance between two brackets.
stretch_pos = 0
for l in inp:
    position += 1
    bar += 1
    '''if the cursor is currently at open bracket(1) add 1 to buffer'''
    if l == 1:
        buffer += 1
    else:
        '''if the cursor is at a closed bracket(2) we need to stop calculating
        higest depth and assign it to highest_depth only if the current value
        is smaller'''
        if highest_depth < buffer:
             highest_depth = buffer
             hpos = position -1 ##position of highest depth.
        buffer -= 1
        '''if buffer is now 0  due to the above line it must mean that all the
           brackets opened have been closed.'''
        if buffer == 0:
            ''' bar which calculates the max distance between two matched brackets
                must be assigned now and reset to zero'''
            if bar > stretch:
                stretch = bar
                stretch_pos = position - stretch + 1
            bar = 0
print(highest_depth , hpos,stretch, stretch_pos)


texts:
I've been trying to create a tree module in JavaScript for implementing a "family tree" style structure. I'm not very experienced in newer JavaScript design styles and want to make sure I am going along the right path with the code I have written so far. Can someone let me know if I am on the right track with how this is organized?

var TREE = (function() {

var treeList = [], //Tree container

    //Constructor for Member object
    Member = function(name, mother, father, children){
        this.name = name || null;
        this.mother = mother || null;
        this.father = father || null;
        this.children = children || null;
    },

    //Constructor for Tree object
    Tree = function(name){
        this.name = name || null;
        this.memberList = [(new Member("root"))];
    };

//Tree methods
Tree.prototype.addMember = function(name, mother, father, children){
    this.memberList.push(new Member(name, mother, father, children));
}
Tree.prototype.getMemberList = function(){
    return this.memberList;
}
return {
    create : function(treeName){
        treeList.push(new Tree(treeName));
        return treeList[treeList.length - 1];
    },
    getTreeList : function(){
        return treeList;
    }
};

}());


texts: Function to find longest word in a string

texts:
Write a function called longest which will take a string of space-separated words and will return the longest one.

My code:

function longest(str) {
  var words = arguments.split(" ");
  var words_count = words.length;

  var longest_word_length = 0;

 for(var i = 0; i < words_count; i++){
   if(longest_word_length < words[i].length){
       longest_word_length = words[i].length;
   }
}
return longest_word_length;
}

Running it with this test:

describe("test for longest function functionality", function() {
  it("should return correct output for normal strings", function() {
  expect(longest("A")).toEqual("A");
  expect(longest("I love Avatar")).toEqual("Avatar");
  expect(longest("The stupidities of youth")).toEqual("stupidities");
  });

  it("should return correct output for gibberish", function() {
  expect(longest("hgdydrxtfEq Rradsc tstsa taeWwwecfgdd")).toEqual("hgdydrxtfEq");
  });

 it("should work for sentences with numbers", function() {
 expect(longest("This is a sentence with a number 7685838788")).toEqual("7685838788");
 });
});


texts:
I created a table with the ability to edit with popup.

This part of the code, which includes:

the ability to send URL to other users with the subsequent opening of the same state (the popup window is empty or with data to be edited)
I get the current URL and then I get data from the server. And if the URL includes ID of the data to be editing, I open popup with this data or the empty popup.
the ability to work the browser using the buttons "back" and "forward".
I used the history.pushState method.

I use the Fetch API for requests to the server. To build the table and the popup, I used jQuery. But in the part of the code with browser history I can't find a way to use jQuery, only pure JS.

I will appreciate any advice about code.

const getLink = window.location.hash.slice(1) // to get the current URL witout hash

fetch('http://localhost:3000/names') // to get the data from the server
    .then((response) => response.json())
    .then((_names) => {
      names = _names //the data
      drawTable() // update table according to data
      if (getLink != 0 && getLink != 'add-new'){ //if URL includes ID of the data
        idEdit = getLink //assign ID from URL as an ID to edit
        addEditValue() // function for popup opening with the data to be editing
      }
    })

 if (getLink == 'add-new') {openAddForm()} //open the empty popup

 top.addEventListener('click', function(e){ // listen a click on the page
    if(e.target == $('#add-new') || e.target.className == 'edit-btn'){
    //if a click on the button for opening empty popup or popup with the data to be editing
    e.preventDefault()
    const data = e.target.id
    const url = "/#" + data
    e.target.setAttribute('href', url)
    history.pushState(data, null, url)
  } else if(e.target.className != 'input-form-body') {
    //if you click after closing the pop-up window, then clear the URL
    window.location.hash = ""
  }
  e.stopPropagation()
  }, false)

window.addEventListener('popstate', function(e){
  const character = e.state
  if(character == null){
    closeForm() // close popup
    } else {
      idEdit = character
      addEditValue() //open popup with the data to be editing
    }
  })


texts: Rearranging DOM elements using inconsistent criteria

texts:
Before you read ahead: ES6 may not be used.

Consider a web-page showing a report of some data that is structured as follows:

<button id='sort-by-category'>Category</button>
<button id='sort-by-timestamp'>Timestamp</button>

        ...

        ...

        ...

Such that each section in the report body needs to be sorted according to the custom data- attributes. The catch is that not all attributes are created equal; for example: sorting by timestamp is straightforward, but sorting by item-id isn't because we also want to group items of the same category together.

Here's the implementation of that in JS:

(function () {
    "use strict";

    var categoryOrder = {
        "fruit" : 0,
        "vegetable" : 1
    };

    function compareStrings(string1, string2) {
        if (string1 < string2) {
            return -1;
        } else if (string1 > string2) {
            return 1;
        }
        return 0;
    }

    function compareCategories(element1, element2) {
        var category1 = element1.getAttribute("data-category-name");
        var category2 = element2.getAttribute("data-category-name");

        if (category1 !== category2) {
            return categoryOrder[category1] - categoryOrder[category2];
        }

        category1 = +element1.getAttribute("data-item-id");
        category2 = +element2.getAttribute("data-item-id");

        return category1 - category2;
    }

    // dates are ISO-8601
    function compareTimestamps(element1, element2) {
        var timeStamp1 = element1.getAttribute("data-timestamp");
        var timeStamp2 = element2.getAttribute("data-timestamp");
        return compareStrings(timeStamp1, timeStamp2);
    }

    function getElementsByClassName(className) {
        var result = document.getElementsByClassName(className);
        return Array.prototype.slice.call(result);
    }

    function makeRearrangeCallback(comparator, reportBody) {
        return function() {
            var reportBlocks = getElementsByClassName("report-section");

            reportBlocks.sort(comparator);

            for (var i = 0; i < reportBlocks.length; ++i) {
                reportBody.appendChild(reportBlocks[i]);
            }
        };
    }

    function addRearrangeCallbackToElement(elementId, comparator, reportBody) {
        var element = document.getElementById(elementId);

        element.addEventListener(
            "click",
            makeRearrangeCallback(comparator, reportBody),
            false);
    }

    function main() {
        var reportBody = document.getElementById("report-body");
        addRearrangeCallbackToElement("sort-by-category", compareCategories, reportBody);
        addRearrangeCallbackToElement("sort-by-timestamp", compareTimestamps, reportBody);
    }

    window.addEventListener("load", main, false);
}());

Note that I'm not looking just for commentary on the JS part. If you believe that there could be a better way to store the information in the markup, feel free to mention it.


texts: Find an ideal speed to cross all traffic lights when they are green

texts:
As a second exercise with Scala I tried to solve another puzzle.
In this puzzle, we have to find the highest speed that allows a driver to cross all the traffic lights when they are green, without committing speeding.
Each traffic light is defined by its distance from the start and its duration. All the lights start green, stay green during the given duration and then turn red for the given duration, etc.

Example of input:

50       //Max speed for this road
1        //Number of traffic lights on the road
200 15   //Distance and duration for the traffic light

My strategy is to start with the max speed and to try to reach as many traffic lights as possible. If I cross the road of a red light, I calculate the highest speed that allows me to reach it at the beginning of its next cycle (right when it turns green again), then I go back from the start with this new speed.

import math._
import scala.util._

object Solution extends App {

class TrafficLight(distance: Integer, duration: Integer) {

    val fullCycleDuration = 2*duration

    def getIdealSpeed(currentSpeed: Float) : Float = {
        //The number of seconds to go from start to this light
        val timeToReachLight = distance.toFloat / currentSpeed
        //The number of seconds that passed since the light went green
        val timeOfArrivalInCycle = timeToReachLight % fullCycleDuration
        //If we reach the green light in time with this speed, leave it as it is
        if(timeOfArrivalInCycle < duration) {
            currentSpeed
        }
        else {
            //We need to slow down the speed to arrive when it is green again
            val newTravelTime = fullCycleDuration * (timeToReachLight.toInt / Math.round(fullCycleDuration.toInt) + 1)
            //New speed
            distance.toFloat / newTravelTime.toFloat
        }
    }
}

def parseTrafficLight(input: String): TrafficLight = {
    val fields = input.split(" ")
    new TrafficLight(fields(0).toInt, fields(1).toInt)
}

def computeIdealSpeed(currentSpeed: Float, currentId : Integer, allLights: List[TrafficLight]): Float = {
    if(currentId >= lights.length) {
        currentSpeed
    }
    else {
        val newSpeed = lights(currentId).getIdealSpeed(currentSpeed)
        if(newSpeed == currentSpeed)
        {
            computeIdealSpeed(currentSpeed, currentId + 1, allLights)
        }
        else {
            computeIdealSpeed(newSpeed, 0, allLights)
        }
        /*newSpeed match {
            case currentSpeed => computeIdealSpeed(currentSpeed, currentId + 1, lights.tail)
            case _ => computeIdealSpeed(newSpeed, 0, allLights)
        }*/
    }
}

val speedInput = readInt
val speed = speedInput * 1000f / 3600f //km/h to m/s
val lightcount = readInt
var lights = (0 until lightcount).map(_ => parseTrafficLight(readLine)).toList

// Write an action using println
// To debug: Console.err.println("Debug messages...")
val idealSpeed = computeIdealSpeed(speed, 0, lights)

println(Math.round(idealSpeed * 3.6)) //m/s to km/h
}

The code above works correctly but I feel like it could be much better. For example, I wanted to use List.tail for the recursion, but I couldn't find how to get the whole list back when I needed to restart the recursion. This is why I used an id in the recursion. I'd love some suggestions on this part.


texts: Moving the player across an ASCII art "world"

texts:
Wow, this one is definitely going to need some improvement.

So, just for fun, I decided to make a program where the player moves across a 2-dimensional ASCII-art map. If the player types something such as down, the on screen representation moves down and "loads" a bit more of the map.

from console import clear

class Move(object):
    up_down = 1
    right_left = 1

class Actions(object):
    action = {
        "down": 1,
        "up": -1,
        "left": -1,
        "right": 1
    }

def set_move_values(action):
    if action == "down":
        Move.up_down += Actions.action["down"]
    elif action == "up":
        Move.up_down += Actions.action["up"]
    elif action == "left":
        Move.right_left += Actions.action["left"]
    elif action == "right":
        Move.right_left += Actions.action["right"]

def render_map(x, y):
    for _ in range(y):
        print(''.join(['.' for _ in range(x + 4)]))
    print(''.join(['.' for _ in range(x + 2)])), '@',
    print(''.join(['.' for _ in range(1)]))
    for _ in range(1):
        print(''.join(['.' for _ in range(x + 4)]))

def run_program():
    while True:
        render_map(Move.right_left, Move.up_down)
        set_move_values(raw_input('> '))
        clear()

if __name__ == "__main__":
    run_program()

All I'm really looking for is, what general stuff can I improve? Also, if possible, I'd like something like right 5 to work to. Note: This is Python 2.7, I just prefer Python3's print function better. Also, console is an ios module, as I wrote this script on ios.


texts: Idiomatic Clojure? Performant & functional enough?

texts:
Problem

Disclaimer: This is my first clojure function & I'm still busy finishing the last chapters of "Programming Clojure". Thanks! :)

I am writing a function to randomly flood-fill parts of a game's map (i.e. this is not a traditional flood-fill that can recursively fill all available space). The idea is to create a random-shaped island, and inside that island create a random-shaped mountain. (i.e. pass the set of island points as a filter to the next flood fill function, so the mountain will be created only within the island's tiles).

This is what my code currently produces (You'll notice the window / drawing code stolen from the snake game in PragProg's Programming Clojure. ;))

Clojure Style

This is my code:

(def dirs2 '([-1 0] [1 0] [0 -1] [0 1]))

(defn neighbours [pt]
  (for [dir dirs2]
    (vec (map + pt dir))))

(defn flood-fill2
  "start -> point to start filling from
   n -> number of tiles to create
   filter-fn -> a fn that must return true for new points"
    ([start n]
      (flood-fill2 start n (fn [& _] true)))
    ([start n filter-fn]
     (loop [result #{}
      candidates #{start}
      i n]
      (if (or (zero? i) (empty? candidates))
        result
        (let [current (rand-nth (seq candidates))]
          (if (and (filter-fn current) (not (result current)))
            (recur
              (conj result current)
              (apply conj (disj candidates current) (neighbours current))
              (dec i))
            (recur result (disj candidates current) i)))))))

Is this idiomatic clojure code? The loop construct in there feels like standard iterative code I learned to write in Java / C++. Do you see a shorter way to write this?
Could I implement this as a lazy-seq somehow? (take 600 (lazy-fill [25 25] optional-src-set)) looks much cooler than (flood-fill2 [25 25] 600 island).
I tried to write an anonymous function that returns true for any argument(s) using this notation #() but had to eventually give up and wrote it using fn: (fn [& _] true). Could I have used #() somehow?

Performance

My intial (naive) implementation looked like this:

(defn flood-fill [filled n]
  (if (zero? n)
    filled
    (let [start-point (rand-nth filled)
      next-point (rand-nth (neighbours start-point))]
      (if (contains? (set filled) next-point)
        (recur filled n)
        (recur (cons next-point filled) (dec n))))))

But:

user=> (time (flood-fill [[25 25]] 1250))
(time (flood-fill [[25 25]] 1250))
"Elapsed time: 8430.56 msecs"
([8 18] [43 40] [23 9] [38 40] ...

My flood-fill2 does much better:

user=> (time (flood-fill2 [25 25] 1250))
(time (flood-fill2 [25 25] 1250))
"Elapsed time: 257.361 msecs"
#{[34 33] [35 34] [36 3] [36 35] [38 5] [10 9] ...

But using (time (flood-fill2 [500 500] 500000)) to fill 50% of a 1000 * 1000 tiles map takes forever (@ 100% CPU). I ended up killing that REPL.

Any performance suggestions? I tried to avoid many conversions from Sets to Vectors/Lists, but rand-nth needs a sequence and I couldn't find a nice "random set element" function.

Thanks for reading all of this.


texts: Easily registering WordPress custom post types and taxonomies

texts:
I am developing a library to easily register WordPress custom post types and taxonomies.

But the problem is I can't use one instance of object because of adding the object in WordPress hooks.

So what I have done as a solution is to re instantiate the class every time when you want to register a custom post type. Is that okay according to the modern PHP development?

 /**
     * @return PostType
     */
    public static function getInstance(){
        // don't need singleton due to wordpress hooks :( sadly i need to learn wp more.
        return new PostType();
    }

    /**
     *
     */
    public function register(){
        // Hook into the 'init' action
        add_action( 'init', array($this,'hookInWordPress'), rand() );
    }

    /**
     * callback of hook in init action
     */
    public function hookInWordPress(){
        $this->toSlug();
        if($this->newTaxonomy){
            $tax = $this->newTaxonomy->register($this);

            $this->addTaxonomy($tax->slug);
        }
        $args = $this->buildArgs();
        $args['labels'] = $this->buildLabels();
        if($this->icon) {
            $args['menu_icon'] = $this->icon;
        }

        register_post_type( $this->slug, $args);
        flush_rewrite_rules();
    }

Full project on GitHub


texts: Dependency Injection with classes which are created often

texts:
I have a question about dependency injection and best practices when using simple classes which are meant to be created often, which have dependencies on external services. Here's a (vastly) simplified version of what I'm working on:

app.js

import {Factory} from './factory.js';
import {Convert} from './convert.js';

let convert = new Convert();
let factory = new Factory({ convert });

// assume this is being imported and executed somewhere
export function run() {
    let avengers = [
          factory.person({ first: 'Iron', last: 'Man' })
        , factory.person({ first: 'Captain', last: 'America' })
        , factory.person({ first: 'Scarlet', last: 'Witch' })
        , factory.person({ first: 'Black', last: 'Panther' })
    ];
    console.log(avengers);
}

convert.js

export class Convert {
    toString(val) {
        if (!val)
            return '';
        return val.toString();
    }
}

person.js

export class Person {
    constructor({
        convert,
        first,
        last
    }) {
        this.convert = convert;
        this.first   = this.convert.toString(first);
        this.last    = this.convert.toString(last);
    }
}

factory.js

import {Person} from './person.js';

export class Factory {

    constructor({ convert }) {
        this.convert = convert;
    }

    person(obj) {
        obj.convert = this.convert;
        return new Person(obj);
    }
}

My main interest is that class Person has a dependency on a function located on an instance of class Convert. My question is this -- is this taking dependency injection too far? Am I better off just importing an instantiated version of Convert into Person.js and referencing it directly? I know that will work, but I was trying to avoid coupling the two classes without a nice way to override. I definitely don't like what I have written here, since Convert will be defined on each Person, which is worse than coupled classes in my opinion.

I had started working on modularizing one of my libraries to decouple classes and use dependency injection, but my pattern broke down when I ran across an instance similar to this. Any suggestions are definitely welcome.

Side note, I know in this example I could just use the Convert methods inside the Factory instead of inside Person -- that doesn't work for my actual project, unfortunately.


texts: Two similar shell functions that run different programs

texts:
I have a script that contains two shell functions:

runhaskells() {
    local DIR=$PWD
    local TARGET="cabal.sandbox.config"
    while [[ ! -e $DIR/$TARGET -a $DIR != "/" ]]; do
        DIR=$(dirname $DIR)
    done
    if [[ $DIR != "/" ]]; then
        local DB=$(sed -ne '/^package-db: */{s///p;q;}' "$DIR/$TARGET")
        runhaskell -no-user-package-db -package-db="$DB" "$@"
    else
        runhaskell "$@"
    fi
}

ghcs() {
    local DIR=$PWD
    local TARGET="cabal.sandbox.config"
    while [[ ! -e $DIR/$TARGET -a $DIR != "/" ]]; do
        DIR=$(dirname $DIR)
    done
    if [[ $DIR != "/" ]]; then
        local DB=$(sed -ne '/^package-db: */{s///p;q;}' "$DIR/$TARGET")
        ghc -no-user-package-db -package-db="$DB" "$@"
    else
        ghc "$@"
    fi
}

which obviously is a repeat of each other except for the fact that it calls a different program in each function.  The first function calls the runhaskell program while the second function calls the ghc program.

How can I DRY this script (either zsh or bash syntax is fine for me) with the end goal that I should be able to call either function at the command line?


texts:
This is a toy project and I am a beginner in Python.

I need to create 10 random 3-letter strings, where characters are a - z.

This is my implementation:

import random

def random_char():
    return random.randint(97, 122)

three_letter_words = []
for i in range(0, 10):
    three_letter_words.append(chr(random_char()) + chr(random_char()) + chr(random_char()))

I really do not like the part where I call chr(random_char()) 3 times.

How can I improve this to make it more compact and cleaner?


texts: Set a time based on hh:mm length, or set time length based on time

texts:
I am using Ionic 3, Angular 5, and moment-timezone. I have a form input that displays EndTime (in the format of 01:23 AM) and another that display the length (in the format of 01:30 which represents hh:mm) that is calculated from the mentioned EndTime and the StartTime both of which are DateTime values. When the user changes the EndTime I need it to update the length, and when the user updates the length I need it to to calculate the end time.

I feel like I am overcomplicating this and making the function too long. Anyway to improve this?

setSessionEndTime() {
  let time = this.sessionForm.controls['sessLength'].value.split(':');
  const endTime = moment(this.startTime).add(time[0], 'hours').add(time[1], 'minutes');
  const newEndTime = (moment(endTime).toISOString());
  this.sessionForm.controls['sessEndTime'].setValue(newEndTime, {emitEvent: false});
  this.endTime = newEndTime;
}

setSessionLength() {
  const startTime = moment(this.startTime);
  const endTime = moment(this.endTime);
  let totalHours = (endTime.diff(startTime, 'hours'));
  const totalMinutes = endTime.diff(startTime, 'minutes');
  const clearMinutes = totalMinutes % 60;
  // Must check if value is less than 10 and prepend 0 to it otherwise the datetime input doesnt accept the value
  const sessLength: string = (totalHours < 10) ?
                             `0${totalHours}:${clearMinutes}` :
                             `${totalHours}:${clearMinutes}`;
  this.defaultSesLength = sessLength;
  this.sessionForm.controls['sessLength'].setValue(sessLength, {emitEvent: false});
}


texts:
Here are two simple classes - Digit class maintains digit behaviour - primarily flipping animations, and Clock class handles everything that is related to time data.

I'm going to use this code for job application, please tell me if there are any improvements that could be done and what do you think of it.

Here is the link for working demo: https://abm0.github.io/flipping-clock.

class Digit {
  constructor({ selector, value = 0 }) {
    const digitEl = document.querySelector(selector);

    this.flipperEls = digitEl.querySelectorAll('.flipper');
    this.prevDigitEls = digitEl.querySelectorAll('.prev .digit');
    this.nextDigitEls = digitEl.querySelectorAll('.next .digit');

    this.value = value;
    this.prevValue = null;

    this.renderInitialValue();
  }

  setValue(nextValue) {
    this.prevValue = this.value;
    this.value = nextValue;

    if (this.value === this.prevValue) return;

    this.flip();
  }

  renderInitialValue() {
    const {
      prevDigitEls,
      nextDigitEls,
    } = this;

    [...prevDigitEls, ...nextDigitEls].forEach(el => (el.innerHTML = this.value));
  }

  flip() {
    this.nextDigitEls.forEach(el => el.innerHTML = this.value);
    this.flipperEls.forEach(el => el.classList.add('turned'));

    setTimeout(() => {
      this.prevDigitEls.forEach(el => (el.innerHTML = this.value));

      this.flipperEls.forEach((el) => {
        el.classList.remove('turned');
      });
    }, 500);
  }
}

class Clock {
  constructor(props) {
    const baseEl = document.querySelector("#clock");
    const currentTime = this.getCurrentTime();

    this.digits = [
      'hours-tens',
      'hours-ones',
      'minutes-tens',
      'minutes-ones',
      'seconds-tens',
      'seconds-ones'
    ];

    this.buildDigits(currentTime);
  }

  getCurrentTime() {
    const date = new Date();

    const time = {
      hours: date.getHours(),
      minutes: date.getMinutes(),
      seconds: date.getSeconds(),
    };

    this.formatValues(time);

    return time;
  }

  formatValues(time) {
    Object.keys(time).forEach(key => {
      if (key === "ampm") return;

      let value = time[key];

      if (parseInt(value) < 10) {
        time[key] = "0" + value;
      }

      time[key] = time[key].toString();
    });
  }

  getDigitProps(digitName) {
    const type = digitName.split('-')[0];
    const position = digitName.split('-')[1];

    let positionIndex;

    switch (position) {
      case 'tens':
        positionIndex = 0;
        break;

      case 'ones':
        positionIndex = 1;
        break;
    }

    return { type, position, positionIndex };
  }

  buildDigits(time) {
    this.digits.forEach((digitName) => {
      const { type, position, positionIndex } = this.getDigitProps(digitName);

      const selector = `#${type} .${position}-digit`;

      this[digitName] = new Digit({
        selector,
        value: time[type][positionIndex]
      });
    });
  }

  tick() {
    const time = this.getCurrentTime();

    this.digits.forEach((digitName) => {
      const { type, positionIndex } = this.getDigitProps(digitName);

      this[digitName].setValue(time[type][positionIndex]);
    });

  }
}

const clock = new Clock();

setInterval(() => {
  clock.tick();
}, 1000);