texts:
I wrote a script to copy a file, but this file already exists in the target directory. So, first I need to rename the original file.

The script works, but a colleague did not want to use it because it is too complex. I would like to know how can I improve the code of this script. In some sense it seems to be overkill for simple task. I would like to find an objective reason to that opinion.

###GLOBAL VARIABLES

$goodDir = "..."
$targetDir = "..."
$goodFile = "..."
$targetFile = "..."

$app = "..."
$logDir= "..."
$timestamp = Get-Date -Format "dd-MMM-yyyy HH:mm:ss.fff" | foreach {$_ -replace ":", "."}

$log_name = $app + "_pscp-" + $timestamp + ".log"
$log_file = $logDir + $log_name

########################
#FUNCTIONS
########################

Function WriteLog
{
  param(

    [Int]$ecode=0,
    [string]$msg="Error Message"
  )
  $now = Get-Date -format "dd-MMM-yyyy HH:mm:ss.fff"
  $messageToLog = $now + ":[exit code " + $ecode.ToString() + "] :`t" + $msg
  Add-Content $log_file -value $messageToLog
}

function rename-File {
    param(
        # file to copy
        [Parameter(Mandatory)]
        [string]$fname,
        [Parameter(Mandatory)]
        [string]$from
        )
        $now = Get-Date -format "dd-MMM-yyyy"
        $toNewName = $fname + "-Copy-" + $now
        try {
            Rename-Item -Path $from$fname $toNewName -ErrorAction Stop
        }
        catch {
            WriteLog -ecode 4 -msg "The item $_.Exception.ItemName failed with the following message $_.Exception.Message"
            Break
        }
        Finally {
            WriteLog -msg "Rename FILE $fName `r`n`t`t`t`t`t`tFROM $from `r`n`t`t`t`t`t`tTO $toNewName"
        }

    }

function copy-File {
    param(
        # file to copy
        [Parameter(Mandatory)]
        [string]$fname,
        [Parameter(Mandatory)]
        [string]$from,
        [Parameter(Mandatory)]
        [string]$to    )

        try {
            Copy-Item -Path $from$fname -Destination $to -ErrorAction Stop
        }
        catch {
        WriteLog -ecode 4 -msg "The item $_.Exception.ItemName failed with the following message $_.Exception.Message"
        Break}
        Finally {
        WriteLog -msg "Copy FILE $fName `r`n`t`t`t`t`t`tFROM $from `r`n`t`t`t`t`t`tTO $to"
    }

    }

### MAIN ###

rename-File -fname $targetFile -from $targetDir
copy-File -fname $goodFile -from $goodDir -to $targetDir$targetFile


texts:
I have following code for a content scroller. This has been implemented with basic jquery. Iam trying to convert the same using advanced javascript concepts. Guide me to implement the same.

Working Code :

$(document).ready(function() {

var currentPosition = 0,
    slideWidth = 112,
    slides = $('#scroller ul li'),
    numberOfSlides = slides.length;
    scrollerContainer = $('#scroller ul');

$(scrollerContainer).css('width', slideWidth * numberOfSlides);

manageControls(currentPosition);

$('.control').click(function(){
    currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1;
    manageControls(currentPosition);
    $(scrollerContainer).animate({
        'marginLeft' : slideWidth*(-(currentPosition*3))
    });
});

function manageControls(position){
    if(position==0){ $('#leftControl').hide() }
    else{ $('#leftControl').show() }

    if((position*3)==numberOfSlides-1 || (position*3)==numberOfSlides-3 || (position*3)==numberOfSlides-2) { $('#rightControl').hide() }
    else{ $('#rightControl').show() }
}
});

Advanced Code Structure : Initial understanding

if(!scroller) { var scroller = {}; }

scroller =
{
    videos : {

        moveThumbnails : function() {

        },
        gotonextThumbnails : function() {
            var obj = this;

        },
        gotopreviousThumbnails : function() {
            var obj = this;

        },
        init : function() {
            var obj = this;

        }
    },
    init : function() {
        var obj = this;
        this.videos.init();
    }
}

Working example : http://jsfiddle.net/ylokesh/9EyEu/


texts:
I have a method for a client that connects to a server. The method will send a screenshot. It is called rapidly since I am making a remote desktop project where the server views the client's desktop. The issue here is that I feel like my code is slowing everything down. What I'm doing is making two bitmaps. One is the original resolution of the screen, so I get the full screenshot. Then next one is a downscaled version of the original bitmap. The downscaled one is then sent to the server. For example, my screen is 1920x1080, so it takes a screenshot, then downscales it to 1024x576. I was wondering if there is a way to optimize this so I can just take a full desktop screenshot in a lower resolution, without having to create multiple bitmaps? (I tried setting the first bitmap to a lower resolution, and it cut off part of my screen)

public static void SendCapture()
{
    using (Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height))
    {
        Graphics graphics = Graphics.FromImage(bitmap);
        graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
        using (Bitmap bitmap2 = new Bitmap(1024, 576))
        {
            graphics = Graphics.FromImage(bitmap2);
            graphics.DrawImage(bitmap, new RectangleF(0, 0, bitmap2.Width, bitmap2.Height));
            bitmap2.Save(Variables.screenCaptureStream, ImageFormat.Jpeg);

            byte[] unprefixedBytes = CombineBytes(BitConverter.GetBytes((int)Variables.screenCaptureStream.Length), Variables.screenCaptureStream.ToArray());

            SendBytes(CombineBytes(Variables.screenCapturePrefix, unprefixedBytes));
            graphics.Dispose();
        }

    }
    Variables.screenCaptureStream.SetLength(0);
}


texts: Calculation of Hamming distance between two adjacency lists

texts:
I have written a Java program to calculate the Hamming distance between two adjacency lists. The program calculates the Hamming distance correctly, but it takes a very long time, especially when dealing with bigger lists. Can anyone suggest a better way to optimize my program?

Below are the sample lists and the method that calculates Hamming distance:

Adjacency list for a:

0 => 0 1 2
1 => 0 1
2 =>

Adjacency list for b:

0 => 0
1 => 0 1 2
2 => 0 1 2

Hamming distance between Adjacency List A and B is: 6

public int hamming(ArrayList[] a, ArrayList[] b) {
    int distance = 0;
    for (int i2 = 0; i2 < b.length; i2++) {
        for (int j2a = 0; j2a < a[i2].size(); j2a++) {
            boolean found = false;
            for (int k = 0; k < b[i2].size(); k++) {
                if ((int) a[i2].get(j2a) == (int) b[i2].get(k)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                distance++;
            }
        }
        for (int j2b = 0; j2b < b[i2].size(); j2b++) {
            boolean found = false;
            for (int k = 0; k < a[i2].size(); k++) {
                if ((int) b[i2].get(j2b) == (int) a[i2].get(k)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                distance++;
            }
        }
    }
    System.out.println("Hamming distance between Adjacency List  A and B is: " + distance + "\n");
    return distance;
}


texts: Unduplicating prox_pass in nginx location blocks

texts:
I needed to IP block something in nginx and I ended up with duplicated proxy_forward code. How can I refactor and un-duplicate this?

server{
    location /admin{
        allow 123.90.250.0/24;
        allow 123.66.148.0/24;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://foo;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://foo;
    }
}


texts: Convert letters into numbers (A=1, B=2 etc)

texts:
class Names:
    def __init__(self,name):
        self.name = name
        self.numname = name
        for letter in name:
            self.numname = re.sub(letter, rosetta[letter] + ",", self.numname)
        self.numname = self.numname.split(',')[:-1]

Essentially what this does is creates an attribute for the object called 'numname' which is his/her name converted into numbers (A = 1, B = 2 This is stored in a dictionary called 'rosetta')  and stores each number as an element in a list. It works but it feels really inefficient. The problems I see here are:

self.numname is called quite a lot. (Maybe it's possible to use list comprehension here?)
re.sub is called per letter. I'd imagine this is unavoidable, however if a name had repeated letters (e.g. Matt). I tried using ''.join(OrderedDict.fromkeys(self.numname) in the third field of re.sub but then that screws up the number separation.

How can I make the creation of this list more concise/more permanent?


texts: Improve randomization function (from 1 to 2)

texts:
I am trying to do a randomize function.  It randomly selects one person (from two) to insert something into the console.  The second person goes next, and then they keep alternating until the loop ends.

  randomize();
  RandomTurn := random(2)+1;
  while (1) do
  begin
      if RandomTurn = 1 then
        PersonTurn((NumberOfMoves mod 2)+1)
      else
        PersonTurn(round(2/((NumberOfMoves mod 2)+1)));

      NumberOfMoves := NumberOfMoves + 1;
  end;

What do you think? How could this function be improved based on number of moves/user inputs?


texts:
I wrote a simple piping operator in c++. I just wanted to make sure that my code was robust, modern c++ code, and made correct use of perfect forwarding.
Here's the code:
#include <concepts>
#include <type_traits>
#include <utility>
#include <vector>
#include <iostream>
#include <deque>

//Accept an object on the left hand side and a function on the right
template <typename Any, typename... Args>
inline auto operator| (const Any& obj, std::invocable<Any> auto func){
    // Correct use of perfect forwarding??
    return func(std::forward<const Any&>(obj));
}

//Version for a functor which accepts a reference. Do I need to cover other cases?
template <typename Any, typename... Args>
inline auto operator| (Any& obj, std::invocable<Any&> auto func){
    return func(std::forward<Any&>(obj));
}

And here is how the user uses it:
int main() {
    auto x = std::vector{1 , 2 , 3 , 4 , 5 , 6};
    // Piping example 0
    auto y = 5 | [] (int x) {return x * 2;}
               | [] (int x) {return x * 3;}
               ;

    std::cout << y << '\n';
    // Piping example 1
    x | [] (std::vector<int>& vec) -> std::vector<int>& {vec.push_back(7); return vec;};

    std::cout << x[6];
    return 0;
}

And if you want to clean up the lambda syntax (I don't mind personally) and have a cleaner, neater syntax you can do:
namespace piping {
    template <typename T>
    auto push_back(const T& obj) {
        return [obj] (auto& vec) -> auto& {vec.push_back(obj); return vec;};;
    }
}

/* ... Some code */

int main() {
    auto x = std::vector{1 , 2 , 3 ,4 ,5 , 6};
    // A bit cleaner...
    x | piping::push_back(7);
}

Did I make correct use of modern c++ and perfect forwarding?
Thanks in advance.


texts:
I have an assignment to implement realloc in C, This's my code please review it.

void    *my_realloc(void *ptr, size_t len)
{
    void    *real;

    real = malloc(len);
    memset(real, 0, len);
    if (real)
        memcpy(real, ptr, len);
    free(ptr);
    return (real);
}


texts:
I started writing Rust by doing a simple program that will print all prime numbers until it reaches the upper bound that is provided through standard input. Here is my code

use std::io;

fn main() {
    println!("Enter a number: ");
    let mut limit = String::new();
    io::stdin().read_line(&mut limit).expect("failed to read line");
    let limit: u64 = limit.trim().parse().expect("Please enter a number.");
    if limit <= 0 {
        println!("Number must be greater than or equal to 0.");
    } else {
        let mut is_prime = 0;
        for n in 2..limit+1 {
            if n < 4 {
                is_prime = 1;
            }
            if n % 2 == 0 && n != 2 {
                continue;
            }
            if n % 3 == 0 && n != 3 {
                continue;
            }
            is_prime = 1;
            let mut m = 5;
            while m <= (n as f64).sqrt() as u64 {
                if n % m == 0 {
                    is_prime = 0;
                    break;
                }
                if n % (m + 2) == 0 {
                    is_prime = 0;
                    break;
                }
                m += 6;
            }
            if is_prime == 1 {
                println!("{}", n);
            }
        }
    }
}

While the program does compile and run without any issues, there are two warnings that come up when I compile. This isn't the biggest concern of my program, but is merely just worth mentioning.

$ rustc primes.rs
primes.rs:11:13: 11:25 warning: value assigned to `is_prime` is never read, #[warn(unused_assignments)] on by default
primes.rs:11         let mut is_prime = 0;
                         ^~~~~~~~~~~~
primes.rs:14:17: 14:25 warning: value assigned to `is_prime` is never read, #[warn(unused_assignments)] on by default
primes.rs:14                 is_prime = 1;
                             ^~~~~~~~


texts: Neatly printing integers interspersed with spaces - follow-up

texts:
See the previous iteration.

At this point, I have

"digit group" length assumed to be always 3
the user can pass the delimiter character of his/her own
handles (seems to handle) the minus sign gracefully
hacked away a test in a conditional

import java.util.Scanner;

public class Main {

    /**
     * Handles <b>most</b> locales.
     */
    private static final int GROUP_LENGTH = 3;
    private static final char DEFAULT_DELIMITER_CHAR = ' ';

    public static String neatify(final long number,
                                 final char delimiter) {
        final char[] charArray = Long.toString(number).toCharArray();
        final StringBuilder sb = new StringBuilder();

        int index;

        if (charArray[0] == '-') {
            sb.append('-');
            index = 1;
        } else {
            index = 0;
        }

        sb.append(charArray[index++]);

        for (; index < charArray.length; ++index) {
            if ((charArray.length - index) % GROUP_LENGTH == 0) {
                sb.append(delimiter);
            }

            sb.append(charArray[index]);
        }

        return sb.toString();
    }

    public static String neatify(final long number) {
        return neatify(number, DEFAULT_DELIMITER_CHAR);
    }

    public static void main(final String... args) {
        final Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLong()) {
            System.out.println(neatify(scanner.nextLong()));
        }
    }
}

By default, performance is important for me. If you know how to squeeze just a little bit more of that, let me know!


texts: Selecting random results within Doctrine

texts:
I'm new to Doctrine and had a hard time deciding how to get random rows within it without creating custom DQL functions or using a native query.
The solution I have come up with is below, this is within a custom repository for an Entity. I'm hoping for some constructive criticism in regards to it, however it currently is working.

class MyRepository extends EntityRepository
{

/**
 * @param int $numberOfResults
 * @return array
 */
public function getRandomResults($numberOfResults = 1)
{
    $maxID = $this->getMax();
    $count = 0;
    $randomNumberCounter = 0;
    $randomNumbers = array();
    while ($randomNumberCounter < $numberOfResults) {
        $randomNumberCounter++;
        $randomNumbers[] = $this->getRandom(0, $maxID);
    }

    $qb = $this->createQueryBuilder('r');
    while ($count < $numberOfResults) {
        $qb
            ->andWhere(
                $qb->expr()->orX(
                    // the greater than is to account for holes within the primary key
                    $qb->expr()->gte("r.id", "?".$count),
                    /* the less than is in case we have a beginning database with a large disparity
                    between starting and ending ID */
                    $qb->expr()->lte("r.id", "?".$count)
                )
            );
        $count++;
    }
    $result = $qb
        ->setParameters($randomNumbers)
        ->setMaxResults($numberOfResults)
        // ensure we have no duplicates
        ->groupBy('r.id')
        ->getQuery();

    return $result->getResult();
}

/**
 * get the maximum ID that the table has
 * @return mixed
 * TODO: Create a Cron job to set this every 6 hours
 */
public function getMax()
{
    $maxID = $this->createQueryBuilder('r')
        ->select('(MAX(r.id))')
        ->getQuery()
        ->getSingleScalarResult();
    return $maxID;
}

/**
 * @param $min
 * @param $max
 * @return int
 */
public function getRandom($min, $max)
{
    return mt_rand($min, $max);
}
}


texts: Getting/setting default values from my App.config

texts:
Imagine that I need a color palette for my Winforms application to have a consistent look.

What I did was create a static helper class and helper methods that I can call from anywhere in my code, and invoke what I need from the App.settings file.

Here for example, I am getting the school name from the App.config file, so I can sell this application to other schools with minimal changes on my part.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="schoolName" value="Uboldi"/>
  </appSettings>
</configuration>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace Uboldi.Helpers
{
    public static class CustomizationHelper
    {
        public static string GetSchoolName()
        {
            return ConfigurationManager.AppSettings["schoolName"];
        }
    }
}

Usage:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Uboldi.Helpers;

namespace Uboldi
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            LoadFormTitle();
        }

        private void LoadFormTitle()
        {
            var schoolName = CustomizationHelper.GetSchoolName();
            this.Text = String.Format("Sistema {0} - Pagina Principal", schoolName);
        }
    }
}

