texts:
I've got a conditional that sets a cookie based on whether a selector exists. There are other places in the code where I do something similar if the selector exists. If the selector exists I either add "nfl" or "nfl-" (notice the dash) to various attributes on the page. I'm trying to remove as much code as I can as there are about five other places I have similar code where I'm adding other attributes. I also feel like there's a better way to approach this without having to write this a ton of times:

if($(".userLocation").length > 0){

I'm banging my head on how to condense this but can't figure this out. Please include code samples; I learn best that way.

if($(".userLocation").length > 0){
    var user_cookie = {
    name: 'nfl-user-profile',
    options: {
        path: '/',
        expires: 365
    }
    };
} else {
    var user_cookie = {
    name: 'user-profile',
    options: {
        path: '/',
        expires: 365
    }
    };
}

if($(".userLocation").length > 0){
$('header').attr("href","#nfl-city");
$('header').attr("href","#nfl-state");
} else {
$('header').attr("href","#city");
$('header').attr("href","#state");
}

if($(".userLocation").length > 0){
$('footer').attr("title","#nflcity");
$('footer').attr("title","#nflstate");
} else {
$('footer').attr("title","#city");
$('footer').attr("title","#state");
}


texts: process numerical input arguments of mixed ints, floats, and "array-like" things of same length>1

texts:
I'm trying to process numerical input arguments for a function. Users can mix ints, floats, and "array-like" things of ints and float, as long as they are all length=1 or the same length>1.

Now I convert them as follows:

convert to float                                convert to np.ndarray; dtype==float
----------------                                -----------------------------------
float
int
np.float64
range object resulting in len == 1              range object resulting in len > 1
len==1 list or tuple of int or float            len > 1 list or tuple of ints & floats
len==1 np.ndarray of dtype np.int or np.float   len > 1 np.ndarray of dtype np.int or np.float

then test all resulting arrays to make sure they are the same length. If so, I return a list containing floats and arrays. If not, return None.

I want to avoid up-conversion of booleans and small byte-length ints.

The script below appears to do what I want by brute force testing, but I wonder if there is a better way?

Desired behaviors:

fixem(some_bad_things) returns None
fixem(all_good_things) returns [42.0, 3.14, 3.141592653589793, 2.718281828459045, 3.0, 42.0, 3.0, 42.0, array([1. , 2.3, 2. ]), array([3.14, 1.  , 4.  ]), array([1., 2., 2.]), array([3., 1., 4.]), array([0., 1., 2.]), array([0, 1, 2])]
and sum(fixem(all_good_things)) returns array([149.13987448 149.29987448 156.99987448])

def fixit(x):
    result = None
    if type(x) in (int, float, np.float64):
        result = float(x)
    elif type(x) == range:
        y = list(x)
        if all([type(q) in (int, float) for q in y]):
            if len(y) == 1:
                result = float(y[0])
            elif len(y) > 1:
                result = np.array(y)
    elif type(x) in (tuple, list) and all([type(q) in (int, float) for q in x]):
        y = np.array(x)
        if y.dtype in (int, float):
            if len(y) == 1:
                result = float(y[0])
            elif len(y) > 1:
                result = y.astype(float)
    elif (type(x) == np.ndarray and len(x.shape) == 1 and
          x.dtype in (np.int, np.float)):
        if len(x) == 1:
            result = float(x[0])
        elif len(x) > 1:
            result = x.astype(float)
    return result

def fixem(things):
    final = None
    results = [fixit(thing) for thing in things]
    floats  = [r for r in results if type(r) is float]
    arrays  = [r for r in results if type(r) is np.ndarray]
    others  = [r for r in results if type(r) not in (float, np.ndarray)]
    if len(others) == 0:
        if len(arrays) == 0 or len(set([len(a) for a in arrays]))==1: # none or all same length
            final = floats + arrays
    return final

import numpy as np

some_bad_things = ('123', False, None, True, 42, 3.14, np.pi, np.exp(1),
                   [1, 2.3, 2], (3.14, 1, 4), [1, 2, 2], (3, 1, 4),
                   (3,), [42], (3.,), [42.], np.array([True, False]),
                   np.array([False]), np.array(False), np.array('xyz'),
                   np.array(42), np.array(42.), np.arange(3.), range(3))

all_good_things = (42, 3.14, np.pi, np.exp(1), [1, 2.3, 2], (3.14, 1, 4),
                   [1, 2, 2], (3, 1, 4), (3,), [42], (3.,), [42.],
                   np.arange(3.), range(3))

for i, things in enumerate((some_bad_things, all_good_things)):
    print(i, fixem(things))

print(sum(fixem(all_good_things))) # confirm


texts:
I have created a LinkedList in Ruby and was wondering if anyone had any input on efficiencies that I could add or deficiencies I could remove.

module LinkedList

    class List
        attr_accessor :node

        def initialize
            self.node = nil
        end

        def add(node)
            if self.node.nil?
                self.node = node
            else
                current_node = self.node
                while ! current_node.getPointer.nil? do
                    current_node = current_node.getPointer
                end
                current_node.setPointer node
            end
        end

        def get(node)
            current_node = self.node
            data_match = nil
            while !current_node.getPointer.nil? and ! data_match.nil? do
                data_match = current_node.getData if node.getData == current_node.getData
                current_node = current_node.getPointer
            end
            return current_node
        end

        def remove(node)
            previous_node = nil
            current_node = self.node
            next_node = current_node.getPointer
            while ! current_node.nil? do
                if current_node.getData == node.getData and current_node.getData == self.node.getData
                    self.node = next_node
                    return true
                end
                if current_node.getData == node.getData
                    previous_node.setPointer next_node
                    return true
                end
                previous_node = current_node
                current_node = next_node
                next_node = current_node.getPointer

            end
            return false
        end

        def print
            current_node = self.node
            while ! current_node.nil? do
                pointerData = current_node.getPointer.nil? ? nil : current_node.getPointer.getData
                puts "data=#{current_node.getData}, pointer=#{pointerData}"
                current_node = current_node.getPointer
            end
            puts
        end

    end

    class Node
        attr_accessor :data
        attr_accessor :pointer

        def initialize(data = nil, pointer = nil)
            self.data = data
            self.pointer = pointer
        end

        def getData
            return self.data
        end

        def getPointer
            return self.pointer
        end

        def setData(data)
            self.data = date
        end

        def setPointer(node)
            self.pointer = node
        end

    end

end


texts: Cropping and combining two images on server

texts:
I've coded following two methods to combine images that are HTTP POSTed to the server:

// Crops two squares out of two separate images
// And then combines them into single image that's returned as byte[]
private byte[] combineImages(HttpPostedFileBase[] itemPayload)
{
    try
    {
        using (var ms = new MemoryStream())
        using (var bitmap = new Bitmap(800, 400, PixelFormat.Format24bppRgb))
        using (var img1 = Image.FromStream(itemPayload[0].InputStream))
        using (var img2 = Image.FromStream(itemPayload[1].InputStream))
        using (var g = Graphics.FromImage(bitmap))
        {
            RectangleF img1Params = getCropParams(img1);
            g.DrawImage(img1, new RectangleF(0, 0, 400, 400), img1Params, GraphicsUnit.Pixel);

            RectangleF img2Params = getCropParams(img2);
            g.DrawImage(img2, new RectangleF(400, 0, 400, 400), img2Params, GraphicsUnit.Pixel);

            var encoderParameters = new EncoderParameters(1);
            encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 90L);
            bitmap.Save(ms, ImageCodecInfo.GetImageDecoders().Single(codec => codec.FormatID == ImageFormat.Jpeg.Guid), encoderParameters);
            return ms.ToArray();
        }
    }
    catch (Exception ex)
    {
        return new byte[0];
    }
}

private RectangleF getCropParams(Image img)
{
    var rect = new RectangleF();
    if (img.Width > img.Height)
    {
        rect.X = (img.Width / 2) - (img.Height / 2);
        rect.Width = (img.Width / 2) + (img.Height / 2) - rect.X;
        rect.Y = 0;
        rect.Height = img.Height;
    }
    else
    {
        rect.X = 0;
        rect.Width = img.Width;
        rect.Y = (img.Height / 2) - (img.Width / 2);
        rect.Height = (img.Height / 2) + (img.Width / 2) - rect.Y;
    }

    return rect;
}

It produces results I expect, but I was curious if my implementation could be improved. I am specifically interested in three things:

Do you see any potential memory leaks?
Do you think code will be performing well when it comes to scalability
Is there a component like ImageResizer that can do this?


texts: Solution to the CodingBat Array-3 [fix34]

texts:
I was studying for arrays from coding-bat and encountered this:

The question is: (fix34)

  Return an array that contains exactly the same numbers as the given
  array, but rearranged so that every 3 is immediately followed by a 4.
  Do not move the 3's, but every other number may move. The array
  contains the same number of 3's and 4's, every 3 has a number after it
  that is not a 3 or 4, and a 3 appears in the array before any 4.

  fix34{1, 3, 1, 4} → {1, 3, 4, 1}

  fix34{1, 3, 1, 4, 4, 3, 1} → {1, 3, 4, 1, 1, 3, 4}

  fix34{3, 2, 2, 4} → {3, 4, 2, 2}

  fix34{2, 3, 5, 3, 2, 4, 4} → {2, 3, 4, 3, 4, 5, 2 }

Code:

public static int[] fix34(int[] nums) {

    // first i stored numbers which are not 3 or 4
    ArrayList<Integer> others = new ArrayList<Integer>();

    for (int i = 0; i < nums.length; i++ )
    {
        if ( nums[i] != 3 && nums[i] != 4 )
            others.add(nums[i]);
    }

    // i created a null array with same length as nums array
    int[] result = new int[nums.length];

    // first i replaced 3's in their specific place, then i replaced 4 near them.
    // so that other spots are 0
    for ( int i = 0; i < nums.length - 1; i++ )
    {
        if ( nums[i] == 3)
        {
            result[i] = 3;
            result[i+1] = 4;
        }
    }

    // now i filled 0s with temped other numbers which i stored in an arraylist.
    // these numbers' size suits with the numbers of zeros
    int j = 0;
    for ( int i = 0; i < result.length; i++ )
    {
        if ( result[i] == 0 )
        {
            int temp = others.get(j);
            j++;
            result[i] = temp;
        }

    }

    return result;

}

I like using ArrayLists, but is it a silly solution? How can I do this with a single loop?


texts: Is there a method to add multiple properties to HtmlTextWriterStyle?

texts:
I am creating new elements for a webpage at run-time and I have code like this:

      var dynDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("Div") {ID = "dynDiv"};
      dynDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Red");
      dynDiv.Style.Add(HtmlTextWriterStyle.Position, "absolute; left: 500px; top: 500px");
      dynDiv.Style.Add(HtmlTextWriterStyle.Height, "30px");
      dynDiv.Style.Add(HtmlTextWriterStyle.Width, "300px");
      dynDiv.InnerHtml = "New Object";
      PlaceHolder1.Controls.Add(dynDiv);

Is there a shorthand method to adding these value? I.e. something like:

