texts:
import socket,time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',0))
port=s.getsockname()[1]
s.setblocking(0)
lines=[]
while True:
    try:
        data, addr = s.recvfrom(1024)
        if addr not in clients:
            clients.append(addr)

        if not lines:
            for client in clients:
                s.sendto(lines, client)
    except:
        pass
s.close()

I have paint application, in which the server sends the co-ordinates to a set of clients. I use the above code for sending, launching on a separate thread. This sends data to each client sequentially. This will cause a delay to the clients at the end of the list. Launching a separate thread for each client has scalability issues. Is there is scalabe way to write the above code maybe using async.io?


texts: Finding which items have at least one common value with other items

texts:
I have the following collection :

var items = new[]
{
    new { Name = "A", Values = new [] { 20, 4, 5, 9, 3, 22 } },
    new { Name = "B", Values = new [] { 10, 7, 9, 8, 42 } },
    new { Name = "C", Values = new [] { 11, 103, 0 } },
    new { Name = "D", Values = new [] { 7, 35, 42 } }
};

I would like to find which items have at least one common integer value with the others items. For example, "A" has 9 in common with "B", so "A" and "B" are related each other.

At the end, this should be the result :

A => [B]
B => [A, D]
C => []
D => [B]

I wrote this code :

var tuples = items
    .SelectMany(x => x.Values, (x, y) => new { x.Name, Value = y })
    .ToList();

var result = tuples.Join(tuples,
           x => x.Value,
           x => x.Value,
           (x, y) => new { NameA = x.Name, NameB = y.Name })
    .Distinct()
    .GroupBy(x => x.NameA, x => x.NameB,
        (a, b) => new { Name = a, Overlaps = b.Where(x => x != a)) });

It works (and return expected results). I was wondering if there would be a more efficient (faster and with a lower memory footprint) way do to it. I wanted to use GroupJoin() but since I need to filter out duplicate values (using Distinct) I used Join() instead.


texts: Matrix multiplication with OpenMP parallel for loop

texts:
I tried implementing matrix multiplication with parallel for loop in OpenMP as follows. It runs correctly but I want to make sure if I'm missing anything. How does this determine the number of threads to run?

Matrix is a class for square matrices.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
# include <omp.h>

Matrix parallel_mat_mul(Matrix a, Matrix b)
{
    int n =a.getSize();
    Matrix c(n);
    clock_t begin_time = clock();
    # pragma omp parallel shared ( a, b, c, n  ) // private ( i, j, k )
    {
        # pragma omp for
        for ( int i = 0; i < n; i++ )
        {
            for (int j = 0; j < n; j++ )
            {
                double local_sum=0;
                for ( int k = 0; k < n; k++ )
                {
                    local_sum+= (a(i,k)*b(k,j));
                }
                c(i,j)=local_sum;
            }
        }

    }
    cout << "Parallel time: "<<float( clock () - begin_time ) / CLOCKS_PER_SEC  <<"\n";
    return c;
}


texts:
Here's my android splash screen. I am trying to figure out a better way to write it. It just moves the logo up to the center of the screen. It's my third time creating a splash screen for an android app. I am just trying to figure out the best way to write more optimized code.

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

final public class Splash extends AppCompatActivity {
    private final static int timeout = 3000;
    final static Handler handler = new Handler();
    static ImageView logo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        logo = findViewById(R.id.companylogo);
        Animation animation = AnimationUtils.loadAnimation(Splash.this, R.anim.myanim);
        logo.startAnimation(animation);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent splashscreen = new Intent(Splash.this, Home.class);
                startActivity(splashscreen);
            }

        }, timeout);

    }

}


texts:
I have a function which gets called very often, for this test 30,720,000 times. It has to run in real-time, so performance is very important. Are there possible improvements?

// This function looks up in the vertice table wheter a vertice at that position already exists
// - If yes, return the vertice index
// - If no, create a new vertice and return the created vertice index
//
// @param cfg: Pointer to a chunkConfig struct
// @param x: x position of the vertice
// @param y: y position of the vertice
inline VERTICE_INDEX GetOrCreateVertice(float x, float y, ChunkGenerator::chunkConfig *cfg)
{
    int x_pos = int((x*POSARR_ADJ_F) + 0.5f);
    int y_pos = int((y*POSARR_ADJ_F) + 0.5f);

    int dict_index = x_pos + (y_pos * cfg->subdivisions_adj);

    VERTICE_INDEX dict_entry = cfg->vertice_pool.vertice_dict[dict_index];
    VERTICE_INDEX current_index = cfg->vertice_pool.current_vertice_index;

    if (dict_entry >= 0 && dict_entry < 65535 && current_index > 0)
        return dict_entry;

    LVecBase3f* offset      = cfg->base_position;
    LVecBase2f* dim         = cfg->dimensions;
    LVecBase2f* tex_offset  = cfg->texture_offset;
    LVecBase2f* tex_scale   = cfg->texture_scale;

    int pool_index = ((int)current_index) * 5;

    float base_scale = 1.0 / (cfg->subdivisions_f-1.0);
    float x_scaled = x * base_scale;
    float y_scaled = y * base_scale;

    cfg->vertice_pool.vertice_array[pool_index+0] = offset->get_x() + (x_scaled * dim->get_x());
    cfg->vertice_pool.vertice_array[pool_index+1] = offset->get_y() + (y_scaled * dim->get_y());
    cfg->vertice_pool.vertice_array[pool_index+2] = offset->get_z();
    cfg->vertice_pool.vertice_array[pool_index+3] = tex_offset->get_x() + (x_scaled * tex_scale->get_x());
    cfg->vertice_pool.vertice_array[pool_index+4] = tex_offset->get_y() + (y_scaled * tex_scale->get_y());

    cfg->vertice_pool.vertice_dict[dict_index] = current_index;
    cfg->vertice_pool.current_vertice_index++;
    return current_index;
}

LVecBase3f and LVecBase2f are vector-types provided by the graphics-engine I use. VERTICE_INDEX is a unsigned short, POSARR_ADJ and POSARR_ADJ_F is constant 2.

This is the chunkConfig struct:

struct chunkConfig {
    int subdivisions;
    int subdivisions_adj;
    float subdivisions_f;
    LVecBase3f *base_position;
    LVecBase2f *dimensions;
    LVecBase2f *texture_offset;
    LVecBase2f *texture_scale;
    verticePool vertice_pool;
};

struct verticePool {
    VERTICE_INDEX current_vertice_index;
    VERTICE_INDEX current_primitive_index;
    VERTICE_INDEX * vertice_dict;
    float *vertice_array;
    VERTICE_INDEX *primitive_array;
};

Performance result measured by very-sleepy: link

Version based on the suggestions made in the comments: very-sleepy, AMD CodeAnalyst, and the assembler for the slow-line: generated assembler,
I also made some arrays global, and renamed "vertice" to "vertex".


texts:
I'm trying to make a program which prints different sized grids (n by n grids).
These grids cannot have the same number in any column or row (like a Sudoku).
My bruteSolve() method runs through every combination and then isValid() checks if the rows and columns add up & multiply up to a certain number too - if they do, then the program prints the grid.

However, this program takes too long and I want one where I could do say, 10 * 10 grids fairly quickly. How would I be able to change the code so it does it much faster?

import java.util.ArrayList;
import java.util.Arrays;

public class MagicSquareSolver2 {

static ArrayList<Integer> numbers;

static int n;

static int [] [] grid;

static int count;

public static void main (String [] args){

    n = 4;

    grid = new int [n] [n] ;

    bruteSolve(0,0,n);
}

public static void bruteSolve(int a, int b, int n){

    for  (int i=1; i<n+1; i++){
        grid [a][b] = i;
        if (b==n-1 && a==n-1){
            if (isValid(grid)){count++;
            System.out.println(Arrays.deepToString(grid));System.out.println(count);
        }
        }
        else if (b==n-1){
            bruteSolve(a+1,0,n);
        }
        else{
            bruteSolve(a, b+1,n);
        }
    }

}

public static boolean isValid (int [] [] grid) {

    int factorial = 1;
    int fibonacci = 0;
    int totalX1 = 1;
    int totalY1 = 1;
    int totalX2 = 0;
    int totalY2 = 0;

    for (int i=n; i>0; i--){
        factorial = factorial * i;
    }

    for (int i=n; i>0; i--){
        fibonacci = fibonacci +i;
    }

    for (int i=0; i<n; i++){
        for (int j=0; j<n; j++){
            totalY1= totalY1 * grid[i][j]; //checks all columns
            totalX1= totalX1 * grid[j][i]; // checks all rows
            totalX2 = totalX2 + grid[j][i];
            totalY2 = totalY2 + grid[i][j];
        }
        if (totalX1 != factorial || totalY1 != factorial || totalX2 != fibonacci || totalY2 != fibonacci) { return false; }
        totalX1 = 1;
        totalY1 = 1;
        totalX2 = 0;
        totalY2 = 0;
    }

    return true;

}

}


texts: Python3 - merge sort, O(n) space efficiency

texts:
Any critique of my implementation of Merge sort would be much appreciated!  I tested it using a driver function (shown below), and everything works.  However, it still feels unwieldy, I am a beginner so I really want to hear any criticisms, constructive or not :)
def inplace_merge_sort( lst, start = 0 , end = None ):
  def inplace_merge( lst1_start, lst1_end , lst2_start, lst2_end ): #needs to take in two sets of unsorted indices
    start, end = lst1_start, lst2_end
    for _ in range( (end - start) ):
      if(lst[lst1_start] < lst[lst2_start]):
        lst1_start += 1

      else:
        lst.insert(lst1_start , lst[lst2_start])
        del lst[lst2_start + 1]
        lst1_start += 1
        lst2_start += 1

      if( lst1_start == lst2_start or lst2_start == lst2_end):
        break

    return start, end #returns indices of sorted newly sublist

  if( len(lst) == 1 or len(lst) == 0): #catches edge cases
    return lst

  if end is None: end = len(lst) #so I don't have to input parameters on first call

  length_sublist = end - start

  if( length_sublist > 1):
    start1, end1 = inplace_merge_sort( lst, start, (end + start) // 2  )
    start2, end2 = inplace_merge_sort( lst, (end + start) // 2 , end  )

    return inplace_merge(start1, end1, start2, end2)

  else:
    return start, end

Here is the test function
def inplace_driver_helper(f_n):
  def modified_list_returner( lst ):
    f_n(lst)
    return lst
  return modified_list_returner

def driver(f_n):
  # NICK I added these two test cases to catch some popular edge cases.
    assert f_n([]) == []
    assert f_n([4]) == [4]

    assert f_n([1,2,3]) == [1,2,3]

    assert f_n([3,2,1]) == [1,2,3]

    assert f_n([1,2,3,1,2,3]) == [1,1,2,2,3,3]

    assert f_n([1,2,3,1,1,2,3]) == [1,1,1,2,2,3,3]

    assert f_n([-1,0,46,2,3,1,2,3]) == [-1,0,1,2,2,3,3,46]

and when we run this,
if __name__ == '__main__':
    driver(inplace_driver_helper(inplace_merge_sort))

    print('done')

The output is 'done'!


texts: Moves box in direction of touch, and has wraparound when reaching edge of screen

texts:
Part of me thinks that it would be simpler to ditch Apple's move API and just updated position with a timer. I know that's what I did with a JS canvas snake game I built a while ago. But I'm also trying to learn the iOS API so unless that's clearly the best choice I'd prefer the most idiomatic way.

Also, I'm pretty sure that technically this could overflow but it seems almost impossibly unlikely unless that were someone's goal.

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */
    snakeHead.removeAllActions()
    var actionMove = SKAction()
    if notYetTouched {
        introLabel.removeFromParent()
        notYetTouched = false
        actionMove = SKAction.moveByX(CGFloat(self.size.width / 2), y: 0, duration: 1)
    } else {
        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)
            actionMove = SKAction.moveBy(CGVector(dx: location.x - snakeHead.position.x , dy: location.y - snakeHead.position.y), duration: 1)
        }
    }