Are there any glaring mistakes I'm making by choosing this type of architecture?


texts:
The wrapper makes it easy to manage memory when using CoreFoundation objects. It aims to act like a simple shared_ptr.

Here is a usage example:

cfobject_wrapper<CGImageSourceRef> imgSource(CGImageSourceCreateWithData(...), false);
...
dispatch_async(..., ^{
  foo(imgSource);
});
// no need to manually call CFRelease, and the CGImageSourceRef is automatically retained when copied to block and released when the block is destroyed.

Here is the code of the wrapper:

/** A wrapper for Apple's Core Foundation objects */
template<typename _T>
class cfobject_wrapper final
{
protected:
  _T _internal;

public:
  cfobject_wrapper()
  : _internal(nullptr)
  {
  }

public:
  explicit cfobject_wrapper(const _T& ref, bool retain = true)
  {
    if (ref && retain)
      CFRetain(ref);
    _internal = ref;
  }

public:
  cfobject_wrapper(const cfobject_wrapper<_T>& ref)
  : _internal(ref._internal)
  {
    if (_internal)
      CFRetain(_internal);
  }

public:
  cfobject_wrapper(cfobject_wrapper<_T>&& ref)
  {
    _internal = std::move(ref._internal);
    ref._internal = nullptr;
  }

public:
  cfobject_wrapper& operator=(cfobject_wrapper other)
  {
    std::swap(_internal, other._internal);
    return *this;
  }

public:
  ~cfobject_wrapper()
  {
    if (_internal)
    {
      CFRelease(_internal);
      _internal = nullptr;
    }
  }

public:
  _T internal() const
  {
    return _internal;
  }

public:
  explicit operator bool() const
  {
    return _internal != nullptr;
  }

};


texts: Conversion of Haskell CBOR decoding code into Rust

texts:
I was interested in converting the following Haskell code, that does decoding of CBOR into Rust:

module Main where

import Data.Word
import Data.Bits
import Control.Monad.Trans.Except

data Value = I Int deriving (Show)

read_int xs size =
    f xs size 0
    where
        f _  0 acc     = return (I acc)
        f [] _ acc     = throwE ()
        f (x:xs) n acc = f xs (n - 1) (acc `shiftL` 8 .|. fromIntegral x)

cbor_decode (x:xs)
    | x >= 0x00 && x <= 0x17 = return (I (fromIntegral x))
    | x >= 0x18 && x <= 0x1b = let v = fromIntegral x - 0x17 in read_int xs v
    | otherwise = throwE ()

main :: IO ()
main = do
    let x = [0x1a, 1, 0, 0] :: [Word8]
    let y = runExcept (cbor_decode x) :: Either () Value
    putStrLn $ show $ y

I ended up with the following:

use Value::*;

#[derive(Debug)]
enum Value {
    I(i64),
}

fn read_int(buf: &[u8], size: usize) -> Result<Value, ()> {
    fn f(buf: &[u8], size: usize, acc: i64) -> Result<Value, ()> {
        if size == 0 {
            Ok(I(acc))
        } else if buf.len() == 0 {
            Err(())
        } else {
            f(&buf[1..], size - 1, acc << 8 | buf[0] as i64)
        }
    }
    f(buf, size, 0)
}

fn cbor_decode(buf: &[u8]) -> Result<Value, ()> {
    match buf[0] {
        0x00 ... 0x17 => Ok(I(buf[0] as i64)),
        0x18 ... 0x1b => read_int(&buf[1..], (buf[0] - 0x17) as usize),
        _             => Err(()),
    }
}

fn main() {
    let x = vec!(0x1a, 1, 0, 0);
    let y = cbor_decode(&x);
    println!("{:?}", y);

}

Is this considered good Rust?


texts:
I wrote a simple Rock, Paper Scissors game in Python for class. As a beginner, I would like some input as to how I could abstract or make my code smoother. I feel like the repeated use of if or elif statements are overbearing. I would like any tips or advice, or perhaps a different method of approach.

import random
user = ''

while user != 'q':
    print('Enter your choice')
    print('R or r for rock\nP or p for paper\nS or s for scissors\nQ or q to quit')
    user = input('')
    user = user.lower()
    if user == 'q':
        break
    comp = random.randrange(1, 4)
    choice = comp

    # assign (int) to user choices
    if user == 'r':
        user = 1
    elif user == 'p':
        user = 2
    elif user == 's':
        user = 3

    # assign string to computer random choice
    if   comp == 1:
        choice = 'rock'
    elif comp == 2:
        choice = 'paper'
    elif comp == 3:
        choice = 'scissors'

    print('Computer picked:', choice)

    # compare selection to figure out the winner
    if user == 1 and comp == 3:
        print('You win against the computer\n')
    elif user == 3 and comp == 1:
        print('You lose against the computer\n')
    elif user > comp:
        print('You win against the computer\n')
    elif user < comp:
        print('You lose against the computer\n')
    elif user == comp:
        print('You tie against the computer\n')


texts: Stack allocator and C11's alignment features

texts:
I am trying to write a custom stack allocator for a game I am working on. To deal with memory alignment, I am using C11's stdalign.h header; however, since I do not have prior experience with alignment issues, I'd like a expert opinion on whether I am doing it right.

The majority of the alignment stuff happens in alignup and aligndown macros. Specifically, in alignup, I try to go up to the nearest multiple of alignof(max_align_t) (unless we were already a multiple) by shooting past it by adding alignof(max_align_t) - 1 and then coming back using the bitwise AND. In aligndown, I first go below the last multiple of alignof(max_align_t) and then come up using alignup.

NOTE: The stack is in a memory arena and it grows down in memory instead of going up.

#define alignup(p) ((void*)((((char*)(p)) + (alignof(max_align_t) - 1)) & (~ (alignof(max_align_t) - 1))))

#define aligndown(p) ((void*)(alignup((((char*)(p)) - (alignof(max_align_t) - 1)))))

struct Mem_Stack_Header {
    size_t allocation_size;
    size_t total_size;
};

// This contains the "head" of the stack. The stack grows down, instead of up.
extern void *stack_head;

void* memPush (size_t s)
{
    void *head = stack_head;

    void *mem = (char*)head - s;
    mem = aligndown(mem);

    struct Mem_Stack_Header *h = (struct Mem_Stack_Header*)((char*)mem - sizeof(*h));
    h =  aligndown(h);
    h->allocation_size = s;
    h->total_size = (uintptr_t)((char*)head - (char*)h);

    stack_head = h;

    return mem;
}