dynDiv.Style.Add(HtmlTextWriterStyle {BackgroundColor = "Red", Position = "absolute; left: 500px; top: 500px", Height = "30px", Width="300px"});

Or any other easier way that anyone can suggest?


texts: Three clickable navigation elements, where only one should be active

texts:
I have three clickable
 elements in the nav bar of a static page I'm making as a practice project. I wrote code so when I click one, it lights up.

Since the page is static, it doesn't actually load another page, so it's just the button lighting up. When I click a different button, I want it to light up, and the previous one to turn off. I do this by adding and removing a class that alters the CSS of the element, however, I can't figure out a way of doing this more concisely than what I've already written, which adds the new class and removes any class for the other two elements. Surely there must be a more efficient way of doing this. I thought about a switch statement but I'm not quite sure how to use those yet.

function activeAbout(){
            var about = document.getElementById('about');
            about.setAttribute('class', 'playing');

            document.getElementById('poop').setAttribute('class', '');
            document.getElementById('dgech').setAttribute('class', '');
            }

        function activePoop(){
            var poop = document.getElementById('poop');
            poop.setAttribute('class', 'playing');

            document.getElementById('about').setAttribute('class', '');
            document.getElementById('dgech').setAttribute('class', '');
        }

        function activeDgech(){
            var dgech = document.getElementById('dgech');
            dgech.setAttribute('class', 'playing');

            document.getElementById('about').setAttribute('class', '');
            document.getElementById('poop').setAttribute('class', '');
        }

About

Poop

DGech

How can I refactor this more efficiently?

Edit: Added CSS code.

        #about{
            grid-column: 1;
            grid-row: ;
            justify-self: end;
            align-self: ;
            color: white;
            font-size: 60px;
            margin-top: 10px;

        }

        #poop{
            grid-column: 2;
            justify-self: center;
            color: white;
            font-size: 60px;
            margin-top: 10px;
        }

        #dgech{
            grid-column: 3;
            color: white;
            font-size: 60px;
            margin-top: 10px;
        }

        .playing{
            border-color: #ffc600;
            text-shadow: 0 0 0.5rem #ffc600;
        }


texts: Testing a Django password reset procedure

texts:
I am writing tests for the password reset flow. It involves emails, links to reset the password etc so I made a really long test.
It is testing quite a lot of things.
If I break up the tests then the full flow is not tested, so this is more like a functional test.
How should I break this up especially with regards to getting the activation/reset link?

def test_reset_password_email_send_existing(self):
    '''Test that an email to reset the password is sent
    and redirected to reset complete
    '''
    self.assertEqual(len(mail.outbox), 0)
    response = self.app.get(reverse('auth_password_reset'))
    form = response.form
    form['email'] = self.user.email
    response = form.submit()
    self.assertEqual(len(mail.outbox), 1)
    site = Site.objects.get(id=1)
    self.assertEqual(
        mail.outbox[0].subject,
        f'Password reset on {site.name}'
    )
    self.assertRedirects(
        response,
        reverse('auth_password_reset_done')
    )
    items = re.search(
        r'http[s]?:[\w/-]+.[\w]+\/(?P<rest>[\w/-]+)',
        mail.outbox[0].body
    )
    activate_url = items.groupdict()['rest']
    # get the reset link
    self.app.reset()
    response = self.app.get(
        f'/{ activate_url }'
    )
    self.assertEqual(response.status_code, 302)
    response = response.follow()
    form = response.form
    form['new_password1'] = 'mynewpass'
    form['new_password2'] = 'mynewpass'
    response = form.submit()

    self.assertRedirects(
        response,
        reverse('auth_password_reset_complete')
    )

    response = response.follow()
    self.assertContains(
        response,
        'Password reset successfully'
    )


texts:
So i got an task from school.
Which ask's me to write a program tad creates an 2d array with 11 rows and 5 columns.
In which the first column starts with 2.0 and increments by 0.1 all the way up to 3.0.
Then in next column it should be devided by 1 so if x is 2.0 then 1 / x and goes trough all 11 rows.
then in next column it has to multiply by 2 so x^2 and repeat in every column up to x^4.
So so far i got it to do what i need , but i know there should be a better way to achieve this. as if there would be a task to go up to x^50 for example i imagine it would be pain to do with my way. as its hardcoded.
So here is my code:
#include<iostream>
#include<iomanip>
#include<array>

using namespace std;

int main()
{
 const int rows = 11;
 const int columns = 5;
 double x = 2.0;

 array<array<double, columns>,rows> A{};
 cout << setprecision(2);
 cout << fixed;
 cout << setw(2) <<"x" << setw(10) << "1/x" << setw(7) << "x^2" << setw(7) << "x^3" << setw(8)<< "x^4\n";
 cout << "------ ------ ------ ------ ------\n";
 A[0][0] = x;
 for(int i = 0; i < A.size(); i++)
 {
     A[i+1][0] = A[i][0] + 0.1;
     A[i][1] = 1 / A[i][0];
     A[i][2] = A[i][0] * A[i][0] * A[i][0];
     A[i][3] = A[i][0] * A[i][0] * A[i][0]* A[i][0];
     A[i][4] = A[i][0] * A[i][0] * A[i][0]* A[i][0] * A[i][0] ;
     for(int j = 0; j < A[0].size(); j++)
     {
         cout << A[i][j] << setw(4)  << " ";
     }
     cout << endl;
 }

 return 0;
 }

and here is how it's supposed to look:

Looking for suggestions or tips. I am strugling here.
And sorry for my english it's not my native.


texts:
Following on from this request Yet another C++ Json Parser

A friend pointed out that he though a recursive decent parser would be more efficient.
Before I agree I want to test it so I wrote it for testing.

I found the implementation of the parser much more complex than using yacc (but that could be a result of using yacc a few times and not trying to write recursive descent parsers).

Any comments on the implementation appreciated:

JsonRecParser.h

#ifndef THORSANVIL_JSON_PARSER_JSON_REC_PARSER_H
#define THORSANVIL_JSON_PARSER_JSON_REC_PARSER_H

#include "JsonRecParser.h"
#include "JsonParser.tab.hpp"

class yyFlexLexer;

using namespace ThorsAnvil::JsonParser;

namespace ThorsAnvil
{
    namespace JsonParser
    {

class JsonRecParser
{
    yyFlexLexer&    lexer;

        int JsonValueParse(int val);
        int JsonMapValueListParse(int val);
        int JsonArrayValueListParse(int val);
        int JsonMapParse(int val);
        int JsonArrayParse(int val);
        int JsonObjectParse(int val);

    public:
        JsonRecParser(yyFlexLexer& lexer)
            : lexer(lexer)
        {}
        int parse();
};
    }
}

#endif

JsonRecParser.cpp

#include "JsonParser.tab.hpp"

using namespace ThorsAnvil::JsonParser;

int JsonRecParser::JsonValueParse(int val)
{
    switch(val)
    {
        case '{':                                       return JsonMapParse(lexer.yylex());
        case '[':                                       return JsonArrayParse(lexer.yylex());
        case yy::JsonParser::token::JSON_STRING:   return 0;
        case yy::JsonParser::token::JSON_NUMBER:   return 0;
        case yy::JsonParser::token::JSON_TRUE:     return 0;
        case yy::JsonParser::token::JSON_FALSE:    return 0;
        case yy::JsonParser::token::JSON_NULL:     return 0;
        default:                                        break;
    }
    return val;
}
int JsonRecParser::JsonMapValueListParse(int val)
{
    if ((val == yy::JsonParser::token::JSON_STRING) && ((val = lexer.yylex()) == ':') && ((val = JsonValueParse(lexer.yylex())) == 0))
    {
        val = lexer.yylex();
        switch(val)
        {
            case '}':   return 0;
            case ',':   return JsonMapValueListParse(lexer.yylex());
            default:    break;
        }
    }
    return val;
}
int JsonRecParser::JsonArrayValueListParse(int val)
{
    if ((val = JsonValueParse(val)) == 0)
    {
        val = lexer.yylex();
        switch(val)
        {
            case ']':   return 0;
            case ',':   return JsonArrayValueListParse(lexer.yylex());
            default:    break;
        }
    }
    return val;
}
int JsonRecParser::JsonMapParse(int val)
{
    if (val == '}')
    {   return 0;   /* Empty Map */
    }
    return JsonMapValueListParse(val);
}
int JsonRecParser::JsonArrayParse(int val)
{
    if (val == ']')
    {   return 0;   /* Empty Array */
    }
    return JsonArrayValueListParse(val);
}
int JsonRecParser::JsonObjectParse(int val)
{
    switch(val)
    {
        case '{':   return JsonMapParse(lexer.yylex());
        case '[':   return JsonArrayParse(lexer.yylex());
        default:    break;
    }
    return val;
}
int JsonRecParser::parse()
{
    return JsonObjectParse(lexer.yylex());
}

All other files are the same.
With this small change to main:

Changes to main.cpp

    //yy::JsonShiftParser parser(lexer);
    ThorsAnvil::JsonParser::JsonRecParser   parser(lexer);

#


texts:
I am a beginner in JavaScript and just wanted to get my code reviewed. Here I have created a function that takes in an array and returns the mode. If there is no more then I just want the function to return the first number. It seems a little too long and I feel like there may be more clever ways to do it. Again, keep in mind that I am a beginner, so I don't have a huge toolbox.

var mode = function(arr){
    var numMapping = {};
    for(var i = 0; i < arr.length; i++){
        if(numMapping[arr[i]] === undefined){
            numMapping[arr[i]] = 0;
        }
            numMapping[arr[i]] += 1;
    }
    var greatestFreq = 0;
    var mode;
    for(var prop in numMapping){
        if(numMapping[prop] > greatestFreq){
            greatestFreq = numMapping[prop];
            mode = prop;
        }
    }
    return parseInt(mode);
}


texts:
I'm in the middle of writing my own little bullet shooter game much in the style of Touhou. Everything works fine so far but I'm disliking certain aspects of my code. Take this function for showing and unshowing the title screen:

    private function runIntro() : void
    {
        if (introFadeInTitle_ && aliceIntroTxt.alpha < 1)
            aliceIntroTxt.alpha += 0.02;
        else if (introFadeInTitle_)
        {
            var timer : Timer = new Timer(1000);
            timer.addEventListener(TimerEvent.TIMER, function() {
                timer.stop();

                introFadeInBtns_  = true;
            });
            timer.start();

            introFadeInTitle_ = false;
        }
        else if (introFadeInBtns_ && startBtn.alpha < 1)
        {
            startBtn.alpha   += 0.02;
            optionsBtn.alpha += 0.02;
        }
        else if (introFadeInBtns_)
        {
            introFadeInBtns_ = false;

            gameState = GameState.READY;
        }

        if (introFadeOutBtns_ && startBtn.alpha > 0)
        {
            startBtn.alpha   -= 0.02;
            optionsBtn.alpha -= 0.02;
        }
        else if (introFadeOutBtns_)
        {
            var timer : Timer = new Timer(500);
            timer.addEventListener(TimerEvent.TIMER, function() {
                timer.stop();

                introFadeOutTitle_ = true;
            });
            timer.start();

            introFadeOutBtns_ = false;
        }
        else if (introFadeOutTitle_ && aliceIntroTxt.alpha > 0)
            aliceIntroTxt.alpha -= 0.02;
        else if (introFadeOutTitle_)
        {
            var timer : Timer = new Timer(500);
            timer.addEventListener(TimerEvent.TIMER, function() {
                timer.stop();

                introFadeOutBg_ = true;
            });
            timer.start();

            introFadeOutTitle_ = false;
        }
        else if (introFadeOutBg_ && introBg.alpha > 0)
            introBg.alpha -= 0.02;
        else if (introFadeOutBg_)
        {
            introFadeOutBg_;

            gameState = GameState.RUNNING;
        }
    }