snakeHead.runAction(
  SKAction.repeatActionForever(
    SKAction.sequence( [ SKAction.runBlock({ self.wraparound(actionMove) }), actionMove]) ) )
}

func wraparound(defaultAction: SKAction) -> SKAction? {

    if snakeHead.position.y > size.height  {
        snakeHead.removeAllActions()
        let repositionSnakeHeadAction = SKAction.moveToY(1, duration:0)

        snakeHead.runAction( SKAction.sequence( [ repositionSnakeHeadAction, SKAction.repeatActionForever(SKAction.sequence([SKAction.runBlock({ wraparound(defaultAction) }), defaultAction]))] ) )
    } else if snakeHead.position.y < 1 {
        snakeHead.removeAllActions()
        let repositionSnakeHeadAction = SKAction.moveToY(size.height - 1, duration: NSTimeInterval(0))

        snakeHead.runAction( SKAction.sequence( [ repositionSnakeHeadAction, SKAction.repeatActionForever(SKAction.sequence([SKAction.runBlock({ wraparound(defaultAction) }), defaultAction]))] ) )
    } else if snakeHead.position.x > size.width  {
        snakeHead.removeAllActions()
        let repositionSnakeHeadAction = SKAction.moveToX(1, duration: NSTimeInterval(0))

        snakeHead.runAction( SKAction.sequence( [ repositionSnakeHeadAction, SKAction.repeatActionForever(SKAction.sequence([SKAction.runBlock({ wraparound(defaultAction) }), defaultAction]))] ) )
    } else if snakeHead.position.x < 1 {
        snakeHead.removeAllActions()
        let repositionSnakeHeadAction = SKAction.moveToX(size.width, duration: NSTimeInterval(0))

        snakeHead.runAction( SKAction.sequence( [ repositionSnakeHeadAction, SKAction.repeatActionForever(SKAction.sequence([SKAction.runBlock({ wraparound(defaultAction) }), defaultAction]))] ) )
    } else {
        return defaultAction
    }
    return nil
}