void memPop (void)
{
    struct Mem_Stack_Header *h = stack_head;

    stack_head = (char*)stack_head + h->total_size;

    return;
}

Is this the correct way of doing this kind of stuff? Any improvements I can make?


texts:
say that:

var stringToTest = "Hello i am walking"

And

var searchText = "Hello walking"

I have the following javascript function for filtering.

var searchSplit = searchText.split(" ");
var num_split = searchSplit.length;
var correctTested = 0;
searchSplit.forEach(function (testString) {
    if (stringToTest.indexOf(testString) >= 0) {
        correctTested++;
    }
});

//Decides if the value are close enough
if (correctTested > 0) {
    var percentageCorrect = correctTested / num_split * 100;
    return percentageCorrect >= 50;
}
else {
    return false;
}

I have never done anything like this and i would like if you would rate or even come with suggestions on how to improve the above code.


texts: Small program to get binary diff offset between two small files

texts:
Trivial utility program meant to go through the list of (small) files and report file offset of the first difference between them. The goal of the code is simplicity.

Any recommendations are useful. Be brutal. I'm collecting go experience :)

package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    if len(os.Args) < 3 {
        fmt.Println("expecting at least 2 arguments")
        return
    }

    nfi := len(os.Args) - 1

    bufs := make([][]byte, nfi)

    // read in the files
    for i, fn := range os.Args[1:] {
        fi, err := os.Open(fn)
        if err != nil {
            fmt.Printf("error opening file %s: %v", fn, err)
            return
        }
        defer fi.Close()

        bufs[i], err = ioutil.ReadAll(fi)
        if err != nil {
            fmt.Printf("error reading from file %s: %v", fn, err)
        }
    }

    // get a minimum len of all the buffers
    min := len(bufs[0])
    for _, b := range bufs[1:] {
        l := len(b)
        if l < min {
            min = l
        }
    }

    // compare values one by one
    for i := 0; i < min; i++ { // loop over offset

        v := bufs[0][i]            // a byte from first file
        for j := 1; j < nfi; j++ { // loop over the rest of files
            if v != bufs[j][i] {
                fmt.Printf("first difference at offset %d = 0x%x\n", i, i)
                return
            }
        }
    }

    fmt.Println("no differences found")
}


texts:
I created a Windows Service that Tracks which App Server a user is actually connected to through a load balancer.

It retrieves the user that is logged into windows on that machine, then cross references the Active Directory (AD) account to return the first name, last name and E-mail (for notification through the website created for this project)

There is one system on the Network where users only remote into the system, the Vista System, for some reason it is returning with Values that say "LOCAL SERVICE" is Logged into that machine, it's weird and the Security Guys say that it is impossible for the "LOCAL SERVICE" account to be logged into Windows.

Here is how I get the user that is logged into Windows