At a glance, it's just a bunch of if-else-if statements that check whether or not a given object has faded out and what the current state of the animation is. I feel that this if-else-if chain is alright for a rather short function like this, but I do have more complicated states that I wish to show (for example a ready-set-go splash before the fight begins) that would just balloon this kind of structure into an unholy mess.

What is the best way to deal with this code?


texts:
I am trying to solve this problem on SPOJ Brazil. I'm trying to approach the problem with a series of logical conditions and my code looks like this and it works perfectly.

#include <stdio.h>

typedef struct {
    int y1;
    int x1;
    int x2;
    int y2;
}coordinate;

int main(){

    int N, C, i, j, xi, xf, nbacterias;

    coordinate coord[100000];

    scanf ("%d %d", &N, &C);

    for (i = 0; i < N; i++){
        scanf ("%d %d %d %d", &coord[i].x1, &coord[i].y1, &coord[i].x2, &coord[i].y2);
    }

    for (i = 0; i < C; i++){
        scanf ("%d %d", &xi, &xf);
        nbacterias = 0;

        for (j = 0; j< N; j++){
            if ((coord[j].x1 >= xf && coord[j].x2 >= xf) || (coord[j].x2 <= xi && coord[j].x1 <= xi))
                nbacterias++;
            else if ((xf < coord[j].x2 && xf > coord[j].x1 && xi <= coord[j].x1 && xi < coord[j].x2) || (xf < coord[j].x1 && xf > coord[j].x2 && xi <= coord[j].x2 && xi < coord[j].x1))
                nbacterias++;
            else if ((xi > coord[j].x2 && xi < coord[j].x1 && xf >= coord[j].x1 && xf > coord[j].x2) || (xi>coord[j].x1 && xi < coord[j].x2 && xf >= coord[j].x2 && xf > coord[j].x1))
                nbacterias++;
            else if ((coord[j].x1 < xi && coord[j].x2 > xf) || (coord[j].x2 < xi && coord[j].x1 > xf))
                nbacterias = nbacterias + 2;

        }
        printf ("%d\n", nbacterias);
    }

    return 0;
}

As you can see, I created a coordinate struct and created a series of conditions in which the bacteria could be divided (in two, when they get hit by the laser in the middle; in one, when the laser cuts out a part of it; when the laser doesn't hit the bacteria at all, leaving the whole bacteria; and when the laser hits the entire bacteria, leaving no parts at all).

This solution works, you can test it with the cases given in the problem link I pasted up there. The problem is that when I submit my code it exceeds the time limit. Any ideas on how to optimize this code or if I am missing some gimmick here? By the way, I'm pretty new to competitive programming, so I may not completely grasp complex answers.


texts: Vigenere Cipher - make code more concise?

texts:
I'm a beginner in programming overall, started about a month ago and so I'm still trying to fully grasph the concept of OOP, for instance. Here I used a class for the encryption and decryption processes, but everything else is in functions in the main part of the program (getting the cipher key, user message etc). What do you guys think? Is my implementation good? How could I improve it?

# Vigenere Cipher program

class Vigenere:
    """Vigenere Cipher program."""

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

    def __str__(self):
        print("Vigenere Cipher program.")

    def __encrypt(self):
        encrypted = ""
        i = 0
        for letter in self.message:
            if ord(letter) + self.key[i] > 90:
                new_key = ord(letter) + self.key[i] - 90
                new_letter = chr(64 + new_key)
                encrypted += new_letter
                i += 1
                if len(self.key) == i:
                    i = 0
            else:
                encrypted += (chr(ord(letter) + self.key[i]))
                i += 1
                if len(self.key) == i:
                    i = 0
        return encrypted

    def __decrypt(self):
        decrypted = ""
        i = 0
        for letter in self.message:
            if ord(letter) - self.key[i] < 65:
                new_key = 65 - (ord(letter) - self.key[i])
                new_letter = chr(91 - new_key)
                decrypted += new_letter
                i += 1
                if len(self.key) == i:
                    i = 0
            else:
                decrypted += chr(ord(letter) - self.key[i])
                i += 1
                if len(self.key) == i:
                    i = 0
        return decrypted

def get_message():
    userMessage = ""
    final_message = ""
    flag = True
    while flag:
        userMessage = input("\nYour message: ")
        if len(userMessage) < 1:
            print("\nYou must enter something!")
            continue
        userMessage = userMessage.replace(" ", "")
        for i in range(len(userMessage)):
            if not userMessage[i].isalpha():
                continue
            else:
                final_message += userMessage[i]
        if len(final_message) < 1:
            continue
        else:
            flag = False
    return final_message.upper()

def get_key():
    userKey = ""
    keys = []
    final_keys = []
    flag = True
    while flag:
        userKey = input("\nYour key: ")
        if len(userKey) < 1:
            print("You must enter something!")
            continue
        userKey = userKey.replace(" ", "")
        for i in range(len(userKey)):
            if not userKey[i].isalpha():
                continue
            else:
                keys.append(ord(userKey[i].upper()))
                final_keys.append(keys[i] - 64)
        if len(final_keys) < 1:
            continue
        flag = False
    return final_keys

def encrypt_or_decrypt():
    userChoice = ""
    flag = True
    while flag:
        userChoice = input("\nEncrypt or decrypt? (E/D): ")
        if userChoice not in ("e", "E", "d", "D"):
            continue
        else:
            flag = False
    return userChoice

if __name__ == "__main__":
    flag = True
    while flag:
        userChoice = encrypt_or_decrypt()
        message = get_message()
        key = get_key()
        cipher = Vigenere(message, key)
        if userChoice in ("e", "E"):
            encrypted = cipher._Vigenere__encrypt()
            print(encrypted)
        else:
            decrypted = cipher._Vigenere__decrypt()
            print(decrypted)
        userInput = input("\nAgain? (Y/N): ")
        while userInput not in ("y", "Y", "n", "N"):
            userInput = input("\nAgain? (Y/N): ")
        if userInput in ("y", "Y"):
            continue
        elif userInput in ("n", "N"):
            print("Exiting.")
            flag = False
    input("\n\nPress the enter key to exit.")


texts: Converting fixed-width text file to CSV in C

texts:
I'm trying to get reacquainted with C after years of higher-level languages.

I wrote a small fixed-width to CSV converter. It works (for ASCII at least) and it's quite fast, but I wonder if I missed anything or if it can be made even faster.

I'm reading the file line by line and process the desired columns (some can be skipped), placing them into an output 8K buffer. I'm using one function to do the substring, appending and trimming trailing space (just the space, in this case I don't want to bother testing for other whitespace characters).

#include <ctype.h>

// number of columns to process
#define COLS 3
#define LINE_SIZE 256
#define BUFFER_SIZE 8192

#define INFILE "in.txt"
#define OUTFILE "out.csv"

size_t RANGES[COLS][2] = {{0, 6}, {6, 20}, {29, 3}};

/*
 * Copy from source to destination, up to len chars, trimming trailing spaces
 * Returns number of chars actually copied
 */
int trimcpy(char *destination, char *source, size_t len) {
    // trim spaces from the end - we only care about the space char
    while (len>0 && source[len-1]==' ')
        len--;

    int i = 0;
    while (i<len && *source != '\0') {
        *destination++ = *source++;
        i++;
    }
    *destination = '\0';

    return i;
}

int main(void) {
    FILE *rfp;
    FILE *wfp;

    char line[LINE_SIZE];
    char out[BUFFER_SIZE];

    rfp = fopen(INFILE, "r");
    if (rfp == NULL)
        exit(EXIT_FAILURE);

    wfp = fopen(OUTFILE, "w");
    if (wfp == NULL)
        exit(EXIT_FAILURE);

    int p = 0;

    // fgets is 4x faster than getline!
    while (fgets(line, LINE_SIZE, rfp) != NULL) {
        // write buffer if almost full (largest column is 20 chars)
        if (p > BUFFER_SIZE - 20) {
            fputs(out, wfp);
            p = 0;
        }

        // go through the columns
        for (int i=0; i<COLS; i++) {
            p += trimcpy(out+p, line+RANGES[i][0], RANGES[i][1]);
            p += trimcpy(out+p, i<COLS-1 ? "," : "\n", 1);
        }
    }

    // write any remaining data in buffer
    fputs(out, wfp);

    fclose(rfp);
    fclose(wfp);

    exit(EXIT_SUCCESS);
}


texts: Summing the digits of a sum of digits of a sum

texts:
I'm a beginner in Python, and computer languages in general, and I'm totally stumped on how to format this iteration into a function. The iteration takes the sum of someone's birth year, month, and day and adds it together to create a sum of those numbers, and then the second iteration takes the first sum and adds those numbers together to create a final sum.

I have the users input their birthyear, month, and day (all converted to int) and this is the first sum (Example: A bday of 01/01/1997= 1999):

first_sum=b_yr + b_dy + b_mo

Then the first iteration takes the sum and adds the numbers together (Example: 1999 = 1+9+9+9 = 28):

z = first_sum
zstr1=str(z)
accum1=0
for x in zstr1:
    accum1 += int(x)
(accum1)

Then the second iteration takes the first sum and adds those numbers again to create the final sum (Example: 28 = 2+8 = 10):

str2=str(accum1)
accum2=0
for cnt2 in str2:
    accum2 += int(cnt2)


texts:
I am building a one-page JS app similar to redditinvestigator.com, and my goal is for it to be 100% done in JavaScript. Coming from a PHP/Java background, I'm more used to working in class oriented languages, so I just want to get a sense if I am implementing them correctly in JavaScript.

My code works as expected, and I am just hoping to get some feedback on if there is anything I technically am doing wrong, or if there is a better way to do some of the things I am implementing.

jsFiddle (the results are just in the console FYI)

var Comment = function(obj) {
    if (obj) {
        this.data = obj.body;
        this.created_utc = obj.created_utc;
        this.downs = obj.downs;
        this.gilded = obj.gilded;
        this.id = obj.id;
        this.link_id = obj.link_id;
        this.link_title = obj.link_title;
        this.name = obj.name;
        this.subreddit = obj.subreddit;
        this.ups = obj.ups;
    }
};

Comment.prototype.getBody = function() {
    return this.data;
};
Comment.prototype.getCreated = function() {
    return this.created_utc;
};
Comment.prototype.getDownvotes = function() {
    return this.downs;
};
Comment.prototype.getUpvotes = function() {
    return this.ups;
};
Comment.prototype.getScore = function() {
    return this.ups - this.downs;
};
Comment.prototype.isGilded = function() {
    return this.gilded;
};
Comment.prototype.getID = function() {
    return this.id;
};
Comment.prototype.getLinkID = function() {
    return this.link_id;
};
Comment.prototype.getLinkTitle = function() {
    return this.link_title;
};
Comment.prototype.getName = function() {
    return this.name;
};
Comment.prototype.getSubreddit = function() {
    return this.subreddit;
};

var RedditInterface = function(username) {
    this.userName = username;
    this.commentCount = 0;
    this.submissionCount = 0;
    this.lastCall = 0;
};

RedditInterface.prototype.getUsername = function() {
    return this.userName;
};

RedditInterface.prototype.sendQuery = function(endpoint, after, func) {
    var curDate = new Date().getTime();
    var timeSince = curDate - this.lastCall;
    if (timeSince < 5000)
        return null;
    this.lastCall = curDate;

    var urlD = '';
    if (after === '')
        urlD = "http://www.reddit.com/user/" + this.userName + "/" + endpoint + ".json?limit=100&jsonp=?";
    else
        urlD = "http://www.reddit.com/user/" + this.userName + "/" + endpoint + ".json?limit=100&after=" + after + "&jsonp=?";

    $.ajax({
        url: urlD,
        dataType: 'json',
        success: func
    });
};

RedditInterface.prototype.loadAllComments = function() {
    var here = this;
    var intervalHandle = window.setInterval(function() {
        here.sendQuery('comments', commentAfter, function(data) {
            if (data.data.children.length === 0) { //We've loaded all the comments reddit will give us
                console.log("Comments loaded. Total: " + commentLog.length);
                window.clearInterval(intervalHandle);
            }
            for (var point in data.data.children) {
                var ret = new Comment(data.data.children[point].data);
                var accept = true;
                for (var i = 0; i < commentLog.length; i++) {
                    if (commentLog[i].name == ret.name) {
                        console.log(i + ' (' + commentLog[i].name + ') is equal to current (' + ret.name + '), ommitting.');
                        accept = false;
                        break;
                    }
                }
                if (accept && typeof ret.name !== 'undefined') {
                    commentLog.push(ret);
                    commentAfter = ret.name;
                }
            }
            console.log(commentLog);
        });
    }, 5500);
    return intervalHandle;
};

//Begin Logic
var commentLog = [];
var submissionLog = [];
var commentAfter = '';

var ri = new RedditInterface("hueypriest");
var handle = ri.loadAllComments();


texts:
I have made a thread pool which will dynamically create threads based on how many you need.

#pragma once

#include <thread>
#include <atomic>
#include <mutex>
#include <vector>
#include <functional>
#include <condition_variable>

class thread_pool {
public:
    thread_pool() : stop(false), busy_workers(0) { }

    ~thread_pool() {
        stop = true;
        task_available.notify_all();
        for (auto& worker : workers) {
            if (worker.joinable()) {
                worker.join();
            }
        }
    }

    void run_task(std::function<void()> task) {
        {
            std::lock_guard<std::mutex> task_lock{ task_mu };
            current_task = std::move(task);
        }

        {
            std::lock_guard<std::mutex> workers_lock{ workers_mu };
            if (workers.size() == busy_workers++) {
                workers.emplace_back(work);
                return;
            }
        }

        task_available.notify_one();
    }
private:
    std::atomic_bool stop;
    std::atomic_size_t busy_workers;
    std::vector<std::thread> workers;
    std::function<void()> current_task;
    std::condition_variable task_available;
    std::mutex task_mu;
    std::mutex workers_mu;

    std::function<void()> work = [&]() {
        while (true) {
            std::unique_lock<std::mutex> task_lock{ task_mu };
            task_available.wait(task_lock, [&]() { return current_task || stop; });

            if (!current_task && stop) return;

            auto task = std::move(current_task);
            task_lock.unlock();

            task();
            busy_workers--;
        }
    };
};

The only problem I have with it is the threads will be destroyed before all the tasks have been completed, even though I join all the threads in the destructor.


texts: Symfony rest endpoint for get a number products of one user

texts:
I want to improve quality of this symfony rest endpoint (solid principle, Kiss, best practice...) Can you review my code please?

Symfony controllController function that return json list of product

/**
 * @Route("/api/products/my_list/{number}", methods={"GET"})
 * @param Security $security
 * @param BeamyAPI $beamyAPI
 * @param Request $request
 * @param ProductService $productService
 * @return string
 */
public function myList(
    Security $security,
    BeamyAPI $beamyAPI,
    Request $request,
    ProductService $productService,
    int $number = 20
)
{
    $productListUser = $this->em->getRepository(ProductAdmin::class)
                             ->findProductsUser(
                                 $security->getUser(),
                                 $number
                        );
    return new JsonResponse(
        $productListUser,
        Response::HTTP_OK
    );
}

Trait to format array response

Trait ArrayFormat
{
    /**
     * format array for user product endpoint
     *
     * @param array $data
     * @return array
     */
    public function formatUserProduct($product) : array
    {
       return [
            'id' => $product['id'],
            'name' => $product['name'],
            'notifications' =>  '',
            'logo' => [
                'contentUrl' => $product['logo']['contentUrl']
            ]
        ];
    }
}

Repository permit to get array of products list for one user

/**
     * get product list of user
     *
     * @param UserInterface $user
     * @param integer $number
     * @return array|null
     */
    public function findProductsUser(UserInterface $user, int $number) :?array
    {

        $listProductUser = $this->em->getRepository(ProductAdmin::class)->findBy(
            ['user' => $user],
            ['product' => 'ASC'],
            $number
        );

        $res = [];
        array_walk($listProductUser, function(&$productUser){
            $product = $this->productService->getProductInfo($productUser->getProduct());
            $productUser =  ArrayFormat::formatUserProduct($product);
        });

        return $listProductUser;
    }

Thanks


texts: Finding the number of capital letters in a word grouped by letter

texts:
Please see the code options below:

Client App - this is the same for both options

LetterCounter lc = new LetterCounter("HeLLo");

Option 1

class LetterCounter
    {
        string _Word;
        List<LetterQuantities> letterQuantities;

        //Other functions will be here.

        public LetterCounter(string Word)
        {
            _Word = Word;
            LetterQuantities lq = new LetterQuantities();
            letterQuantities = lq.GetCapialLetterQuantities(Word);
        }
    }

    class LetterQuantities
    {
        int _Quantity;
        char _Letter;

        public LetterQuantities()
        {
        }

        public LetterQuantities(int Quantity, char Letter)
        {
            _Quantity = Quantity;
            _Letter = Letter;
        }

        public List<LetterQuantities> GetCapialLetterQuantities(string Word)
        {
            List<LetterQuantities> letterQuantitiesList = new List<LetterQuantities>();
            for (char c = 'A'; c <= 'Z'; c++)
            {
                int count = Word.Split(c).Length - 1;
                if (count > 0)
                {
                    LetterQuantities lq = new LetterQuantities(count, c);
                    letterQuantitiesList.Add(lq);
                }
            }
            return letterQuantitiesList;
        }
    }

Option 2

class LetterCounter
    {
        string _Word;
        List<KeyValuePair<char, int>> LetterQuantities = new List<KeyValuePair<char, int>>();

        //Other functions will be here.

        public LetterCounter(string Word)
        {
            _Word = Word;
            GetCapialLetterQuantities();
        }

        public void GetCapialLetterQuantities()
        {
            for (char c = 'A'; c <= 'Z'; c++)
            {
                int count = _Word.Split(c).Length - 1;
                if (count > 0)
                {
                    LetterQuantities.Add(new KeyValuePair<char,int>(c,count));
                }
            }
        }
    }

The concerns I have are:

1) Option 1: LetterQuantities returns a list of itself.  Not sure this is ideal.  However, it is how a Tree data structure works.
2) Option 2: This is simpler.  However, I am not sure whether 'Letter' is a valid key.
3) I am not sure whether the object(s) should be Singletons as they are value objects rather than entity objects.

