texts: Create conversations and add new members while avoiding duplicates

texts:
In a Node app where there is a messaging service, I've added a method to add a conversation and a member. The method functionality is that when a new request hit an API for messaging, that calls a method called JoinConversation. In the request there are some inputs from a client and based on those inputs the method do a check based on some conditions

There is a first check if a conversations of the same already exist in the DB. If that exists then checks if the member already exist. If the member input info are presents in DB for that conversations it is returning the conversation related but if the member not preset then is creating a new member for that conversation.
If above is false means the conversation does not exist then a new conversation is created and also a new member is created also

The method is doing fine the job but the way I wrote it sounds redundant to me and was seeking a better way to write it and in less lines if that would be possible.
The code of it and ignore DAO is a security external plugin I cannot explain.
The method uses KnexJS and Apollo.
      joinConversation({ input }) {
    const { ApolloError } = this.errors;
    return this.withDAO(async ({ conversation, member }) => {
      const { originId, memberId, memberType, name, originType } = input;

      const existingConversation = await conversation.selectFirst({
        originId,
        originType,
      });

      if (existingConversation) {
        const existingMemberPerDocument = await member.selectFirst({
          memberId,
        });

        if (!isEmpty(existingMemberPerDocument)) {
          await conversation.selectFirst({
            conversationId: existingConversation.conversationId,
            originType: existingConversation.originType,
          });

          return existingConversation;
        }

        await member.insert({
          conversationId: existingConversation.id,
          memberId,
          memberType,
          name,
        });

        if (isEmpty(member)) {
          throw new ApolloError('Error while Adding new conversation member!');
        }

        return existingMemberPerDocument;
      }

      const createdConversation = await conversation.insert({
        ...input,
      });

      if (isEmpty(createdConversation)) {
        throw new ApolloError('Error while Adding new conversation!');
      }

      await member.insert({
        conversationId: createdConversation.id,
        memberId,
        memberType,
        name,
      });

      return createdConversation;
    });
  }


texts: Compose n functions where the innermost function expects multiple arguments

texts:
I want to perform function composition like this:

f(g(...(z(x) (y));

I have already compn:

const id = x => x;

const comp = f => g => x => f(g(x));

const foldr = f => acc => xs =>
 xs.reduceRight((acc, x, i) => f(x) (acc, i), acc);

const compn = foldr(comp) (id);

I tried to derive the desired function from compn, but failed. All I've got is a hideous wrapper function that applies the composition accordingly:

// generic functions

const id = x => x;

const last = xs => xs[xs.length - 1];

const init = xs => xs.slice(0, -1);

const sqr = x => x * x;

const inc = x => x + 1;

const sub = y => x => x - y;

const uncurry = f => (y, x) => f(x) (y);

const comp = f => g => x => f(g(x));

const foldr = f => acc => xs =>
 xs.reduceRight((acc, x, i) => f(x) (acc, i), acc);

// derived functions

const compn = foldr(comp) (id);

// wrapper function

const compn2 = fs => x => compn([...init(fs), last(fs) (x)]);

// arbitrary computation

const f = uncurry(compn2([sqr, inc, sub]));

console.log(f(5, 2)); // yields 16

Is there a way to derive compn2 from compn or from other combinators?


texts: Jest unit test that handles a wrapped Promise

texts:
I've wrapped an imported function (a promise) and attempted to write unit tests that bring my codebase to 100% coverage.

import { Auth } from 'aws-amplify';

import signIn from './shared';

describe('signIn', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });

  it('invokes the success callback on success', (done) => {
    const mockUser = { username: 'jon', password: 'snow' };

    jest
      .spyOn(Auth, 'signIn')
      .mockImplementation(() => Promise.resolve(mockUser));

    const mockSuccessCb = (user) => {
      expect(user).toBe(mockUser);
      done();
    };

    const mockErrorCb = (err) => {
      done(err);
    };

    signIn('jon', 'snow', mockSuccessCb, mockErrorCb);
  });

  it('invokes the error callback on err', (done) => {
    const mockUser = { username: 'jon', password: 'snow' };

    jest
      .spyOn(Auth, 'signIn')
      .mockImplementation(() => Promise.reject(mockUser));

    const mockSuccessCb = (user) => {
      expect(Auth.signIn).toHaveBeenCalledWith('jon', 'snow');
      expect(user).toBe(mockUser);
      done();
    };

    const mockErrorCb = () => {
      expect(Auth.signIn).toHaveBeenCalledWith('bob', 'tom');
      done();
    };

    signIn('bob', 'tom', mockSuccessCb, mockErrorCb);
  });
});

Auth is the imported object that is getting wrapped. In my first test, I attempt verify a successful login by returning a resolved promise. In the second test, I reject the promise. I got my 100% coverage, but since I tell my promise how to resolve itself, I can't help but feel like I'm setting myself up for false positives. Is this a good test? How can it be improved?

Edit: Added the original wrapper function for detail:

import { Auth } from 'aws-amplify';

const signIn = (
  username,
  password,
  successCallback,
  errorCallback,
) => {
  Auth.signIn(username, password)
    .then(user => successCallback(user))
    .catch(err => errorCallback(err));
};

export default signIn;


texts: Amalgamate two toggle functions into one

texts:
I want to amalgamate these two functions into one, Any ideas?

  function toggleVisibility() {

        document.getElementById('regStart').style.visibility = 'hidden';
        document.getElementById('regPage').style.visibility = 'visible';

        document.getElementById('facebook').src = "/images/js project/FacebookGray.png"
        document.getElementById('google').src = "/images/js project/GoogleGray.png"
        document.getElementById('winlive').src = "/images/js project/WinLiveGray.png"
        document.getElementById('yahoo').src = "/images/js project/YahooGray.png"
}

function toggleSave() {

    document.getElementById('regStart').style.visibility = 'visible';
    document.getElementById('regPage').style.visibility = 'hidden';

    document.getElementById('facebook').src = "/images/js project/FacebookDepressed.ico"
    document.getElementById('google').src = "/images/js project/GoogleDepressed.ico"
    document.getElementById('winlive').src = "/images/js project/WinLiveDepressed.ico"
    document.getElementById('yahoo').src = "/images/js project/YahooDepressed.ico"

  }


texts:
I'm trying to improve my php oop programming skills. As an exercise I wrote this class that will generate and execute dynamic sql queries. I've also writed a class to call various sanitization filters that php has built in.

QueryBuilder.php class

<?php

class QueryBuilder{

private $db = null;
private $stmt;
private $table;
private $param;
private $cols, $columns;
private $holders, $placehold;
private $fields, $field;

public $data;
public $results;

public function __construct(\PDO $db){
    $this->db = $db;
}

public function insert($table, array $data, array $columns){
    $holders = $this->setHolders($columns);
    $cols = $this->setColumns($columns);
    $stmt = $this->db->prepare("INSERT INTO $table ($cols) VALUES ($holders)");
    return $stmt->execute($data);
}

public function select($table, array $columns, $field, $param){
    $cols = $this->setColumns($columns);
    $stmt = $this->db->prepare("SELECT $cols FROM $table WHERE $field = ?");
    $stmt->execute(array($param));
    $result = $stmt->fetch();
    return json_encode($result);
}

public function edit($table, array $columns, array $data, $param){
    $fields = $this->setFields($columns);
    $stmt = $this->db->prepare("UPDATE $table SET $fields WHERE $param = ?");
    return $stmt->execute($data);
}

public function delete($table, array $data, $param){
    $stmt = $this->db->prepare("DELETE FROM $table WHERE $param = ?");
    return $stmt->execute($data);
}

private function setColumns(array $columns){
    $cols = implode(', ', array_values($columns));
    return $cols;
}

private function setFields(array $columns){
    $fields = implode(' = ?, ', array_values($columns));
    return $fields.' = ?';
}

private function setHolders(array $columns){
    $holders = array_fill(1 ,count($columns),'?');
    return implode(', ',array_values($holders));
}

}

?>

DataSanitizer.php class

<?php

class DataSanitizer{

private $value;
private $sanitized_value;

public function intSanitize(int $value){
    $sanitized_value = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
    return $sanitized_value;
}

public function stringSanitize(string $value){
    $sanitized_value = filter_var($value, FILTER_SANITIZE_STRING);
    return $sanitized_value;
}

public function floatSanitize(float $value){
    $sanitized_value = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT);
    return $sanitized_value;
}

public function emailSanitize(string $value){
    $sanitized_value = filter_var($value, FILTER_SANITIZE_EMAIL);
    return $sanitized_value;
}

public function validateEmail(string $value){
  $sanitized_value = filter_var($value, FILTER_VALIDATE_EMAIL);
  return $sanitized_value;
}

}

?>

Classes usage example:

<?php
// Usaually i use the spl_autoloader_register();
require_once 'QueryBuilder.php';
reqiure_once 'DataSanitizer.php';

// this file holds the PDO connection stored inside the $db variable
require_once 'Config.php';

$query = new QueryBuilder($db);
$sanitize = new DataSanitizer;

$table = 'test_table';
$data = array($sanitize->stringSanitize('hello'),$sanitize->stringSanitize('world'));
$col = array('col1','col2');

$query->insert($table, $data, $col);

?>


texts: Calculate the number of primes in a range

texts:
I wrote some code to return how many prime numbers are in a specific range and what they are. It also tells you whether the number of primes is also a prime!

I feel like this seems like a fairly long winded approach for something that's probably very simple, can someone please tell me how I can improve this?

def prime_number():
    primes = []
    primes_2 = []
    low = int(input("What number would you like to start at? "))
    high = int(input("What number would you like to go up to? "))
    if int(low) == 1 and int(high) == 1:
        print("1 isn't a prime number dumb dumb")
    elif high < 2:
        print("Don't be annoying")
    else:
        for x in range(int(low), int(high)):
            for i in range(2, x):
                if (x % i) == 0 and x != i:
                    break
                elif (x % i) == 1 and i <= (x - 2):
                    continue
                elif (x % i) == 1 and i == (x - 1):
                primes.append(x)
            x = x + 1
        print("The number of prime numbers is: ", len(primes))
        for y in range(2, int(low)):
            for z in range(2, y):
                if (y % z) == 0 and y != z:
                    break
                elif (y % z) == 1 and z <= (y - 2):
                    continue
                elif (y % z) == 1 and z == (y - 1):
                    primes_2.append(y)
            y = y + 1
        if int(len(primes)) in primes or int(len(primes)) in primes_2:
            print("Huh, fancy that!", len(primes), "is also also a prime number!")
        print("The prime numbers are: ",primes)


texts:
I have created a Path finder.
The aim is to find ALL paths that join a Point A to a Point B.
I have defined an object Segment which is a link between two assets.
It is readable in both directions.
==> Segment(A->B) === Segment(B<-A)

Here is my code:
# Exemple Path finder

class Segment:
  # A segment is a link (physical, radio, logical) beetween two assets
  def __init__(self, sku, e1, e2, re1, re2):
    # The SKU is the unique ID of the segment
    # A segment as two endpoint that can be inversable
    self.sku = sku
    self.sku_endpoint_1 = e1
    self.sku_endpoint_2 = e2
    self.reverse_sku_endpoint_1 = re1
    self.reverse_sku_endpoint_2 = re2

# We can instanciante a segment like that