texts:
I have image files consisting of black and white pixels encoded as RGB8. I want to count the number of blobs i.e. contiguous areas of white pixels. I rewrote this algorithm in haskell.
The algorithm works as follows: The image is traversed and whenever a white pixel is encountered the counter is incremented and all accessible pixels are set to black(so they don't get counted again).

import System.Environment
import Codec.Picture
import Codec.Picture.Types
import Data.Vector.Storable ( (!),  (//), Vector, toList )
import GHC.Word

main = do
  args <- getArgs
  Right im <- readPng (head args)
  let imgRGB8 = (\(ImageRGB8 t) -> t) im
  let imgGray = pixelMap computeLuma imgRGB8
  let w = imageWidth  imgGray
  let h = imageHeight imgGray
  let imVec = imageData imgGray
  let coords = [0..(w*h -1)]
  print (loop w h imVec coords 0)

type I = Data.Vector.Storable.Vector GHC.Word.Word8

loop :: Int -> Int -> I -> [Int] -> Int -> Int
loop _ _ _     []     blobCount = blobCount
loop w h image (c:cs) blobCount = if (image ! c) == 255 then loop w h (deleteBlob w h image c) cs (blobCount+1)
                                   else loop w h image cs blobCount

deleteBlob :: Int -> Int -> I -> Int -> I
deleteBlob w h image c | image ! c == 255 = foldl (deleteBlob w h) (image // [(c, 0)]) coords
                       | otherwise        = image
                       where
                          coords = environment w h c

environment w h i = takeWhile (< w*h) $ dropWhile (<0) [i-w-1, i-w, i-w+1
{- in a vector image the row above is -}               ,i  -1,      i  +1
{- imageWidth apart. perks: easy clipping -}           ,i+w-1, i+w, i+w+1]

My main concern is that my haskell version is so much slower than my python version.
Second concern is am I loading the images right? Should I have used a more recent library? This is the only way I could make it work.
Thirdly, is this how a haskeller would write a blob count?


texts: How to make business logic code maintainable when working with multiple states?

texts:
I am developing a UI Application for a very simple phone app, the UI is based entirely on the state of Call in a container provided to me by a third party library.

Below is a sample Call object that I am working with;

public class Call {
    private boolean isTannoyCall;
    private long callStart;
    private int callId;
    private int callState;
    private CallDirection mCallDirection = CallDirection.OUTGOING;
    private int mediaStatus;
    private boolean mediaHasVideoStream;
    private long connectStart;
        private int lastStatusCode;
        private boolean callIsMuted;
        private boolean callIsInConference;

    //removed getters and setters
}

A populated call object is then passed around my application, in various places I have to carry out business logic to check if I should be carrying out an action etc. Below is an example of an event listener method for new calls within the app.

public void update() {
    int activeCallCount = 0;
    int incomingCallCount = 0;

    for (Call call : container.getCalls()) {

        boolean isIncomingDirection = call.getCallDirection() == CallDirection.INCOMING;

        boolean isIncomingCall = isIncomingDirection
                && call.getCallState() == CallState.INCOMING && !call.isTannoyCall();

        boolean isActiveCall = call.isActive()
                && call.getCallState() != call.InvState.INCOMING && !call.isTannoyCall();

        if (isIncomingCall) {
            incomingCallCount++;
        } else if (isActiveCall) {
            activeCallCount++;
        }

        boolean isMissedCall = isIncomingDirection
                && call.getCallState() == call.InvState.DISCONNECTED
                && call.getCallStart() == 0
                && !call.isTannoyCall();

        if (isMissedCall) {
            missedCallManager.increment();
        }
    }
    incomingCallUpdate(incomingCallCount);
    activeCallUpdate(activeCallCount);
}

In areas of the application where I need to do a lot of boolean based checks, like sample 1. How can I do this whilst keeping the code maintainable?  As every time I need to add a new condition (e.g. the latest "don't update if tannoy call"), I have to modify the appropriate if statements.


texts:
This simple JavaScript code styles all file inputs to match with Bootstrap's style.

Simply, it turns this:

Into this input:

(function(window){
    window.jQuery(function($){
        $('input[type="file"]').each(function(){
            var $this = $(this);
            var $parent = $this.parent();
            $this.detach();
            $parent.prepend(
                $('
' +
                    '' +
                        '' + ($this.attr('data-label') || 'New image:') + '' +
                    '' +
                    '<input id="' + $this.attr('id') + '_path" type="text" class="form-control" readonly="readonly">' +
                    '' +
                        '' +
                            ($this.attr('data-button-label') || 'Browse') +
                            '

' +
                        '' +
                    '' +
                '
')
            );

            $this.appendTo('#' + $this.attr('id') + '_input-group label:last-child div:last-child');

            var $path = $('#' + $this.attr('id') + '_path', $parent).click(function(){
                $this.click();
            });

            $this.bind('change.input_file_styler', function(){
                $path.val(this.files[0] ? this.files[0].name : '');
            });
        });
    });
})(Function('return this')());

I really can't put my finger on what's wrong... but I know that something is stinking in there!

What can I improve in this code?

If you want to try it out:

(function(window){
 window.jQuery(function($){
  $('input[type="file"]').each(function(){
   var $this = $(this);
   var $parent = $this.parent();
   $this.detach();
   $parent.prepend(
    $('
' +
     '' +
      '' + ($this.attr('data-label') || 'New image:') + '' +
     '' +
     '<input id="' + $this.attr('id') + '_path" type="text" class="form-control" readonly="readonly">' +
     '' +
      '' +
       ($this.attr('data-button-label') || 'Browse') +
       '

' +
      '' +
     '' +
    '
')
   );

   $this.appendTo('#' + $this.attr('id') + '_input-group label:last-child div:last-child');

   var $path = $('#' + $this.attr('id') + '_path', $parent).click(function(){
    $this.click();
   });

   $this.bind('change.input_file_styler', function(){
    $path.val(this.files[0] ? this.files[0].name : '');
   });
  });
 });
})(Function('return this')());

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>

<input type="file" id="file" data-label="Select file to upload:" data-button-label="...">


texts:
I'm still a newbie when it comes to javascript, so I don't know yet how to optimize this code.

customize.js

 // Get the modal
  var modal = document.getElementById('myModal');
  var modal2 = document.getElementById('myModal2');
  var modal3 = document.getElementById('myModal3');

  // Get the image and insert it inside the modal - use its "alt" text as a      caption
  var img = document.getElementById('myImg');
  var modalImg = document.getElementById("img1");
  var captionText = document.getElementById("caption");

  var img2 = document.getElementById('myImg2');
  var modalImg2 = document.getElementById("img2");
  var captionText2 = document.getElementById("caption2");

  var img3 = document.getElementById('myImg3');
  var modalImg3 = document.getElementById("img3");
  var captionText3 = document.getElementById("caption3");

  img.onclick = function(){
 modal.style.display = "block";
 modalImg.src = this.src;
 captionText.innerHTML = this.alt;
  }

  img2.onclick = function(){
 modal2.style.display = "block";
 modalImg2.src = this.src;
 captionText2.innerHTML = this.alt;
  }

  img3.onclick = function(){
 modal3.style.display = "block";
 modalImg3.src = this.src;
 captionText3.innerHTML = this.alt;
  }
  // Get the  element that closes the modal
  var span = document.getElementsByClassName("close")[0];
  var span2 = document.getElementsByClassName("close")[1];
  var span3 = document.getElementsByClassName("close")[2];
  // When the user clicks on  (x), close the modal
  span.onclick = function() {
 modal.style.display = "none";
  }

  span2.onclick = function(){
 modal2.style.display = "none";
  }

  span3.onclick = function(){
 modal3.style.display = "none";
  }

And this how my html looks like

HTML


texts: palindrome code in C times out in program challenge?

texts:
Hello I am making a code in C to find the value of the last sequence of palindromes of a specified size (d) and I need to optimize this code as it is for an exercise platform called URI Online Judge and is giving Time Limit exceeded.
https://www.urionlinejudge.com.br/judge/en/problems/view/1686

Given a string s[1..N], we define a palindromic sequence of length p and displacement d (1 <= p <= d) as a sequence of k (k >= 1) disjoint substrings of s (each of which is a palindrome of length p) distant d characters from each other.
More formally, it can be written as the following sequence of disjoint substrings of s : A= (s[i..i+p-1], s[i+d..i+d+p-1], s[i+2d..i+2d+p-1], ...), where each element of A is a palindrome of length p. Recall that a string is called a palindrome if it reads the same forwards and backwards.
The value of a palindromic sequence is the total number of characters from string s it uses (i.e., if the sequence has k palindromes of length p, its value is k*p). Given a fixed displacement value D, calculate the largest value of a palindromic sequence contained in a string S.
Input
Each test case is described using two lines. The first line contains two integers N and D (1 <= N <=10^5), 1 <= D <=10^5) representing respectively the length of the string S and the required displacement value. The next line contains the string S of length N consisting only of lowercase letters.
The last test case is followed by a line containing two zeros.
Output
For each test case output a line with the maximum value of a palindromic sequence with displacement D in string S.
Samples
Input
5 1
abbbc
Output
5

#include <stdio.h>

char palavra[100000];

int palindrome(const int inicio, const int fim) {
    if (inicio >= fim) {
        return 1;
    }
    if (palavra[inicio] != palavra[fim - 1]) {
        return 0;
    }
    return palindrome(inicio + 1, fim - 1);
}

int maior_sequencia(const int n, const int d) {

    int valor = 0, temp;
    int i, j;

    for (i = 1; i <= d; i++) {
        temp = 0;
        for (j = 0; j < n; j += d) {
            if (palindrome(j, j + i)) {
                temp++;
            }
        }
        if (temp * i > valor) {
            valor = temp * i;
        }
    }

    return valor;
}

int main() {

    int n, d;

    while (1) {

        scanf("%d %d", &n, &d);

        if (n == 0 || d == 0) {
            return 0;
        }

        scanf("%s", palavra);
        printf("%d\n", maior_sequencia(n, d));

    }

    return 0;

}

edit: Now i have a functional code, but give Time Limit exceeded again :/
edit 2: I added another version of the code, how could I optimize one of these two versions?


texts: C# Code to Find all Divisors of an Integer

texts:
I made this so I can feed it integers and return an array with all the divisors of that integer.  I put checks in in case the integer is less than 2.  Order of integers in the array must be smallest to largest.  The code works.  What I need is to optimize this code to be as fast as possible.  Right now on an online IDE I am getting around 40ms combined against the given test.  I need to trim this down as much as possible.

using System.Collections.Generic;

public class Divisors
{
    public static bool IsPrime(int n)
    {
        if (n == 2) return true;
        if (n % 2 == 0) return false;

        for (int x = 3; x * x <= n; x += 2)
            if (n % x == 0)
                return false;

        return true;
    }

    public static int[] GetDivisors(int n)
    {
        List<int> divisors = new List<int>();

        if (n < 2)
        {
            return null;
        }
        else if (IsPrime(n))
        {
            return null;
        }
        else
        {
            for (int i = 2; i < n; i++)
                if (n % i == 0)
                    divisors.Add(i);
        }

        return divisors.ToArray();
    }
}

namespace Solution
{
  using NUnit.Framework;
  using System;

  [TestFixture]
  public class SolutionTest
  {
    [Test]
    public void SampleTest()
    {
      Assert.AreEqual(new int[] {3, 5}, Divisors.Divisors(15));
      Assert.AreEqual(new int[] {2, 4, 8}, Divisors.Divisors(16));
      Assert.AreEqual(new int[] {11, 23}, Divisors.Divisors(253));
      Assert.AreEqual(new int[] {2, 3, 4, 6, 8, 12}, Divisors.Divisors(24));
    }
  }
}


texts:
For educational purposes and to understand how iterators are working in C++, I've create an input iterator and I would like others to look at and provide any feedback on my code.

template<typename T>
class iter_input {
 public:
  typedef T         value_type;
  typedef T&        reference_type;
  typedef const T&  const_reference_type;
  typedef T*        pointer_type;
  typedef const T*  const_pointer_type;

  iter_input(pointer_type& pointer) : pointer_(pointer) {}
  iter_input(const iter_input& other) : pointer_(other.pointer_) {}

  iter_input& operator= (const iter_input& rhs) {
    this->pointer_ = rhs.pointer_;
    return (*this);
  }

  iter_input& operator++ (void) {
    ++this->pointer_;
    return (*this);
  }

  iter_input operator++ (int) {
    iter_input temp(*this->pointer_);
    ++*this;
    return (temp);
  }

  bool operator== (const_reference_type rhs) {
    return (this->pointer_ == rhs.pointer_);
  }

  bool operator!= (const_reference_type rhs) {
    return (this->pointer_ != rhs.pointer_);
  }

 private:
  T* pointer_;
};

References:

apache.org
sgi.com


texts: Checks if user is part of Active Directory group

texts:
I'm working in C# using PrincipalContext to do a check if user is part of security group for access to the site. Site is asp.net MVC and part of an internal network with security groups set up via active directory.

Currently load times for pages are about 2.5-3 seconds on first load and then about 1.4-1.5 seconds on subsequent loads for each action. I'd like to decrease the time if possible and have set the query to check the domain of the user which cut some time out.

public override void OnAuthorization(AuthorizationContext filterContext)
{
    var alias = HttpContext.Current.User.Identity.Name;
    var domain = alias.Substring(0, alias.IndexOf("\\"));
    alias = alias.Substring(alias.IndexOf("\\") + 1);
    var accessLevel = this.Roles;

    if (CheckAccess(accessLevel, alias, domain))
    {
        return;
    }
}

private bool CheckAccess(string group, string user, string userDomain)
{
    PrincipalContext ctx;
    GroupPrincipal AdGroup = null;
    UserPrincipal AdUser = null;
    using (Forest forest = Forest.GetCurrentForest())
    {
        foreach(Domain domain in forest.Domains)
        {
            if (domain.Name.Contains("domain1"))
            {
                ctx = new PrincipalContext(ContextType.Domain, domain.Name, null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer, "username", "password");
                if (group == "WRITE")
                {
                    AdGroup = GroupPrincipal.FindByIdentity(ctx, "group1");
                }

                if (userDomain.ToLower().Contains("domain1"))
                {
                    AdUser = UserPrincipal.FindByIdentity(ctx, user);
                }
            }
            else if (domain.Name.Contains("domain2"))
            {
                if (userDomain.ToLower().Contains("domain2"))
                {
                    ctx = new PrincipalContext(ContextType.Domain, domain.Name, null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer, "username", "password");
                    AdUser = UserPrincipal.FindByIdentity(ctx, user);
                }
            }
        }

        if (AdGroup != null && AdUser != null)
        {
            if (AdUser.IsMemberOf(AdGroup))
            {
                return true;
            }
            else
            {
               return false;
            }
        }
        else
        {
            return false;
        }
     }
}

Also first question on CodeReview, let me know if there is anything to do to improve the question that I might have missed in the FAQ.


texts:
I'm working on a program that handles UTF-8 characters.  I've made the following macros to detect UTF-8. I've tested them with a few thousand words and they seem to work.

I'll add another one to do error-checking later, but for now I would like to know what mistakes I've made and how these macros can be improved.

//check if value is in range of leading byte
#define IS_UTF8_LEADING_BYTE(b) (((unsigned char)(b) >= 192) && (unsigned char)(b) < 248)

//check if value is in range of sequence byte
#define IS_UTF8_SEQUENCE_BYTE(b) ((unsigned char)(b) >= 128 && (unsigned char)(b) < 192)

//can be any utf8 byte, first, last...
#define IS_UTF8_BYTE(b) (IS_UTF8_LEADING_BYTE(b) || IS_UTF8_SEQUENCE_BYTE(b))

//no error checking, it must be used only on leading byte
#define HOW_MANY_UTF8_SEQUENCE_BYTES(b) ((((unsigned char)(b) & 64) == 64) + (((unsigned char)(b) & 32) == 32) + (((unsigned char)(b) & 16) == 16))


texts: Swift protocol with lazy property requirement

texts:
First question here on CodeReview. I was directed here from a question I asked on SO: Swift protocol with lazy property - Cannot use mutating getter on immutable value: '$0' is immutable.

Goal: Create a protocol that allows lazy computation of a property for structs that conform to the protocol. The computation is intensive and should only be executed once, hence the lazy requirement.

So, after lots of reading (eg Swift Struct with Lazy, private property conforming to Protocol, where I based this code on) and trial and error, I came up with something that works:

import Foundation

protocol Foo {
    var footype: Double { mutating get }

    func calculateFoo() -> Double
}

struct Bar: Foo {
    private lazy var _footype: Double = {
        let value = calculateFoo()

        return value
    }()

    var footype: Double {
        mutating get {
            return _footype
        }
    }

    func calculateFoo() -> Double {
        print("calc")
        return 3.453
    }
}

Testing this in a Playground:

var bar = Bar()
print(bar.footype)
print(bar.footype)

And the output is:

calc
3.453
3.453

So it is working. But it feels like a hack using _footype

Also in the comments, it was suggested that

  However, I would not put calculateFoo in the protocol because it sounds like an implementation detail.

Appreciate any comments and/or improvements.


texts: Synchronous and asynchronous motor movement

texts:
I am working on an API that is mostly intended to be used interactively/little scripts. There are some classes with methods that could act slightly differently depending on the intention of the user, I have explored several options and would like to get some feedback on caveats, and alternative options.

I will use a simple example:

class Motor(object):
    def __init__(self, name):
        self.name = name
        self._blocking = True

    def move_to(self, position):
        self.block_until_idle() # protects from conflict in any case
        #internal move call here
        if self._blocking:
            self.block_until_idle()
        else:
            self._blocking = True

    def block_until_idle(self):
        #internal status query loop

I want to use an instance of Motor in two ways (dictated by the value of _blocking attribute)

The movement call blocks until idle, because I want to take a picture at that position.
The movement call returns ASAP, because I want to do other things meanwhile (for example move a completely different motor).

There are many different calls (not only move_to) that would follow this pattern.

The wish: Usage like:

motor = Motor("A")
motor2 = Motor("B")

motor.move_to(20)
# > wait until done

noblock(motor.move_to(50))
# > returns immediately so I can move another
motor2.move_to(30)

So, in summary, the desire is that it is quick and fast to switch between behaviors, preferably within the same line of code and without lasting side effects.

Explored but discarded options:

Manually handling the flag variable: potentially dangerous (easy to forget), three liner every time.

Duplicate the methods into blocking and not blocking: API duplicates in size.

Context manager: Taking care of the flag and cleaning up the logic in the move_to method. Still a bit too verbose for my taste, specially for command line (I skip the context manager code). Note that the advantage of the context manager of being able to unblock many calls is not useful here, since the pre-blocking safety would kick in and only the last call would be affected. Also heavy to combine several unblocked motors.

with noblock(motor) as nbmotor:
    nbmotor.move_to(25)

Extra parameter: requires changes on each method, polluting call signature, still the best of the trivial options

def move_to(self, position, blocking = True):

Decoration / wrapper: I did not make it work so far in a way that would not scare users:

# syntax error, decorators do not work this way, and besides two liner
@noblock
motor.move_to(20)

# hi is evaluated before polite is applied
noblock(motor.move_to(15))

# almost, but problems to extract self inside the wrapper, the syntax starts to get tricky
noblock(motor.move_to) (20)

# this works, but awful!
noblock(Motor.move_to) (motor2, 15)

My best solution so far:

Some twisty implementation, but can be invoked in a single line.

class Motor(object):
    def __init__(self, name):
        self.name = name
        self._blocking = True
        self.noblock = Noblock(self)

    def move_to(self, position):
       self.block_until_idle() # protects from conflict in any case
       #internal move call here
       if self._blocking:
           self.block_until_idle()
       else:
           self._blocking = True

class Noblock(object):
    def __init__(self, other):
        self.other = other

    def __getattribute__(self, name):
        if name in ["move_to"]: #list of methods we intercept
            self.other._blocking = False
            return self.other.__getattribute__(name)
        else:
            return object.__getattribute__(self, name)

motor = Motor("A")

motor.move_to(20)
# > wait
motor.noblock.move_to(20)
# > returns ASAP

Thoughts? Any wrapper/decoration strategy that I missed and does the same?


texts:
I have written code for insertion sort. I just want some feedback whether the above implementation is correct and can be improved.

public class InsertionSortNew {

    static int temp;

    public static void InsertionSort(int [] array){

        for(int i =0;i<=array.length-1;i++){

            int key = array[i];

            for(int j=i-1;j>=0;j--){

                if(key<array[j]){
                    temp = key;
                    array[j+1] = array[j];
                    array[j] = key;
                    key = array[j];

                }else{
                    break;
                }

            }
        }
    }


texts:
I have the following:

A set of K time-series in a numpy array with dimensions  T x K.
A set of P permuted approximation of them in a numpy array with dimensions P times T.

I need a dictionary that tells me which is the most probable permutation. For that I've created the following function, but I would like to know if can be done in a more efficient way and with less code to do this.

def find_permutation(true, permuted):
    """
    Finds the most probable permutation of true time series in between permuted time series
    :param true: true ordered time series of shape T times X
    :param permuted: Permuted time series of shape P times T. P > K
    :return: A dict containing {true idx: permuted idx}
    """
    N = true.shape[1]
    max_comps = permuted.shape[0]

    permutation_dict = {}
    used_comps = []

    corr_matrix = np.zeros((N, max_comps))

    # Find correlations
    for i in range(N):
        for j in range(max_comps):
            corr_matrix[i, j] = np.corrcoef(true[:, i], permuted[j, :])[0, 1]

    # Find best order
    per_matrix = np.argsort(-np.abs(corr_matrix), axis=1)
    for i in range(N):
        for j in per_matrix[i, :]:
            if j in used_comps:
                continue
            else:
                permutation_dict[i] = j
                used_comps.append(j)
                break

    return permutation_dict

if __name__ == "__main__":

    import numpy as np

    a = np.array([1, 2, 3, 4.])
    b = np.array([4, 8, 9, 12.])
    c = np.array([9, 5, 8, 9.])

    true = np.vstack([a, b, c]).transpose()
    permuted = np.vstack([b*0.2, c*0.5, a*0.7])

    print(find_permutation(true, permuted))
    # {0: 2, 1: 0, 2: 1}

Here a Cython version

# C imports first
cimport numpy as np

# other imports
import numpy as np
import cython

# Type declarations
DTYPE = np.float
ctypedef np.float_t DTYPE_t

@cython.boundscheck(False)  # Deactivate bounds checking
@cython.wraparound(False)   # Deactivate negative indexing.
def find_permutation(np.ndarray[DTYPE_t, ndim=2] true, np.ndarray[DTYPE_t, ndim=2] permuted):
    """
    Finds the most probable permutation of true time series in between permuted time series
    :param true: true ordered time series of shape T times X
    :param permuted: Permuted time series of shape P times T. P > K
    :return: A dict containing {true idx: permuted idx}
    """

    cdef unsigned int N = true.shape[1]
    cdef unsigned int max_comps = permuted.shape[0]

    cdef dict permutation_dict = {}
    cdef list used_comps = []

    cdef np.ndarray[DTYPE_t, ndim=2] corr_matrix
    corr_matrix = np.zeros((N, max_comps))

    cdef Py_ssize_t i
    cdef Py_ssize_t j

    # Find correlations
    for i in range(N):
        for j in range(max_comps):
            corr_matrix[i, j] = np.corrcoef(true[:, i], permuted[j, :])[0, 1]

    # Find best order
    cdef np.ndarray[long, ndim=2] per_matrix
    per_matrix = np.argsort(-np.abs(corr_matrix), axis=1)

    for i in range(N):
        for j in per_matrix[i, :]:
            if j in used_comps:
                continue
            else:
                permutation_dict[i] = j
                used_comps.append(j)
                break

    return permutation_dict

Any suggestion is more than welcome.


texts: My implementation of (open) Knight's Tour

texts:
This is my implementation of the (open) Knight's Tour on a 5v5 board. My original assignment for CS was to solve the Knight's Tour from any startings position (0,0 -> 4,4). The goal for myself was to make this class as clean as it could be. I would like some feedback (and constructive criticism!) on the code and its performance.

I have used the StdDraw class from Princeton to display the 5v5 board with graphics.

private final int N;
private final int startX;
private final int startY;
private boolean[][] visited;
private boolean done;
private final int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2},
        {-2, 1}, {-2, -1}, {-1, -2}}; //x, y.
private int[][] board;
private int total;

public Board(final int N, final int startX, final int startY) {
    this.N = N;
    this.startX = startX;
    this.startY = startY;
    visited = new boolean[N][N];
    board = new int[N][N];
    init();
}

private void init() {
    for (int x = 0; x < N; x++) {
        for (int y = 0; y < N; y++) {
            visited[x][y] = false;
            board[x][y] = -1;
        }
    }
    done = false;
    total = N * N;
}

public boolean solve() {
    board[startX][startY] = 0;
    return solve(startX, startY, 0);
}

private boolean solve(int x, int y, int currentMove) {
    if ((x < 0) || (x >= N) || (y < 0) || (y >= N)) return false;
    if (done || visited[x][y]) return false;

    visited[x][y] = true;
    board[x][y] = currentMove;

    final List<int[]> moves = movesList(x, y);

    if (moves.isEmpty())
        return false;

    if (hasVisitedAll()) {
        done = true;
    }

    StdDraw.setPenColor(Color.BLUE);

    if (x == startX && y == startY)
        StdDraw.setPenColor(StdDraw.RED);

    StdDraw.filledCircle(x + 0.5, y + 0.5, 0.25);
    StdDraw.show(1_000); //1sec per next move

    for (final int[] m : moves) {
        int x2 = m[0];
        int y2 = m[1];

        if (solve(x2, y2, currentMove + 1)) {
            board[x2][y2] = currentMove + 1;
            return true;
        } else if (isLegitMove(x2, y2)) {
            visited[x2][y2] = false;
        }
    }
    return done;
}

private boolean hasVisitedAll() {
    int count = 0;
    for (final int[] v : board) {
        for (final int v2 : v) {
            if (v2 >= 0) count++;
        }
    }
    return (count == total);
}

private List<int[]> movesList(final int x, final int y) {
    final List<int[]> move = new ArrayList<>();
    for (int[] m : moves) {
        int x2 = m[0];
        int y2 = m[1];
        move.add(new int[]{x + x2, y + y2});
    }
    return move;
}

private boolean isLegitMove(final int x, final int y) {
    return ((x > 0 && x < N)) && ((y > 0 && y < N));
}


texts:
The method below recursively checks if a string contains another string. Example: contains(hello, lo, 0) should return true, while contains(hello, eh, 0) should return false. The method itself works, but I was wondering how it could be made more efficient/generally better.

Method:

public static boolean contains(String word1, String word2, int index)
{
    if((word1 == null) || (word2 == null)){
        return false;
    }

    if(index + (word2.length() - 1) >= word1.length()){
        return false;
    }

    int count = 0, j = 0;

    for(int i = index; i < (word2.length() + index); i++){
        if(word1.charAt(i) == word2.charAt(j)){
            if((i != 0) && (j != 0)){
                if(word1.charAt(i - 1) == word2.charAt(j - 1)){
                    count++;
                }
            } else {
                count++;
            }
        }
        j++;
    }

    if(count == word2.length()){
        return true;
    }

    return contains(word1, word2, index + 1);
}


texts: Chaining method calls and "bubbling" the results

texts:
I need a way to build up a sort of stack of places to search for an item.

What I would like to do is to have each layer searched for an item, and if it is found at that level, then it should be loaded by each higher level (successively).

What I have so far is just a basic framework, but I was wondering if I was missing some more apt abstraction here in terms of command flow. Does anyone have any suggestions?

type Result = String
type Query = String
type Search = Query -> Maybe Result
type Load = Result -> Maybe Result

data LoadFunc = LoadFunc {
  search :: Search,
  load :: Load }

data RunFunc = RunFunc { runner :: [RunFunc] -> Maybe Result }

mkRunFunc :: Query -> LoadFunc -> RunFunc
mkRunFunc q lf = RunFunc r
  where r (x:xs) =
          case search lf q of
            Nothing -> runner x xs >>= load lf
            a       -> a
        r []    = search lf q

inMem :: LoadFunc
inMem = LoadFunc { search = search, load = load }
  where search q = if q == "hi" then return $ "Found in mem." else Nothing
        load = addToLog "Loaded to mem."

renDisk :: LoadFunc
renDisk = LoadFunc { search = search, load = load }
  where search q = if q == "foo" then return $ "Found rendered." else Nothing
        load = addToLog "Added rendered."

onDisk :: LoadFunc
onDisk = LoadFunc { search = search, load = load }
  where search q = if q == "bar" then return $ "Found on disk." else Nothing
        load = addToLog "Now on disk."

addToLog :: Result -> Result -> Maybe Result
addToLog next str = return $ str ++ (' ':next)

tester :: [LoadFunc] -> Query -> Maybe Result
tester caches q = runner first rem
  where caches' = mk `fmap` caches
        first   = head caches'
        rem     = tail caches'
        mk      = mkRunFunc q

To see this in action, it should be sufficient to load up ghci and enter:

tester "bar" [inMem,renDisk,onDisk]


texts: Normalizing strings using PHP preg_replace and regex expressions

texts:
I needed a way to normalize nearly any given input for a configuration parameter on a dashboard.  Server side code is in PHP so I wrote a test script to experiment with preg_replace and regex.  When I say normalize meaning, the resulting value must match the following restrictions:

Take any cased value and return all lower case. For example, given "ValiDVoicE", after normalizing, "validvoice" would be returned.
Strip away all special characters and white space except underscores. For example, given "@@Valid  _voice" return only "valid_voice".
Trim all nonessential white space from front and end of string. For example, given "   (&&   (*Paxus-Demo    " return "paxus_demo".

Solution: (I copied my test script below)

$myvar =
[
    "Paxus-Demo",
    "Paxus Demo",
    "paxus_demo",
    "Paxus  Demo",
    "paxus-Demo",
    "paxus_ Demo",
    "Paxus _Demo",
    "*(&*&   (*Paxus-Demo   ",
    "@@Valid  _voice",
    "Valid-Voice",
    "PortaL-Demo",
    "gui_demo",
    "Gui-Demo   ",
    "VoiceInstance",
    "vAlid Voice",
    "  vaLid_  _voiCe  ",
];

for( $i = 0; $i < sizeof( $myvar ); ++$i )
{
    $modded = trim( strtolower( preg_replace( array( '/[^a-zA-Z0-9 ]/i', '<\W+>'), array( ' ', '_' ), $myvar[$i] ) ), '_' );
    echo "modded2 = " . $modded." [ ". $i ." ] = " .$myvar[$i]. "<br />";
}

My question is not necessarily for elegance, but could I have done this all in one regex expression using lookarounds?  Bear in mind, I never took the time to truly understand using regex before today so my knowledge of using lookarounds is still a bit wonky.  That said, if someone can simplify the use of lookarounds it'll be greatly appreciated.


texts:
I need to handle configuration errors and ask the user for the right credentials if something is wrong. I cannot decide between three implementations. Which style is better in Python and why?

A:

while not backend.check_config():
    click.echo('Invalid Configuration parameters!')
    for param_name, question in backend.config.check_config_requires:
        value = prompt(question, default=getattr(backend.config, param_name))
        setattr(backend.config, param_name, value)

B:

while True:
    try:
        backend.check_config()
        break
    except ConfigurationError:
        click.echo('Invalid Configuration parameters!')
        for param_name, question in backend.config.check_config_requires:
            value =prompt(question, default=getattr(backend.config, param_name))
            setattr(backend.config, param_name, value)

C:

while True:
    try:
        backend.check_config()
    except ConfigurationError:
        click.echo('Invalid Configuration parameters!')
        for param_name, question in backend.config.check_config_requires:
            value =prompt(question, default=getattr(backend.config, param_name))
            setattr(backend.config, param_name, value)
    else:
        break


texts: Adding object to database, using linq or sql connection

texts:
I have a table called tblDelegates in my database which I need to populate with some data.  I have created a class called Delegates which has various properties to hold the bulk of the information.

I am fairly new to C#, so I wanted to get the answers to a few questions as to why you should be doing things in a particular way and also to get some advice on how I could improve my code.

Please can someone take a look at the questions below and give me a few pointers as to whether this is the correct way to do things.

Is this the correct way to do this, by first creating an instance of an object and then adding the fields to it before adding the object to the database?
This will sound like a total noob question (so I apologies), but why bother having to create the delegates class object, why could/should you not just add the fields directly into the database?
In my Delegates object, should I also add the fields such as Created_User Created_Dttm Updated_User Updated_Dttm, or am I ok leaving them out of this object like I have done below.
Is the most efficient/quickest way to do this using LINQ like I have done below, or should I be using a SQL connection, or is it just preference?
Can anyone tell me if the formatting of my code is correct, or if I should separate out the steps into separate functions perhaps?

Code to add data to database

        var del = new Delegates
        {
            Pending = true,
            ManagerAlias = row.Cells[4].Text,
            ManagerName = row.Cells[1].Text + " " + row.Cells[2].Text,
            DelegateAlias = ADLookup.AD("alias"),
            DelegateName = ADLookup.AD("GivenName") + ADLookup.AD("sn"),
            DelegateEmail = ADLookup.AD("mail")
        };

        var dc = new LinqToSqlDataContext();
        var Del = new tblDelegate
        {
            Pending = del.Pending,
            Manager_Alias = del.ManagerAlias,
            Manager_Name = del.ManagerName,
            Delegate_Alias = del.ManagerAlias,
            Delegate_Name = del.DelegateName,
            Delegate_Email = del.DelegateEmail,
            Created_User = ADLookup.ADCurrentUser(),
            Created_Dttm = DateTime.Now,
            Updated_User = ADLookup.ADCurrentUser(),
            Updated_Dttm = DateTime.Now
        };

        dc.tblDelegates.InsertOnSubmit(Del);
        dc.SubmitChanges();

Delegates Class

public class Delegates
{
    public bool Pending { get; set; }
    public string ManagerAlias {get;set;}
    public string ManagerName {get;set;}
    public string DelegateAlias {get;set;}
    public string DelegateName {get;set;}
    public string DelegateEmail {get;set;}

    public Delegates()
    {
    }

    public Delegates(bool pending, string manageralias, string managername, string delegatealias, string delegatename, string delegateemail)
    {
        Pending = pending;
        ManagerAlias = manageralias;
        ManagerName = managername;
        DelegateAlias = delegatealias;
        DelegateName = delegatename;
        DelegateEmail = delegateemail;
    }
}


texts: Creating and updating link to instagram image or video

texts:
I've been using the InstagramPhotoLink extension for Opera for some time but instagram broke it recently. I thought I could try to fix it... and I did.

The original extension is rather limited and it supports only a link to the first image and no videos so while fixing it I completely rewrote it in order to extend it.

It works by looking for an image or video element with a specific class and extracts the src attribute from it and puts it in a new a-element inside the media-container.

Switching images/videos is supported by the MutationObserver that updates the links when either a div or an attribute changes.

I came across a problem where the MutatorObserver reacts too quickly and before the src attribute of the new image is set. I solved it by adding a small delay by adding a call to setTimeout to wait until everything is updated.

function createMediaLink() {

    let mo = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
            if (mutation.type == "attributes") {
                //console.log(mutation.attributeName);
                addOrUpdateVideoLink();
            }
            if (mutation.type == "childList") {
                //console.log(mutation.childList);
                addOrUpdateImageLink();
            }
        });
    });

    return (
        addOrUpdateImageLink(mo) ||
        addOrUpdateVideoLink(mo)
    );
}