I believe I should use option 1 from a TDD point of view.


texts:
In my VBA code, I am trying to generate a specific list of cell row positions.

Basically, I first fill a collection with the entire list of row positions pertaining to a specific column:

Dim arrPos As New Collection
....
For i = 3 To bottomRow
arrPos.Add i
Next i

Then I try to remove remove values from this collection if there's no problem at that specific row.

For h = matchRow To 3 Step -1
    For g = arrPos.Count To 1 Step -1
        If CLng(Worksheets(".....").Range("C" & h).Value) = arrPos(g) Then
            arrPos.Remove (g)
            Exit For
        End If
    Next g
Next h

Basically Range("C" & h).Value is a column where the =MATCH function was used so there's a whole list row positions in that column. If the MATCH worked, then I can remove it from the collection. A similar type of loop is made use of further down the code for the rows where the MATCH came up false.

The code gives the proper results but it can drag on at times (especially since row counts can get up to the 5000's) and even crash my puny laptop. As you can see, the method makes use of nested loops and I believe that significant results could be attained by re-factoring this portion.

Does anyone have any suggestions?  The question is basically requesting a more efficient way to identify the row positions that did not come up from a MATCH function: either because the value was slightly erroneous or just simply missing.


texts: Hello Functional World: Counting occurrences of each letter

texts:
Coming from a OO (C#) background, I am trying to learn some FP. To help me transition, I am trying to learn F#. I am taking baby steps.

I set myself a simple challenge to count the instances of each letter in a sentence, ordered alphabetically. ("Hello World" -> "[D, 1]; [E, 1]; [H, 1]; [L, 3]; [O, 2]; [R, 1]; [W, 1]; ").

My solution works but I can't help but thinking that I am not able to break out of an imperative style (my solution is based on Linq type thinking).

open System

let getLetterCount xs =
    xs |>
    Seq.filter Char.IsLetter |>
    Seq.map Char.ToUpper |>
    Seq.groupBy id |>
    Seq.sortBy fst |>
    Seq.map (fun (k,v) -> (k, Seq.length v))

let tuplesToString = Seq.fold (fun a (k,v) -> a + sprintf "[%c, %i]; " k v) ""

printfn "%s" (tuplesToString (getLetterCount "Hello World"))

Does anyone know of a good source of challenges to help me get my teeth into learning this?


texts:
I ve got a table called EXP it looks like this

The table contains

REG_ID - (id of the registred users)
TRA_TYPE - (type of transportation the user chose 1-export 2-import)
PRO_ID - (product id in rande [1-16])

When a user registers he can choose transportation type EXPORT and products for EXPORT or import AND PRODUCTS for IMPORT or BOTH

Then his data (name, password) is inserted into REGISTRATION table and (id form registration tabl, type/s of transportation and selected products into EXP table)

I need to retrieve an array to process the data, I expect to get this array

Array
(
    [0] => Array
        (
            [id] => 1
            [tra_type] => 1
            [prod_import] => Array
                (
                    [0] => 2
                    [1] => 6
                    [2] => 10
                )

        )

)

I use this block of code to get it

    //get all the rows containing choosen products
    $mas = array(2,6,10);
    $implode_mas = implode(',',$mas);
    $g = $qw->query("select * from exp where pro_id in ($implode_mas) and tra_type = '1';");
    while($o = $g->fetch(PDO::FETCH_ASSOC)){
        $k[] = $o;
    }

   //extract only IDs
    for($hk=0;$hk<count($k);$hk++){
        $O[] = $k[$hk]['reg_id'];
    }

    //removing equal IDs
    $O = array_values(array_unique($O));

    //define an empty array
    $Ty = array();

    //run for loop
    for($ep=0;$ep<count($O);$ep++){

        // getting current ID
        $cId = $O[$ep];

        //add id to array
        $Ty[$ep]['id'] = $cId;

         ///add tra_type to array
        $Ty[$ep]['tra_type'] = $k[$ep]['tra_type'];

        for($hj=0;$hj<count($k);$hj++){
         // if the array IDS if equal IDs from $O array  add its pro_id to array $Ty
         if($k[$hj]['reg_id'] == $cId )
           $Ty[$ep]['prod'][]= $k[$hj]['pro_id'];
        }

    }

    print_r($Ty);

Could give me advice how to do the same in an easier way?


texts: Transfer values from one LinkedList to another

texts:
Write a method transferFrom that accepts a second LinkedIntList as a
  parameter and that moves values from the second list to this list. You
  are to attach the second list's elements to the end of this list. You
  are also to empty the second list. For example, suppose two lists
  store these sequences of values:

  list1: [8, 17, 2, 4] list2: [1, 2, 3] The call of
  list1.transferFrom(list2); should leave the lists as follows:

  list1: [8, 17, 2, 4, 1, 2, 3] list2: [] The order of the arguments
  matters; list2.transferFrom(list1); would have left the lists as
  follows:

  list1: [] list2: [1, 2, 3, 8, 17, 2, 4] Either of the two lists could
  be empty, but you can assume that neither list is null. You are not to
  create any new nodes. Your method should simply change links of the
  lists to join them together.

  Assume that you are adding this method to the LinkedIntList class as
  defined below:

  public class LinkedIntList {
      private ListNode front;   // null for an empty list
      ... }

It is also worth noting that this is based on a custom implementation called LinkedIntList, which you can find here.

I'd like to get some general feedback for writing using the calling method vs the called (am I doing this right?) I was a bit confused when writing this code, and felt like I had to hardcode too many edge-cases. This might result in some bugs I don't currently see. I hope that this code can be simplified so that I can better understand it for future problems.

public LinkedIntList transferFrom(LinkedIntList list) {
    if (list.front != null) {
        if (this.front == null) {
            this.front = list.front;
            list.front = null;
        } else {
            boolean isConcated = false;
            for (ListNode p = this.front; p != null; p = p.next) {
                if (p.next == null && !isConcated) {
                    p.next = list.front;
                    isConcated = true;
                    list.front = null;
                }
            }
        }
    }
    return this;
}


texts: Computing the total different between a pixel and its neighborhood

texts:
I have C++ code which written for mex in MATLAB. It used to compute the total different between a pixel and its neighborhood (8 neighborhood in my code). The code ran and gave me an expected result. However, I think that we can make my code more faster (because of a lot of if statement). I am very happy if someone can help me to speed up it.

#include "mex.h"
#include <vector>
#include <math.h>
#define img(i,j) img[(i) + (j)*M]
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    double  *img, *G;
    int    N, M, class_count;
    int ndim=3;
    double beta, energy;
    N           = (int) mxGetN(prhs[0]); //cols
    M           = (int) mxGetM(prhs[0]); //rows
    img         = (double *)mxGetData(prhs[0]);
    beta        = (double )*mxGetPr(prhs[1]);
    class_count = (int )*mxGetPr(prhs[2]);
    /* Initial zeros matrix*/
    int dims[3] = {M-2, N-2, class_count};
    plhs[0]     = mxCreateNumericArray(ndim, dims, mxDOUBLE_CLASS, mxREAL);
    G           = (double *) mxGetPr(plhs[0]);
    /////////////Main///////////////
    for (int label=2; label <= class_count+1; label++) {
       for (int i=1; i < M-1; i++) {
         for (int j=1; j < N-1; j++) {
                energy = 0;
                 // North, south, east and west
                if (label == img(i-1,j)) energy = energy-beta;
                else energy = energy+beta;
                if (label == img(i,j+1)) energy = energy-beta;
                else energy = energy+beta;
                if (label == img(i+1,j)) energy = energy-beta;
                else energy = energy+beta;
                if (label == img(i,j-1)) energy = energy-beta;
                else energy = energy+beta;
                if (label == img(i-1,j-1)) energy = energy-beta;
                    else energy = energy+beta;
                if (label == img(i-1,j+1)) energy = energy-beta;
                    else energy = energy+beta;
                if (label == img(i+1,j+1)) energy = energy-beta;
                    else energy = energy+beta;
                if (label == img(i+1,j-1)) energy = energy-beta;
                    else energy = energy+beta;
                G[(i-1) + (j-1)* (M-2) + (label-2) * (N-2) * (M-2)]=energy;
             }
        }
    }
}


texts:
When learning a new language, one of my first tasks I like to go through is writing a few different sorting algorithms in that language to help familiarize myself with the syntax and see if there are creative ways that algorithm can be conceived in the language.

In Go, I wanted to use this as an opportunity to work with Goroutines and see if there are other interesting functions/uses that I had missed while writing this out. Effectively, my goal is to have the divide-and-conquer portion of the algorithm happen concurrently.

One possible area of improvement would be to have the combination of the left and right sides also happen concurrently, rather than wait for the left and right sides to complete before moving on to combining. Overall, my concerns boil down to:

1) How could I, if possible, use concurrency inside/around the for loops from the mergesort function to speed up the end portion of the algorithm?