seg1 = Segment("SEGMENT1","A", "B", "B", "A")
seg2 = Segment("SEGMENT2","B", "C", "C", "B")
seg3 = Segment("SEGMENT3","C", "D", "D", "C")
seg4 = Segment("SEGMENT4","C", "E", "E", "C")
seg5 = Segment("SEGMENT5","E", "A", "A", "E")
seg6 = Segment("SEGMENT6","E", "D", "D", "E")

# Then create a liste of segment
liste_segments = [seg1, seg2, seg3, seg4, seg5, seg6]

--
# The function below allow to find neibhors of a segment
def neighbors(liste_segments, node):
  for segment in liste_segments:
    if node == segment.sku_endpoint_1:
      yield segment

--
# And the function below solve all paths existing beetween an start et end.
def solve(liste_segments, s, e, current_path=None, nb_call=0):
  nb_call += 1
  if nb_call == 1:
    # We create a new liste with the inversable values to have all possibility of linking
    liste_segments = clone(liste_segments)
  if current_path is None:
    current_path = []
  if s == e:
    # Here, we end the function because we found the end.
    yield current_path
  else:
    # Else we call recursively the solve function on each neibhors
    for node in neighbors(liste_segments, s):
      print(node.sku_endpoint_1, node.sku_endpoint_2)
      if node not in current_path:
        for result in solve(liste_segments, node.sku_endpoint_2 , e, current_path + [node], nb_call):
          yield result

--
# The yield function return a generator
# The function here create a dictionnary of all paths found.
# On all paths we check if the paths is meaningful.
# Ex: if a segment is found twice on the same path...this is not meaningful.
# So we delete the entry from the dict to keep only understanding paths.
def list_to_dict(paths):
  d = {}
  index = 0
  for path in paths:
    index+=1
    d[index] = []
    for segment in path:
      d[index].append(segment.sku)

  to_del = []
  for k, v in d.items():
    temp = []
    for seg in v:
      if seg not in temp:
        temp.append(seg)
      else:
        if k not in to_del:
          to_del.append(k)
  for i in to_del:
    del d[i]
  return d

--
# The clone function create a new list of segment with all possibility.

def clone(liste_segments):
  new_list_segments = []
  for seg in liste_segments:
    new_list_segments.append(Segment(seg.sku, seg.sku_endpoint_1, seg.sku_endpoint_2, "", ""))
    new_list_segments.append(Segment(seg.sku, seg.reverse_sku_endpoint_1, seg.reverse_sku_endpoint_2, "", ""))
  return new_list_segments

Is my code pythonic? What could be changed?


texts: Can I speed up this simple versioning/backup script?

texts:
I'm writing a simple automatic backup/versioning bash script.

It should basically mirror a directory structure somewhere, and then copy files over there when they've been altered. The ghost files should then be named filename.YYYYMMDD-HHMMSS.ext (the included date/time being the time of last modification).

This is what I came up with - it seems to work already, sort of. but since I've never written shell scripts before, I suspect I might be doing some things fundamentally wrong and inefficiënt.

How can I make this faster? The iterating over files seems to be really slow.
Is this robust? It seems to "lock up" without error messages sometimes, and I can't explain or understand why. What am I doing wrong?

I intend to run this as a cron job, every 30 minutes or so.

#!/bin/sh

# $1 : backup "root"
# $2 : from: directory to be backed up
# $3 : to: destination

rpath=$1

for f in $(find $2); do
  r=$(./rel.sh $rpath $f)
  if [ -f $f ]
  then
    basename=$(basename $f)
    dir=$(dirname $r)
    name=$(echo $basename | cut -d'.' -f1)
    ext=$(echo $basename | cut -d'.' -f2)
    mod=$(stat --format=%y $f | awk -F'.' '{printf $1}' | sed 's/[-:]//g' | sed 's/ /-/g')

    if [ ! -f "$3/$dir/$name.$mod.$ext" ]
    then
      echo "+f   $mod $r"
      # cp $f "$3/$dir/$name.$mod.$ext"
    fi
  elif [ -d $f ]
  then
    if [ ! -d "$3/$r" ]
    then
      echo "+dir $r"
      mkdir "$3/$r"
    fi
  fi
done
exit


texts: Authentication system - AngularJS & Ionic Framework

texts:
I am building a small mobile app using ionic framework and angularJS. It will consume a Restful Web Service that requires authentication (User token). This means I need to keep my users token by myself. Could anyone tell me if there is room for improvement in my code? Specifically regarding to my "Session" service which I feel kind of useless. I based my development in this article.

.run(function ($rootScope, EVENTS, AuthService) {
  $rootScope.$on('$stateChangeStart', function (event, next) {
    if (next.requiresAuth === true && !AuthService.isAuthenticated()) {
      event.preventDefault();
      $rootScope.$broadcast(EVENTS.notAuthenticated);
      console.log('You can not access here without login in.');
    }

  });
})
.constant('apiAddress', 'http://api.test.com')
.constant('EVENTS', {
  loginSuccess: 'auth-login-success',
  loginFailed: 'auth-login-failed',
  logoutSuccess: 'auth-logout-success',
  sessionTimeout: 'auth-session-timeout',
  notAuthenticated: 'auth-not-authenticated',
  signupSuccess: 'auth-signup-success'
})
.service('Session', function() {
  this.create = function(user) {
    this.user = user;
  };
  this.destroy = function() {
    this.user = null;
  }
  return this;
})
.factory('AuthService', function($http, $rootScope, $localstorage, Session, apiAddress, EVENTS) {
  var authService = {};
  authService.login = function(credentials){
    return $http.post(apiAddress + '/users/', credentials).then(function(res) {
      Session.create(res.data);
      $localstorage.setObject('user', res.data);
      return res.data;
    });
  };
  authService.signup = function(signForm){
    return $http.post(apiAddress + '/users/', signForm).then(function(res) {
      $rootScope.$broadcast(EVENTS.signupSuccess);
      return res.data;
    });
  };
  authService.logout = function(){
    Session.destroy();
    $localstorage.destroy('user');
    $rootScope.$broadcast(EVENTS.logoutSuccess);
  };
  authService.isAuthenticated = function() {
    return !!Session.user;
  };

  return authService;
})
controller('appCtrl', function($scope, $rootScope, $state, AuthService, EVENTS, $localstorage, Session) {
  $scope.currentUser = null;
  $scope.isAuthorized = AuthService.isAuthorized;
  $scope.setCurrentUser = function (user) {
    $scope.currentUser = user;
  };
  function logout() {
    AuthService.logout();
  }
  function redirectToLogin() {
    $state.go('login');
  }

  if ($localstorage.isSet('user') && Session.user == null) {
    Session.create($localstorage.getObject('user'));
    $scope.setCurrentUser($localstorage.getObject('user'))
    $state.go('cobranzas.clientes.index');
  }
  // We listen to auth related broadcasts.
  $scope.$on(EVENTS.notAuthenticated, logout);
  $scope.$on(EVENTS.sessionTimeout, logout);
  $scope.$on(EVENTS.signupSuccess, logout);
  $scope.$on(EVENTS.logoutSuccess, redirectToLogin);
})
.controller('loginCtrl', function($scope, $rootScope, $state, EVENTS, AuthService) {
  $scope.credentials = {
    username: '',
    password: ''
  };
  $scope.login = function (credentials) {
    AuthService.login(credentials).then(function (user) {
      $rootScope.$broadcast(EVENTS.loginSuccess);
      $scope.setCurrentUser(user);
      $state.go('index');
    }, function () {
      $rootScope.$broadcast(EVENTS.loginFailed);
    });
  };
})
.controller('signupCtrl', function($scope, $rootScope, $state, EVENTS, AuthService) {
  $scope.signForm = {
    FirstName: '',
    LastName: '',
    Password: '',
    Country: '',
    Phone: '',
    Gender: '',
    Position: ''
  };
  $scope.signup = function (signForm) {
    AuthService.signup(signForm).then(function (data) {
      $state.go('login');
    }, function (data) {
      console.log("Failed");
    });
  };
})

I don't feel right storing user in scope and in the service. Also I feel weird verifying localstorage in app controller. (App controller is a controller placed high at DOM so it's inherited by the others).


texts:
First off, not the greatest with jQuery but know enough to get by. I created this mock up that is base on my application and wanted to see if there is a better way to update hidden values and a tags. When the form is saved I am using the sortorder to find the corresponding .ui-sortable li that has a tag and hidden fields to get updated on the page. I am trying to update the correct one and looping all of them checking with the sortorder  I just wanted to know if there is a better way to do this?

https://jsfiddle.net/tjmcdevitt/vh9n5srL/35/

actual code from a project