function addOrUpdateImageLink(mo) {

    let image = document.getElementsByClassName('FFVAD');

    if (image.length == 0) {
        return false;
    }

    image = image[0];

    if (mo) {
        // the nearest div to the image that stays there when switching images
        var div = document.getElementsByClassName("rQDP3");
        mo.observe(div[0], {
            childList: true
        });
    }

    setTimeout(() => {
        addOrUpdateMediaLink(image.src);
    }, 50);

    return true;
}

function addOrUpdateVideoLink(mo) {

    let video = document.getElementsByClassName('tWeCl');

    if (video.length == 0) {
        return false;
    }

    video = video[0];

    if (mo) {
        mo.observe(video, {
            attributes: true
        });
    }

    setTimeout(() => {
        addOrUpdateMediaLink(video.src);
    }, 50);

    return true;
}

function addOrUpdateMediaLink(src) {
    console.log(`src: ${src}`);
    let a = document.getElementsByClassName('_open_');
    if (a.length == 0) {
        a = document.createElement("a");
        a.className = "_open_";
        a.innerHTML = 'Open in new tab';
        a.target = "_blank";
        // media container
        document.getElementsByClassName("_97aPb")[0].appendChild(a);
    } else {
        a = a[0];
    }
    a.href = src;
}

createMediaLink();