2) Other than the algorithm itself which, to my understanding, already is in the "sort" package, are there any other Go-specific problems with my code that could be made more..."Go-thic"?

package main

import (
    "crypto/rand"
    "fmt"
    "os"
    "strconv"
)

var (
    nums    []byte //The slice of numbers we want to sort
    numVals int    = -1
)

//User can optionally add a parameter that determines how many random numbers will be sorted
//If none are provided, 100 will be used
func main() {
    if len(os.Args) >= 2 {
        numVals, _ = strconv.Atoi(os.Args[1])
    } else {
        numVals = 100
    }
    nums = initSlice()
    ms := make(chan []byte)
    go mergeSort(nums, ms)
    nums = <-ms
    for _, value := range nums {
        fmt.Printf("%d\n", value)
    }
}

func initSlice() []byte {
     vals := make([]byte, numVals)
     _, err := rand.Read(vals)
     if err != nil {
        panic(err)
     }
     return vals
}

func mergeSort(arr []byte, ms chan []byte) {
    if len(arr) <= 1 { //base case
        ms <- arr
        return
    }
    leftMS := make(chan []byte)
    go mergeSort(arr[:len(arr)/2], leftMS)
    rightMS := make(chan []byte)
    go mergeSort(arr[len(arr)/2:], rightMS)
    left, right := <-leftMS, <-rightMS
    sortArr := make([]byte, len(arr))
    lIndex, rIndex := 0, 0
    //Combine both sides
    for lIndex < len(left) && rIndex < len(right) {
        leftLeast := left[lIndex] <= right[rIndex]
        if leftLeast {
            sortArr[lIndex+rIndex] = left[lIndex]
            lIndex++
        } else {
            sortArr[lIndex+rIndex] = right[rIndex]
            rIndex++
        }
    }
    //Fill in whichever 'pile' is empty
    if lIndex < len(left) {
        for ; lIndex < len(left); lIndex++ {
            sortArr[lIndex+rIndex] = left[lIndex]
        }
    }
    if rIndex < len(right) {
        for ; rIndex < len(right); rIndex++ {
            sortArr[lIndex+rIndex] = right[rIndex]
        }
    }
    ms <- sortArr
}

Of course, please feel free to add any other suggestions. Thanks!


texts: Entity Framework Core DbFunction for square root

texts:
I'm porting my site over from .NET Framework / MVC 5 / EF6 to .NET Core 3.1 MVC / EF Core. MSSQL Server for the database.
EF6 has SqlFunctions of which one method is SquareRoot, which translates to using SQRT in sql queries against MSSQL Server.
EFCore does not have the SqlFunctions class. It does have an equivalent DbFunctions class but this is missing lots of methods.
After some googling about I've come up with the following for translating the LINQ query to sql:
MyDbFunctions.cs
public static class MyDbFunctions
{
    public static double? SquareRoot(double? arg) => throw new Exception();
}

OnModelCreating method in DbContext
var sqrtMethodInfo = typeof(MyDbFunctions).GetMethod(nameof(MyDbFunctions.SquareRoot));
modelBuilder
    .HasDbFunction(sqrtMethodInfo)
    .HasTranslation(args => SqlFunctionExpression.Create("SQRT", args, typeof(double?), null));

Usage:
from a in context.Posts
let sqrt = MyDbFunctions.SquareRoot(a.someColumnWithDoubleValue)
where sqrt < 1337
select new MyViewModel
{
   Sqrt = sqrt
    ...
};

This seems to work nicely. I can see the use of SQRT within the generated query (using SQL Server Profiler) and the where clause being applied. It also looks near identical to what EF6 generates.
I'm wondering if any EF Core pros can see anything wrong/pitfalls with the implementation (or improve on it)?


texts:
I'm new to Laravel and trying to figure out how I can reduce/refactor this store() call in my SessionController.

Basically, the SessionController is used to authenticate a user against an LDAP server (using wells/l4-ldap-ntlm instead of the default auth driver)

On LDAP auth success, it then checks if the user has an account/profile for this webapp. If they do not, it creates it. If they already have one, it just logs them in (user/profile only created on first login).

If LDAP auth fails, it redirects back to the login page.

I know this is a lengthy method for a controller, so I want to know the best practices for:

Refactoring this code out, so the controller is cleaner, and adhering to the "single responsibility" rule.
I need to use LDAP just for authentication, but I also want to store information for this webapp that is not stored in LDAP. Right now I am creating a User and a Profile model, but I don't know a good way to "link" them to the LDAP authenticated user once logged in.

public function store()
{
    // store credentials
    $input = Input::all();

    // attempt authentication
    $attempt = Auth::attempt([
        'username' => $input['user'],
        'password' => $input['pass']
    ]);

    if ($attempt) {
        // LDAP auth success
        $un   = Auth::user()->username;
        $role = Auth::user()->type;

        // check if user exists, creating a user and profile if they do not.
        try {
            $user = User::whereUsername($un)->firstOrFail();
        }
        catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            $user = User::create(['username'=>$un]);
            $user->roles()->attach( $role );
            $user->createProfile();
        }

        // redirect
        return Redirect::intended('/profile')
                        ->with('flash_message', 'welcome, ' . $un);
    }
    else {
        // LDAP auth failed.
        return Redirect::back()
                        ->with('flash_message', 'The credentials you entered were invalid. Please try again.')
                        ->withInput();
    }

}


texts: Circular buffer implementation using linked list

texts:
I'm a beginner with C.
The below is the implementation of circular buffer using linked list. Please review my code and suggest any improvements to make it efficient or to improve in coding style.

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