$("#submit-form").submit(function (event) {
    event.preventDefault();
    var sortOrder = $(this).data('sortorder');
        $('.ui-sortable li').each(function (i) {
        if (i == sortOrder) {
            console.log('Updating');

            $("#References_0_UI").html(data.referenceText);
            $("#References_0_UI").attr("href", data.GuidelineExternalReference);

            $('input[name="References[0].Text"]').val(data.referenceText);
            $('input[name="References[0].Link"]').val(data.GuidelineExternalReference);
            $('input[name="References[0].GuidelineId"]').val(data.Value);
            console.log("Completed Task");
        }
});


texts:
I have made one architecture on my project and want to know. Is it good or bad?

events = {
      init: function() {
        for (var callback in this.events){
          this.bind(this.events[callback].selector, this.events[callback].event, this[callback], this.events[callback].params || {})
        }
      },
      events: {
        initSettings: {
          selector: ".js-settingsCollapse",
          event: "click",
          params: {
            ss: "11"
          }
        },
        settingTrigger: {
          selector: ".js-settingTrigger",
          event: "click",
          params: {
            ss: "22"
          }
        },
        themeTrigger: {
          selector: ".js-themeTrigger",
          event: "click",
          params: {
            ss: "33"
          }
        }
      },
      bind: function(selector, event, callback, params) {
        $(selector).on(event, params, callback)
      },
      initSettings: function(e) {
        ...
      },
      settingTrigger: function(e) {
        ...
      },
      themeTrigger: function(e) {
        ...
      }
    }

And in document.ready I run the events.init() function. All events in the events.events object takes and bind them using the jQuery method on.


texts: Class CatalogWalker can walk thru a list of catalogs, calculate and report some statistics

texts:
Just for review and may be useful for somebody

from os import walk
from time import time

from abc import ABCMeta, abstractmethod

class Reporter(object):
    __metaclass__=ABCMeta

    @abstractmethod
    def report(self, catalogs_cntr, files_ctnr, speed):
        """ output catalogs_cntr, files_ctnr, speed to somewhere """
        #pass

class ConsoleIndicator(Reporter):
    def __init__(self, out_splitter):
        self.__out_splitter=out_splitter

    def report(self, catalogs_cntr, files_ctnr, speed):
        if self.__out_splitter and self.__out_splitter.pipes:
            _result = "\rcataloges:" + repr(catalogs_cntr).rjust(8)
            _result += "\tfiles:" + repr(files_ctnr).rjust(13)
            _result += "\tspeed: %12.3f"%speed + " files/s"

            self.__out_splitter.write(_result)
            self.__out_splitter.flush()

class CatalogsWalker(object):
    """ """

    def __init__(self, catalogs, reporter=None):
        """ """

        self.__files_cntr, self.__catalogs_cntr, self.__start_time, self.__speed = 0, 0, 0, 0
        self.__reporter = reporter
        self.__catalogs = catalogs if hasattr(catalogs, "__iter__") else [catalogs]

    def __iter__(self):
        self.__files_cntr, self.__catalogs_cntr, self.__start_time, self.__speed = 0, 0, 0, 0
        self.__start_time=time()
        for catalog in self.__catalogs:
            for p,d,ns in walk(catalog):
                _ = d;
                self.__catalogs_cntr+=1
                for n in ns:
                    self.__files_cntr+=1
                    self.__speed=self.__files_cntr/(time()-self.__start_time)
                    if self.__reporter:
                        self.__reporter.report(self.__catalogs_cntr, self.__files_cntr, self.__speed)
                    yield p,n

    @property
    def reporter(self):
        return self.__reporter

    @property
    def catalog_counter(self):
        return self.__catalogs_cntr

    @property
    def file_counter(self):
        return self.__files_cntr

    @property
    def start_time(self):
        return self.__start_time

    @property
    def speed(self):
        return self.__speed


texts:
I wrote a Twitter scraper using the tweepy so I can scrape user information and tweets. Given that the free API doesn't let me get the number of messages per tweet, I had to rely on BeautifulSoup to do so.

class TweetAPI():

    def __init__(self, k1,k2,k3,k4):
        self.key = k1
        self.secret_key = k2
        self.token = k3
        self.secret_token = k4

        auth = tweepy.OAuthHandler(self.key, self.secret_key)
        auth.set_access_token(self.token, self.secret_token)

        api = tweepy.API(auth, wait_on_rate_limit=True)
        self.api = api

    def tweet_getter(self, user_id, n):
        api = self.api
        tweets = []
        try:
            for tweet in tweepy.Cursor(self.api.user_timeline, id = user_id).items(n):
                url = "https://twitter.com/{}/status/{}".format(user_id, tweet.id_str)
                page = requests.get(url)
                page = BeautifulSoup(page.content, 'html.parser')
                message_count = int(page.find('span',{"class":"ProfileTweet-actionCount"}).text.strip().split()[0])
                temp = [user_id, tweet.created_at, tweet.id_str,
                        tweet.favorite_count, tweet.retweet_count, message_count, tweet.text]
                tweets.append(temp)
            return tweets
        except:
            print("Unable to get user @{} tweets".format(user_id))
            pass

I'm worried about two things:

Does the wait_on_rate_limit=True really prevent the over doing request in terms of limits?
Should I add an artificial delayer to the in the BeautifulSoup part in order to avoid getting blocked off from the page content of the Twitter website?


texts:
I have an interactor/usecase class in my application. My application follows MVVM architecture with interactor/usecases responsible for logic (e.g. get data from api-service, store in local-database etc).

Now I am trying to write unit tests for my interactor classes.

Here is one on those classes:

public class ChangeUserPasswordInteractor {

    private final FirebaseAuthRepositoryType firebaseAuthRepositoryType;

    public ChangeUserPasswordInteractor(FirebaseAuthRepositoryType firebaseAuthRepositoryType) {
        this.firebaseAuthRepositoryType = firebaseAuthRepositoryType;
    }

    public Completable changeUserPassword(String newPassword){
        return firebaseAuthRepositoryType.getCurrentUser()
                .flatMapCompletable(firebaseUser -> {
                        firebaseAuthRepositoryType.changeUserPassword(firebaseUser, newPassword);
                        return Completable.complete();
                })
                .observeOn(AndroidSchedulers.mainThread());
    }
}

This class changes the password for a Firebase user.

Now here is a test class I wrote:

@RunWith(JUnit4.class)
public class ChangeUserPasswordInteractorTest {

    @Mock
    FirebaseAuthRepositoryType firebaseAuthRepositoryType;
    @Mock
    FirebaseUser firebaseUser;

    @InjectMocks
    ChangeUserPasswordInteractor changeUserPasswordInteractor;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        RxAndroidPlugins.reset();
        RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerCallable -> Schedulers.trampoline());
    }

    @Test
    public void changeUserPassword() {
        Mockito.when(firebaseAuthRepositoryType.getCurrentUser()).thenReturn(Observable.just(firebaseUser));
        Mockito.when(firebaseAuthRepositoryType.changeUserPassword(firebaseUser, "test123")).thenReturn(Completable.complete());
        changeUserPasswordInteractor.changeUserPassword("test123")
                .observeOn(Schedulers.trampoline())
                .test()
                .assertSubscribed()
                .assertNoErrors()
                .assertComplete();
    }
}

I would like some criticism and suggestions on these tests. Is this a good way to test my interactor method?


texts: Oracle trigger to keep a copy of deleted records in another table

texts:
I am using this trigger to keep a copy of the deleted record from table Orders_Details in table Orders_Details_Deleted.

I am using this trigger for two reasons:

security, in case the record is accidentally deleted
to keep a history of deleted records by the user

Is there any better way?

CREATE OR REPLACE TRIGGER TRG_Record_Deleted
   BEFORE DELETE
   ON Orders_Details
   FOR EACH ROW
BEGIN
   INSERT INTO Orders_Details_Deleted
      SELECT *
        FROM Orders_Details
       WHERE Orders_Details.Order_ID = Orders_Details.Order_ID;
END;


texts: Babel code in React component to display tasks

texts:
I'm trying to think of ways to clean up this component in my app so it looks more readable to other devs. This is the best I came up with so far. It's not that bad, but I think it could be a lot better. What do you guys think? How would you clean this code up to make it more readable?