I don't write javascript too often so this is the best I can do but I'm pretty sure this can still be improved. What do you think?


texts:
This is a wrapper that can be used to do additional external REST call to some API. Since I have to provide support to legacy code so I added three static functions to support them.

However, the question that comes to my mind is where to actually set default value either in the constructor or it should be in the main function.

is_optional = kwargs.get('is_optional', False) can also be set directly in constructor. So what is correct way to handle such situations?

class ExternalRestService:
    def __init__(self, endpoint, method=sc.REQUEST_GET):
        self.endpoint = endpoint
        self.method = method
        self.timeout = sc.REQUEST_TIMEOUT

    @staticmethod
    def get(endpoint, request_headers, timeout):
        """
          Handle GET External Call
        """
        logging.debug("About to make an external *** GET *** to url %s", endpoint)
        response = requests.get(url=endpoint, headers=request_headers,
                                timeout=timeout)
        return response

    @staticmethod
    def post(endpoint, request_headers, json_data, timeout):
        """
          Handle POST External Call
        """
        logging.debug("About to make an external *** POST *** to url %s", endpoint)
        request_headers["Content-type"] = "application/json"
        response = requests.post(url=endpoint, headers=request_headers, json_data=json_data,
                                 timeout=timeout)
        return response

    @staticmethod
    def put(endpoint, request_headers, json_data, timeout, fallback=False):
        """
          Handle PUT External Call
        """
        logging.debug("About to make an external *** PUT *** to url %s", endpoint)
        request_headers["Content-type"] = "application/json"
        response = requests.put(url=endpoint, headers=request_headers, json_data=json_data,
                                timeout=timeout)
        if fallback and response.status_code == 405:
            logging.debug("PUT action failed, applying fallback strategy")
            response = requests.put(url=endpoint, headers=request_headers, json_data=json_data,
                                    timeout=timeout)
        return response

    def invoke(self, **kwargs):
        """
        Execute the external call
        """
        is_fallback = kwargs.get('is_fallback', False)
        is_optional = kwargs.get('is_optional', False)
        request_headers = kwargs.get('request_headers', {})
        json_data = kwargs.get('json_data', {})

        response_list = None
        try:
            logging.info("About to make an external *** %s *** call", self.method)
            if self.method == sc.REQUEST_POST:
                response = self.post(self.endpoint, request_headers, json_data, self.timeout)
            elif self.method == sc.REQUEST_PUT:
                response = self.put(self.endpoint, request_headers, json_data,
                                    self.timeout, fallback=is_fallback)
            else:
                response = self.get(self.endpoint, request_headers, self.timeout)
            response_list, error_list = self.__response_handler(response, is_optional)
        except requests.RequestException as err:
            error_list = err
        return response_list, error_list

    @staticmethod
    def __response_handler(response, is_optional=False):
        """
       Handle API response
       """
        status_code = response.status_code
        if is_optional and status_code == 404:
            return response, None
        if not 200 <= status_code < 300:
            return None, response
        response_list = response.json()
        return response_list, None


texts:
My code already works perfectly. Here is the JS file:

var movieData = {
   count: 6,
   movies: [{
       id: 1,
       title: "Lorem Ipsum",
       thumb: "assets/img/placehold.png"
     },
     {
       id: 2,
       title: "Lorem Ipsum",
       thumb: "assets/img/placehold.png"
     },
     {
       id: 3,
       title: "Lorem Ipsum",
       thumb: "assets/img/placehold.png"
     },
     {
      id: 4,
      title: "Lorem Ipsum",
      thumb: "assets/img/placehold.png"
    },
    {
      id: 5,
      title: "Lorem Ipsum",
      thumb: "assets/img/placehold.png"
    },
    {
      id: 6,
      title: "Lorem Ipsum",
      thumb: "assets/img/placehold.png"
    },
   ]
 };

 $(document).ready(function() {

    if (typeof movieData === 'object' && typeof movieData !== null) {
      // List the movies
      for (var i in movieData.movies) {
         var movie = movieData.movies[i];
         var movieDiv =

         '
' +
            '' +
               '' +
               '

' + movie.title + '' +
            '' +
         '
';

         $('#films').append(movieDiv);
      }
    }

 });

I actually have everything into one file. As a code review I am asking your help if you have any idea about how to improve the code.

Knowing that as an improvement I already though about making this code into 2 different files (one JS and one JSON) but I would like to know your point of view.