struct link_list
{
    int item;
    struct link_list *next;
};

struct link_list *read=NULL;
struct link_list *write=NULL;
int size=NULL; //buffer size
static int p_size=0; //present size of buffer

void enqueue()
{
    int value;
    struct link_list *newnode=(struct link_list*)malloc(sizeof(struct link_list));
    printf("Enter new value : \n");
    scanf("%d",&value);
    newnode->item=value;
    newnode->next=NULL;

    if(read==NULL&&write==NULL)
    {
    read=write=newnode;
        p_size++;
    }
    else
    {
        if (p_size<size)
        {
            printf("still buffer not filled\n");
            write->next=newnode;
            write=newnode;
            p_size++;
        }
        else
        {
            printf("size is exceeded\n");
            write=write->next;
            read->item=value;
            read=read->next;
        }
        write->next=read;
    }
    write->next=read;
}

void dequeue()
{
    int val;
    struct link_list *ptr=read;
    if(read==NULL)
    {
        printf("Stack is empty \n");
    }
    else
    {
        if (p_size>0)
        {
            val=read->item;
            read=read->next;
            free(ptr);
            p_size--;
            printf("removed %d\n",val);
        }
        else
        {
            p_size=0;
            read=write=NULL;
            printf("nothing else to remove\n");
        }
    }
}

void print()
{
    printf("psize= %d\n",p_size);
    struct link_list *ptr=read;
    if (read==NULL)
    {
        printf("nothing in queue\n");return;
    }
    if (p_size==0)
    {
        printf("stack empty\n");
        return;
    }
    else
    {
        while (ptr!=NULL)
        {
            if (ptr!=write)
            {
                printf("Value= %d Aderss= %p Next Address= %p\n", ptr->item,ptr, ptr->next);
                ptr=ptr->next;
            }
            else
            {
                printf("Value= %d Aderss= %p Next Address= %p\n", ptr->item,ptr, ptr->next);
                break;
            }
        }
        printf("read--@Value= %d Aderss= %p Next Address= %p\n", read->item,read, read->next);
        printf("write--@Value= %d Aderss= %p Next Address= %p\n", write->item,write, write->next);

    }
}

void main()
{
    char ch;
    int val;
    int loop=1;
    printf("enter the buffer size---\n");
    scanf("%d",&size);
    while(loop==1)
    {
        printf("select a) to add to queue, b) to dequeue s) sort p) print x)ext\n");
        scanf("%c",&ch);
        switch(ch)
        {
            case 'a':
                enqueue();
                break;
            case 'b':
                dequeue();
                break;
            case 'p':
                print();
                break;
            case 'x':
                loop=0;
                break;
        }
    }
}


texts:
import re

def replace_token_regex(s, token=" "):
    return re.sub(token, '20%', s.strip())

def replace_token_inplace(s, token=" "):

    for index, char in enumerate(s):
        if ord(char) == ord(token):
            s[index] = '20%'
    return s

print replace_spaces_regex("Foo Bar ")
s = list("Foo Bar ")
replace_spaces_inplace(s)
print ''.join(s)

The run time complexity of the above code is \$O(n)\$, can it be further optimized? or is there any better way to do the above computation?


texts: Print a Connect 4 grid based on some rules for each cell

texts:
In a game of Connect4:

we start with an empty grid
two players place pieces X and O on the grid
the first player to achieve 4 pieces in a line wins!
this is a text based console game

Here is the code I wrote to print each cell in the grid:

def asText(grid: Grid) = {

      def asText(x:Int, y:Int) = {

        val isTop = y == 0 && x != grid.x + 1 && x != 0
        val newLine = x == grid.x + 1
        val isBottom = y == grid.y + 1 && x != 0
        val isLeft = x == 0
        val isX = grid.pieces.contains(Piece("X", x,y))
        val isY = grid.pieces.contains(Piece("O", x,y))

        List(isTop, newLine, isBottom, isLeft, isX, isY) match {
          case true::_ => "-"
          case _::true::_ => "|\n"
          case _::_::true::_ => "-"
          case _::_::_::true::_ => "|"
          case _::_::_::_::true::_ => "X"
          case _::_::_::_::_::true::_ => "O"
          case _ => "."
        }
      }

      val v = for {
        y  <- 0 to grid.y + 1
        x  <- 0 to grid.x + 1
        text = asText(x, y)
      } yield text

      v.mkString("")
    }

I don't like this _::_::_::_::_::true::_ but can't think of a way to improve it. Can this style be improved? Is there a more Scala idiomatic style to do this?

Example output:

|------|
|XO....|
|......|
|......|
|......|
|......|
|......|
|......|
|------|

Edit: As requested

case class Piece(symbol:String, x:Int, y:Int)
case class Grid(x:Int = 6, y:Int = 7, pieces:List[Piece] = List())


texts: Optimizing Sieve of Eratosthenes for larger numbers

texts:
I am having difficulty optimizing my code for the Sieve of Eratosthenes. The code works fine for smaller numbers (up to 10,000) but takes a long time to run for numbers over 100,000.

import java.util.Arrays;
import java.util.Scanner;

public class SieveOfErasthostenes {

    static int num = 1;
    static int count = 0;
    int i;
    static int nthPrime;

    public static void main(String[] args) {
        System.out.println("Enter the number of the prime: ");
        Scanner sc = new Scanner(System.in);
        nthPrime = sc.nextInt();
        long start = System.currentTimeMillis();
        boolean[] primes = new boolean[2*nthPrime*(int)Math.log(nthPrime)];
        Arrays.fill(primes,true);
        primes[0]=primes[1]=false;
        for (int i=2;i<Math.sqrt(primes.length);i++) {
            while (count < nthPrime){
                num=num+1; //find the next prime number
                for (i = 2; i <= num; i++){
                    if (num % i == 0) {
                        break; //prime not found
                    }
                }
                if ( i == num){
                    count = count+1; //prime found
                }
            }
        String th;
        if (nthPrime % 10 == 1) {
            th = "st";
        }   else if (nthPrime % 10 == 2) {
            th = "nd";
            }   else if (nthPrime % 10 == 3) {
                th = "rd";
            }   else {
                th = "th";
            }
        long elapsed = System.currentTimeMillis() - start;
        System.out.println("The " + nthPrime + th + " prime number is: " + num);
        System.out.println("Running time: " + elapsed);
        sc.close();
        }
    }
}


texts:
I have the following code which works perfectly fine. I am using the dial pad to set the number and also to send the DTMF tones. But I find the code to bit more repitive. Is there any better way to optimize the code or the approach I have is good enough ?
Thank you in advance for your valuable suggestions. Cheers :)

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button btnZero, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btnAsh, btnHash;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    // Buttons
    btn1 = findViewById(R.id.btnOne);
    btn2 = findViewById(R.id.btnTwo);
    btn3 = findViewById(R.id.btnThree);
    btn4 = findViewById(R.id.btnFour);
    btn5 = findViewById(R.id.btnFive);
    btn6 = findViewById(R.id.btnSix);
    btn7 = findViewById(R.id.btnSeven);
    btn8 = findViewById(R.id.btnEight);
    btn9 = findViewById(R.id.btnNine);
    btnZero = findViewById(R.id.btnZero);
    btnAsh = findViewById(R.id.btnAsterisk);
    btnHash = findViewById(R.id.btnHash);

    dialPadTone();
}

public dialPadTone() {
    btn1.setOnClickListener(this);
    btn2.setOnClickListener(this);
    btn3.setOnClickListener(this);
    btn4.setOnClickListener(this);
    btn5.setOnClickListener(this);
    btn6.setOnClickListener(this);
    btn7.setOnClickListener(this);
    btn8.setOnClickListener(this);
    btn9.setOnClickListener(this);
    btnZero.setOnClickListener(this);
    btnAsh.setOnClickListener(this);
    btnHash.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    // Read current phone dialPadnumber
    String phoneNo = dialPadnumber.getText().toString();
    int value;
    if (btnZero.equals(view)) {
        value = 48;
        phoneNo += btnZero.getText();
    } else if (btn1.equals(view)) {
        value = 49;
        phoneNo += btn1.getText();
    } else if (btn2.equals(view)) {
        value = 50;
        phoneNo += btn2.getText();
    } else if (btn3.equals(view)) {
        value = 51;
        phoneNo += btn3.getText();
    } else if (btn4.equals(view)) {
        value = 52;
        phoneNo += btn4.getText();
    } else if (btn5.equals(view)) {
        value = 53;
        phoneNo += btn5.getText();
    } else if (btn6.equals(view)) {
        value = 54;
        phoneNo += btn6.getText();
    } else if (btn7.equals(view)) {
        value = 55;
        phoneNo += btn7.getText();
    } else if (btn8.equals(view)) {
        value = 56;
        phoneNo += btn8.getText();
    } else if (btn9.equals(view)) {
        value = 57;
        phoneNo += btn9.getText();
    } else if (btnAsh.equals(view)) {
        value = 42;
    } else if (btnHash.equals(view)) {
        value = 35;
    } else {
        throw new IllegalStateException("Unexpected value: " + view.getId());
    }

    setPhoneNum(phoneNo);
    Intent intent = new Intent("send_dtmf_tones");
    Message message = new DTMFtones(
            value
    );
    sendBroadcast(intent);
}
}


texts:
For a school project I have been asked to create a login system for a website. The language I have to use is PHP with no database as of yet (for a later assignment). I'm just wondering if this code has any security flaws.

Here is my current code:

Navigation.php note that this is to be included in another html document.

<link type="text/css" rel="stylesheet" href="style_nav.css">

Index

Test

not-in-use

    <?php
    session_start();

    $_SESSION['last_phage'] = $_SERVER['PHP_SELF'];

    if (empty($_SESSION['user'])) {
        echo '
        <form action="login.php" method="POST">

        Username: <input type="text" name="username">
        Password: <input type="password" name="password">&nbsp;&nbsp;
        <input type="submit" value="Login">

        </form>';
    } else {
        echo 'Welcome! ' . $_SESSION['user'] . '<form action="login.php" method="POST"><input type="submit" value="logout" name="logout"></form>';
    }
    ?>

Login.php

<?php

session_start();

if (isset($_POST['logout'])) {
    session_destroy();
    header("Location: index.php");
}