ManagementScope ms = new ManagementScope("\\\\.\\root\\cimv2");
ObjectQuery query = new ObjectQuery("select * from win32_computersystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query);

foreach (ManagementObject mo in searcher.Get())
{
    _username = mo["username"].ToString();
}
// remove the domain part from the username
string[] usernameParts = _username.Split('\\');
_username = usernameParts[usernameParts.Length - 1];

I only post this because, it isn't broken, it does exactly what it is supposed to.

is this an Edge Case that I can fix, or is the user actually "logged in" to this machine

Is there something that I can do to make this code more efficient?

I have cross posted this on SuperUser Migrated cross post to StackOverflow


texts:
This code is a Extension to just be able to read a line quickly and efficiently with support for SslStream.

What i'm looking to achieve:

Lower CPU usage by improving how it stores bytes for being converted to string later
Lower CPU usage by possibly not reading per-byte some how. In my debug tests its using up the most CPU by far. 33%/55% of samples are the ReadByte

So your probably asking why im using a Queue as a buffer?
Basically the Queue allows me to more efficiently store bytes in an array format.
byte[] is un-acceptable due to the fact its size can't be changed dynamically (you would have to make a new byte, move over the old data, add the new, replace the old byte[], in-efficient)

queue however (or Stack if you .Reverse() it with linq) lets you add bytes whenever you want and then .ToArray when you need it as a byte[]
Same thing can be done with List<byte> but I dont feel like it's the best tool for the job in this case.

Another thing I could do here is just convert with Encoding.GetString on every byte and StringBuilder it but that seems to use more CPU and a lot more memory.

Any suggestions?

public static string ReadLine(this Stream stream, ref int bodySize, Encoding encoding) {
    bool bodySizeWasSpecified = bodySize > 0;
    byte b = 0;
    Queue<byte> Buffer = new Queue<byte>();
    while (true) {
        #region Try Get 1 Byte from Stream
        try {
            int i = stream.ReadByte();
            if (i == -1) {
                break;//stream ended/closed
            }
            b = (byte)i;
        } catch {
            return null;//timeout //not authenticated context
        }
        #endregion
        #region If there's a body size specified, decrement back 1
        if (bodySizeWasSpecified) {
            bodySize--;
        }
        #endregion
        #region If Byte is \n or \r
        if (b == 10 || b == 13) {
            #region If ByteArray is Empty and the byte is \n reloop so we dont start with a leading \n
            if (Buffer.Count == 0 && b == 10) {
                continue;
            }
            #endregion
            #region We hit a newline, lets finish the reads here.
            break;
            #endregion
        }
        #endregion
        #region Add the read byte to the Byte Array
        Buffer.Enqueue(b);
        #endregion
        #region Break if bodysize was greater than 0 but now its 0
        if (bodySizeWasSpecified && bodySize == 0) {
            break;
        }
        #endregion
    }
    return encoding.GetString(Buffer.ToArray());
}


texts:
I have a HttpGet method which returns XML file:

[HttpGet]
public async Task<IActionResult> Get()
{
    XmlDocument xmlDoc = new XmlDocument();
    await Task.Run(() => xmldoc.Load(_appEnvironment.WebRootPath + @"\\user.config"));
    return Ok(xmlDoc);
}

Colleague said to me that this piece of code has smell and that I interrupted SOLID principles, but he did not explained to me what exact I do wrong.

Guys, please review my code and please explain me what I've done wrong.


texts: Managing multiple forms with individual updates and batch delete with checkboxes

texts:
I have a JSP page with a table containing data from java.util.List. The items from the list are taken from the database.

Each row has an edit button that will get all the values from that specific row to be edited on another page.
Each row has a checkbox where if selected means it will be deleted from the table. The "delete all" button at the end will do the batch delete.

I think I can do this very easily with nested forms, placing the update form inside the delete form and calling update form whenever an edit button is clicked. But since we are not aloud to do that, I created those forms separately instead and used HTML5's form attribute to refer to delete form.

Are there other, better ways of doing this, seeing that I can't do this in HTML4 for compatibility with older browsers, but I don't care about compatibility that much at this time. I just feel this code is too ugly. How can I improve my code?

<%@ include file="design/header.jsp" %>

Reservation List

    <form id="delete" action="deletereservations.html" method="post"></form>

            Check In Date
            Check Out Date
            Room Type
            Status
            Action-Edit
            Action-SELECT Delete

        <c:forEach var="reservation" items="${reservations}">

                ${reservation.strCheckInDate}
                ${reservation.strCheckOutDate}
                ${reservation.roomType}
                <c:choose>
                    <c:when test="${reservation.status eq 1}">
                        approved
                    </c:when>
                    <c:when test="${reservation.status eq 2}">
                        pending

                            <form action="updatereservation.html" method="post">
                                <input type="hidden" name="checkInDate" value="${reservation.strCheckInDate}">
                                <input type="hidden" name="checkOutDate" value="${reservation.strCheckOutDate}">
                                <input type="hidden" name="roomType" value="${reservation.roomType}">
                                <input type="hidden" name="id" value="${reservation.reservationID}">
                                <input type="image" src="images/edit.jpg" height="30" width="30"  value="edit">
                            </form>

                            <input type="checkbox" name="id" value="${reservation.reservationID}" form="delete">

                    </c:when>
                    <c:when test="${reservation.status eq 3}">
                        denied
                    </c:when>
                </c:choose>

        </c:forEach>

    <input type="image" src="images/delete.jpg" height="30" width="30"  name="deleteall" value="delete all" form="delete">
<%@ include file="../design/footer.html" %>


texts:
Below you'll find a Symfony2 service I wrote to assist in handling the Library entity. Each user in my app has a personal library where one can upload items to and a purchased library, that contains items one has purchased. Both libraries fall under a parent library.

At several points in my controller, I need to get the library for the user to save data. If the library doesn't exist yet, I want to create it.

The two switches in the getUserLibrary() function especially bother me.

<?php

namespace Smoovi\SmooviBundle\Entity\Manager;

use Doctrine\ORM\EntityManager;

use Smoovi\SmooviBundle\Entity\Library,
    Smoovi\UserBundle\Entity\User;

class LibraryManager
{
    const TYPE_PURCHASED = 1;
    const TYPE_PERSONAL  = 2;

    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * Get a user's personal library
     *
     * @param \Smoovi\UserBundle\Entity\User $user
     * @return Library
     */
    protected function getPersonalLibrary($user)
    {
        return $this->getUserLibrary($user, self::TYPE_PERSONAL);
    }

    /**
     * Get a user's library for purchased objects
     *
     * @param \Smoovi\UserBundle\Entity\User $user
     * @return Library
     */
    public function getPurchasedLibrary($user)
    {
        return $this->getUserLibrary($user, self::TYPE_PURCHASED);
    }

    /**
     * Get or create a library based on $type
     *
     * @param User $user
     * @param $type
     * @return Library
     * @throws \Exception
     */
    protected function getUserLibrary(User $user, $type)
    {
        $libRepo = $this->em->getRepository('SmooviSmooviBundle:Library');

        // we first try to find the user's parent library
        // if not, create it
        /** @var \Smoovi\SmooviBundle\Entity\Library $topLibrary */
        $topLibrary = $libRepo->findOneBy(array('user' => $user, 'parent' => null));
        if (is_null($topLibrary)) {
            $library = new Library();
            $library
                ->setUser($user)
                ->setName($user->getFirstname()."'s Library")
                ->setIndex(1)
            ;
            $this->em->persist($library);
        }

        // look for the sublibrary
        // create it if necessary
        $where = array('user' => $user, 'parent' => $topLibrary);
        switch($type) {
            case self::TYPE_PURCHASED:
                $where['purchased'] = true;
                $libraryName = 'Purchases';
            break;
            case self::TYPE_PERSONAL:
                $where['personal'] = true;
                $libraryName = 'Objects';
            break;
            default:
                throw new \Exception('Library subtype not implemented');
        }
        /** @var \Smoovi\SmooviBundle\Entity\Library $subLibrary */
        $subLibrary = $libRepo->findOneBy($where);
        if (is_null($subLibrary)) {
            $subLibrary = new Library();
            $subLibrary
                ->setParent($topLibrary)
                ->setUser($user)
                ->setName($libraryName)
                ->setIndex(1)
            ;
            switch($type) {
                case self::TYPE_PURCHASED:
                    $subLibrary->setPurchased(true);
                break;
                case self::TYPE_PERSONAL:
                    $subLibrary->setPersonal(true);
                break;
                default:
                    throw new \Exception('Library subtype not implemented');
            }
            $this->em->persist($subLibrary);
        }
        $this->em->flush();

        return $subLibrary;
    }
}


texts: Is this the rigth way to write power and factorial functions with nasm?

texts:
I wrote factorial and power functions with nasm but I don't know if it is the right to write assembly code. For example, by executing the functions I make some changes in the registers and I don't know if I have to revert them to their original value a the end with push and pop.

To write the factorial function, I first wrote it in C, compiled it with gcc and disassembled it with gdb. It gave me inspiration to write the code. Then I followed the same way of coding for my power function.

I use 64 bits registers.

Here is my code :

; Factorial function n!
; Argument from rsi and return in rax
factorial:
  push rbp
  mov rbp, rsp

  sub rsp, 0x10 ; Allocate 2 bytes on the stack
  mov DWORD [rbp-4], esi ; Put the parameter on the stack
  cmp DWORD [rbp-4], 1 ; if ==1 there is nothing to do
  jne factorial_rec
  mov eax, 1 ; return 1
  jmp fin_factorial
factorial_rec:
  mov eax, DWORD [rbp-4] ; Move the parameter in eax
  sub eax, 1
  mov esi, eax
  call factorial ;Call factorial recursively with eax-1
  imul eax, DWORD [rbp-4] ; multiply eax by the parameter
fin_factorial:
  leave
  ret

; Power function x^n
; Argument from rsi and rdi return in rax
; rsi at the power rdi
power:
  push rbp
  mov rbp, rsp

  cmp rdi, 0 ; if == 0
  jne power_init
  mov eax, 1 ; Return 1 (x^0=1)
  jmp power_end
power_init:
  sub rsp, 0x10 ; Allocate 2 bytes on the stack
  mov DWORD [rbp-4], esi ; Put the parameter on the stack
  mov eax, esi ; first power
power_loop:
  dec edi
  cmp edi, 0
  je power_end
  imul eax,DWORD[rbp-4] ; Multiply eax by the parameter until edi == 0
  jmp power_loop
power_end:
  leave
  ret

Thank you for your comments.


texts: A class for simple and efficient operations on boost::unordered_set

texts:
I wrote this class to perform simple template-set operations on boost::unordered_set. These operations are part of a larger code base. Calling them will be explicit with SetUtilities::set_intersection(setA, setB).

The main reason I wanted this was to optimize intersection operations (using constant time find in the larger set). After taking to heart the comments from here, I edited the class and provided the rest of the methods.

For now I want to use Boost instead of C++11. I can always do this in the future.

#ifndef SET_UTILITIES
#define SET_UTILITIES

#include <boost/unordered_set.hpp>
#include <boost/foreach.hpp>

class SetUtilities{

public:

    //!set OPERATION intersection for boost::unordered_set
    template<typename Type>
    static boost::unordered_set<Type>
        set_intersection(const boost::unordered_set<Type> &setA,
                         const boost::unordered_set<Type> &setB)
    {
        //iterate the smaller set O(n)
        if(setA.size() <= setB.size()){
            boost::unordered_set<Type> intersectionSet;
            BOOST_FOREACH(const Type &element, setA){
                //find element in O(1)
                if(set_hasElement(setB,element)){
                    intersectionSet.insert(element);
                }
            }
            return intersectionSet;
        }else{
            return set_intersection(setB,setA);
        }
    }

    //!set OPERATION union for boost::unordered_set
    template<typename Type>
    static boost::unordered_set<Type>
        set_union(const boost::unordered_set<Type> &setA,
                  const boost::unordered_set<Type> &setB)
    {
        if(setA.size() <= setB.size()){
            boost::unordered_set<Type> unionSet = setB;
            //iterate the smaller set O(n)
            BOOST_FOREACH(const Type &element, setA){
                unionSet.insert(element);
            }
            return unionSet;
        }else{
            return set_union(setB,setA);
        }
    }

    //!set OPERATION difference A - B
    template<typename Type>
    static bool
        set_difference(const boost::unordered_set<Type> &setA,
                       const boost::unordered_set<Type> &setB)
    {
        boost::unordered_set<Type> differenceSet;
        //is size are not equal, sets are not equal
        BOOST_FOREACH(const Type &element,setA){
            if(set_hasElement(setB,element) == false){
                differenceSet.insert(element);
            }
        }
        return differenceSet;
    }

    //!set UTILITY funciton to determine if a set contains an element
    template<typename Type>
    static bool
        set_hasElement(const boost::unordered_set<Type> &mySet,
                       Type element)
    {
        return mySet.find(element) != mySet.end();
    }

    //!set equality test for boost::unordered_set
    template<typename Type>
    static bool
        are_equal(const boost::unordered_set<Type> &setA,
                  const boost::unordered_set<Type> &setB)
    {
        //is size are not equal, sets are not equal
        if(setA.size() != setB.size()){
            return false;
        }else{
            BOOST_FOREACH(const Type &element, setA){
                if(set_hasElement(setB,element)){
                    return false;
                }
            }
            return true;
        }
    }
};
#endif

I believe that this version is very readable and explicit. I think that adding typedefs with stuff like this in a single class would create more confusion. Let me know what you think.


texts:
Scenario: I am using a helper class called 'OutputHelper' to add a new record to the table 'Output'. My 'Output' object contains the following:

ShiftID
Model
WorksOrder
LotNo
Quantity
ShiftHour

I do not want a record to be added if a record already exists with the ShiftID and ShiftHour of the record that I am trying to add.

The way I am achieving this currently is having the property 'RecordOutput' in the helper class try and add the record then return a string which I handle with a switch statement and provide feedback to the user accordingly.

This seems to be working fine but I can't help but think it's a terrible way of doing things. Can anyone provide any feedback and suggestions for improvement?

Output helper class:

public class OutputHelper
{
    public string RecordOutput(Models.Output output)
    {
        var shiftId = output.ShiftID;
        var shiftHour = output.ShiftHour;

        using (var db = new TestContext())
        {
            try
            {
                if (db.Outputs.Any(x => x.ShiftID == shiftId && x.ShiftHour == shiftHour))
                {
                    return "Exists";
                }
                db.Outputs.Add(output);
                db.SaveChanges();
            }
            catch (Exception)
            {
                return "NotSaved";
            }
            return "Success";
        }
    }
}

Code from button click on form

 var outputHelper = new OutputHelper();

        switch (outputHelper.RecordOutput(output))
        {
            case "Exists":
                lblErrorMessage.Text = "Output already recorded for this timeframe";
                failMessage.Visible = true;
                break;
            case "Not Saved":
                lblErrorMessage.Text = "There was a problem saving this record. Please try again";
                failMessage.Visible = true;
                break;
            default:
                lblSuccess.Text = "Output record added to database";
                successMessage.Visible = true;
                ResetForm();
                break;
        }


texts:
I am wondering if I could implement this in a cleaner, more elegant, strictly functional way:

const convert2dArrayToJsonList = (array) => {

    if (!is2dArrayParsableToJsonList(array)) {
        throw new Error("The 2D array cannot be converted to a json list" + array);
    }

    const propertyKeys = array[0];

    return array
        .slice(1)
        .map( row => {
            return row.reduce( (accumulatedElement, propertyValue, currentIndex, array) => {

                accumulatedElement[propertyKeys[currentIndex]] = propertyValue;
                return accumulatedElement;
            }, {});
        });
}

The implementation of is2dArrayParsableToJsonList(array) is not relevant in this context, it does what it says.

The 2D array parameter has the property keys in the top row and all other rows represent individual elements in the list.


texts:
I have a Multivalued map (javax.ws.rs.core.MultivaluedMap<String, String>) which I want to convert to regular HashMap so I got below code:

private Map<String, String> convertMultiToRegularMap(MultivaluedMap<String, String> m) {
    Map<String, String> map = new HashMap<String, String>();
    if (m == null) {
        return map;
    }
    for (Entry<String, List<String>> entry : m.entrySet()) {
        String qKey = entry.getKey();
        List<String> values = entry.getValue();
        if (values.size() > 1) {
            String val = "";
            int i = 0;
            for (String s : values) {
                if (i > 0) {
                    val += ",";
                }
                val += s;
                i++;
            }
            map.put(qKey, val);
        } else {
            map.put(qKey, values.get(0));
        }
    }
    return map;
}

Is there any improvement I can do here? I am using Java7.


texts:
I am currently converting a project from Java to kotlin and re-writing the code in the process to make the most out of kotlin's capabilities. The project contains a Battle System which uses elements to establish inferiority/superiority or neutrality of attacks based on the attacker's and defender's element. The code is much more concise than the java version but I have the feeling there is an even better way to do it, I am just not sure what that way is, so any input would be greatly appreciated, also in regard to improvements in regard to the current code:

internal class Element {

    enum class Type {
        NEUTRAL {
            override fun superiorTo(): List<Type> = emptyList()
            override fun inferiorTo(): List<Type> = emptyList()
        },
        FIRE {
            override fun superiorTo(): List<Type> = listOf(EARTH)
            override fun inferiorTo(): List<Type> = listOf(WATER)
        },
        WATER {
            override fun superiorTo(): List<Type> = listOf(FIRE)
            override fun inferiorTo(): List<Type> = listOf(WIND)
        },
        WIND {
            override fun superiorTo(): List<Type> = listOf(WATER)
            override fun inferiorTo(): List<Type> = listOf(EARTH)
        },
        EARTH {
            override fun superiorTo(): List<Type> = listOf(WIND)
            override fun inferiorTo(): List<Type> = listOf(FIRE)
        };

        private val typeCount = Type.values().size

        abstract fun superiorTo(): List<Type>
        abstract fun inferiorTo(): List<Type>

        fun compare(defender: Type): ComparisonResult {
            val result: ComparisonResult
            if (inferiorTo().contains(defender)) {
                result = ComparisonResult.INFERIOR
            } else if (superiorTo().contains(defender)) {
                result = ComparisonResult.SUPERIOR
            } else {
                result = ComparisonResult.NEUTRAL
            }
            return result
        }
    }

    enum class ComparisonResult {
        NEUTRAL, SUPERIOR, INFERIOR
    }
}

The reason I am going for Lists instead of single types is twofold:

account for the option to have inferiorities/superiorities towards
multiple elements
but mostly to make it easy to take the Neutral element into account and treat it just like all the others


texts:
We have following endpoint on our api that should grab some events from db, aggregate them and output as a json. But I am having hard time reading this function and hope you could help me out with some ideas how to refactor this to something more reasonable. Or maybe its fine and I just need to read harder?

[HttpGet]
public AmazonDTO GetCRSTimeStatuses(string countryId, string regionId, string storeId, string dateFrom, string dateTo)
{
    List<CRSTimeStatus> res = new List<CRSTimeStatus>();

    try
    {
        DateTime _dateFrom;
        DateTime.TryParse(dateFrom, out _dateFrom);

        _dateFrom = _dateFrom.Date;

        DateTime _dateTo;
        DateTime.TryParse(dateTo, out _dateTo);

        int _countryId;
        int.TryParse(countryId, out _countryId);

        int _regionId;
        int.TryParse(regionId, out _regionId);

        int _storeId;
        int.TryParse(storeId, out _storeId);

        PageDetailType _pageDetailType = ModelHelper.GetActualPageType(_countryId, _regionId, _storeId, tillId: 0);

        var eventValue = _cache.Get<List<Event>>("eventsChache");

        var events = new List<Event>();
        var countries = new List<Country>();

        // Read base relation data from DB.
        countries = _countryRepository.GetAll().ToList();
        _regionRepository.GetAll().ToList();
        _storeRepository.GetAll().ToList();
        _askoTillRepository.GetAll().ToList();

        if (_hostingEnvironment.IsDevelopment())
        {
            EventCache evc = new EventCache(_eventRepository, _cache);
            evc.SetEventsCache(_dateFrom, _dateTo);
        }

        events = _cache.Get<List<Event>>("eventsChache");

        Dictionary<int, List<Event>> eventsForPos = new Dictionary<int, List<Event>>();

        events = events == null ? new List<Event>() : events;

        var forEvets = events.FindAll(x => x.DateFrom >= _dateFrom && (x.DateTo <= _dateTo || !x.DateTo.HasValue));

        foreach (Event e in forEvets)
        {
            if (eventsForPos.ContainsKey(e.PosTillId))
            {
                eventsForPos[e.PosTillId].Add(e);
            }
            else
            {
                eventsForPos[e.PosTillId] = new List<Event>() { e };
            }
        }

        foreach (var item in countries)
        {
            var tills = item.Regions.SelectMany(t => t.Stores.Where(e => e.PosTills != null).SelectMany(r => r.PosTills));

            foreach (var till in tills)
            {
                till.Events = eventsForPos.ContainsKey(till.Id) ? eventsForPos[till.Id] : null;
            }

        }

        switch ((PageDetailType)_pageDetailType)
        {
            case PageDetailType.CountriesDetail:

                break;
            case PageDetailType.CountryDetail:
                res = ModelHelper.GetGraphStatusesCountry(countries, _countryId);
                break;
            case PageDetailType.RegionDetail:
                res = ModelHelper.GetGraphStatusesRegion(countries, _regionId);
                break;
            case PageDetailType.StoreDetail:
                res = ModelHelper.GetGraphStatusesStore(countries, _storeId);
                break;
            case PageDetailType.TillDetail:

                break;
            default:
                break;
        }
    }
    catch (Exception ex)
    {
        _logger.LogError(ex.ToString());
        return AmazonDTO.Error(((int)HttpException.InternetServerError).ToString(), ex.ToString());
    }

    return AmazonDTO.Data(res);
}

My initial suggestion is to remove data parsing at the start and move it elsewhere. The code also looks like it is trying to do three things at once based on incoming parameters, maybe split it into three endpoints or use some form of inheritance would help here.

Any ideas are welcomed!


texts:
I tried to implement something like a C++ enum class in Fortran. That means it should be typesafe and scope bound. (No comparison between integers and enum values for example.)
The following works, but it is still possible to compare two instances of different enum classes at compile time. Do you have suggestions for possible improvements?
module enum_class_mod
    implicit none(type, external)
    private
    public :: EnumBase_t

    type, abstract :: EnumBase_t
        integer :: val
    contains
        private
        procedure :: eq_EnumBase_t
        procedure :: neq_EnumBase_t
        generic, public :: operator(==) => eq_EnumBase_t
        generic, public :: operator(/=) => neq_EnumBase_t
    end type

contains

    logical elemental function eq_EnumBase_t(this, other)
        class(EnumBase_t), intent(in) :: this, other
        if (.not. SAME_TYPE_AS(this, other)) error stop 'Can only compare objects of same type'
        eq_EnumBase_t = this%val == other%val
    end function

    logical elemental function neq_EnumBase_t(this, other)
        class(EnumBase_t), intent(in) :: this, other
        if (.not. SAME_TYPE_AS(this, other)) error stop 'Can only compare objects of same type'
        neq_EnumBase_t = this%val /= other%val
    end function
end module

program test_enum_class
    use enum_class_mod, only: EnumBase_t
    implicit none(type, external)

    type, extends(EnumBase_t) :: Color_t
    end type

    type :: PossibleColors_t
        type(Color_t) :: Red = Color_t(1), Blue = Color_t(2)
    end type

    type(PossibleColors_t), parameter :: possible_colors = PossibleColors_t()

    type, extends(EnumBase_t) :: Day_t
    end type

    type :: PossibleDays_t
        type(Day_t) :: Monday = Day_t(1), Tuesday = Day_t(2)
    end type

    type(PossibleDays_t), parameter :: possible_days = PossibleDays_t()

    write(*, *) possible_colors%Red == possible_colors%Blue
    write(*, *) possible_colors%Red == possible_colors%Red

    write(*, *) possible_days%Monday == possible_days%Tuesday

    ! fails at runtime, I would like it to fail at compile time
    write(*, *) possible_days%Monday == possible_colors%Red
end program

```


texts: Approximating sines and cosines using up to five terms of the Taylor series

texts:
I have one programming question:

  The sine and cosine of \$x\$ can be computed as follows:

    \$\sin(x) = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \frac{x^9}{9!} - \dots\$

    \$\cos(x) = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \frac{x^8}{8!} - \dots\$

  Your task is to compute the sine and cosine for given values of \$x\$ (where \$x\$ is in radians) using the above series up to 5 terms.

  Input Format

  First line will contain \$N\$, the number of test cases. Next \$N\$ lines will contain the input values of \$x\$:

    \$1 \le N \le 50\$

    \$0 \lt x \lt 10\$

  Each value of \$x\$ can contain up to 2 places of decimal in radians.

  Output Format

  2 \$N\$ lines, corresponding to the \$N\$ input values of \$x\$.  For each input, you will output 2 lines. First line will be the sine and the second line will be the cosine of \$x\$.  An error margin of \$\pm\$0.001 will be tolerated while evaluating the answers.  Please round off your answer to 3 decimal places.

  Sample Input

5
2.83
3.24
0.99
2.74
5.04

  Sample Output [sic]

 0.309
-0.943
-0.089
-0.963
 0.836
 0.549
 0.392
-0.914
 0.195
 2.746

and what I have tried:

public class Trigonometric_Ratios
{
  int factorial(int number)
  {
    int result = 1;
    for (int i = 1; i <= number; i++)
    {
      result = result * i;
    }
    return result;
  }

  void calc(double x)
  {
    double sinx=0,cosx=0;

    int i,j = 0;

    int c;
    for(i=1;i<10;i+=2)
    {
      c=i;
      sinx += Math.pow(-1,j++)*Math.pow(x,i) / factorial(i);
      if(i>0)
      cosx+=Math.pow(-1,j)*Math.pow(x,c-1)/factorial(c-1);
    }
    sinx=Math.round( sinx * 1000.0 ) / 1000.0;

    cosx=-cosx;
    cosx=Math.round( cosx * 1000.0 ) / 1000.0;
    System.out.println(sinx+" \n"+(cosx));
  }

  public static void main(String [] args)
  {
    int n;
    Trigonometric_Ratios tr=new Trigonometric_Ratios();

    Scanner sc=new Scanner(System.in);

    n=sc.nextInt();

    double a[]=new double[n];
    for(int i=0;i<n;i++)
    {
      a[i]=sc.nextDouble();
    }

    for(int i=0;i<n;i++)
    {
      tr.calc(a[i]);
    }
  }
}

Please review my code.  In particular, I am concerned about performance, and would appreciate suggestions on reducing the time complexity.


texts:
I have the following code, which does the following:

Reads from the packet from UDP (SNMP) into an array, check if this number is > 127, if yes then '&' this with 127, now pad it with leading zero's to make it 7 bits in total. Combine it with result.
Now check the next one in the packet and repeat the above.
It works for if 3 numbers > 127. Can this code be optimized check for unlimited throughout the length of the array

Please do let me know if you require any further information.

Thank you.

 int[] obj = new int[Objectlength];
 string result = string.Empty;
 for (int cnt = 0; cnt < Objectlength; cnt++)
 {
     obj[cnt] = Convert.ToInt16(packet[objectstart]);
     objectstart++;

     if (obj[cnt] >127)
     {

         int brush = 127;
         int bin = obj[cnt] & brush;
         string binR1 = Convert.ToString(bin, 2).PadLeft(7, '0');
         result = result + binR1;
         cnt++;

         if ((packet[objectstart] > 127) | (packet[objectstart]  < 127))
         {

             Console.WriteLine(packet[objectstart]);
             int bin1 = packet[objectstart] & brush ;
             binR1 = Convert.ToString(bin1, 2).PadLeft(7, '0');
             result = result + binR1;

             obj[cnt] = Convert.ToInt16(packet[objectstart]);
             cnt++;
             objectstart++;

             if ((packet[objectstart] > 127) | (packet[objectstart] < 127))
             {

                 Console.WriteLine(packet[objectstart]);
                 int bin2 = packet[objectstart] & brush;
                 binR1 = Convert.ToString(bin2, 2).PadLeft(7, '0');
                 result = result + binR1;

                 obj[cnt] = Convert.ToInt16(packet[objectstart]);
                 objectstart++;
             }

         }

     }

}


texts:
I am making a data-driven bond screening and I have as input a big dataset of 1526 columns and 2412 rows. For 10 columns it takes 2 minutes processing time at the moment, which is too much. The following function takes 90% of the time:

Input of the function is df: a pandas series, where the index is a time series and the first column has floats, like this:

https://imgur.com/a/3pQSQZC

def future_returns(df):
    grid_columns = np.arange(len(df))
    grid = pd.DataFrame(index=df.index, columns=grid_columns)

    # fill grid with copies of df, shifted 1 element forward for each column
    for no, idx in enumerate(grid.columns):
        grid.loc[:, idx] = df.shift(-no)

    # calculate future returns from every point in the index
    future_returns = grid.divide(grid.iloc[:, 0], axis=0) - 1

    return future_returns


texts:
I have solved a problem of a game named 'Set'.
The full problem is detailed on it's website: https://www.urionlinejudge.com.br/judge/en/problems/view/1090

However my code for the search algorithm is too slow, I'd like to achieve something around \$O(n)\$. How can I make SetGameManager::CountSet() better?

This is not the full code, it's just so that you have an idea of what's going on:

#include <iostream>
#include <vector>
#include <chrono>
#include <algorithm>

enum TYPE{
    SQUARE,
    CIRCLE,
    TRIANGLE,
};

struct _card
{
    TYPE type;
    int amount;
    _card( int a, TYPE t) { type = t; amount = a;};
};

inline bool canMatch(_card a, _card b)
{
    return((a.type == b.type && a.amount != b.amount) || (a.type == b.type && a.amount == b.amount) );
}

inline bool canMatch3(_card a, _card b, _card c)
{
    return((a.type == b.type && a.type == c.type)
           && ((a.amount != b.amount && b.amount != c.amount && a.amount != c.amount) ||
               ( a.amount == b.amount && a.amount == c.amount )));
}

inline bool cannotMatch(_card a, _card b)
{
    return(a.type != b.type && a.amount != b.amount);
}

inline bool cannotMatch3(_card a, _card b, _card c)
{
    return((a.type != b.type && b.type != c.type && a.type != c.type) &&
           (a.amount != b.amount && b.amount != c.amount && a.amount != c.amount));
}

class SetGameManager {
public:
    std::vector<_card> gameCards;
}

inline unsigned int SetGameManager::CountSet()
{
    unsigned int SetMatches = 0;

    unsigned int i1 = 0;

    std::sort(this->gameCards.begin(), this->gameCards.end());

    while(gameCards.size() > 2)
    {
        auto continue_outer_loop(true);
        for(unsigned int i2=1; continue_outer_loop && (i2<gameCards.size()); i2++)
        {
            if(i2 == 2) continue;
            auto const p_match_3_func
            (
                cannotMatch(gameCards.at(i1), gameCards.at(i2))
                ?
                &cannotMatch3
                :
                &canMatch3
            );
            for(unsigned int i3=2; i3<gameCards.size(); i3++)
            {
                if((*p_match_3_func)(gameCards.at(i1), gameCards.at(i2), gameCards.at(i3)))
                {
                    SetMatches++;
                    gameCards.erase(gameCards.begin()+i3);
                            gameCards.erase(gameCards.begin()+i2);
                    continue_outer_loop = false;
                    break;
                }
            }
        }
        gameCards.erase(gameCards.begin());
    }

    return SetMatches;
}


texts:
I posted some code as part of an answer to another question and I thought it would be a good idea to get that code reviewed also.

Any comments are welcomed, but I am mostly annoyed by terminalNode.  It is basically a slightly convenient factory method, but I think it should either be renamed to something more enlightening, or something entirely different should be done.

object TreeTraversal extends App {

  case class Node[+T](value: T, left: Option[Node[T]], right: Option[Node[T]]) {
    def map[V](f: T => V): Node[V] =
      Node(f(value), left.map(l => l.map(f)), right.map(r => r.map(f)))
    def childrenLeftRight: List[Node[T]] = List(left, right).flatten
  }
  def terminalNode[T](value: T) = Node(value, None, None)

  def dfs[T](tree: Node[T]): List[T] = {
    var output = List[T]()
    tree.map(t => (output = t :: output))
    output.reverse
  }

  def bfs[T](tree: Node[T]): List[T] = {
    @tailrec
    def bfsLoop(accum: List[List[T]], nextLayer: List[Node[T]]): List[T] = nextLayer match {
      case Nil => accum.reverse.flatten
      case _ => bfsLoop(nextLayer.map(_.value) :: accum, nextLayer.flatMap(_.childrenLeftRight))
    }
    bfsLoop(List[List[T]](), List(tree))
  }

  val tree1 = Node[Int](6, Some(Node(13, Some(terminalNode(101)), None)), Some(Node(42, Some(terminalNode(666)), Some(terminalNode(65)))))
  println("map: " + tree1.map(i => s"Hello$i"))
  println("dfs: " + dfs(tree1))
  println("bfs: " + bfs(tree1))
}

Node looks like a monad.  Could I get all other operations such as flatMap and foldLeft for free somehow?


texts:
As a learn-by-doing project to learn Java webapps, I'm creating a website for registering and displaying happenings using JSP/Servlets, Apache Tomcat server, JDBC and a MySQL database.

I use JSP for views, Servlets for controller functionality and business logic, and I've created ONE DBManager.java class (my only DAO) to abstract SQL statements from my Servlets and JSPs. In my Servlets, I use the DBManager class by declaring a new instance and calling its public methods.

For instance:

DBManager dbm = new DBManager();
Boolean userIsUpdated = dbm.updateUserInDB(user);

My DAO looks briefly like this:

public class DBManager {

    final String DATABASE_URL = "NOPE, I won't give you this one ;)";
    Connection connection = null;
    PreparedStatement pstmt = null;

    public DBManager() {
        //Nothing in constructor yet.
    }

    public ArrayList<Happening> getAllActivatedHappenings() {
        //code removed for readability
    }

    public User logInAndGetUserByEmailAndPassword(String email, String password) {
        //code removed for readability
    }

    public User insertUserIntoDB(User user) {
        //code removed for readability
    }

    public boolean updateUserInDB(User user) {
        //code removed for readability
    }

    public boolean insertHappeningIntoDB(Happening happening) {
        //code removed for readability
    }

    public boolean deleteHappeningFromDB(int happeningId, int userId) {
        //code removed for readability
    }

    public ArrayList<HappeningType> getAllHappeningTypes() {
        //code removed for readability
    }

    public ArrayList<Happening> getAllHappeningsByUserId(int userid) {
        //code removed for readability
    }

    public byte[] getPhotoByHappeningId(int happeningId, String imageType) {
        //code removed for readability
    }

    public Map<Integer, String> getCountiesMap() {
        //code removed for readability
    }

    public Boolean userIsHappeningOwner(int userId, int happeningId) {
        //code removed for readability
    }

    public Happening getHappeningByHappeningId(int happeningId) {
        //code removed for readability
    }

    public boolean updateHappening(Happening happeningDummy, String updateImage) {
        //code removed for readability
    }

    public ArrayList<Happening> getFilteredActivatedHappenings(HttpServletRequest request) {
        //code removed for readability
    }

    public boolean activateHappening(int happeningId) {
        //code removed for readability
    }

    public boolean updateEmailNotificationForUser(User user, String emailnotificationhappeningtypeids, String emailnotificationcountyids) {
        //code removed for readability
    }

    public User getUserByEmail(String email) {
        //code removed for readability
    }
}

As you can see, my DAO handles quite a lot of different transfer objects (happenings, users, cities, happening types etc.). Should I break this DAO into several smaller DAO classes (like HappeningDAO, UserDAO, etc.)? Any other reasons for doing this than readability?

Also, is this approach thread-safe as long as I declare a new instance of DBManager within my doGet/doPost methods in the servlets?


texts: Grid search parameter combinations in Python

texts:
For a computation engineering model, I want to do a grid search for all feasible parameter combinations. Each parameter has a certain possibility range, e.g. (0 … 100) and the parameter combination must fulfil the condition a+b+c=100. An example:

ranges = {
    'a': (95, 99),
    'b': (1, 4),
    'c': (1, 2)}
increment = 1.0
target = 100.0

So the combinations that fulfil the condition a+b+c=100 are:

[(95, 4, 1), (95, 3, 2), (96, 2, 2),
 (96, 3, 1), (97, 1, 2), (97, 2, 1),
 (98, 1, 1)]

This algorithm should run with any number of parameters, range lengths, and increments.

The solutions I have come up with is brute-forcing the problem. That means calculating all combinations and then discarding the ones that do not fulfil the given condition. I have to use np.isclose(), because when using floats, the rounding error in Python's will not lead to an exact sum.

def solution(ranges, increment, target):
    combinations = []
    for parameter in ranges:
        combinations.append(list(np.arange(ranges[parameter][0], ranges[parameter][1], increment)))
        # np.arange() is exclusive of the upper bound, let's fix that
        if combinations[-1][-1] != ranges[parameter][1]:
            combinations[-1].append(ranges[parameter][1])
    result = []
    for combination in itertools.product(*combinations):
        # using np.isclose() so that the algorithm works for floats
        if np.isclose(sum(combination), target):
            result.append(combination)
    df = pd.DataFrame(result, columns=ranges.keys())
    return df

However, this quickly takes a few days to compute. Hence, both solutions are not viable for large number of parameters and ranges. For instance, one set that I am trying to solve is (already unpacked combinations variable):

[[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0],
 [22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 59.0, 60.0, 61.0, 62.0, 63.0, 64.0, 65.0, 66.0, 67.0, 68.0, 69.0, 70.0, 71.0, 72.0, 73.0, 74.0, 75.0, 76.0, 77.0, 78.0, 79.0, 80.0, 81.0, 82.0, 83.0, 84.0, 85.0, 86.0, 87.0, 88.0],
 [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0],
 [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0],
 [0.0, 1.0, 2.0],
 [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
 [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0],
 [0.0],
 [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0],
 [0.0]]

This results in memory use of >40 GB and calculation time >400 hours.
Do you see a solution that is either faster or more intelligent, i.e. not trying to brute-force the problem?


texts:
I was asked a weighted probability question in a technical interview a few months ago that went something like this:

  Given an input of colors and an integer "weight" value, randomly return a color based on its weight.

The sample input would be something like this:

[("Red", 20), ("Blue", 50), ("Green", 70)]

The probability that each color would be returned would be something like:

Red: 20/140

Blue: 50/140

Green: 70/140

(where 140 is the sum of the weight of the input colors)

I was thinking about this recently and decided to give it another go in Swift.

My first pass was:

func weightedColor(input: [(String, Int)]) -> String {

    var total = 0

    for tuple in input {
        total += tuple.1
    }

    let rand = Int(arc4random_uniform(UInt32(total)))

    var sum = 0
    for tuple in input {
        let range = sum + tuple.1

        if rand <= range {
            return tuple.0
        } else {
            sum += tuple.1
        }
    }

    return ""
}

Then I realized I could optimize the total weight calculation with map-reduce:

let total = UInt32(input.map { $0.1 }.reduce(0, combine: +))

My current implementation is as follows:

func weightedColor(input: [(String, Int)]) -> String {

    let total = UInt32(input.map { $0.1 }.reduce(0, combine: +))

    let rand = Int(arc4random_uniform(total))

    var sum = 0
    for tuple in input {
        let range = sum + tuple.1

        if rand <= range {
            return tuple.0
        } else {
            sum += tuple.1
        }
    }

    return ""
}

I don't like the for tuple in input loop and feel it can be optimized further.  How can I improve this answer?


texts: A rails controller needs to validate certain values exist

texts:
I need to pass some values from a CMS to a rails view. I should check these values are defined in the CMS. These values are meant to be use in all pages, hence the use of application_controller.rb. As of now I'm using the set_favicon method to check for the existence of a favicon, but doing this with other values will result in a new validation method for every field (address, email, phone, etc...).

class ApplicationController < ActionController::Base
  before_action :set_constants

  def set_favicon
    if Fae::Option.instance.try(:favicon).nil?
      @favicon = ''
    else
      @favicon = Fae::Option.instance.favicon.asset.url
    end
  end

 def set_constants
   set_favicon
   @company            = {
      address:       CompanyInfo.instance.address.content,
      email:         CompanyInfo.instance.email.content,
      phone:         CompanyInfo.instance.phone.content,
      facebook_url:  CompanyInfo.instance.facebook_url.content,
      instagram_url: CompanyInfo.instance.instagram_url.content,
      youtube_url:   CompanyInfo.instance.youtube_url.content
  }
  end

end


texts: Dataset and frequency list generation by looping over files

texts:
I have been told that it would be wise to split up my code into semantically useful blocks. I tried the following but I need feedback.

What I already did:

As you can see I create two .csv files, so it seemed logical to have two functions. One for the main dataset, the other for a frequency table
I only import modules where I need them, though I did need some globally.

I probably should give fn, c and s better variable names. However, I'm not sure how to name them because they are identical to the column names they will be assigned to (e.g. node = node, sentence = sentence).

So what else can I do to better format my code into useful functions? Do note that I want to put an emphasis on performance, so any edits that decrease performance are discouraged.

import os, pandas as pd, numpy as np

from datetime import datetime

start_time = datetime.now()

# Create empty dataframe with correct column names
column_names = ["fileName", "component", "precedingWord", "node", "leftContext", "sentence" ]
df = pd.DataFrame(data=np.zeros((0, len(column_names))), columns=column_names)

# Create correct path where to fetch files
subdir = "rawdata"
path = os.path.abspath(os.path.join(os.getcwd(), os.pardir, subdir))

def main_dataset():
    import regex as re
    from html import unescape
    # Loop files in folder
    filenames = [name for name in os.listdir(path) if re.match(".*?[.]lst", name)]

    # "Cache" regex
    # See http://stackoverflow.com/q/452104/1150683
    p_filename = re.compile(r"[./\\]")

    p_sentence = re.compile(r"<sentence>(.*?)</sentence>")
    p_typography = re.compile(r" (?:(?=[.,:;?!) ])|(?<=\( ))")
    p_non_graph = re.compile(r"[^\x21-\x7E\s]")
    p_quote = re.compile(r"\"")
    p_ellipsis = re.compile(r"\.{3}(?=[^ ])")

    p_last_word = re.compile(r"^.*\b(?<!-)(\w+(?:-\w+)*)[^\w]*$", re.U)

    fn_list = []
    c_list = []
    pw_list = []
    n_list = []
    lc_list = []
    s_list = []

    for filename in filenames:
        with open(path + '/' + filename, 'r+', encoding="utf-8") as f:
            [n, c] = p_filename.split(filename.lower())[-3:-1]
            fn = ".".join([n, c])
            for line in f:
                s = p_sentence.search(unescape(line)).group(1)
                s = s.lower()
                s = p_typography.sub("", s)
                s = p_non_graph.sub("", s)
                s = p_quote.sub("'", s)
                s = p_ellipsis.sub("... ", s)

                if n in re.split(r"[ :?.,]", s):
                    lc = re.split(r"(^| )" + n + "( |[!\",.:;?})\]])", s)[0]

                    pw = p_last_word.sub("\\1", lc)

                    fn_list.append(fn)
                    c_list.append(c)
                    pw_list.append(pw)
                    n_list.append(n)
                    lc_list.append(lc)
                    s_list.append(s)
                continue

    # Assign data frame
    df['fileName'] = fn_list
    df['component'] = c_list
    df['precedingWord'] = pw_list
    df['node'] = n_list
    df['leftContext'] = lc_list
    df['sentence'] = s_list

    # Reset indices
    df.reset_index(drop=True, inplace=True)

    # Export dataset
    df.to_csv("dataset/py-dataset.csv", sep="\t", encoding="utf-8")

def frequency_table():
    # Define neuter and non_neuter
    neuter = ["het"]
    non_neuter = ["de"]

    # Create crosstab
    df.loc[df.precedingWord.isin(neuter), "gender"] = "neuter"
    df.loc[df.precedingWord.isin(non_neuter), "gender"] = "non_neuter"
    df.loc[df.precedingWord.isin(neuter + non_neuter) == 0, "gender"] = "rest"

    freqDf = pd.crosstab(df.node, df.gender)

    freqDf.to_csv("dataset/py-frequencies.csv", sep="\t", encoding="utf-8")

    # How long has the script been running?
    time_difference = datetime.now() - start_time
    print("Time difference of", time_difference)

main_dataset()
frequency_table()


texts: Converting from strings to byte arrays with LINQ in C#

texts:
I'm taking in a string of input from the command line, and when prefixed by 0o or 8# interpreting it as an octal string. I'd like to convert it to a byte array more directly, but I'm not sure how to perform the bit carrying in LINQ.

All three of these methods are fully working; you can checkout the repository or just download the built executable and run it from the command line if need be.

I'd like a review of all three working methods, but more specifically I'd like to have the Octal method, below, not use a BitArray intermediary, similar to the Binary and Hex methods.

Here's how I'm doing it for hexadecimal (mostly LINQ):

public static byte[] GetHexBytes(this string hex, bool preTrimmed = false)
{
    if (!preTrimmed)
    {
        hex = hex.Trim();
        if (hex.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            hex = hex.Substring(2);
        else if (hex.StartsWith("16#"))
            hex = hex.Substring(3);
    }

    if (hex.Length % 2 != 0) hex = hex.PadLeft(hex.Length + 1, '0');

    return Enumerable.Range(0, hex.Length)
            .Where(x => x % 2 == 0)
            .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
            .ToArray();
}

And here's binary (mostly LINQ):

public static byte[] GetBinaryBytes(this string binary, bool preTrimmed = false)
{
    if (!preTrimmed)
    {
        binary = binary.Trim();
        if (binary.StartsWith("0b", StringComparison.OrdinalIgnoreCase) || binary.StartsWith("2#"))
            binary = binary.Substring(2);
    }

    if (binary.Length % 8 != 0) binary = binary.PadLeft(binary.Length + 8 - binary.Length % 8, '0');

    return Enumerable.Range(0, binary.Length)
            .Where(x => x % 8 == 0)
            .Select(x => Convert.ToByte(binary.Substring(x, 8), 2))
            .ToArray();
}

And here's what I've got for Octal (LINQ, then a BitArray, then more LINQ):

public static byte[] GetOctalBytes(this string octal, bool preTrimmed = false)
{
    if (!preTrimmed)
    {
        octal = octal.Trim();
        if (octal.StartsWith("0o", StringComparison.OrdinalIgnoreCase) || octal.StartsWith("8#"))
            octal = octal.Substring(2);
    }

    octal = octal.TrimStart('0');
    if (octal.Length == 0)
        octal = "0";

    BitArray bits = new BitArray(octal
        .Reverse()
        .SelectMany(x =>
            {
                byte value = (byte)(x - '0');
                return new bool[] { (value & 0x01) == 1, (value & 0x02) == 2, (value & 0x04) == 4 };
            })
        .ToArray());

    byte[] bytes = new byte[bits.Length / 8 + 1];
    bits.CopyTo(bytes, 0);

    bytes = bytes.Reverse().SkipWhile(b => b == 0x00).ToArray();
    if (bytes.Length == 0)
        bytes = new byte[] { 0x00 };

    return bytes;
}

I don't like using the BitArray intermediary, but I don't know how to do it without it. If possible, I'd like the whole conversion in a single LINQ statement like the hex and binary.

This is part of a C# console application for computing hashes. Here's a link to the relevant source file on Github.


texts: Mutex and condition variable implementation using futex

texts:
I have implemented mutex and conditional variables using the futex syscall. I believe that my implementation is correct, but would like it to be verified by someone else. Any suggestions for further improvements in the performance of the mutex and conditional variables would also be appreciated.

  #ifndef __SYNCHRONIZATION__
  #define __SYNCHRONIZATION__

  #include <unistd.h>
  #include <limits.h>
  #include <sys/syscall.h>
  #include <linux/futex.h>
  #include "types.h"
  #include "assembly.h"

  typedef UINT32 mutex;
  typedef struct condvar condvar;

  struct condvar    {
   mutex *m;
   int seq;
  };

  void mutex_init(mutex *m) {
   *m = 0;
  }

  void mutex_destroy(mutex *m)  {
   *m = 0;
  }

  void mutex_lock(mutex *m) {
   UINT32 c;
   if((c = __sync_val_compare_and_swap(m, 0, 1)) != 0)  {
    do  {
        if((c == 2) || __sync_val_compare_and_swap(m, 1, 2) != 0)
            syscall(SYS_futex, m, FUTEX_WAIT_PRIVATE, 2, NULL, NULL, 0);
    } while((c = __sync_val_compare_and_swap(m, 0, 2)) != 0);
   }
  }

  void mutex_unlock(mutex *m)   {
   if(__sync_fetch_and_sub(m, 1) != 1)  {
    *m = 0;
    syscall(SYS_futex, m, FUTEX_WAKE_PRIVATE, 1, NULL, NULL, 0);
   }
  }

  void cond_init(condvar *c, mutex *m)  {
   c->m = m;
   c->seq = 0;
  }

  void cond_destroy(condvar *c) {
   c->m = NULL;
   c->seq = 0;
  }

  void cond_signal(condvar *c)  {
   __sync_fetch_and_add(&(c->seq), 1);
   syscall(SYS_futex, &(c->seq), FUTEX_WAKE_PRIVATE, 1, NULL, NULL, 0);
  }

  void cond_broadcast(condvar *c)   {
   __sync_fetch_and_add(&(c->seq), 1);
   syscall(SYS_futex, &(c->seq), FUTEX_REQUEUE_PRIVATE, 1, (void *) INT_MAX, c->m, 0);
  }

  void cond_wait(condvar *c)    {
   UINT32 oldSeq = c->seq;
   mutex_unlock(c->m);
   syscall(SYS_futex, &(c->seq), FUTEX_WAIT_PRIVATE, oldSeq, NULL, NULL, 0);
   while (xchg32(c->m, 2))  {
    syscall(SYS_futex, c->m, FUTEX_WAIT_PRIVATE, 2, NULL, NULL, 0);
   }
  }

  #endif


texts: A function to print a character number of times and in number of lines

texts:
My task was:

Write a function that takes three arguments: a character and two integers. The
character is to be printed. The first integer specifies the number of times that the
character is to be printed on a line, and the second integer specifies the number
of lines that are to be printed. Write a program that makes use of this function.

And my code is: (i know i did not add different scenarios like if the first char is number etc, but please let me know if it looks ok)

#include <stdio.h>
void printing_char (char ch, int numberOfChars, int numberOfLines);

int main (void)
{
    char userChar;
    int lines,times;
    printf ("please enter a character, number of times in a line, and number of lines:\n");
    while ((scanf ("%c%d%d", &userChar, &times, &lines)) == 3)
    {
        printing_char (userChar, times, lines);
    }
    return 0;
}

void printing_char (char ch, int numberOfChars, int numberOfLines)
{
    int x;
    int y = 0;

    while (++y <= numberOfLines)
    {
            for (x = 0; x<numberOfChars; x++)
            {
                printf ("%c", ch);
            }
            printf ("\n");
    }
}


texts: Solve multi-dimentional optimization problem using basinhopping

texts:
I am searching for an optimization solution, which is a 8d vector representing 4 complex elements, where each element is within the complex circle with maximal radius 1.2.

The objective function is:

$$f: \left\|\mathbf{c}_{ref}-\mathbf{c}\right\|_{2}+\left|2-\|\mathbf{c}\|_{2}\right|$$

I am using the scipy.optimize.basinhopping module.

import numpy as np
from scipy import optimize

class MyBounds(object):
    def __init__(self, xmax=[360, 360, 360, 360, 1.2, 1.2, 1.2, 1.2], xmin=[0, 0, 0, 0, 0, 0, 0, 0] ):
        self.xmax = np.array(xmax)
        self.xmin = np.array(xmin)

    def __call__(self, **kwargs):
        x    = kwargs["x_new"]
        tmax = bool(np.all(x <= self.xmax))
        tmin = bool(np.all(x >= self.xmin))
        return tmax and tmin

class MyTakeStep(object):
    def __init__(self, stepsize=45):
        self.stepsize = stepsize
    def __call__(self, x):
        s = self.stepsize
        x[0] += np.random.uniform(0, 1*s)
        x[1] += np.random.uniform(0, 2*s)
        x[2] += np.random.uniform(0, 3*s)
        x[3] += np.random.uniform(0, 4*s)
        s = 1
        x[4] += np.random.uniform(0, 1*s)
        x[5] += np.random.uniform(0, 1*s)
        x[6] += np.random.uniform(0, 1*s)
        x[7] += np.random.uniform(0, 1*s)
        return x

def f(input_list):
    polar_form = [rphi for rphi in zip(input_list[4:], input_list[:4])]
    x          = np.array([z(e[0], e[1]) for e in polar_form])
    # objective function componenets
    result  = abs(2 - np.linalg.norm(x, 2)) + np.linalg.norm(cref-x, 2)
    return result

def hopping_solver(min_f, min_x):
    minimizer_kwargs = {"method":'Nelder-Mead'}
    comb             = np.array([0, 0, 0, 0, 0, 0, 0, 0])
    # define bounds
    mybounds   = MyBounds()
    mytakestep = MyTakeStep()
    optimal_c  = optimize.basinhopping(f, x0 = comb, niter=50000, T=45, stepsize=1, minimizer_kwargs=minimizer_kwargs, take_step=None, accept_test=mybounds, callback=None, interval=5000, disp=False, niter_success=None)

    min_x, min_f = optimal_c['x'], optimal_c['fun']
    print(optimal_c)
    return min_x, min_f

min_f = 10**10
min_x = []
min_x, min_f = hopping_solver(min_f, min_x)

My questions relate to the step essentially: My first elements are angles in [0,360] and the others are in [0,1.2]. What is a suitable way to define a good step here to balance between precision and fast processing?

I am aware that this code does not return the global minimum.

Also here I chose the center of my solutions space as x0, is there on recommendations on how to choose the starting point?


texts:
I have a function for generating RGB colors in VB6.0, and it is working properly.  Please suggest improvements for this, if any.

Public Function RandomRGBColor() As Long
    RandomRGBColor = RGB( _
        Int(Rnd() * 256), _
        Int(Rnd() * 256), _
        Int(Rnd() * 256))
End Function


texts:
I have a query like this "abc=1, def=2, ghi=3" and I need to parse it into arrays like this keys = [abc, def, ghi] and values = [1,2,3]

currently my code is like this

String[] terms = query.split(",");
int termsCount = terms.length;
String[] keys = new String[termsCount];
String[] values = new Object[termsCount];

for(int i=0; i<termsCount; i++)
{
    if(terms[i].contains("="))
    {
        keys[i] = terms[i].split("=")[0];
        values[i] = terms[i].split("=")[1];
    }
}

sometimes, the query might be empty or may not be well formed - I need to take care of that scenarios too.

Am I doing this right? Is there a better way to do this?


texts: Authenticating an internal API with Flask

texts:
I'm developing an internal API using Flask, although due to limitations with our platform the endpoints will be accessible over the public internet. It will only have a very small number of users and it's not likely that this will increase much in the future. They will query the service programatically from a backend.

As only a small number of users will be consuming the API I think it makes sense to have a single key that can be used to access it. This will keep the authentication process simple and as the API doesn't provide access to anything really sensitive I don't believe we need to go too extreme on security. I've written the following:

app_config.py

import yaml
config = yaml.safe_load(open('config.yml'))

auth.py

from functools import wraps
from flask import request
from app_config import config

def valid_auth(func):
    @wraps(func)
    def func_wrapper(*args, **kwargs):
        if 'x-api-key' not in request.headers:
            return("Credentials not present in request", 401)
        elif request.headers['x-api-key'] != config['api_key']:
            return ("Credentials not valid", 401)
        else:
            return func(*args, **kwargs)
    return func_wrapper

main.py

import api_module as api
from flask import Flask, request
from auth import valid_auth

app = Flask(__name__)

@app.route('/route1')
@valid_auth
def api_function():
    #do api stuff here

Essentially the process is:

API key is stored in config.yml on API server
(SSL) Request from backend includes the key in a header called x-api-key
A wrapper function checks that the key sent in this header matches the key in the configuration before executing any API functions. If not, the user gets an error.

Does this seem like a reasonable approach to authentication for an internal API that will be used by a small number of users and that doesn't provide access to any sensitive information? Any general suggestions for how this process might be improved?


texts: How to apply multiple filters in one statement

texts:
While trying to grasp the potentials of the collection features in F#, I encountered this one:
let needSpecialDocument country = (not country.IsEea) && (not country.IsInSchengen)
// could also be: not (country.IsEea || country.IsInSchengen)
let wantToMoveTo country = country.Name = "CC"

let potentialDestinations =
    countries
    |> Seq.filter needSpecialDocument2
    |> Seq.filter wantToMoveTo

Is there a way to combine the two filters into one? I managed the one below but it feels like there is a more fsharpish way to do so..
|> Seq.filter (fun c -> (needSpecialDocument c) && (wantToMoveTo c))

Test data:
type Country = {Name : string; IsEea : bool; IsInSchengen : bool}
let uk = {Name = "UK"; IsEea = false; IsInSchengen = false}
let ir = {Name = "IR"; IsEea = true; IsInSchengen = false}
let fr = {Name = "FR"; IsEea = true; IsInSchengen = true}
let ch = {Name = "CH"; IsEea = false; IsInSchengen = true}
let cc = {Name = "CC"; IsEea = false; IsInSchengen = false}
let countries = [uk;ir;fr;ch;cc]


texts:
I've made a python program that can brute-force both MD5 and SHA1 hashes, and I would like know if I could make the program faster or any way I could improve it.
I'm still a beginner in python and in coding in general
(this program is only for learning purposes).

The code:

import time
import string
import hashlib
ready = False
start = time.time()
chars = list(string.printable)[:95]
base = len(chars)
n = 0
hashmethod = 0
password = ""
solved = False
quit = ""
while ready != True:
    password = input("Enter a valid MD5 or SHA-1 hash:")

if len(password) == 32:
    ready = True
elif len(password) == 40:
    ready = True
    hashmethod = 2
else:
    continue

def numberToBase(n, b):  # converts number N base 10 to a list of digits base b
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return digits[::-1]

# check edge cases like empty, or 0
if password == '':
    print('Your password is empty')
    solved = True

# begin systematically checking passwords
while not solved:
    lst = numberToBase(n, base)
    word = ''
    for x in lst:
        word += str(chars[x])
    if hashmethod == 2:
        hashedGuess = hashlib.sha1(bytes(word, 'utf-8')).hexdigest()

    else:
        hashedGuess = hashlib.md5(bytes(word, 'utf-8')).hexdigest()
        print(word)
    if password == hashedGuess:
        solved = True
        print('-Stats-')
        print('Pass: ' + word)
        print('Attempts: ' + str(n))
        print('time: ' + str((time.time() - start)) + ' sec')
        while quit != " QUIT":
            quit = input('Type <QUIT> to quit')
    else:
        n += 1


texts: Downloads historical data from a yahoo finance csv and returns a pandas DataFrame

texts:
Not too long ago, yahoo-finance shut down its public API for downloading historical data. There are however works around and the below code is on of them. I started looking for solutions of how to grab the correct cookie and crumb pair and then implemented that into it's own function.

I am new to Pandas and don't know the best practices for accessing data and creating DataFrames. Are there any ways that I can make this project more efficient?

This project can be downloaded here https://github.com/AndrewRPorter/yahoo-historical

import datetime as dt
import pandas as pd
import requests
import re
import csv
import time

class Fetcher:
    def __init__(self, ticker, start, *args):
        self.ticker = ticker.upper()
        self.cookie, self.crumb = self.init()

        self.start = int(time.mktime(dt.datetime(start[0],start[1],start[2]).timetuple()))

        if args:
            end = args[0]
            self.end = int(time.mktime(dt.datetime(end[0],end[1],end[2]).timetuple()))
        else:
            self.end = int(time.time())

    def init(self):
        """Returns a tuple pair of cookie and crumb used in the request"""
        url = 'https://finance.yahoo.com/quote/%s/history' % (self.ticker)
        r = requests.get(url)
        txt = r.content
        cookie = r.cookies['B']
        pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}')

        for line in txt.splitlines():
            m = pattern.match(line.decode("utf-8"))
            if m is not None:
                crumb = m.groupdict()['crumb']
        return cookie, crumb  # return a tuple of crumb and cookie

    def getHistorical(self):
        """Returns a list of historical data from Yahoo Finance"""
        url = "https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=1d&events=history&crumb=%s" % (self.ticker, self.start, self.end, self.crumb)
        data = requests.get(url, cookies={'B':self.cookie})
        content = data.content.decode("utf-8")
        csv_content = csv.reader(content.splitlines(), delimiter=',')
        return pd.DataFrame(list(csv_content))

    def getDatePrice(self):
        """Returns a DataFrame for Date and Price from getHistorical()"""
        return self.getHistorical().ix[0:,5]

    def getDateVolume(self):
        """Returns a DataFrame for Date and Volume from getHistorical()"""
        return self.getHistorical().ix[0:,6]


texts:
You are writing your web-page and relentlessly adding links, as you think that links are the best thing a web-page can offer.

The fact is that you write links even to pages that do not exist just yet, because you will write them later.

But later becomes a lot later and now you have your website in your directory with a lot of links pointing to nothing.

You decide to systematically write a page for each link, as to eliminate all the pending links, and using this script to list all such pending links:

An example output looks like:

['addition.html', 'definition.html', 'division.html', 'infinity.html', 'multiplication.html', 'primitive_concept.html', 'recursion.html', 'set.html', 'subtraction.html']

The code is very straightforward, but there is always potential for improvement:

"""
Given a folder of html pages, gives a list of all the pages that are linked to,
but do not exist.
"""
import doctest
import itertools
import os
import re

PATH = os.path.dirname(os.path.realpath(__file__))
flatten = itertools.chain.from_iterable

def destinations(html):
    """
    >>> destinations('''
The natural numbers are an infinitesetdefined recursivelyas follows:''')
    ['infinity.html', 'set.html', 'recursion.html']
    """
    return re.findall('[a-z_]+\.html', html)

def read(f):
    with open(f) as c:
        return c.read()

def missing_pages(directory=PATH):
    """
    Lists all the pending links of the html pages if the `directory`.
    """
    all_pages = sorted(set((flatten(destinations(read(i)) for i in os.listdir(directory)))))
    return list(i for i in all_pages if i not in os.listdir(directory))

if __name__ == "__main__":
    doctest.testmod()
    print(missing_pages())


texts: Implementation of Newton's method of finding root of a function

texts:
The following is an implementation of Newton's method of finding root of a function.

using System;
using System.Drawing;
using ZedGraph;

//Newton's Method
//https://www.youtube.com/watch?v=2GrfaB88w4M&t=350s
//https://stackoverflow.com/questions/12915317/how-to-find-derivative-of-a-function-using-c
//https://www.geeksforgeeks.org/program-for-newton-raphson-method/
namespace _1_22_Newton_Method_of_Root_Finding
{
    public delegate double MyFunction(double x);
    public class RootFinder
    {
        static double EPSILON = 0.01;
        static double h = 1.0e-6;

        public static double Derivative(MyFunction func, double x0)
        {
            double x1 = x0 - h;
            double x2 = x0 + h;
            double y1 = func(x1);
            double y2 = func(x2);
            double der = (y2 - y1) / (x2 - x1);//<==== i am not sure about this.

            return der;
        }

        private static double NextNewton(MyFunction func, double guess)
        {
            return guess - func(guess) / Derivative(func, guess);
        }

        public static double Newton(MyFunction func, double init)
        {
            double x = init;
            double y = NextNewton(func, x);

            //for(int i=0 ; i < 10 ; i++)
            while(Math.Abs(y) >= EPSILON)
            //while(true)
            {
                y = NextNewton(func, x);

                if (x == y)
                {
                    break;
                }

                Console.WriteLine("Root = {0}", y);
                x = y;
            }

            return y;
        }
    }

Kindly, review the source code.

Does this source code have any pitfall?