const DisplayTasks = ({ tasksArray, removeTask, crossOutTask }) => {
  return (

        {tasksArray.map((task, index) => (

 crossOutTask(index) } key={index} >

            { task.crossedOut
              ? {task.title}
              : task.title }

            <button id="removeButton" onClick={ event => removeTask(event, index) } >
              Remove
            </button>

        ))}

  );
};
```


texts:
I have a Web API 2 using Dapper.net, and it's accessed by various client with their own database. Currently, I'm using custom header called Client-Id to identify the client.

This Client-Id contains a ConnectionString name and I passed this connection string into my constructor.

Here's my project structure:

Api.Persentation -> Api.Service -> Api.Logic

The connection string will pass from Api.Persentation to Api.Logic as follows:

Api.Persentation

public string testApi()
{
//using the service
//consider the connection string was handled on base class
var _myService = new testApiService(base.ConnectionString);

return _myService.HelloWorld();
}

Api.Service

public class testApiService: BaseService
{
    #region const
    //This class was from API.Logic
    private readonly testApiRepo _testApiRepo;

    //the connectionString passed into base class to use a log repo
    public testApiService(string connectionString)
        : base(connectionString)
    {
        this._testApiRepo = new testApiRepo(connectionString);
    }
    #endregion

    public string HelloWorld()
    {
        //access API.Logic
        return this._testApiRepo.GetHelloWorld();
    }
}

Api.Logic

It has two classes, where BaseConnection is an abstract class to open the connection (the class how I use ConnectionString). The second one is, testApiRepo showing how I use the connection to get a database value.

/*-------------
BaseConnection Class
-------------*/
    public abstract class BaseConnection
    {
        private string _connectionString;
        public BaseConnection(string ConnectionString)
        {
            this._connectionString = ConnectionString;
        }

        public MyDbConnection GetOpenConnection(bool mars = false)
        {
            string cs = this._connectionString;
            if (mars)
            {
                SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(cs);
                scsb.MultipleActiveResultSets = true;
                cs = scsb.ConnectionString;
            }

            //Finally we use the connection string in here
            var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[this._connectionString].ToString());
            MyDbConnection DbConnection = new MyDbConnection(connection);
            DbConnection.Open();
            return DbConnection;
        }
    }

/*-------------
testApiRepo Class
-------------*/
    public class testApiRepo : BaseConnection
    {
        #region Const
        //the connection will handled on base class
        public CommissionRepo(string connectionString)
            : base(connectionString)
        {
        }
        #endregion

        public string GetHelloWorld()
        {
        //using base class to open connection
        using (var _db = base.GetOpenConnection())
        {
            string query = "SELECT 'HelloWorld'";
            var result = _db.Query<string>(query);
            return result.FirstOrDefault();
        }
    }
}


texts: Application of higher-order function in Python

texts:
If \$f\$ is a numerical function and \$n\$ is a positive integer, then
  we can form the \$n\$th repeated application of \$f\$, which is
  defined to be the function whose value at \$x\$ is
  \$f(f(...(f(x))...))\$. For example, if \$f\$ adds 1 to its argument,
  then the \$n\$th repeated application of \$f\$ adds \$n\$. Write a
  function that takes as inputs a function \$f\$ and a positive integer
  \$n\$ and returns the function that computes the \$n\$th repeated
  application of \$f\$:

def repeated(f, n):
    """Return the function that computes the nth application of f.

    f -- a function that takes one argument
    n -- a positive integer

    >>> repeated(square, 2)(5)
    625
    >>> repeated(square, 4)(5)
    152587890625
    """
    "*** YOUR CODE HERE ***"

Below is the solution:

from operator import mul

def repeated(f, n):
    """Return the function that computes the nth application of f.

    f -- a function that takes one argument
    n -- a positve integer

    >>> repeated(square, 2)(5)
    625
    >>> repeated(square, 4)(5)
    152587890625
    """
    def g(x):
        i = 1
        while i <= n:
            x, i = f(x), i + 1
        return x
    return g

def square(x):
    return mul(x, x)

print(repeated(square,4)(2))

I've tested it and it looks fine.

Can I optimise this code better? Do you think I can use better names instead of i & g?


texts: Can MD5ing all the files in a table cause a memory leak?

texts:
I'm running this code with the FastMD5 library. Could it lead to memory leaks, or does it seem OK?

File[] directory = new File("/PATH/TO/FOLDER/WITH/LOTS/OF/FILES").listFiles();

    for(int i = 0; i < directory.length;i++){

    System.out.println(MD5.asHex(MD5.getHash(directory[i])));

    }


texts: Efficient communication across multiple processors for finite elements

texts:
I am implementing finite element code using MPI. Obviously, when using MPI I will have to include communication between different nodes so that all processors have all relevant information. As this is my first time doing something like this, I have implemented a very naive algorithm to get updated volume information for each element as shown below:

!loop over all of the processors
do n=0,numProcs-1
    !for each iteration of the loop, one processor will hand out relevant information
    if( my_id .eq. n ) then
        do i=0,numProcs-1
            if( i .ne. my_id ) then
                currProc=i
                !get the number of volumes processor i needs from processor n
                call MPI_RECV( numNeeded,1,MPI_INTEGER,i,my_id, &
                               MPI_COMM_WORLD,status,ierr )

                !for each volume that processor i needs:
                do j=1,numNeeded
                    !get the element number
                    call MPI_RECV( currNeeded,1,MPI_INTEGER,i,j, &
                                   MPI_COMM_WORLD,status,ierr )
                    !return the volume of that element
                    call MPI_SEND( myElements(elementGlobalToLocal(currNeeded))%xsj,1, &
                                   MPI_REAL8,i,j,MPI_COMM_WORLD,status,ierr )
                enddo
            endif
        enddo
    else
        !tell processor n how many volumes are needed from it, calculated elsewhere
        call MPI_SEND( numElementsNeeded(n+1),1,MPI_INTEGER,n,n, &
                       MPI_COMM_WORLD,status,ierr )

        !for each volume needed
        do j=1,numElementsNeeded(n+1)
            !send the element number, calculated elsewhere
            call MPI_SEND( elementsNeeded(n+1, j),1,MPI_INTEGER,n,j, &
                           MPI_COMM_WORLD,status,ierr )
            !receive the appropriate volume
            call MPI_RECV( myExternalXsj(currReceived),1,MPI_REAL8,n,j, &
                           MPI_COMM_WORLD,status,ierr )
            !global element numbering is 1-numTotElems
            !local numbering is 1-numElemsPerProc
            !elementGlobalToLocal keeps track of conversion from local to global
            elementGlobalToLocal(elementsNeeded(n+1, j))=currReceived
            currReceived=currReceived+1
        enddo
    endif
enddo

While this code does give the right results (i.e., all of the processors have all the information they need, and the values passed are the correct values), the performance is abysmal. Even when using -np 2, roughly 50% of the total time spent on volume calculations is spent doing this communication; when using -np 8 that comes up to a startling 94%. The major issue I see with the code above is that it doesn't scale very well; when process 0 is communicating to process 1, processes 2 and 3 are just hanging, which will cause a significant slowdown.

What would be a good way to address this? Also, are there any other major issues with the code that I am not seeing?


texts: Get count of unread messages from google firestore

texts:
I am creating an app (with react native) on where messages can be viewed. On the home screen you can see a badge with the unread/new messages. It shows the badge (after a short delay, you will see this in the code).

Although it works, I think there is room for improvement, so I hope one of you can take a look at the code and see where the improvements/performance increase can be made.

This is the code I have so far:

export default class Home extends React.Component {
    constructor(props) {
        super(props)
        this.announce = firebase.firestore().collection('announcements');
        this.state = {
            newAnnouncements: 0,
        }
    }
    componentDidMount() {
        let userId;
        let countHasRead;
        let countAnnounce;
        firebase.auth().onAuthStateChanged((user) => {
            if (user) {
                userId = user.uid
            }
        });
        setTimeout(() => {
            this.announce
                .get()
                .then(snapshot => {
                    countAnnounce = snapshot.size;
                });
            this.announce
                .where('hasread.userId', '==', userId)
                .get()
                .then(snapshot => {
                    countHasRead = snapshot.size;
                })
                .catch(err => {
                    console.log('Error getting documents', err);
                });
            setTimeout(() => {
                this.setState({newAnnouncements: countAnnounce - countHasRead});
            }, 1000);
        }, 500);
    }
}

I then use this.state.newAnnouncements in the badge.


texts:
I was trying to solve the final puzzle at the end of the classes chapter (Chapter 8) in "Python Programming for the Absolute Beginner" which is stated as:

  Create a Critter Farm program by instantiating several Critter objects and keeping track of them through a list. Mimic the Critter Caretaker program, but instead of requiring the user to look after a single critter, require them to care for an entire farm. Each menu choice should allow the user to perform some action for all the critters (feed all the critters, play with all of the critters, or listen to all of the critters). To make the program interesting, give each critter random starting hunger and boredom levels.

Here is my solution:

from random import randrange

class Critter(object):
    def __init__(self, name):
        self.__name = name
        self.__hunger = randrange(7)
        self.__boredom = randrange(7)

    def __str__(self):
        return "Hi, I'm " + self.__name + " and I feel " + self.mood + "."

    def talk(self):
        print(self)
        self.__passTime()

    def eat(self):
        self.__hunger -= 3
        if self.__hunger < 0:
            self.__hunger = 0
        self.__passTime()

    def play(self):
        self.__boredom -= 3
        if self.__boredom < 0:
            self.__boredom = 0
        self.__passTime()

    def __passTime(self):
        self.__hunger += 1
        self.__boredom += 1

    @property
    def mood(self):
        happiness = self.__hunger + self.__boredom
        if happiness < 5:
            return "happy"
        elif happiness < 10:
            return "ok"
        else:
            return "sad"

class CritterFarm(object):
    def __init__(self):
        self.__critters = []

    def talk(self):
        for critter in self.__critters:
            critter.talk()

    def add(self, name):
        self.__critters.append(Critter(name))

    def eat(self):
        for critter in self.__critters:
            critter.eat()

    def play(self):
        for critter in self.__critters:
            critter.play()

def main():
    farm = CritterFarm()
    option = ""
    while option != "0":
        choice = input("""
        0 - Quit
        1 - Add a Critter to your Farm
        2 - Listen to your Critters
        3 - Feed your Critters
        4 - Play with your Critters

        Choice: """)

        if choice == "0":
            print("Exiting...")
        elif choice == "1":
            name = input("Enter your new Critter's name: ")
            farm.add(name)
        elif choice == "2":
            farm.talk()
        elif choice == "3":
            farm.eat()
        elif choice == "4":
            farm.play()

if __name__ == "__main__":
    main()

Can anyone offer a code review? Thanks.


texts: Navigation bar React component, with a "back" and a "close" variant

texts:
I am working on a component for a navigation bar. This navigation bar currently has two variations: a "back" version, and a "close" version.

I have come up with three different implementations but I am uncertain of which one is the best. Currently, I am leaning towards this implementation as it reads the best in my opinion.

const NAVIGATION_BAR_TYPE = {
  back: "back",
  close: "close",
}

const NavigationBar = ({ type = NAVIGATION_BAR_TYPE.back, text, linkTo }) => {
  return (
    <div className={`navigation-button ${type}`}>
      <Link to={linkTo}>{text}</Link>

  )
}

NavigationBar.Close = (props) => (
  <NavigationBar { ...props } type={NAVIGATION_BAR_TYPE.close} />
)

NavigationBar.Back = (props) => (
  <NavigationBar { ...props } type={NAVIGATION_BAR_TYPE.back} />
)

// Usage: <NavigationBar.Close linkTo="/" />

This is similar to the first one, but you need to import the object that holds the navigation bar types:

const NAVIGATION_BAR_TYPE = {
  back: "back",
  close: "close",
}

const NavigationBar = ({ type = NAVIGATION_BAR_TYPE.back, text, linkTo }) => {
  return (
    <div className={`navigation-button ${type}`}>
      <Link to={linkTo}>{text}</Link>

  )
}

// Usage: <NavigationBar type={NAVIGATION_BAR_TYPE.back} linkTo="/" />

Or this one, leveraging props:

const NavigationBar = ({ back, close, text, linkTo }) => {
  const navigationType = back ? 'back' : 'close'

  return (
    <div className={`navigation-button ${navigationType}`}>
      <Link to={linkTo}>{text}</Link>

  )
}

// Usage: <NavigationBar back linkTo="/" />

I don't like the third solution because if I need to add more variations, I feel like it clutters the props. And I don't like the second solution because then you are importing this enum-like object to define the type.


texts:
I'm trying to incorporate the advice found in https://docs.python.org/3.5/library/heapq.html in order to make a priority queue implementation (see corresponding section) in a class priorityQ. Not going to reinvent the wheel so i use the the python's heapq implementation

class priorityQ():
    import heapq
    import itertools

    def __init__(self,mylist):

        self._entry_finder = {}               # mapping of tasks to entries
        self._counter = itertools.count()     # unique sequence count
        self.REMOVED = '<removed-task>'      # placeholder for a removed task

        if mylist:
            self.data = []
            for element in mylist:
                priority, count, task = element[0], next(self._counter), element[1]
                entry = [priority,count,task]
                self._entry_finder[task] = entry
                heapq.heappush(self.data,entry)
        else:
            self.data = []

    def add_task(self,task,priority):
        if task in self._entry_finder:
            self.remove_task(task)
        count = next(self._counter)
        entry = [priority,count,task]
        self._entry_finder[task] = entry
        heapq.heappush(self.data, entry)

    def remove_task(self,task):
        'Mark an existing task as REMOVED.  Raise KeyError if not found.'
        entry = self._entry_finder.pop(task)
        entry[-1] = self.REMOVED

    def pop_task(self):
        while self.data:
            priority, count, task = heapq.heappop(self.data)
            if task is not self.REMOVED:
                del self._entry_finder[task]
                return task
        raise KeyError('pop from an empty priority queue')

The code as it is seems to solve the implementation challenges listed in 8.5.2 in the link I gave. I just wonder if this is a clean implementation of such a candidate class. Is it better to just implement with the procedural style suggested in the manual and incorporate it in whatever project i'm working on or is it a better practice to make use of a class like the above (or a more refined version of that).

PS: I know it's slightly off-topic for this stack exchange site, but i wonder if there is a way around the side effect of having a bunch of deleted-entries residing in the queue after doing a set of priority updates in existing tasks. (Something different than copying/cleaning the entire queue every fixed period of time)


texts: Using EF 6.1 for updating objects and their children

texts:
I have an application that allows a user to create a poll that includes questions and answer choices as part of the poll. The hierarchy is a poll has one or more questions, a question has one or more answers, and each answer has a vote.

The following code is my implementation that allows the updating of an existing poll. The update allows for properties of the poll to be updated, including the addition or removal of children.

The implementation works, but it feels like there is a better way to achieve the functionality. As you will see from my code, I'm creating a context object each time I want to add or update any of the objects.

 public string Update(Poll poll)
    {
        try
        {
            if (poll == null)
                return null;

            using (var context = new PollContext())
            {
                context.Entry(poll).State = poll.PollId == Guid.Empty ? EntityState.Added : EntityState.Modified;
                context.Polls.AddOrUpdate(poll);
                context.SaveChanges();
            }

            //update the questions
            using (var context = new PollContext())
            {
                foreach (var question in poll.Questions)
                {
                    context.Entry(question).State =
                        question.QuestionId == Guid.Empty ? EntityState.Added : EntityState.Modified;
                    context.Questions.AddOrUpdate(question);
                }

                context.SaveChanges();
            }

            //update the answers
            using (var context = new PollContext())
            {
                foreach (var answers in poll.Questions.Select(question => question.Answers).ToList())
                {
                    var questionId = answers.ElementAt(0).QuestionId;
                    var originalAnswerList = GetOriginalAnswerList(questionId);

                    using (var context2 = new PollContext())
                    {
                        foreach (var originalAnswer in originalAnswerList)
                        {
                            if (answers.All(a => a.AnswerId != originalAnswer.AnswerId))
                            {
                                Delete(originalAnswer);
                                Delete(originalAnswer.Votes);
                            }
                        }
                    }

                    foreach (var answer in answers)
                    {
                        context.Entry(answer).State =
                            answer.AnswerId == Guid.Empty ? EntityState.Added : EntityState.Modified;
                        context.Answers.AddOrUpdate(answer);

                        context.Votes.AddOrUpdate(answer.Votes);
                    }
                }

                context.SaveChanges();
            }

            return "Poll updated";
        }
        catch (NullReferenceException ex)
        {
            throw new NullReferenceException("A null exception occurred in updating poll.\r\n" + ex.InnerException);
        }
        catch (Exception ex)
        {
            throw new Exception("An exception occurred in the updating poll.\r\n" + ex.InnerException);
        }

    }


texts: Print max occurring character in a String

texts:
This prints the character that occurs the most in a given string.

Input: String of word(s)

Output: Max occurring character

public class mostOccurringCharacter {
public static  Character findMaxOChar(String text){
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    Character maxChar = ' ';
    long max = Integer.MIN_VALUE;
    for(int i=0;i<text.length();i++){
        Character current = text.charAt(i);
        if(map.containsKey(current)){
            map.put(current,map.get(current)+1);
        }
        else{
            map.put(current,1);
        }
        if(map.get(current)>max){
            maxChar = current;
            max = map.get(current);
        }
    }
    return maxChar;
}

public static void main(String args[]){
    String text = "wfaveqr caaaaaaaaaaaafwefwgqrvwerwbhqfvwrfwvbetqfwef q fwgwfw erfq";
    System.out.println("The max character is : "+ findMaxOChar(text));
}
}


texts:
I tried my hands on Rock-Paper-Scissors. But the twist is that the game has a brain that aims to learns your behaviour.

The brain is a simple counter that updates the player's current choice based on players previous choices. The level determines the number of previous choices cpu will remember. In any event the player tracks its own inputs and makes calculated choices to defeat the CPU, I have added a timed input function i.e. if you don't provide input within 5 secs, you lose.

The game works perfectly, however I am unhappy with the main function. There are too many try-except blocks. My questions are

What are possible improvements ?
How do I improve the print_cpu_data function in the way it shows the information ?
If I wish to make a GUI for the game (e.g tkinter, Pygame, etc), what part of the code should be made into functions and how to do so efficiently ?

As I am not a beginner (somewhat less than intermediate) , I appreciate some advanced ideas and concepts.

"""
Rock-Paper-Scissor with CPU
"""
from itertools import product
import select
import sys

SCORE_TABLE = [[1, 0, 2],
               [2, 1, 0],
               [0, 2, 1]]
SCORE_STR = ['LOSE', 'DRAW', 'WIN']
ROCK = 0
PAPER = 1
SCISSOR = 2
CHOICE_STR = ['ROCK', 'PAPER', 'SCISSOR']
WIN_MOVE = [PAPER, SCISSOR, ROCK]

class GameCpu:
    """Class to create game CPU"""
    def __init__(self, level=1):
        self.level = level
        self.probs = {}
        for t in product([ROCK, PAPER, SCISSOR], repeat=level):
            self.probs[t] = [0, 0, 0]
        self.prev = [0]*level

    def get_cpu_choice(self):
        """Return CPU choice"""
        tmp = self.probs[tuple(self.prev)]
        pred = tmp.index(max(tmp))
        return WIN_MOVE[pred]

    def train_cpu(self, choice_player):
        """Train CPU with current player choice"""
        self.probs[tuple(self.prev)][choice_player] += 1
        self.prev.pop(0)
        self.prev.append(choice_player)

    def print_cpu_data(self):
        """Print CPU data"""
        print('\nPattern', '\t'*self.level, 'Choice count\n')
        for key, val in self.probs.items():
            print(*[f'{CHOICE_STR[k]}' for k in key], sep=', ', end='\t\t')
            print(*[f'{CHOICE_STR[i]}:{v}' for i, v in enumerate(val)])

def input_with_timeout(prompt, timeout):
    """Timed input"""
    sys.stdout.write(prompt)
    sys.stdout.flush()
    ready, _, _ = select.select([sys.stdin], [], [], timeout)
    if ready:
        return sys.stdin.readline().rstrip('\n')
    raise Exception

def main():
    """main function"""
    while True:
        try:
            level = int(input('Enter CPU level (Level 1,2,3): '))
            assert 1 <= level <= 3
            break
        except:
            print('Invalid.')

    print('\nPress Q to quit game\
        \nRemember you have got only 5secs to give input.\
        \nThe choices are ROCK:1  PAPER:2  SCISSOR:3\n')

    cpu = GameCpu(level)
    scores = [0, 0, 0]
    timeout = 5
    while True:
        choice_player = None
        try:
            choice_player = input_with_timeout('Enter choice: ', timeout)
        except:
            print('Times up')

        if not choice_player:
            break
        if choice_player.lower() == 'q':
            break
        try:
            choice_player = int(choice_player)-1
            assert 0 <= choice_player <= 2
        except:
            print('Invalid. ', end='\n')
            continue

        choice_cpu = cpu.get_cpu_choice()
        s = SCORE_TABLE[choice_player][choice_cpu]
        scores[s] += 1
        print(f'{SCORE_STR[s]}')

        cpu.train_cpu(choice_player)

    total = max(1, sum(scores))
    percent = [100*s/total for s in scores]

    print('\nSTATS: \n')
    print(f'Total games played: {total}')
    print(*[f'{SCORE_STR[i]}:{p:.2f}% ' for i, p in enumerate(percent)])
    cpu.print_cpu_data()

if __name__ == '__main__':
    main()


texts: Service Layer, using Entity Framework 6.2

texts:
I would like you to review a part of my warehouse application, a Service Layer to be exact. The architecture of the program is:

DB --> .Data (EF's DbContext/Entities) --> .ServiceLayer (Business) --> WCF services

I have Repo/UoW patterns implemented in Data (EF's DbConext has it built in). Basically nothing more. Raw DbSets and Entities. The whole magic is being done in Business layer obviously.

In Business layer I have implemented a bunch of Services, like PurchaseOrderService or ReceivingService. The thing is those services can be used by WCF Service directly AND by Business themselves. For example GetItemStatus can be used by WCF Service with the same name "GetItmeStatus" OR it can be used by GetItemQuantity service (because if the Item is Blocked, the Qty is 0). Let me post the code:

public class ItemService
{
    IContextFactory ContextFactory { get; set; }

    public ItemService(IContextFactory contextFactory)
    {
        ContextFactory = contextFactory;
    }

    public ItemStatus GetItemStatus(int itemId, WarehouseContext warehouseContext = null)
    {
        ItemStatus returnedItemStatus = ItemStatus.New;

        //DBContext should be disposed only if it was created here, locally
        bool shouldBeDisposed = (warehouseContext == null);
        if (shouldBeDisposed) warehouseContext = ContextFactory.CreateWarehouseContext();

        try
        {
            returnedItemStatus = warehouseContext.Items.Where(p => p.ItemId == itemId).Status;
        }
        finally
        {
            if (shouldBeDisposed) warehouseContext?.Dispose();
        }

        return returnedItemStatus;
    }

    public int GetItemQuantity(int itemId, WarehouseContext warehouseContext = null)
    {
        int returnedQuantity = 0;

        //DBContext should be disposed only if it was created here, locally
        bool shouldBeDisposed = (warehouseContext == null);
        if (shouldBeDisposed) warehouseContext = ContextFactory.CreateWarehouseContext();

        try
        {
            if (GetItemStatus(itemId, warehouseContext) != ItemStatus.Blocked)
            {
                returnedQuantity = warehouseContext.Items.Where(p => p.ItemId == itemId).Quantity;
            }
        }
        finally
        {
            if (shouldBeDisposed) warehouseContext?.Dispose();
        }

        return returnedQuantity;
    }
}

Of course, this example shows two methods from the same service. It's possible that one service will create another service and calls its function.

I would like you, to review the way I handle optional Context parameter, try finally block instead of pretty using block. This way, I don't have to create DbContext during every trip to the database. I can create a DbContext per Context. When I must get ItemStatus (ItemStatus only) from the WCF (or any other client) layer.. I can do it! and the DbContext will be created and disposed.

How do you like it? Thanks!


texts:
I came across the following challenge. Here is my implementation in Python 3.7

  A room has 100 chairs numbered from 1-100. On the first round of the game the FIRST individual is eliminated. On the second round, the THIRD individual is eliminated. On every successive round the number of people skipped increases by one (0, 1, 2, 3, 4...). So after the third person, the next person asked to leave is the sixth (skip 2 people - i.e: 4 and 5).

  This game continues until only 1 person remains.

  Which chair is left by the end?

I actually don't know what the true answer is, but my code outputs 31.

I think this is the fastest solution and at worst has an O(N^2) time complexity

n = 100
skip = 0
players = [x for x in range (1, n+1)]
pointer = 0
while len(players) > 1:
    pointer += skip
    while pointer >= len(players):
        pointer = pointer - len(players)
    players.pop(pointer)
    skip += 1
print(players[0])


texts:
In our embedded application, we have to replace ::operator new and ::operator delete to call a special malloc(), to ensure that the memory is allocated correctly. The code, written with this guide in mind, looks like this:

#include <new>
#include <stdexcept>

// Regular scalar new
void* operator new(std::size_t n) throw(std::bad_alloc)
{
    using namespace std;

    for (;;) {
        void* allocated_memory = ::operator new(n, nothrow);
        if (allocated_memory != 0) return allocated_memory;

        // Store the global new handler
        new_handler global_handler = set_new_handler(0);
        set_new_handler(global_handler);

        if (global_handler) {
            global_handler();
        } else {
            throw bad_alloc();
        }
    }
}

// Nothrow scalar new
void* operator new(size_t n, std::nothrow_t const&) throw()
{
    if (n == 0) n = 1;

    return malloc(n);
}

// Regular array new
void* operator new[](size_t n) throw(std::bad_alloc)
{
    return ::operator new(n);
}

// Nothrow array new
void* operator new[](size_t n, std::nothrow_t const&) throw()
{
    return ::operator new(n, std::nothrow);
}

// Regular scalar delete
void operator delete(void* p) throw()
{
    free(p);
}

// Nothrow scalar delete
void operator delete(void* p, std::nothrow_t const&) throw()
{
    ::operator delete(p);
}

// Regular array delete
void operator delete[](void* p) throw()
{
    ::operator delete(p);
}

// Nothrow array delete
void operator delete[](void* p, std::nothrow_t const&) throw()
{
    ::operator delete(p);
}

// Driver function to make the sample code executable.
int main()
{
    int* x = new int;
    delete x;

    int* y = new int[10];
    delete[] y;
}

Is this code correct?

In particular:

Do I need any special alignment handling?
Should there be any other differences between operator new and operator new[]?


texts:
Created this little config class, any room for improvements? Think I have done an alright job but would like to know if any improovements could be made?

<?php
defined("SECURE") or exit('Please define SECURE keyword to continue.');
class config
{
    private $configValues;
    private $configFile;

    public function __construct()
    {
        $configValues = array();
    }

    public function loadConfiguration($configFile = "C:\Users\ashle\Miracle\config\config.ini")
    {
        if (!file_exists($configFile))
            loadDefault();

        $content = file($configFile);
        foreach ($content as $line)
            $this->setConfig(explode("=", $line)[0], explode("=", $line)[1]);
    }

    private function loadDefault()
    {
        /* DEFAULT CONFIG SETTINGS!!
           THIS SHOULD NOT BE THE CASE... */

        setConfig("database.host", "localhost");
        setConfig("database.username", "root");
        setConfig("database.password", "");
        setConfig("database.title", "mydb");
        setConfig("database.port", "3306");
    }

    private function setConfig($name, $value)
    {
        $this->configVlaues[$name] = $value;
    }

    public function getConfig($name)
    {
        return $this->configValues[$name];
    }
}
?>


texts:
I have these three helper functions that I've used on some projects as a slightly better alternative to the C memset function. The objective is to simplify and clarify code, as well as add asserts where possible:

// Zero fills a POD type, such as a structure or union.
template<class T>
void ZeroStruct(T & s)
{
    std::memset(&s, 0, sizeof(T));
}

// Zero fills a statically allocated array of POD or built-in types. Array length inferred by the compiler.
template<class T, size_t N>
void ZeroArray(T (&arr)[N])
{
    std::memset(arr, 0, sizeof(T) * N);
}

// Zero fills an array of POD or built-in types, with array length provided by the caller.
template<class T>
void ZeroArray(T * arr, size_t arrayLength)
{
    assert(arr != nullptr);
    assert(arrayLength != 0);
    std::memset(arr, 0, sizeof(T) * arrayLength);
}

Usage example:

int arr[128];
ZeroArray(arr);

struct S {
    int   x;
    float y;
};
S s;
ZeroStruct(s);

I'd like to further improve those functions with C++11/14 features. I think it would be a good idea to static_assert with std::is_pod to ensure they are never called on a class instance. Do you agree?

Also, should I make them noexept?

Any other recommendations?


texts:
Let's keep this simple.

Input:

- abc
- def
- ghi

Desired output (whitespace optional):

abc

def

ghi

Current code:

$output = preg_replace_callback(
    "((^- (.*)$\r*\n*)+)m",
    function($m) {
        return "

".
            implode(
                "

",
                preg_split(
                    "(^- )m",
                    substr($m[0],2)
                )
            ).
            "

";
    },
    $input
);

It works, the output is exactly what I want, but it seems kinda... hackish. Having a preg_split inside a preg_replace_callback seems a bit redundant, but I can't seem to find a way of capturing subpatterns that are inside a quantifier. If I could do that then I would implode the subpatterns rather than having to split the matched part again.

Any suggestions?


texts: Reading set of large log files line by line and count how many hostnames appear on each line

texts:
I have around 300 log files in a directory and each log file contains around 3300000 lines. I need to read through each file line by line and count how many hostnames that appear on each line. I wrote basic code for that task, but it takes more than 1 hour to run and takes lots of memory as well. How can I improve this code to make it run faster?

import pandas as pd
import gzip

directory=os.fsdecode("/home/scratch/mdsadmin/publisher_report/2018-07-25")#folder with 300 log files
listi=os.listdir(directory)#converting the logfiles into a list

for file in listi:#taking eaching log file in the list
    tt=os.path.join(directory,file)# joining log file name along with the directory path
    with gzip.open(tt,'rt') as f: #unzipping the log file
        rows=[]#clearing the list after every loop
        for line in f: #reading each line in the file
            s=len(line.split('|'))
            a=line.split('|')[s-3]
            b=a.split('/')[0] #slicing just the hostname out of each line in the log file
            if len(b.split('.'))==None:
                ''
            else:
                b=b.split('.')[0]
            rows.append(b) # appending it to a list

    df_temp= pd.DataFrame(columns=['hostname'],data=rows) #append list to the dataframe after every file is read
    df_final=df_final.append(df_temp,ignore_index=True) #appending above dataframe to a new one to avoid overwriting
    del df_temp #deleting temp dataframe to clear memory
df_final=df_final.groupby(["hostname"]).size().reset_index(name="Topic_Count") #doing the count

Sample log lines

tx:2018-05-05T20:44:37:626 BST|rx:2018-05-05T20:44:37:626 BST|dt:0|**wokpa22**.sx.sx.com/16604/#001b0001|244/5664|2344|455
tx:2018-05-05T20:44:37:626 BST|rx:2018-05-05T20:44:37:626 BST|dt:0|**wokdd333**.sc.sc.com/16604/#001b0001|7632663/2344|342344|23244

Desired output


texts: Trigger Updating another table - Baseball Database

texts:
This is my first time writing T-SQL so I'd like to get some criticism on how I wrote this trigger.

I'm building a Pitch-Tracking App that will use a relational database to track Pitches, At-Bats, Games, etc. Everything starts with tracking the individual Pitch in an individual AB, so I figured whenever tbl_PitchLog is updated, it would update that individual At Bat ID in the tbl_AtBats table. Let me know if I'm straying or if I'm on some semblance of a straight path to elegant T-SQL

CREATE TABLE [dbo].[tbl_PitchLog]
(
    [Id] BIGINT NOT NULL PRIMARY KEY IDENTITY,
    [At_Bat_ID] BIGINT NOT NULL,
    [Batter_ID] BIGINT NOT NULL,
    [Pitcher_ID] BIGINT NOT NULL,
    [Game_ID] BIGINT NOT NULL,
    [Season_ID] BIGINT NOT NULL,
    [Pitch_Type] VARCHAR(50) NULL,
    [Pitch_Speed] BIGINT NULL,
    [Pitch_X] BIGINT NULL,
    [Pitch_Y] BIGINT NULL,
    [Strike] BIT NULL,
    [Swung] BIT NULL,
    [Contact] BIT NULL,
    [Fair] BIT NULL,
    [R] BIT NULL,
    [H] BIT NULL,
    [1B] BIT NULL,
    [2B] BIT NULL,
    [3B] BIT NULL,
    [HR] BIT NULL,
    [RBI] INT NULL,
    [BB] BIT NULL,
    [SO] BIT NULL,
    [IBB] BIT NULL,
    [HBP] BIT NULL,
    [SH] BIT NULL,
    [SF] BIT NULL,
    [GIDP] BIT NULL
)

GO

CREATE TRIGGER [dbo].[Trigger_tbl_PitchLog]
    ON [dbo].[tbl_PitchLog]
    FOR DELETE, INSERT, UPDATE
    AS
    DECLARE @Strikes integer, @Balls integer
    DECLARE @Fouls integer
    DECLARE @Contact integer
    IF Strike = 1
    BEGIN
        SET @Strikes = 1;
        SET @Balls = 0;
    END
    ELSE
    BEGIN
        SET @Strikes = 0;
        SET @Balls = 1;
    END
    IF Fair = 0
    BEGIN
        SET @Fouls = 1;
    END
    ELSE
    BEGIN
        SET @Fouls = 0;
    END
    IF Contact = 0
    BEGIN
        SET @Contact = 1;
    END
    ELSE
    BEGIN
        SET @Contact = 0;
    END
    BEGIN
        SET NoCount ON
        UPDATE tbl_AtBats
        SET tbl_AtBats.PitchCount = tbl_AtBats.PitchCount + 1,
        tbl_AtBats.Strikes = tbl_AtBats.Strikes + @Strikes,
        tbl_AtBats.Balls = tbl_AtBats.Balls + @Balls,
        tbl_AtBats.Fouls = tbl_AtBats.Fouls + @Fouls,
        tbl_AtBats.Contact = tbl_AtBats.Contact + @Contact,
        tbl_AtBats.Swings = tbl_AtBats.Swings + inserted.Swung,
        tbl_AtBats.R = inserted.R,
        tbl_AtBats.H = inserted.H,
        tbl_AtBats.[1B] = inserted.[1B],
        tbl_AtBats.[2B] = inserted.[2B],
        tbl_AtBats.[3B] = inserted.[3B],
        tbl_AtBats.HR = inserted.HR,
        tbl_AtBats.RBI = inserted.RBI,
        tbl_AtBats.BB = inserted.BB,
        tbl_AtBats.SO = inserted.SO,
        tbl_AtBats.IBB = inserted.IBB,
        tbl_AtBats.HBP = inserted.HBP,
        tbl_AtBats.SH = inserted.SH,
        tbl_AtBats.SF = inserted.SF,
        tbl_AtBats.GIDP = inserted.GIDP
        WHERE tbl_AtBats.Id = inserted.At_Bat_ID;
    END


texts:
The weekly coding challenge in Eric Normand's newsletter this week involves implementing Langton's ant.

I wanted something on my screen so I put together a simple re-frame app. The core functions relating to the ant:

world.cljs

(ns ant.world)

(defn init-world [width height]
  {:width width
   :height height
   :grid (into [] (repeat height (into [] (repeat width 0))))
   :ant-pos [(quot width 2) (quot height 2)]
   :ant-dir :up
   :stopped? false})

(defn within-bounds? [[row col] width height]
  (and (>= row 0) (>= col 0)
       (< row width) (< col height)))

(defn turn-right [dir]
  (case dir
    :up :right
    :right :down
    :down :left
    :left :up))

(defn turn-left [dir]
  (case dir
    :up :left
    :left :down
    :down :right
    :right :up))

(defn move [[x y] dir]
  (case dir
    :up    [x (dec y)]
    :right [(inc x) y]
    :down  [x (inc y)]
    :left  [(dec x) y]))

(defn iter-world [{:keys [width height grid
                          ant-pos
                          ant-dir
                          stopped?]
                   :as world}]
  (if (and (not stopped?) (within-bounds? ant-pos width height))
    (let [cell-color (get-in grid ant-pos)
          is-white? (= cell-color 0)
          next-dir (if is-white? (turn-right ant-dir) (turn-left ant-dir))
          next-pos (move ant-pos next-dir)
          next-grid (assoc-in grid ant-pos (if is-white? 1 0))]
      {:width width
       :height height
       :grid next-grid
       :ant-pos next-pos
       :ant-dir next-dir
       :stopped? false})
    (assoc world :stopped? true)))

And the view:

views.cljs

(ns ant.views
  (:require
   [re-frame.core :as re-frame]
   [ant.subs :as subs]
   [ant.events :as ev]
   [cljs.pprint :refer [pprint]]
   ))

(defn main-panel []
  (let [grid (re-frame/subscribe [::subs/grid])]
    (into [:table {:style {:border "1px solid red"}}]
          (for [row @grid]
            (into [:tr]
                  (for [cell row]
                    [:td {:width "5px" :height "5px"
                          :style {:backgroundColor (if (= cell 1) "black" "white")}}]))))))

(defn dispatch-timer-event
  []
  (let [now (js/Date.)]
    (re-frame/dispatch [::ev/timer now])))  ;; <-- dispatch used

;; Call the dispatching function every second.
;; `defonce` is like `def` but it ensures only one instance is ever
;; created in the face of figwheel hot-reloading of this file.
(defonce do-timer (js/setInterval dispatch-timer-event 50))

subscriptions:

subs.cljs

(ns ant.subs
  (:require
   [re-frame.core :as re-frame]))

(re-frame/reg-sub
 ::grid
 (fn [db]
   (:grid db)))

Events:

events.cljs

(ns ant.events
  (:require
   [re-frame.core :as re-frame]
   [ant.db :as db]
   [ant.world :as aw]
   ))

(re-frame/reg-event-db
 ::initialize-db
 (fn [_ _]
   db/default-db))

(re-frame/reg-event-db
 ::timer
 (fn [db _]
   (aw/iter-world db)))

DB:

db.cljs

(ns ant.db
  (:require [ant.world :as aw]))

(def default-db
  (aw/init-world 100 100))

This works. But is quite slow. Though the timer is supposed to trigger an event every 50ms, the drawing rate is not so high.

What can I do to improve the performance here? Is it possible without resorting to mutable data structures?

(Any general code improvement suggestions are also most welcome)

Full code is here:
https://github.com/nakiya/langton-ant


texts:
The evaluate_guess function below returns the evaluation of a guess with respect to Mastermind game rules:

# sample secret code and guess
secret_code = ["a", "a", "c", "a"]
guess = ["c", "a", "a", "b"]

def evaluate_guess(secret_code, guess):
    score = []
    temp_list = secret_code.copy()

    for i in range(len(secret_code)):
        if guess[i] == temp_list[i]:
            score.append(1)
            temp_list[i] = None

        elif guess[i] in temp_list:
            score.append(0)
            temp_list[temp_list.index(guess[i])] = None

    score.sort(reverse=True)
    return score

print(evaluate_guess(secret_code, guess))

>>> [1, 0, 0]

Without changing the essence of the algorithm: Can I implement the evaluate_guess function in a more Pythonic way? Is it possible to implement the algorithm in a purely functional fashion?
Is there a more straightforward algorithm?


texts:
In Cookie Clicker there are Golden cookies, and Wrath Golden Cookies.

Golden cookies are Clickable cookies that randomly appear, and when clicked they give Bonus cookies, or temporary boosts to clicking/Cookies Per second (i.e. Cps).

The Wrath Golden cookies can still give boosts and bonuses, but they have the chance of taking cookies or giving a reverse boost to Cps.

Wrath Golden Cookies happen as an effect of pushing the Grandmas too far.

Some "power-ups" require Golden cookies to stay on the screen and not be clicked right away, so I wanted a fast way to turn off the clicker.

I came up with a way to turn on and off the Golden/Wrath switches using a single command in the console, and they give a little more information as well.

// allows me to turn on and off the clicking of the Wrath Cookies

var wrathCookieSwitchOn = false;
var cookieSwitchOn = false;

var wrathSwitch = function() {
    wrathCookieSwitchOn = !wrathCookieSwitchOn;
    console.log("WrathCookieSwitchOn is set to " + wrathCookieSwitchOn);
}

var flipCookieSwitch = function(){
    cookieSwitchOn = !cookieSwitchOn;
    if (cookieSwitchOn) {
        var SpecialCookieClicker =
            setInterval(function() {
                Game.shimmers.forEach(function(shimmer) {
                    (shimmer.type == "golden") && (shimmer.wrath == 0 || wrathCookieSwitchOn) ? shimmer.pop() : 0;
                })
            }, 500);
        console.log("Golden Cookie Clicker is on and wrathCookieSwitchOn is set to " + wrathCookieSwitchOn);
    } else {
        clearInterval(SpecialCookieClicker);
        console.log("Golden Cookie Clicker is Turned off");
    }
};
flipCookieSwitch();

I was thinking about overloading the function so that I could flip the Wrath Switch as well, but I haven't decided how I want to do that yet.

Does the code make sense to you? Is there anything I could make better or more efficient?

Link to the Game itself, it is addicting and YOU HAVE BEEN WARNED

none of the scripts that I have posted here are considered cheating by the game


texts:
Here is the piece of my controller action that takes a session[:auth] hash and then assigns the values to the ActiveRecord object represented by @user whilst the key names happen to be the same.

def new
  @user = User.new

  if session[:auth].present?
    @user.first_name = session[:auth].extra.raw_info.first_name
    @user.last_name = session[:auth].extra.raw_info.last_name
    @user.username = session[:auth].extra.raw_info.username
    @user.email = session[:auth].extra.raw_info.email
  end
end

I wonder if there's a way to eliminate the duplications in assigning the values from the hash to the object.


texts:
I have a challenge, which is to create a JavaScript function that turns a given number into the string representation. For example:

console.log(inToEnglish(15)) should print fifteen

console.log(inToEnglish(101)) should print one hundred one

and so on...

This challenge covers Non-Negative, greater than zero Integer numbers.

I have accomplished this objective with the following code:

var b4Twenty = ["one", "two", "three", "four", "five", "six", "seven", "eight",
    "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
    "seventeen", "eighteen", "nineteen"
];

var b4Hundred = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy",
    "eighty", "ninety"
];

function intToEnglish(n) {
    return translator(n).trim();
}

function translator(n) {
    if( n == 0)
        return "";
    else if (n <= 19)
        return b4Twenty[n - 1] + " ";
    else if (n <= 99)
        return b4Hundred[Math.floor(n / 10 - 2)] + " " + translator(n % 10);
    else if (n <= 199)
        return "one hundred " + translator(n % 100);
    else if (n <= 999)
        return translator(Math.floor(n / 100)) + "hundred " + translator(n % 100);
    else if (n <= 1999)
        return "one thousand " + translator(n % 1000);
    else if (n <= 999999)
        return translator(Math.floor(n / 1000)) + "thousand " + translator(n % 1000);
    else if (n <= 1999999)
        return "one million " + translator(n % 1000000);
    else if (n <= 999999999)
        return translator(Math.floor(n / 1000000)) + "million " + translator(n % 1000000);
    else if (n <= 1999999999)
        return "one billion " + translator(n % 1000000000);
    else if (n <= 999999999999)
        return translator(Math.floor(n / 1000000000)) + "billion " + translator(n % 1000000000);
    else if (n <= 1999999999999)
        return "one trillion " + translator(n % 1000000000000);
    else if(n <= 999999999999999)
        return translator(Math.floor(n / 1000000000000)) + "trillion " + translator(n % 1000000000000);
    else if (n <= 1999999999999999)
        return "one quadrillion " + translator(n % 1000000000);
    else
        return translator(Math.floor(n / 1000000000000000)) + "quadrillion " + translator(n % 1000000000000000);
}

This is my recursive function to achieve the given goal. It works, and it takes 65ms to complete the battery of 50 tests.

However, I have some concerns regarding its performance:

Given that recursive functions are usually slower than iterative ones, is there a way to make this iterative?
Should I use a switch case, or is my if statement OK?
I keep using Math.floor to round the numbers and find the indexes. Perhaps there is a better solution out there without using this technique?
I have to wrap the translator function (who does all the work) into another function because I need to trim the final result of extra spaces. Is there a way I can avoid this?

I am open to suggestions on how to improve this. Thanks!


texts:
This animation makes my fans spin up after several seconds, and it seems to have a sub-par framerate. I am trying to understand why, and optimize its performance.

Codepen

The animation function (this is the main part of the code):

function animate() {
    t++
    ctx.clearRect(0, 0, c.width, c.height);

    for (var i = 40; i < max; i+= 60) {
        var radius = Math.floor(i+Math.sin(t/10)*10)
        ctx.beginPath()
        ctx.arc(center[0], center[1], radius, 0, 2 * Math.PI, false)
        ctx.closePath()
        ctx.stroke()
    }

    requestAnimationFrame(animate)
}

The for loop draws the minimum number of circles needed in order to fill the screen. Their radius pulses in and out with a sine function based on the 't' variable.

Am I doing something wrong?


texts: Demonstrating the speed advantage of parallel computation

texts:
I am teaching a class on parallel computation and am looking for a simple example that illustrate the speed gains from using "CompletableFuture"s in Java. Currently my example problem is very simple: calculate the sum of an array. Each CompletableFuture calculates the sum of about 1/4 of the array, and when all of them finish, the main program calculates the total sum.

The line sum += Math.pow(Math.pow(Math.pow(array[i],0.3),0.4),0.5); was initially just sum += array[i]; I added all the "pow"s just to make the serial computation appear longer.

Currently, on my machine with 4 cores, when I put NUM_OF_THREADS = 1 the sum is calculated in 4 seconds, while with NUM_OF_THREADS = 4 the sum is calculated in 5.5 seconds, so this is not a good example - it does not show that parallel computation is more efficient.

what should I change in the example, to demonstrate the advantage of parallel computation?

public class ConcurrencyTest {

    static final int SIZE = 10000000;
    static final int NUM_OF_THREADS = 1;

    static int iThread;
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int[] array = new int[NUM_OF_THREADS*SIZE];
        Arrays.fill(array, 1);

        ExecutorService executor = Executors.newCachedThreadPool();
        Instant startTime = Instant.now();

        CompletableFuture<Integer>[] futures = new CompletableFuture[NUM_OF_THREADS];
        for (iThread=0; iThread<NUM_OF_THREADS; ++iThread) {
            final int iThreadLocal = iThread;
            futures[iThread] = CompletableFuture.supplyAsync( () -> {
                int sum=0;
                int start = iThreadLocal*SIZE;
                int end = (iThreadLocal+1)*SIZE;
                for (int i=start; i<end; ++i) {
                    Thread.yield();
                    sum += Math.pow(Math.pow(Math.pow(array[i],0.3),0.4),0.5);
                }
                System.out.println(iThreadLocal+": "+sum +
                        "   "+Duration.between(startTime, Instant.now()).toMillis()+" [ms]");
                return sum;
            }, executor);
        }

        CompletableFuture.allOf(futures).thenRun(
                () -> {
                    try {
                        Arrays.stream(new int[] {1,2,3}).sum();
                        int totalSum = 0;
                        for (iThread=0; iThread<NUM_OF_THREADS; ++iThread)
                            totalSum += futures[iThread].get();
                        System.out.println("Total: "+totalSum+
                                "   "+Duration.between(startTime, Instant.now()).toMillis()+" [ms]");
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                    }
                }
        );

        executor.shutdown();
    }
}


texts:
I have the following code in a portion of my program that hides/shows certain elements based on the status of a certain checkbox:

private void enableFolderVariableRemoval_CheckedChanged(object sender, EventArgs e)
{
    if (enableFolderVariableRemoval.Checked)
    {
        cleanFolderTextPanel.Visible = true;
        cleanTextPanel.Visible = true;
    }
    else
    {
        cleanFolderTextPanel.Visible = false;
        if (cleanFilenameTextPanel.Visible == false)
        {
            cleanTextPanel.Visible = false;
        }
    }
}

Is there a better way to handle this without a whole bunch of conditionals that set other controls to hide/show?


texts:
I run into issues where I forget to run UI changes on the main thread.

I've just fixed an issue for loading and unloading an activity indicator and fixed it with the following code:

if active {
    DispatchQueue.main.async {
        UIApplication.shared.keyWindow?.startIndicatingActivity()
    }
} else {
    DispatchQueue.main.async {
        UIApplication.shared.keyWindow?.stopIndicatingActivity()
    }
}

Now an alternative is this code:

DispatchQueue.main.async {
    if active { UIApplication.shared.keyWindow?.startIndicatingActivity()
    } else { UIApplication.shared.keyWindow?.stopIndicatingActivity()
    }
}

Now which one is right / more maintainable for the future?


texts: Colorizing Excel cells with a date range filter

texts:
In a table there is a number of column (chambre) and a number of row (alveole). If these matches in a list in an other sheet then it checks if it the date is between two dates on that second sheets. If it matches those 3 things, then it puts the sheet

My code works if I add DoEvents in every For, else Excel and VBA stops responding. But it takes around 5 minutes and I need to to this for 4 tables.

Is it my code that is not efficient? Do you have any ideas how to make it better?

Sub alveoles()

    Application.ScreenUpdating = True
    Dim moment As Date
    'variables Photo
    Dim four As Integer
    Dim chambre As Integer
    Dim alveole As Integer
    Dim aaa As Integer
    Dim ccc As Integer

    'variables Gems
    Dim ligne As Integer
    Dim enfournement As Date
    Dim defournement As Date

    Dim lastrow As Integer

    'set date and lastrow
    moment = Worksheets("Photo").Range("O2").Value
    lastrow = Worksheets("Gems").Range("A" & Rows.Count).End(xlUp).Row
    four = 1
    'Four1 1 row
    For ligne = 2 To lastrow
    DoEvents

            For chambre = 1 To 38
            DoEvents
                For alveole = 1 To 6
                 DoEvents

                enfournement = Worksheets("Gems").Range("D" & ligne).Value
                defournement = Worksheets("Gems").Range("E" & ligne).Value

                If four = Worksheets("Gems").Range("A" & ligne).Value And _
                   chambre = Worksheets("Gems").Range("B" & ligne).Value And _
                   alveole = Worksheets("Gems").Range("C" & ligne).Value And _
                    moment > enfournement And _
                    moment < defournement Then

                                aaa = alveole + 5
                                ccc = chambre + 2

                            Worksheets("Photo").Cells(aaa, ccc).Interior.ColorIndex = 1 'NOIR

                End If
                Next alveole
            Next chambre
Next ligne

End Sub


texts: Handling create, update, and destroy for sync

texts:
I'm pretty sure there's a way to make this "3 times" duplicated code into only one. Any idea how to do this?

if (typeof sync.create!='undefined') {
    for (var i = 0; i <sync.create.length; i++) {
        sync.create[i].modified.id_partenaire=false;
    };
}
if (typeof sync.update!='undefined') {
    for (var i = 0; i <sync.update.length; i++) {
        sync.update[i].modified.id_partenaire=false;
    };
}
if (typeof sync.destroy!='undefined') {
    for (var i = 0; i <sync.destroy.length; i++) {
        sync.destroy[i].modified.id_partenaire=false;
    };
}


texts: Encrypting a user's file with a key that isn't stored but only known by the user

texts:
I want to make some kind of file vault. I want to store encrypted files in a MySQL table, and the key to encrypt/decrypt them is never stored but only known to the user (that's the goal, anyway).

The user has to be logged in to view a list of his files. Then, to view a file, the user has to enter a key to decrypt a file to read it. So assuming a user's account was hacked and his password was discovered, I want the hacker to still be unable to decrypt the files, since the hacker doesn't know the key used to encrypt it.

What are the biggest holes in this? Please help me improve it rather than just saying 'this is terrible', 'use a library', or 'don't do it yourself'. I know the security of this depends on other code that I didn't put here. I just tried to put the most relevant parts.

Here is some code from the controller to add a new file:

public function addFile($request, $response) {

    $user = Security::getUser();
    if (!$user) { $this->denyAccess('add-file'); }

    $unencrypted_content = $request->getParam('content');
    $key = $request->getParam('key');
    if (Security::authenticate($user->username, $key)) {
        $this->flash->addMessage('error', 'You can not use your password as the key to your files.');
        return $this->redirect('new-file');
    }

    $otherFile = $user->files()->first();
    if ($otherFile && !Crypt::decrypt($otherFile->content, $key, $otherFile->iv)) {
        $this->flash->addMessage('error', 'The key you entered failed to decrypt another one of your files. You must always use the same key.');
        return $this->redirect('new-file');
    }

    $iv = Crypt::iv();
    $encrypted_content = Crypt::encrypt($unencrypted_content, $key, $iv);

    $file = new File;
    $file->owner()->associate($user);
    $file->name = $request->getParam('name');
    $file->content = $encrypted_content;
    $file->iv = $iv;
    $file->save();

    return $this->redirect('all-files');
}

Here is the Crypt class:

public static function iv() {
    $letters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $iv = '';

    for ($i = 0; $i < 16; $i++) {
        $iv .= substr($letters, rand(0, 35), 1);
    }

    return $iv;
}

public static function encrypt($content, $key, $iv) {
    return openssl_encrypt($content, 'aes-256-cbc', $key, 0, $iv);
}

public static function decrypt($content, $key, $iv) {
    return openssl_decrypt($content, 'aes-256-cbc', $key, 0, $iv);
}

And again in the controller to view a file:

public function viewFile($request, $response) {
    $csrf_name = $request->getAttribute('csrf_name');
    $csrf_value = $request->getAttribute('csrf_value');

    $file = File::find($request->getAttribute('id'));
    if ($file->owner->id !== Security::getUser()->id) { $this->denyAccess('view-file/' . $file->id); }

    $key = $request->getParam('key');
    $decrypted_content = Crypt::decrypt($file->content, $key, $file->iv);

    if (!$decrypted_content) {
        $this->flash->addMessage('error', 'The key you entered is not valid.');
        return $this->redirect('authorize', ['id' => $file->id]);
    }

    $file->content = $decrypted_content;
    $file->key = $key;

    return $this->render($response, 'file/view.html.twig', compact('file', 'csrf_value', 'csrf_name'));
}


texts: Logging leads when interactions happen for a contact

texts:
I have been trying to get as close to SRP in my code as possible. I have a situation where I need to log leads when interactions happen for a contact. A lead may be created or updated. There are three different states that I would like to set leads to.

Active - new interested interactions causes active lead to be created
Converted - a existing lead is updated to converted if the product was purchased - this is managed with conversion flag
Stale - a existing lead is updated to stale if the contact is not interested

class LeadGeneration

  def initialize contact_id, options={}
    @lead = Lead.find_or_initialize_by(contact_id: contact_id)

    options.reverse_merge!(conversion: false, interested:true)
    @conversion = options[:conversion]
    @interested = options[:interested]
  end

  def call
    if conversion?
      convert_lead
    else
      process_lead
    end
  end

  private

  def lead
    @lead
  end

  def conversion?
    @conversion
  end

  def interested?
    @interested
  end

  def convert_lead
    lead.converted! unless lead.new_record?  # new leads cannot be saved as converted
  end

  def process_lead
    if interested?
      activate_lead
    else
      stale_lead
    end
  end

  def activate_lead
    lead.active!
  end

  def stale_lead
    lead.stale! unless lead.new_record? # new leads cannot be saved as stale
  end
end

Right now I feel like I should be splitting up converting a lead and managing stale/active states.  I'm not really sure what to do and tests are a little confusing right now.


texts: Convert top-down subset sum to bottom-up

texts:
I have written the code for calculating subset-sum and also printing the first encountered non-empty subset from the left that sums up to the given sum.

My code in Java is as follows:

import java.util.HashMap;
import java.util.Map;

public class SubsetSum {

    public static void main(String[] args) {

        int set[] = {-2, -3, 5, 7};

        int sum = 10;

        findSubsetSum(set, sum, set.length - 1);
    }

    public static void findSubsetSum(int arr[], int sum, int limit) {

        Map<Integer, Boolean> memo[] =
                new Map[limit + 1];

        for(int i = 0; i < memo.length ; i++) {
            memo[i] = new HashMap<Integer, Boolean>();
        }

        int A = 0, B = 0;

        for(int i = 0 ; i <= limit; i++) {
            if(arr[i] < 0) A+=arr[i];
            else if(arr[i] >= 0) B+=arr[i];
        }
        //This is there just in case the set size is 1.
        memo[0].put(sum, arr[0] == sum);

        for(int i = 1; i <= limit && limit < arr.length; i++) {
            Q(arr, sum, i, A, B, memo);
        }

        boolean prev = Boolean.parseBoolean(memo[limit].get(sum)+"");

        String str = "{";

        Integer found =null;
    int s = sum;

    for(int i = limit - 1; i >= 0 && (found==null || found != sum); i--) {

        if(i == 0 && (found == null ? 0 : found) + arr[0] == sum)
            {
                str += arr[0];
                break;
            }

        boolean b = Boolean.parseBoolean(memo[i].get(s)+"");

        if(!b && prev) {
            s-=arr[i + 1];
            found = (found == null ? 0 : found) + arr[i + 1];
            str+=arr[i + 1] + " ";
            i++;
        }
    }

        str+="}";

        System.out.println(str);
    }

    private static boolean Q(int arr[], int sum, int index,
            int A, int B, Map<Integer, Boolean> memo[]) {

        if(index < 0) return false;

        if(sum < A || sum > B) return false;

        Boolean c = memo[index].get(sum);

        if(c != null) return c;

        Boolean res = Q(arr, sum, index - 1, A, B, memo)
                    || arr[index] == sum
                    || Q(arr, sum - arr[index], index - 1, A, B, memo);

        memo[index].put(sum, res);

        return res;
    }

}

Some of the improvements I need help with are the following:

Convert the DP approach from top-down to a bottom-up approach. Is it really necessary for me to keep the whole memo[] array in memory ? Or can I optimize it somehow ?
I am really interested in how I can optimize my subset printing code. It begins from the 22nd line of the function findSubsetSum. I really am sure there is a more elegant way to do it, but I just can't think of it.
Any other code/logic improvements in general.


texts: Are these C# and Python code snippets functionally identical?

texts:
I have a bit of Python source code that I want to recreate in C#. The code is about reading and decrypting a binary file. I have tested the function on an existing file and it runs without errors; while the resulting string is not garbled or anything, it does not appear to be useful to me.

But that is outside the scope of this question.  I only want to know if I have translated the function correctly to C# so it does the same as in Python.

The Python code:

    filename = os.path.basename(path_and_filename)
    key = 0
    for char in filename:
        key = key + ord(char)
    f = open(path_and_filename, 'rb')
    results = ''
    tick = 1
    while True:
        byte = f.read(2)
        if byte:
            if tick:
                key = key + 2
            else:
                key = key - 2
            tick = not tick
            res = struct.unpack('h', byte)[0] ^ key
            results = results + chr(res)
            continue
        break
    f.close()
    return results

path_and_filename is an absolute path to the encrypted file.

Here is the C# code I wrote:

        string path = _path;
        string fileName = _fileName;
        char[] chars = fileName.ToCharArray();
        int key = 0;
        foreach (char c in chars)
        {
            key += c;
        }
        StringBuilder builder = new StringBuilder();

        using (FileStream file = new FileStream(path, FileMode.Open))
        {
            bool tick = true;

            while (true)
            {
                int i = file.ReadByte();
                if (i == -1)
                    break;
                if (tick)
                    key += 2;
                else
                    key -= 2;
                tick = !tick;

                //The next 2 lines are for parsing the short, equivalent(?) to struct.unpack('h', byte)
                i <<= 8;
                i += file.ReadByte();

                i ^= key;
                byte b = (byte)i;
                char c = (char)b;
                builder.Append(c);
            }
        }
        string result = builder.ToString();

Never mind the dirtiness of the code. Will those 2 snippets give the same output to a certain input?


texts: Implementing Haskell's \\ (Set Difference)

texts:
Learn You a Haskell presents the \\ function.

  \\ is the list difference function. It acts like a set difference,
  basically. For every element in the right-hand list, it removes a
  matching element in the left one.

Example:

ghci> [1..10] \\ [2,5,9]
[1,3,4,6,7,8,10]

Please critique my implementation.

setDifference :: (Eq a) => [a] -> [a] -> [a]
setDifference xs excludes = filter (not . (`elem` excludes)) xs

Test:

*Main> setDifference [1,2,3] [2,4,5,6]
[1,3]