if (isset($_POST['username']) && isset($_POST['password'])) {
    if (!empty($_POST['username']) && !empty($_POST['password'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];

        if ($username == 'kad' && $password == 'lol') {  //this is just temporary without a database
            $_SESSION['user'] = $username;

            header("Location:" . $_SESSION['last_phage']);
        }

        header("Location: " . $_SESSION['last_phage']);
    }
}
?>


texts: Pipeline processing for a command line interface (CLI) program

texts:
I currently have this code that is controlling my CLI flow:

const FLOW = [
  'Mapping',
  'Extract',
  'Convert',
  'Exports'
].reduce((m, fn) => {
  cli.info(`${fn} phase starting.`);
  let current = extract[fn];

  // Ensure that all my itens inside FLOW are functions
  if (Object.prototype.toString.call(current) !== '[object Function]') {
    cli.error('You have a non-function in your FLOW.');
  }

  let result = new current(m).process(); // Store the new MAP
  cli.info(`${fn} phase ending.`);
  return result;
}, MAP);

I'm working with files, so i'm using sync code.

at each stage I have some code that looks like the other phases:

module.exports = Class NameOfPhase {
   constructor (MAP) {
     this.MAP = MAP || {};
   }

   process () {
    // DO WHAT U NEED AND RETURN
   }
};

And I'm using these lines to print the current phase:

cli.info(`${fn} phase starting.`);
cli.info(`${fn} phase ending.`);

I would like to improve the initializer. I don't want let this lines there. Do you have some suggestions for me? Also, are there any ways to improve the code?


texts: Embedding a Text -> Maybe MyDataType function in a Parser to parse JSON into a custom data type

texts:
I have these types:

data PizzaType = Cheese | Pepperoni | Anchovy

data PizzaOrder = PizzaOrder
    { p_type :: PizzaType
    , p_specialInstructions :: Text
    }

I want to use Aeson to create PizzaOrder instances from this JSON structure:

{
    "type": "pepperoni",
    "specialInstructions": "please cut into nine slices"
}

I have this function to convert from a Text to a PizzaType:

convertPizzaType :: Text -> Maybe PizzaType
convertPizzaType "cheese" = Just Cheese
convertPizzaType "pepperoni" = Just Pepperoni
convertPizzaType "anchovy" = Just Anchovy
convertPizzaType _ = Nothing

(The actual code to convert from a Text to my custom data type is much more involved, but it’s not the main point of my question.) In order to use my convertPizzaType function in the JSON parsing process, I wrote this general function

parseMaybe :: String -> (a -> Maybe b) -> Parser a -> Parser b
parseMaybe err f p = do
    result <- p
    case f result of
      Nothing -> fail err
      Just x -> pure x

which I use like this:

instance FromJSON PizzaOrder where
    parseJSON (Object v) = PizzaOrder <$>
        parseMaybe "Unknown pizza type" convertPizzaType (v .: "type") <*>
        v .: "specialInstructions"
    parseJSON _  = mzero

My question involves my parseMaybe function. It takes the raw input from Aeson, runs the given conversion function, and aborts the parsing if Nothing was returned. This seems to work but I have the sneaking suspicion that I’m reinventing a wheel. Is this a reasonable way to embed my convertPizzaType function in a Parser or should I be doing something simpler?

Complete runnable example

#!/usr/bin/env stack
-- stack --resolver lts-3.14 --install-ghc runghc --package aeson

{-# LANGUAGE OverloadedStrings #-}

import Control.Monad (mzero)
import Data.Aeson
import Data.Aeson.Types (Parser)
import Data.Text (Text)

data PizzaType = Cheese | Pepperoni | Anchovy deriving (Show)

data PizzaOrder = PizzaOrder
    { p_type :: PizzaType
    , p_specialInstructions :: Text
    }

instance FromJSON PizzaOrder where
    parseJSON (Object v) = PizzaOrder <$>
        parseMaybe "Unknown pizza type" convertPizzaType (v .: "type") <*>
        v .: "specialInstructions"
    parseJSON _  = mzero

parseMaybe :: String -> (a -> Maybe b) -> Parser a -> Parser b
parseMaybe err f p = do
    result <- p
    case f result of
      Nothing -> fail err
      Just x -> pure x

convertPizzaType :: Text -> Maybe PizzaType
convertPizzaType "cheese" = Just Cheese
convertPizzaType "pepperoni" = Just Pepperoni
convertPizzaType "anchovy" = Just Anchovy
convertPizzaType _ = Nothing

main :: IO ()
main = do
    let example1 = "{\"type\": \"pepperoni\", \"specialInstructions\": \"none\"}"
        parsedExample1 = decode example1 :: Maybe PizzaOrder
    case parsedExample1 of
      Nothing -> putStrLn "Example 1 couldn't be parsed"
      Just o -> putStrLn $ "The type of example 1 was " ++ (show $ p_type o)

    let example2 = "{\"type\": \"broccoli\", \"specialInstructions\": \"EXTRA BROCCOLI\"}"
        parsedExample2 = decode example2 :: Maybe PizzaOrder
    case parsedExample2 of
      Nothing -> putStrLn "Example 2 couldn't be parsed"
      Just o -> putStrLn $ "The type of example 2 was " ++ (show $ p_type o)


texts: Thread-safe game engine: multi-threading best practices?

texts:
I'm writing a multithreaded game engine, and I'm wondering about best practices around waiting for threads. It occurs to me that there could be much better options out there than what I've implemented, so I'm wondering what you think.

wait() method gets called at the top of every other method in the class. This is my current implementation, and I'm realizing it's not ideal.

class Texture {
public:
    Texture(const char *filename, bool async = true);
    ~Texture();

    void Render();

private:
    SDL_Thread *thread;
    const char *filename;

    void wait();
    static int load(void *data);
}

void Texture::wait() {
    if (thread != NULL) {
        SDL_WaitThread(thread, NULL);
        thread = NULL;
    }
}

int Texture::load(void *data) {
    Texture *self = static_cast<Texture *>(data);

    // Load the Image Data in the Thread Here...

    return 0;
}

Texture::Texture(const char *filename, bool async) {
    this->filename = filename;
    if (async) {
        thread = SDL_CreateThread(load, NULL, this);
    } else {
        thread = NULL;
        load(this);
    }
}

Texture::~Texture() {
    // Unload the Thread and Texture Here
}

void Texture::Render() {
    wait();

    // Render the Texture Here
}

Convert the wait() method in to a function pointer. This would save my program from a jmp at the top of every other method, and simply check for thread != NULL at the top of every method. Still not ideal, but I feel like the fewer jumps, the better. (I've also considered just using the inline keyword on the function... but would this include the entire contents of the wait function when all I really need is the if (thread != NULL) check to determine whether the rest of the code should be executed or not?)
Convert all of the class' methods in to function pointers, and ditch the whole concept of calling wait() except while actually loading the texture. I see advantages and disadvantages to this approach... namely, this feels the most difficult to implement and keep track of. Admittedly, my knowledge of the inner workings on GCC's optimizations and assembly and especially memory->cpu->memory communication isn't the best, so using a bunch of function pointers might actually be slower than a properly defined class.

Anyone have any even better ideas?


texts:
Link to original question: Successful use of strtol() in C

After getting excellent feedback from the code review community I attempted to redo my string to long conversion program! I believe I enhanced it significantly(Most ideas from answers on my last post) but I did add my own 'style' to it and am looking to see if I missed anything or need to change the way I implemented the solution.

#include "stdafx.h"
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
#include <stdlib.h>

#define MAXLENGTH 1024

bool readline(char** buf, const size_t buf_len);
char* str_to_long(const char* const buf, long* out);
void str_cmp(char* str);

int main() {
    char* str = malloc(sizeof(char) * MAXLENGTH);
    long cnvt_numb = 0;
    printf("Enter a number: ");
    while (!readline(&str, MAXLENGTH)) {
        printf("Try again...\n");
    }
    char* err = str_to_long(str, &cnvt_numb);
    if (err == NULL) {
        if (cnvt_numb == LONG_MAX) {
            fprintf(stderr, "INPUT OUT OF RANGE...\n");
        }
        else {
            printf("Your number was: %ld\n", cnvt_numb);
        }
    }
    else {
        fprintf(stderr, "That number '%s' was not convertable...\n", err);
    }

    free(str);

    printf("Press any key to continue...\n");
    getch();
    return EXIT_SUCCESS;
}

bool readline(char** buf, const size_t buf_len) {
    if ((fgets(*buf, buf_len, stdin)) != NULL) {
        str_cmp(*buf);
        return true;
    }
    return false;
}

void str_cmp(char* str) {
    if ((strchr(str, '\n')) != NULL) {
        str[strcspn(str, "\n")] = 0;
    }
}

//if returns anything other than NULL, conversion failed
char* str_to_long(const char* const str, long* out) {
    char* end = NULL;
    long number = strtol(str, &end, 10);
    if ((!*end) && (end != str)) {
        *out = number;
        end = NULL;
    }
    return end;
}


texts: Partial Maven clean install after Git pull

texts:
I had searched for a solution to mvn clean install on my changed projects after a git pull. I even asked a question over at SO about the same thing. The answer I got pointed me into creating my own script to achieve what I wanted to accomplish. So I went, I saw, and I conquered the script that I wanted. However, it is probably not efficient, and could use refactoring. I am new to bash scripting and learned a bit while doing this.

The structure I was targeting is a Maven POM Project. That project contains several sub-POM Projects, which in turn contain Maven Java Projects.

Example Structure:

-Parent
|-Sub_Parent_A
 |-Child_1
 |-Child_2
|-Sub_Parent_B
 |-Child_3
 |-Child_4

I wanted to only call mvn clean install if a project had files that changed in the child projects. This would reduce time on going to each project by hand and calling the command or by just calling the command on the parent project.

The code, along with revisions, can also be found on GitHub

################################################################################
#
# License:.....GNU General Public License v3.0
# Author:......CodeMonkey
# Date:........14 November 2018
# Title:.......GitMavenCleanInstall.sh
# Description: This script is designed to cd to a set Maven POM Project,
#   perform a git remote update and pull, and clean install the changed
#   files projects.
# Notice:......The project structure this script was originally set to target
#   is structured as a Maven POM Project that contains several sub-POM Projects.
#   The sub-POM Projects contain Maven Java Application projects. The targets
#   should be easy to change, and allow for others to target other structures.
#
################################################################################
#
# Change History: N/A
#
################################################################################

#!/bin/bash
#Function to check if array has element
containsElement () {
    local e match="$1"
    shift
    for e; do [[ "$e" == "$match" ]] && return 0; done
    return 1
}

#Navigate to the POM Project
cd PATH/TO/POM/PROJECT
#Remote update
git remote update -p
#Pull
git pull

#Get the current working branch
CURRENT_BRANCH="$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')"
#Get the output of the command git diff
GIT_DIFF_OUTPUT="$(git diff --name-status HEAD@{1} ${CURRENT_BRANCH})"

#Split the diff output into an array
read -a GIT_DIFF_OUTPUT_ARY <<< $GIT_DIF_OUTPUT
#Declare empty array for root path
declare -a GIT_DIFF_OUTPUT_ARY_ROOT_PATH=()
FORWARD='/'
#Loop diff output array
for i in "${GIT_DIFF_OUTPUT_ARY[@]}"
do
    #Check that the string is not 1 Character
    if [[ "$(echo -n $1 | wc -m)" != 1 ]]
    then
        #Split the file path by /
        IFS='/' read -ra SPLIT <<< $i
        #Concatenate first path + / + second path
        path=${SPLIT[0]}$FORWARD${SPLIT[1]}
        #Call function to see if it already exists in the root path array
        containsElement "$path" "${GIT_DIFF_OUTPUT_ARY_ROOT_PATH[@]}"
        if [[ $? != 0 ]]
        then
            #Add the path since it was not found
            GIT_DIFF_OUTPUT_ARY_ROOT_PATH+=($path)
        fi
    fi
done

#Loop root path array
for val in ${GIT_DIFF_OUTPUT_ARY_ROOT_PATH[@]}
do
    #CD into root path
    cd $val
    #Maven call to clean install
    mvn -DskipTests=true --errors -T 8 -e clean install
    #CD back up before next project
    cd ../../
done


texts:
This is completely optimization question, I have a pagination query like this:

$this->paginate    = array(
        'fields'    =>  array(
                        'DISTINCT Contact.contact_id',
                        'Contact.first_name',
                        'Contact.last_name',
                        'Contact.email',
                        'Contact.created',
                        'ContactGroup.name',
                      ),
        'conditions' => array(
                        $this->conditions,
                        'ContactsContactGroup.contact_group_id'=>$viewList,
                        isset($keywordQuery)?$keywordQuery:"",
                      ),
        'limit'      => 5,
         'group'     => array('Contact.contact_id')
                      );
$data = $this->paginate('ContactsContactGroup');
$data = $this->paginate('ContactsContactGroup');

This query is called in every if and else statement, I have four conditions of if and else, and in all conditions the above piece of code is written.

I want to optimize, and avoid the big line of code in every condition. How can I optimize it? Any answer will be appreciated.


texts: Coding convention when using differential inheritance

texts:
Ever since reading Crockford's "Good Parts" and Johansen's TDD book, I have wanted to use more of the differential inheritance pattern in my coding at work (as in avoiding new by using Object.create()), but I find that I am having a hard time argumenting for the clearness of the code when trying to make "types" that can be used for object creation. Most of my co-workers are "classically" inclined.

I guess this question somehow boils down to these points

downcasing/UpperCasing (i.e. "car" vs "Car")
prefixing the base instances (i.e "prototypeCar"). This practice is for instance seen in the code of the author of Fluent Javascript
init() methods VS factory methods.

// init style
car.init = function(brand) {
    this.brand = brand;
}
myCar = Object.create(car).init("Nissan");

// versus

// factory method
function createCar(brand) {
    var o = Object.create(car);
    o.brand = brand;
    return o;
}

// alternative factory method
function createCar(brand) {
    var o = Object.create(car, { brand : brand } )
    return o;
}

myCar = createCar("nissan")

My problem with having lower cased car types is that for someone glancing over parts of the code, they might think that car is an instance of some kind of 'class' Car, and get confused when I suddenly start creating new instances from it. In my opinion, the notion of using a prefix, such as "prototype", seems to more clearly state my intentions with the instance. So do saying Car, but that implies that it should be used together with new, so one should perhaps refrain from that ... (?)


texts:
I'm trying to migrate from JavaScript to CoffeeScript. However I'm not sure about the best way to optimize the code generated by js2coffee.

Below is the original JavaScript source :

var async = require('async');

var context = {};
context.settings = require('./settings');

async.series([setupDb, setupApp, listen], ready);

function setupDb(callback)
{
  context.db = require('./db.js');
  context.db.init(context, callback);
}

function setupApp(callback)
{
  context.app = require('./app.js');
  context.app.init(context, callback);
}

// Ready to roll - start listening for connections
function listen(callback)
{
  context.app.listen(context.settings.http.port);
  callback(null);
}

function ready(err)
{
  if (err)
  {
    throw err;
  }
  console.log("Ready and listening at http://localhost:" + context.settings.http.port);
}

And below is the generated CoffeeScript :

setupDb = (callback) ->

  # Create our database object
  context.db = require("./db")

  # Set up the database connection, create context.db.posts object
  context.db.init context, callback
setupApp = (callback) ->

  # Create the Express app object and load our routes
  context.app = require("./app")
  context.app.init context, callback

# Ready to roll - start listening for connections
listen = (callback) ->
  context.app.listen context.settings.http.port
  callback null
ready = (err) ->
  throw err  if err
  console.log "Ready and listening at http://localhost:" + context.settings.http.port
async = require("async")
context = {}
context.settings = require("./settings")
async.series [setupDb, setupApp, listen], ready

Now, I'm not sure if the context variable is required in CoffeeScript. In the JavaScript source its function is to share the common set of setting across the various components of the application such as database and the settings. Will a proper use of the => operator in CoffeeScript help ? If yes how ?


texts:
I have implemented a simple client-server solution using Java sockets and useful classes from java.util.concurrent.

The communication protocol is rather simple:

Client sends a string with the appended request_info#.
A server responds to a client with the message that provides a description on how to use a server.
If client sends server_time then a server will send back a current server time.
If client sends a quit - a server will process a client disconnect.
A default case: client sends an arbitrary string then a server simply bounces it back to a client.

I have tested my solution by spawning a fixed number of client threads. Each of them sends a command from a txt file to a server.

Some technical remarks:

A configuration for the client and server (such as port number and host address) is loaded from an .xml file.
To start a server: java –jar app.jar –server –config config.xml.
To start a client: java –jar app.jar –client –config config.xml.

I would like to seek any suggestions on whether I have correctly implemented the following class (serves as an abstraction for a message between client and server):

public class Message {
    private Socket socket;
    private String message;
    private static Logger logger = Logger.getLogger(Message.class);

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public String getMessage() {
        return message;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setStringMessage(String message) {
        this.message = message;
    }

    public void setMessageInputSources(InputStream inputStream) throws IOException {
        String s;
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(inputStream));
        s = bufferRead.readLine();
        this.message = s;
    }

    public synchronized String getCommand() {
        String stringMessage = this.getMessage();
        return StringUtils.upperCase(stringMessage.split("#")[0]);
    }

    public void send(String message) throws IOException{
        DataOutputStream dataOutputStream = new DataOutputStream(this.socket.getOutputStream());
        dataOutputStream.writeUTF(message);
        dataOutputStream.flush();

        this.setStringMessage(message);
    }

    public Message receive() throws IOException {
        String data;
        DataInputStream dataInputStream = new DataInputStream(this.socket.getInputStream());
        data = dataInputStream.readUTF();
        this.setStringMessage(data);
        return this;
    }

    @Override
    public String toString() {
        return this.message;
    }
}

Do I properly manage a case when all client threads are done with their jobs and I shut down an application? Are there any improvements to be made?

public class MainTest {

    private static final int NUMBER_OF_THREADS = 4;

        public static void main(String[] args) throws IOException, InterruptedException {
            CountDownLatch countDownLatch = new CountDownLatch(NUMBER_OF_THREADS);

            Thread serverThread = new Thread(() -> Server.start(new File("config.xml"), countDownLatch));
            serverThread.setName("server_thread");

            Thread clientThread = new Thread(() -> {
                try {
                    new Client(new File("config.xml"), new FileInputStream("commands.txt")).start(NUMBER_OF_THREADS, countDownLatch);

                } catch (ExecutionException | IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            });
            clientThread.setName("Running client threads, " + 10);
            serverThread.start();
            clientThread.start();
            if(countDownLatch.getCount() == 0){
                System.exit(0);
            }
        }
    }

Here is the link to my project: GitHub Repository


texts: Custom setInterval to run function synchronously

texts:
This customSetInterval function makes sure that the function inside it is executed synchronously. It also gives that function the ability to determine run or stop the timer. The object returned by customSetInterval has stop function to stop the timer explicitly, later it could have more properties related to the timer status if needed.

What do you think about this function? Are there any possible problems? I am concerned whether it could cause any memory leak issue.

This is my customSetInterval function:

function customSetInterval(func, interval, data, handler = {
  timerId: null,
  stop() {
    return clearTimeout(this.timerId);
  }
}) {
  const isContinue = func(data);

  if (isContinue) {
    handler.timerId = setTimeout(
        customSetInterval,
        interval,
        func,
        interval,
        data,
        handler
    );
  }

  return handler;
}


texts:
The "Images" exercise in A Tour of Go asks for an implementation of image.Image.  I wrote two solutions, one easy and one harder (just for practice in dealing with interfaces).

SOLUTION 1: (HARD WAY)

package main

import (
    "golang.org/x/tour/pic"
    "image"
    "image/color"
)

type Image struct{
    // one array for x value, one array for y values, array of integer for pixel RGBA values
    image_ [][][]uint8
    x0, y0, x1, y1 int
}

func (i *Image) NewImage(x, y int) *Image {
    image := make([][][]uint8, y)
    for i := 0; i < x; i++ {
        image[i] = make([][]uint8, x)
        for j := 0; j < y; j++ {
            image[i][j] = make([]uint8, 4)
        }
    }
    return &Image{image, 0, 0, x, y}
}

func (p *Image) ColorModel() color.Model { return color.RGBAModel }

func (p *Image) At(x, y int) color.Color {
    var c color.Color
    rgba := color.RGBA{
        p.image_[x][y][0],
        p.image_[x][y][1],
        p.image_[x][y][2],
        p.image_[x][y][3],
    }
    c = rgba
    return c
}

func (p *Image) Bounds() image.Rectangle {
    rectangle := image.Rect(p.x0, p.y0, p.x1, p.y1)
    return rectangle
}

func (p *Image) crazyColors() *Image {
    for i := 0; i < len(p.image_) - 1; i++ {
        for j := 0; j < len(p.image_[i]) - 1; j++ {
            p.image_[i][j][0] = uint8(i + j / 2)
            p.image_[i][j][1] = uint8(i + j * 2)
            p.image_[i][j][2] = uint8(i + j * 2)
            p.image_[i][j][3] = uint8(255)
        }
    }
    return p
}

func main() {
    var i *Image
    i = i.NewImage(255, 255)
    i.crazyColors()
    pic.ShowImage(i)
}

SOLUTION 2: (EASY WAY)

package main

import (
    "golang.org/x/tour/pic"
    "image"
)

type Image struct{
    image.RGBA
}

func (i Image) crazyColors() Image {
    for p := 0; p < len(i.Pix); p += 4 {
        i.Pix[p] = uint8(p + p*2)
        i.Pix[p+1] = uint8(p + p*2)
        i.Pix[p+2] = uint8(p + p*2)
        i.Pix[p+3] = uint8(p + p*2)
    }
    return i
}

func main() {
    rect := image.Rect(0,0,255,255)
    m := Image{*image.NewRGBA(rect)}
    m.crazyColors()
    pic.ShowImage(&m)
}


texts:
I created this program originally for Project Euler 14.

Here's the code:

from sys import setrecursionlimit
setrecursionlimit(10 ** 9)

def memo(f):
    f.cache = {}

    def _f(*args):
        if args not in f.cache:
            f.cache[args] = f(*args)
        return f.cache[args]

    return _f

@memo
def collatz(n):
    if n == 1:
        return 1

    if n % 2:
        print(3 * n + 1)
        return 1 + collatz(3 * n + 1)

    if not n % 2:
        print(n // 2)
        return 1 + collatz(n // 2)

if __name__ == '__main__':
    number = None

    while True:
        try:
            number = input('Please enter a number: ')
            number = int(number)
            break

        except ValueError:
            print(f'Value has to be an interger instead of "{number}"\n')

    print('\nThe collatz sequence: ')

    length = collatz(number)

    print(f'\nLength of the collatz sequence for {number}: {length}')

I would like to make this faster and neater if possible.