texts:
I am writing a simple merge algorithm in Haskell. I wanted to add simple logging, hence am using the Writer Monad to include logging.

type ArrayWithLogging a = WriterT [String] Identity [a]

merge :: (Show a, Ord a) => ArrayWithLogging a -> ArrayWithLogging a -> ArrayWithLogging a
merge al bl = do
    a <- al
    b <- bl
    case (a, b) of
        ([], b') -> tell ["Returning " ++ show b'] >> return b'
        (a', []) -> tell ["Returning " ++ show a'] >> return a'
        (a'@(x:xs), b'@(y:ys)) -> if (x <= y)
                                    then tell ["Min " ++ show x ++ " merging " ++ show xs ++ " with " ++ show b]
                                        >> ((merge (return xs) (return b')) >>= \z -> return (x : z))
                                  else tell ["Min " ++ show y ++ " merging " ++ show a ++ " with " ++ show ys]
                                        >> ((merge (return a') (return ys)) >>= \z -> return (y : z))

I feel there are too many returns inside the monadic context. Is this style correct?


texts: Dropdown form that shows data from 2 different tables

texts:
I am very new to this and am using php and MySQLi to create a form which will create a record in a third table.  This works fine but I can't help but think that there is a way to do it with a single query rather than a query for each table as I have now.  The third table is called tblcars, and I will use this form to build records for that table by selecting data from these dropdowns.

    <?php

    //Database Login
    require_once 'includes/connection.php';

    $sql = ("SELECT * FROM tblmake");

    $getclass = ("SELECT * FROM tblclass");

    $result = $conn->query($sql);
    $results = $conn->query($getclass);

    ?>

        <title>Car Makes</title>

Car Makes

            <form action="" method="get">
            <select name="makeID">
                <option value="">Choose Make</option>
                <?php
                    while($make = $result->fetch_assoc()) {
                        echo "<option value={$make['makeID']}>";
                        echo $make['carmake'];
                        echo "</option>";
                    }
                ?>
            </select>
            <select name="classID">
                <option value="">Choose Class</option>
                <?php
                    while($class = $results->fetch_assoc()) {
                        echo "<option value={$class['classID']}>";
                        echo $class['carclass'];
                        echo "</option>";
                    }
                ?>
            </select>
            <input type="submit" value="Insert">
        </form>


texts: Redux: button click potentially fires 3 action for different reducers

texts:
I’m using Redux and thunk, I have a list component

class List extends Component {
  render() {

    //code
  }
  return(
    <Aux>
      <Button
        type="button"
        click={() => this.props.addNew(data)}
        btnType="add" >
        Add
      </Button>
      <Button
        type="button"
        click={() => this.props.deleteB(id, type)}
        btnType="Delete" >
        Delete
      </Button>
      <Button
        type="button"
        click={() => this.props.editStart(id)}
        btnType="edit" >
        Edit
      </Button>
      <Button
        type="button"
        click={() => this.props.editSave(data, type)}
        btnType="save" >
        save
      </Button>
    </Aux>
  )
}

const mapStateToProps = state => {
    return {
        editing: state.list.editing
    };
};

const mapDispatchtoProps = dispatch => {
  return {
    deleteB: (id, type) => {dispatch(actions.deleteB(id, type))},
    editStart: (id) => {dispatch(actions.editStart(id))},
    editSave: (data, type) => {dispatch(actions.editSave(data, type))},
    addNew: (data) => dispatch(actions.addNew(data))
  };
};

export default connect(mapStateToProps, mapDispatchtoProps)(List);

A reducer

const addNew = ( state, action ) => {
  //immutable state
  //add new
  //return updated state
};

const deleteB = ( state, action ) => {
  //immutable state
  //delete
  //return updated state
};

const editStart = ( state, action ) => {
  //immutable state
  //update editing to true
  //return updated state
};

const editSave = ( state, action ) => {
  //immutable state
  if(action.type === state.editing.type) {
    //update object with user data
  } else {
    //delete old data same code of deleteB
    //add data user like addNew
    //update editing to false
  }
  //return updated state
};

const reducer = ( state = initialState, action ) => {
  //switch case
};

export default reducer;

When the user clicks on the “save” button if the type of the data changed the reducer uses the same functions that the buttons “add” and “delete” uses.
I’ve created an utility function for deleting and adding data, but It still looks ugly.

I was wondering if when the user clicks “Save” it is better to call a function in the List component that calls “addNew” and “deleteB” and  finally “editSave” to only update the state for the “editing” state property.

I think that a reducer needs to know only the state he needs to update, so editSave should only update the editing slice of state, and I need to reuse the others reducers.
But I don’t know if there is a better way, or if I wrote a bad pattern for the reducers.


texts: Sum of switch-triggered integers in VHDL

texts:
I've implemented a VHDL program that sums up the positions of switches and shows it on a 7-segment LED, but I've had to use lots of temporaries and a division. Is there a better way?

library ieee;
use ieee.std_logic_1164.all;

entity light is
  port(
        LEDR : out std_logic_vector(0 to 9);
        LEDG : out std_logic_vector(0 to 7);
        SW : in std_logic_vector(0 to 9);
        KEY : in std_logic_vector(0 to 3);
        HEX0 : out std_logic_vector(0 to 6);
        HEX1 : out std_logic_vector(0 to 6);
        HEX2 : out std_logic_vector(0 to 6);
        HEX3 : out std_logic_vector(0 to 6)
  );
end light;

architecture arch of light is

signal sum, sum2 : integer := 0;
signal x1,x2,x3,x4,x5,x6,x7,x8,x9 : integer := 0;

function led_value(x:integer)
    return std_logic_vector is
begin
    case x is
       when 0 => return "0000001";
        when 1 => return "1001111";
        when 2 => return "0010010";
        when 3 => return "0000110";
        when 4 => return "1001100";
        when 5 => return "0100100";
        when 6 => return "0100000";
        when 7 => return "0001111";
        when 8 => return "0000000";
        when 9 => return "0000100";
        when others => return "1111111";
    end case;
end led_value;

begin
    x1 <= 1 when sw(1) = '1' else 0;
    x2 <= 2 when sw(2) = '1' else 0;
    x3 <= 3 when sw(3) = '1' else 0;
    x4 <= 4 when sw(4) = '1' else 0;
    x5 <= 5 when sw(5) = '1' else 0;
    x6 <= 6 when sw(6) = '1' else 0;
    x7 <= 7 when sw(7) = '1' else 0;
    x8 <= 8 when sw(8) = '1' else 0;
    x9 <= 9 when sw(9) = '1' else 0;

    sum <= x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9;
    sum2 <= (sum - sum mod 10) / 10;

    hex0 <= led_value(sum mod 10);
    hex1 <= led_value(sum2);
    hex2 <= led_value(11);
    hex3 <= led_value(11);
end arch;


texts: Compare contents of a variable with several values

texts:
Let's say I have this function called coolName that takes an argument name and decides whether it's a cool name:

function coolName(name) {
  const n = name.toLowerCase();
  return n === 'peter' || n === 'paul' || n === 'mary';
}

You could achieve the same using this approach:

function coolName(name) {
  return ['peter', 'paul', 'mary'].includes(name.toLowerCase());
}

For 3 or more values I need to compare to, I prefer the second approach.

Your thoughts?


texts: Repositioning images in a gallery based on the current image

texts:
I'm working on extending the functionality of a photo gallery by adding a thumbnail display, I have multiple if statements set up to adjust the position of the thumbnails. Obviously this is not ideal, I'm trying to put my head around how to use a for loop to iterate the width multiplier and curSlide position.

Ideally I would like the curSlide to increment after every 5 slide and the thumbGalwidth*i to increment as well.

var thumbGalwidth = 795;

if(currSlide < 6) {
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*0 + 'px');
}
if(currSlide >= 6) {
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*1 + 'px');
}
if (currSlide >= 11) {
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*2 + 'px');
}
if (currSlide >= 16) {
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*3 +     'px');
}
if (currSlide >= 21) {
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*4 +    'px');
}
if (currSlide >= 26) {
jQuery('#view-all-container').css('margin-left', '-' + thumbGalwidth*5 +    'px');
}


texts: Grep to search for array of location targets

texts:
Please review my short 65 lines of code:

Is there a way to avoid eval (security)?
Is there a better way or place to use shopt -s nullglob?
Does shopt -u nullglob always need to be unset through each iteration?
Is there a smarter way to define a list of locations?

#!/bin/bash
if [ $# -eq 0 ]
then
    echo specify at least a regular expression pattern
    exit 1
fi
# make an array. Use 'single quotes'
SEARCH_LOCATIONS=(
'$BIN_HOME/*'
'$PBIN_HOME/*'
'$PBIN_HOME/lib/*'
'$SH_HOME/* '
'$SH_HOME/*/*'
'$PROD_HOME/psp/*.psp'
'$PROD_HOME/sql/*.sql'
'$PROD_HOME/sql/*/*.sql'
'$PROD_HOME/rpt/[A-Z]*.rpt'
'$PROD_HOME/script/*'
'$PROD_HOME/fmb/[A-Z]*.pll'
'$PROD_HOME/xml/[A-Z]*.pld'
'$PROD_HOME/fmb/[A-Z]*.mmb'
'$PROD_HOME/xml/[A-Z]*.xml'
'$PROD_HOME/cgi/*'
'$ELETTUS_HOME/*'
'$ELETTUS_HOME/*/*'
'$PROD_HOME/guicommon/*'
)
for LOCATION in ${SEARCH_LOCATIONS[@]}
do
    # ---- evaluate array contents
    echo --------------------------------------------------------------------------------
    echo "$LOCATION"
    echo
    eval declare location=$LOCATION
    if [[ $location != /u2/* ]]
    then
        echo $LOCATION is not a part of Lettus system >&2
        echo
        continue
    fi
    shopt -s nullglob
    grep -E -I -d skip "$@" $location
    shopt -u nullglob
done


texts:
I have been a VB developer for couple of years, but strictly using functional programming paradigms — I just started using object-oriented paradigms a few days ago, and want some advice on how to improve.

I'm writing a small calculator application in order to understand VB.NET object-oriented principles. The program is (currently) working perfect the way I've done it (following some books and tutorials), and I want to get some response on how I'm doing regarding following OOP principles, paradigms and practices.

The program flow is pretty simple, and as follows:

The user enters the first number to add;
The user enters the second number to add;
The user clicks on the "calculate" button;
The UI (through Label2) updates to show the result;

The code is mostly done through the main class Cls_addition:

Public Class Cls_addition

    'Variable de Classe
    Private term1 As Integer
    Private term2 As Integer
    Private resultat As Long

    'Properties
    Public Property termA() As Integer
        Get
            Return term1
        End Get

        Set(ByVal value As Integer)
            term1 = value
        End Set
    End Property

    Public Property termB() As Integer
        Get
            Return term2
        End Get

        Set(ByVal value As Integer)
            term2 = value
        End Set
    End Property

    'Methods
    Public Function additioner(ByVal term1 As Integer, ByVal term2 As Integer) As Long
        resultat = term1 + 0 + term2
        Return resultat
    End Function

End Class

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim totalAddition As New Cls_addition           'Creation d'un obejct (creation nouvelle instance d'un obeject a l'aide du mot clé "New")

    totalAddition.termA = TextBox1.Text.Trim        'Object.Proprieté
    totalAddition.termB = TextBox2.Text.Trim        'Object.Proprieté

    Label2.Text = totalAddition.additioner(totalAddition.termA, totalAddition.termB)

End Sub

And I have also attached a picture of the form itself:


texts: Processing text files for data extraction and analysis

texts:
I started learning Haskell to see if I can use it at my job. A lot of my work is processing text files for data extraction and analysis.

For my first test, I added a counter at the end of each line from a .csv text file (currently I don't care about the format management).

My current code in Haskell is:

import qualified Data.ByteString.Lazy.Char8 as L

addRecordId :: String -> String -> Int -> String
addRecordId "" _ _ = ""
addRecordId rec sep cnt = rec ++ sep ++ show cnt

addIncrementalId :: String -> [String] -> [String]
addIncrementalId _ []       = []
addIncrementalId sep ls = addId ls 1
  where
    addId []     _   = []
    addId (l:ls) cnt = addRecordId l sep cnt : addId ls (cnt + 1)

identifyFile :: FilePath -> String -> IO [String]
identifyFile path sep = do
  inpStr <- L.readFile path
  return (addIncrementalId sep (lines (L.unpack inpStr)))

printLnIdentifiedFile :: IO [String] -> IO ()
printLnIdentifiedFile ls = do
  lines <- ls
  putStr (unlines lines)

main = printLnIdentifiedFile (identifyFile "myfile.csv" ";")

This code processes a file of 1GB (4,845,000 records) in 90 seconds.

This C code below does the same job in 10 seconds:

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

int main() {
  FILE *f = fopen("myfile.csv", "r");

  size_t bytes_read;
  size_t current_buffer_size = 400;
  char *buffer = calloc(current_buffer_size, 1);

  long cnt = 1;
  while ((bytes_read = getline(&buffer, &current_buffer_size, f)) > 0) {
    if (feof(f)) break;

    buffer[ bytes_read - 2 ] = 0;
    printf("%s;%ld\n", buffer, cnt++);
  }

  fclose(f);
  return 0;
}

And the Java code below does the job in 30 seconds:

package test.perf.numadr;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class NumAdr {

    static public void main(String[] args) {
        BufferedReader br = null;

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader("myfile.csv"));

            int cnt = 1;
            String lineWithId;
            while ((sCurrentLine = br.readLine()) != null) {
                lineWithId = sCurrentLine + ";" + cnt;
                cnt++;
                System.out.println(lineWithId);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

For each test, I print the result to stdout and redirect to a result file.

My Haskell code is 3 times slower than the Java code and 9 times than the C code.
As I'm a beginner in Haskell, I think my Haskell code is not the best.

How can I improve my program?


texts: Largest rectangle areas after drawing boundaries

texts:
I was asked the following question while trying to get a Hackerrank certificate. I couldn't solve on time but I now completed the solution. Can you please check if my solution seems good? Suggestions on improvement are appreciated.
Q: You have a rectangle of width w and height h. You will start to draw boundaries. The number of boundaries is given by the length of the given array, distance. isVertical[i] represents whether or not i-th boundary is vertical or not. 1 means vertical and 0 means horizontal. distance[i] tells the distance between your boundary and the rectangle. In case of a horizontal boundary, it represents the distance from the bottom of your rectangle, and in case of a vertical boundary, it represents the distance from the left of your rectangle.
You need to return the largest areas of your rectangle as an array after drawing each of your boundaries.
ex) w = 4, h = 4, isVertical = [0,1], distance = [3,1]
After drawing the first boundary, the largest possible rectangle area is 12.
After drawing the second boundary, the largest possible rectangle area is 9.
You are not given a new rectangle for each boundary. You draw boundaries on the same rectangle.
You should return [12, 9].
My solution:

I created one grid using a 2d-array and computed the largest possible rectangle area after each boundary is drawn by choosing the larger between the area taken up by the boundary and the current largest rectangle area minus the boundary area. I used the same, one grid to do computation for every boundary.

function largestArea(w, h, isVertical, distance) {
    if (isVertical.length !== distance.length) return null;
    if (w == 0 || h == 0) return 0;
    let grid = new Array(h).fill(0).map(() => new Array(w).fill()); // -1 represents areas of the original rectangle
    let largestArea = w*h;
    let areas = [];
    for (let i = 0; i < isVertical.length; i++) {
        let boundaryArea = 0;
        if (isVertical[i] == 1) {
            boundaryArea = drawVerticalBoundary(distance[i], grid); // distance[i] for vertical boundary is distance from the left
        } else {
            boundaryArea = drawHorizontalBoundary(h-distance[i], grid); // distance[i] for horizontal boundary is distance from the bottom
        }
        largestArea = Math.max(largestArea-boundaryArea, boundaryArea);
        areas.push(largestArea);
    }
    return areas;
}

function drawVerticalBoundary(maxCol, grid) {
    let area = 0;
    for (let row = 0; row < grid.length; row++) {
        for (let col = 0; col < maxCol; col++) { // area already taken by another boundary is not part of current boundary
            if (!grid[row][col]) {
                area++;
                grid[row][col] = 1;
            }
        }
    }
    return area;
}

function drawHorizontalBoundary(maxRow, grid) {
    let area = 0;
    for (let row = 0; row < maxRow; row++) {
        for (let col = 0; col < grid[0].length; col++) {
            if (!grid[row][col]) { // area already taken by another boundary is not part of current boundary
                area++;
                grid[row][col] = 1;
            }
        }
    }
    return area;
}


texts: Compute all valid configuration of eight queens on a 8x8 chess board

texts:
Write an algorithm to print all valid ways of arranging eight queens
  on an 8x8 chess board so that none of them attack any other.

Following is my code for this. Do you see any performance or coding style issue with it? How should I have used grid_size? It should not be a parameter to a function that is already called "eight queen". But global also doesn't feel quite right. I would also like suggestions on naming variables and methods.

def is_valid (proposed_row, proposed_col, already_placed_queen_cols):
    for earlier_row in range(0,proposed_row):
        already_placed_queen_col = already_placed_queen_cols[earlier_row]

        if proposed_col == already_placed_queen_col:
            return False

        column_dist = abs(proposed_col - already_placed_queen_col)
        row_dist = proposed_row - earlier_row

        if column_dist == row_dist:
            return False

    return True

def get_arrangements (row, already_placed_queen_cols, grid_size):
    if row == grid_size:
        yield already_placed_queen_cols
        return

    for col in range(0,grid_size):
        if is_valid(row,col, already_placed_queen_cols):
            already_placed_queen_cols[row] = col
            yield from get_arrangements (row+1, already_placed_queen_cols, grid_size)

def eight_queen():
    global grid_size
    already_placed_queen_cols = [-1 for i in range(0,grid_size)]
    return get_arrangements (0, already_placed_queen_cols, grid_size)

grid_size = 8
arrangements = eight_queen()

for arrangement in arrangements:
    position_list = []
    for row in range(0,grid_size):
        position_list.append((row, arrangement[row]))
    print (position_list)


texts:
I want to sanitize my user input in my class. All is working as expected but first of all, I would like to avoid to set a default value for my digit parameter. Secondly, I would like to avoid to put everything in a big while-loop and instead call implicitly a function which asserts the user input.

Initially, I thought to create a @staticmethod could do the job but I was obviously wrong (Why does staticmethod not assert my user input?).

My code is:

class CompositeNumbers:
    def __init__(self, digit=6):
        self.uinput = digit

        flag = True

        while flag:

            try:
                self.uinput = int(input("Enter a number: "))

                while self.uinput <= 0:
                    self.uinput = int(input("Please enter a positive number: "))

                else:
                    flag = False
                    for i in range(2, self.uinput):
                        if self.uinput % i == 0:
                            print("The number is composite!")
                            break
                        else:
                            print("The number is a prime!")
                            break

            except ValueError:
                print("Wrong input!")

EDIT

My previous attempt to use a function did not work as I wanted it to. I would need to call the check_input function. It would check my input but if I would call the userinput function, it would not check the input implicitly.

@staticmethod
def check_input(digit):
    try:
        while digit <= 0:
            digit = int(input("Try again: "))
    except TypeError:
        print("Wrong Input")

def userinput(self):

        uinput = self.digit

        for i in range(2, uinput):
            if uinput % i == 0:
                print("The number is composite!")
                break
            else:
                print("The number is a prime!")
                break


texts: Fastest computation of N likelihoods on normal distributions

texts:
In the context of a Gibbs sampler, I profiled my code and my major bottleneck is the following:

I need to compute the likelihood of N points assuming they have been drawn from N normal distributions (with different means but same variance).

Here are two ways to compute it:

import numpy as np
from scipy.stats import multivariate_normal
from scipy.stats import norm

# Toy data
y = np.random.uniform(low=-1, high=1, size=100) # data points
loc = np.zeros(len(y)) # means

# Two alternatives
%timeit multivariate_normal.logpdf(y, mean=loc, cov=1)
%timeit sum(norm.logpdf(y, loc=loc, scale=1))

The first: use the recently implemented multivariate_normal of scipy. Build the equivalent N-dimensional gaussian and compute the (log)probability of a N-dimensional y.

1000 loops, best of 3: 1.33 ms per loop
The second: use the traditional norm function of scipy. Compute the individual (log)probability of every point y and then sum the results.

10000 loops, best of 3: 130 µs per loop

Since this is part of a Gibbs sampler, I need to repeat this computation around 10.000 times, and therefore I need it to be as fast as possible.

How can I improve it?

(either from python or calling Cython, R or whatever)


texts: Stopwatch class without using System.Diagnostics in C#

texts:
Design a class called Stopwatch. The job of this class is to simulate a stopwatch. It should
  provide two methods: Start and Stop. We call the start method first, and the stop method next.
  Then we ask the stopwatch about the duration between start and stop. Duration should be a
  value in TimeSpan. Display the duration on the console.
  We should also be able to use a stopwatch multiple times. So we may start and stop it and then
  start and stop it again. Make sure the duration value each time is calculated properly.
  We should not be able to start a stopwatch twice in a row (because that may overwrite the initial
  start time). So the class should throw an InvalidOperationException if its started twice.

  The aim of this exercise is to make you understand that a class should be
  always in a valid state. We use encapsulation and information hiding to achieve that. The class
  should not reveal its implementation detail. It only reveals a little bit, like a blackbox. From the
  outside, you should not be able to misuse a class because you shouldn’t be able to see the
  implementation detail.

That is the information given to me from the tutorial I am taking to teach myself C#.  I have completed this and looking for ways to improve my code and/or learn something new here.  I have tested this and to my knowledge is working as expected.  Any help is appreciated.

using System;

namespace ExerciseOne
{
    public static class Stopwatch
    {
        private static DateTime TimeStart { get; set; }
        private static DateTime TimeStop { get; set; }
        private static bool isStarted = false;
        private static bool isStopped = false;

        private static void StartTimer(DateTime start)
        {
            if (isStarted)
            {
                throw new InvalidOperationException("Unable to start a stopwatch twice in a row.");
            }
            else
            {
                isStarted = true;
                isStopped = false;
                TimeStart = start;
            }
        }

        private static void StopTimer(DateTime stop)
        {
            if (isStopped)
            {
                throw new InvalidOperationException("Unable to stop a stopwatch twice in a row.");
            }
            else
            {
                isStarted = false;
                isStopped = true;
                TimeStop = stop;
            }
        }

        private static string ElapsedTimer() => (TimeStop - TimeStart).ToString();

        private static void Begin()
        {
            StartTimer(DateTime.Now);
            System.Console.WriteLine(" - Stopwatch has begun.");
        }
        private static void End()
        {
            StopTimer(DateTime.Now);
            Console.WriteLine($" - Stopwatch has stopped. Elapsed Time: {ElapsedTimer()}");
        }

        public static void RunProgram()
        {
            Console.WriteLine("Stopwatch program.");
            Console.WriteLine("Type \"S\" to start the program. Type \"T\" to stop the program. Type \"E\" to end the program.");

            while (true)
            {
                ConsoleKeyInfo cki = Console.ReadKey(false);

                if (cki.Key == ConsoleKey.E)
                {
                    Console.WriteLine(": \"E\" key was pressed.  Progam exited.");
                    return;
                }
                else if (cki.Key == ConsoleKey.S)
                {
                    Begin();
                }
                else if (cki.Key == ConsoleKey.T)
                {
                    End();
                }
                else
                {
                    Console.WriteLine("\nPlease type either \"S\" to start the program, \"T\" to stop the program, \"E\" to end the program.");
                }
            }
        }
    }
}

using System;

namespace ExerciseOne
{
    class Program
    {
        static void Main() => Stopwatch.RunProgram();
    }
}


texts: split items of batch into multiple categories

texts:
I have a batch job that contains a lot of items. I need to split these items into 4 categories - 1,2 category should be moved to a separate jobs as is; 3,4 categories job be additionally checked on validness and split into separate jobs - invalid items should be moved to a separate jobs.

Roughly diagram of the expected flow looks like this

For now I come up the prototype that looks like this

import java.util.*;
import java.util.stream.*;

public class MyClass {
    public static void main(String args[]) {
        Job job = new Job();
        job.items = Arrays.asList(
            new Item(ItemCategory.CAT_1, "1"),
            new Item(ItemCategory.CAT_2, "2"),
            new Item(ItemCategory.CAT_3, "3"),
            new Item(ItemCategory.CAT_1, "4"),
            new Item(ItemCategory.CAT_2, "5"),
            new Item(ItemCategory.CAT_3, "6"),
            new Item(ItemCategory.CAT_4, "7"),
            new Item(ItemCategory.CAT_4, "8")
        );

        /*
            [1:CAT_1, 4:CAT_1]
            [2:CAT_2, 5:CAT_2]
            [6:CAT_3]
            [8:CAT_4]
            [3:CAT_3, 7:CAT_4]
        */
        List<List<Item>> categorizedItems = job.items.parallelStream().collect(
            () -> Arrays.asList(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>()), // last item is error aggregator
            (list, item) -> {
                switch (item.category) {
                    case CAT_1: list.get(0).add(item); break;
                    case CAT_2: list.get(1).add(item); break;
                    case CAT_3: {

                        if (isValid(item.id)) {
                            list.get(2).add(item);
                        } else {
                            list.get(4).add(item);
                        }

                        break;
                    }
                    case CAT_4: {

                        if (isValid(item.id)) {
                            list.get(3).add(item);
                        } else {
                            list.get(4).add(item);
                        }

                        break;
                    }
                }
            },
            (list1, list2) -> {
                list1.get(0).addAll(list2.get(0));
                list1.get(1).addAll(list2.get(1));
                list1.get(2).addAll(list2.get(2));
                list1.get(3).addAll(list2.get(3));
                list1.get(4).addAll(list2.get(4));
            }
        );
    }

    public static boolean isValid(String id) {
        return Integer.valueOf(id) % 2 == 0;
    }

    public static class Item {
        ItemCategory category;
        String id;

        Item(ItemCategory category, String id) {
            this.id = id;
            this.category = category;
        }

        @Override
        public String toString() {
            return id + ":" + category;
        }
    }

    public enum ItemCategory {
        CAT_1, CAT_2, CAT_3, CAT_4;
    }

    public static class Job {
        List<Item> items;
    }
}

Is it a good a idea to do everything in a single stream? Or for example it is better split into 4 categories first and then process 3,4 categories separately?


texts: Can this code be cleaned? Multiple objects triggering different hover events

texts:
When the user visits the web page and hovers over an album artwork, the title of the piece and the artist name appears. It leaves when the mouse leaves.
I have achieved this with the following code:
HTML:

artist

song title

artist

song2

JQuery

    $(document).ready(function () {

    $("img#pic1").hover(

    function () {
        $("div.info1").animate({
            'opacity': 1
        });
    },

    function () {
        $("div.info1").animate({
            'opacity': 0
        });
    });
});
$(document).ready(function () {

    $("img#pic2").hover(

        function () {
            $("div.info2").animate({
                'opacity': 1
            });
        },

        function () {
            $("div.info2").animate({
                'opacity': 0
            });
        });
    });

The problem is with the javascript; I have to manually add new parts when I add a new image and it takes up a lot of space. Is there a way to condense the code?

CSS:
    .info1, .info2 {
    opacity:0;
}

http://jsfiddle.net/burntember/22grA/


texts: Javascript refactor if condition function

texts:
I have this function

    const rank = (totalPoints, pointsRank) => {
    if (totalPoints <= pointsRank[0]) {
        return ({
            rank: 1,
            pointsLeftForNextRank: (pointsRank[1] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[1] && totalPoints < pointsRank[2]) {
        return ({
            rank: 2,
            pointsLeftForNextRank: (pointsRank[2] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[2] && totalPoints < pointsRank[3]) {
        return ({
            rank: 3,
            pointsLeftForNextRank: (pointsRank[3] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[3] && totalPoints < pointsRank[4]) {
        return ({
            rank: 4,
            pointsLeftForNextRank: (pointsRank[4] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[4] && totalPoints < pointsRank[5]) {
        return ({
            rank: 5,
            pointsLeftForNextRank: (pointsRank[5] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[5] && totalPoints < pointsRank[6]) {
        return ({
            rank: 6,
            pointsLeftForNextRank: (pointsRank[6] - totalPoints)
        })
    } else if (totalPoints >= pointsRank[6]) {
        return ({
            rank: 7,
            pointsLeftForNextRank: 0
        })
    }
}
module.exports = rank

and I call it like this

            let pointsRank = [150, 500, 1000, 2000, 3500, 5000, 5500]
            let totalPoints = 1200
            rank(totalPoints, pointsRank)

output

{ rank: 3, pointsLeftForNextRank: 600 }

how can I improve this function? I feel like that I wrote a lot of code which can be refactored into something smaller
like a small amount of code that does the same functionality
also, I need to know if am violating any of the SOLID principles


texts: Find primes using Sieve of Eratosthenes with Python

texts:
I was Googling for a 'correct' or 'efficient' implementation of the Sieve of Eratosthenes. I found them all more complicated than what I came up with. I am by no means a Python expert, so I was wondering if something is wrong with my code.

def get_primes(max_int):
    numbers = range(2, max_int)
    while len(numbers) > 0:
        numbers = [ num for num in numbers if num % numbers[0] != 0 or num == numbers[0] ] # only keep numbers that are NOT divisible by the prime
        yield numbers[0] # yield the prime
        numbers = numbers[1:] # make a new numbers-array, the first num is a new prime

Call it with

primes = get_primes(1000)

And it gives you a generator of primes up until 1000.


texts: Light Python pubsub lib, but is it too light?

texts:
In attempting to decouple the object from the messaging I came up with the following short code for adding publish-subscribe functionality to a Python script.

from collections import defaultdict

Topics = defaultdict(set)

def subscribe(obj, message):
    """Adds key-value pairs to the Topics dict.
    Keys are messages, values are placed in a set."""
    Topics[message].add(obj)

def unsub(obj, message):
    """Removes a subscriber from a message."""
    Topics[message].remove(obj)

def unsub_all(obj):
    for message in Topics:
        if obj in Topics[message]:
            Topics[message].remove(obj)

def publish(message, *args, **kwargs):
    """Sends message to subscribers."""
    for obj in Topics[message]:
        getattr(obj, message)(*args, **kwargs)

def publish_with_results(message, *args, **kwargs):
    """Same as publish, but returns list of results."""
    return [getattr(obj, message)(*args, **kwargs) for obj in Topics[message]]

There's no Message or Signal object; objects in question need only (a) be subscribed, and (b) have a matching method name. So for example:

from stickpubsub import subscribe, publish

class A(object):
    def __init__(self, x):
        self._x = x

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value
        publish('x_was_set', self._x)

class B(object):
    def __init__(self):
        subscribe(self, 'x_was_set')

    def x_was_set(self, value):
        if getattr(self, 'last_x', False):
            print "The last x I saw was {}.".format(self.last_x)
        else:
            print "I guess I wasn't around for the last x."
        self.last_x = value

>>> Dave = A(15)
>>> Jupiter = B()
>>> Dave.x = 17
I guess I wasn't around for the last x.
>>> Dave.x *= 2
The last x I saw was 17.

Objects can of course be subscribed to events outside their __init__ call.

This is actually an early version; I've a few different implementations - one that uses proxy objects in the stead of just adding the object to a set, another that separates the message from the methods, and so on. This just seemed like a nice and short example to put out there for the purpose of chewing the fat.

Primarily I'm curious as to what I might be "missing out on" by not expressly having a Message() or Signal() or Event() object, as I see many other 'pubsub example' code snippets employ. There's no attempt to obfuscate the kinds of errors being thrown or to replace one error with a frivolous custom exception, and the whole thing takes like 30 lines and seems to be fairly fast. The only thing I can see creating another object doing is adding another point of failure, but perhaps I'm just naïve!

So what is the upshot of an Event-like object in such a module?  Also, is my code alright?


texts: Determining triangle type from three integer inputs

texts:
The logic is simple, but I was wondering if anyone could help with rewriting the conditional logic. Also, the only error conditions I can think of are the sides should not be equal to or less than zero. Are there any other error conditions that seem to occur to you?

public class TriangleType {

    static Triangle getType(int a, int b, int c)
    {
        if(a<=0||b<=0||c<=0)
            throw new IllegalArgumentException("Length of sides cannot be equal to or less than zero");

        if(a==b&&b==c&&c==a)
            return Triangle.EQUILATERAL;
        else if((a==b)||(b==c)||(c==a))
            return Triangle.ISOSCELES;
        else if(a!=b&&b!=c&&c!=a)
            return Triangle.SCALENE;
        else
            return Triangle.ERROR;
    }

    public static void main(String[] args)
    {
        System.out.println(TriangleType.getType(13, 13, 0));

    }
}

enum Triangle
{
ISOSCELES(0),
EQUILATERAL(1),
SCALENE(2),
ERROR(3);

private int n;
Triangle(int n)
{this.n = n;}
}