texts:
My friend and I, have made a timetable viewer in Python 3.4 for a mock timetable. The format is a 2 week school timetable with 5 daily lessons with each lesson having a room. We have tried to make it as object-oriented as possible, yet is the solution overkill? Our goal was to make the classes into a module so you can just import timetable and create your own Lesson() and Day() objects to make your own timetable. So, is our solution overkill, and any general feedback on the code?

class Lesson:
    def __init__(self, name, room):
        self.room = room
        self.name = name
    def __repr__(self):
        return ('{}: {}').format(self.name, self.room)

class Day:
    def __init__(self, name, week, lessons):
        self.name = name
        self.week = week
        self.lessons = lessons
    def __repr__(self):
        return ((str([x for x in self.lessons]).replace('[', ' ')).replace(']', '')).replace(',', '\n')

physics = Lesson("Physics", "B27")
prod_des = Lesson("Product Design", "B2")
comp_sci = Lesson("Computer Science", "B14")
french = Lesson("French", "C9")
english = Lesson("English", "C11")
maths = Lesson("Maths", "T15")
private_study = Lesson("Private Study", "N/A")
chem = Lesson("Chemistry", "B12")
engineering = Lesson("Engineering", "Off Campus")
biol = Lesson("Biology", "B24")
add_math = Lesson("Additional Math", "T19")
games = Lesson("Games", "Sports Field")
re = Lesson("R.E.", "M20")
engineering_voc = Lesson("Engineering (Vocational)", "B2")

monday = Day("Monday", "Week 1",[physics, prod_des, comp_sci, french, english])
tuesday = Day("Tuesday", "Week 1", [english, maths, prod_des, physics, private_study])
wednesday = Day("Wednesday", "Week 1", [french, chem, comp_sci, engineering, engineering])
thursday = Day("Thursday", "Week 1", [french, private_study, biol, maths, english])
friday = Day("Friday", "Week 1", [comp_sci, prod_des, maths, add_math, games])

monday2 = Day("Monday", "Week 2",[maths, prod_des, biol, english, private_study])
tuesday2 = Day("Tuesday", "Week 2", [prod_des, french, chem, maths, private_study])
wednesday2 = Day("Wednesday", "Week 2", [comp_sci, physics, re, engineering, engineering])
thursday2 = Day("Thursday", "Week 2", [games, maths, biol, french, english])
friday2 = Day("Friday", "Week 2", [french, chem, engineering_voc, english, comp_sci])

days = { 1: monday, 2: tuesday, 3: wednesday, 4: thursday, 5: friday,
         6: monday2, 7: tuesday2, 8: wednesday2, 9: thursday2, 10: friday2
}

while True:
    while True:
        try:
            day = int(input("\nDay: "))
            if day in days.keys():
                day_obj = days[day]
                print(day_obj.name, day_obj.week)
                print(day_obj)
                break
            raise ValueError
        except:
            print("It has to be a number between 1 and 10")
    while True:
        again = input("Again? (y/n): ").lower()
        if again == "n":
            quit()
        elif again not in ["y", "n"]:
            print("Type 'y' or 'n'")
        elif again == "y":
            break


texts: Django query ManyToMany for tagged items

texts:
I've got a item inventory that each inventory item is tagged with multiple tags. What I've got is an API that takes a query parameter with multiple comma separated query items and returns a list of all items that match all of the tags.

The following code is working, however this isn't really using the ManyToMany attributes in the Django models and I'm sure there is a better way to do this.

Schema ---

class InventoryTag(models.Model):
    class Meta:
        unique_together = ('key', 'value')

    key   = models.CharField(max_length=240, db_index=True)
    value = models.CharField(max_length=240, db_index=True)

class InventoryItem(models.Model):
    instance_id = models.CharField(max_length=255)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    tags = models.ManyToManyField(InventoryTag, through='InventoryItemTag', through_fields=('item', 'tag'))

    def as_json(self):
        return serializers.serialize('json', [self])[0]

class InventoryItemTag(models.Model):
    class Meta:
        unique_together = ('item', 'tag')

    item = models.ForeignKey(InventoryItem, db_index=True, related_name='invitem')
    tag  = models.ForeignKey(InventoryTag, db_index=True, related_name='invtag')

    created_at = models.DateTimeField(auto_now_add=True)

Get Function --

def get(self, request, *args, **kwargs):
    query = request.GET.get('q', '').strip()
    start = int(request.GET.get('start', 0))
    count = int(request.GET.get('count', 50))

    query_items = [q.strip() for q in query.split(',') if q.strip()]

    items = InventoryItem.objects
    if query_items:
        for q in query_items:
            tags = InventoryTag.objects
            q = q.lstrip(':')
            if ':' in q:
                (k, v) = q.split(':', 1)
                tags = tags.filter(Q(key = k) & Q(value__startswith = v))
            else:
                tags = tags.filter(value__startswith = q)

            tags_pks = InventoryItemTag.objects.filter(Q(tag__in = tags.values_list('id')))
            items = items.filter(pk__in=tags_pks.values_list('item_id'))

    items = items.all()

How this is used:

InventoryItem -- For practical purpose this is an AWS instance with an instance_id
InventoryTag -- Other attributes of that instance (e.g. Name) or IP address. This is unique for any key/value pair of the tag.

You might have a set of instances like:

Item(id=1) -- tags:  name=dev.test zone=us-east-1a
Item(id=2) -- tags:  name=dev.vpc  zone=us-east-1a
Item(id=3) -- tags:  name=dev.cron zone=us-east-1a
Item(id=4) -- tags:  name=dev.test zone=us-east-1c
Item(id=5) -- tags:  name=dev.test zone=us-west-2a

So the goal is that you should be able to do a search where you ask for all name=dev.test and zone=us-east-1a machines and get item #1 and #4.


texts:
I am using the ruby sunspot gem to create a search users function on my site.
It works fine and the users controller for the index page where there is a search form is this

def index
 if params[:search].nil?
  @users = nil
 else
  @search = User.search do
    fulltext params[:search]
  end
  @users = @search.results.paginate(page: params[:page], :per_page => 10)
 end
end

on the index page, I do this

  <% if @users %>
    <ul class="users followers">
      <%= render @users %>
      <%= will_paginate @users%>
    </ul>
  <% end %>

My question is this. I think setting @users to nil looks and feels wrong. I want the index page to show nothing but my search form if nothing is put in the field. There must be some easy Ruby way to express this. By the way I am fairly new to Ruby on Rails.


texts:
My goal is to implement a function that accepts a Follower object that will be used to report progress through a complex function (a depth-first traversal of a graph). Here's my attempt:

pub trait Follower<'a, N> {
    fn root(&mut self, node: &'a N);
}

pub fn depth_first<'a, N>(
    node: &'a N, follower: &mut dyn Follower<'a, N>
) {
    follower.root(node);

    // TODO
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fmt::Display;

    struct DebugFollower<'a, N> {
        nodes: Vec<&'a N>
    }

    impl<'a, N: Display> DebugFollower<'a, N> {
        fn new () -> Self {
            DebugFollower { nodes: vec![ ] }
        }

        fn to_string(&self) -> String {
            self.nodes.iter().map(ToString::to_string).collect()
        }
    }

    impl<'a, N> Follower<'a, N> for DebugFollower<'a, N> {
        fn root(&mut self, item: &'a N) {
            self.nodes.push(item);
        }
    }

    #[test]
    fn walks_p1() {
        let mut follower = DebugFollower::new();

        depth_first(&0, &mut follower);

        assert_eq!(follower.to_string(), "0");
    }
}

The code compiles and performs as expected. However, I suspect that, in trying to silence the many compile errors I encountered, I may have added unnecessary lifetime parameters. Previous experience has shown me that it's very easy to get into a situation wherein so many useless parameters have been added that removing them one at a time isn't possible. Still, I have tried to do that and can't find any lifetime parameters that can be removed.

In particular, I'm suspicious of the lifetime parameter on Follower, which appears to leak implementation details from DebugFollower. For example, removing the nodes property from DebugFollower, and updating the rest of the code, Follower no longer needs a lifetime parameter.

Does this example follow idiomatic Rust use of lifetime parameters? If not, how can I improve the use of lifetime parameters here?


texts:
I am trying to reset a password when password_reset_token is received in the controller. But it's becoming a long if else ladder of many conditions. Can it be reduced in a better way?

def set_new_password
    if params[:password_reset_token].present?
      @user = User.find_by(password_reset_token: params[:password_reset_token])
      if @user.present?
        if params[:password] != params[:password_confirmation]
          render json: {errors: ["Your password confirmation doesn't match"]}, status: :unprocessable_entity
        elsif @user.password_reset_sent_at < 2.hours.ago
          render json: {errors: ["Your password reset expired. Please require a new password reset from the app."]}, status: :unprocessable_entity
        elsif @user.update(user_params)
          @user.update(password_reset_token: nil, password_reset_sent_at: nil)
          render :json => {:success => true}
        end
      else
         render json: {errors: ["Password reset not found. Please request a new password reset!"]}, status: 404
      end
    else
      render json: {errors: ["Password reset not found. Please request a new password reset!"]}, status: 404
    end
  end


texts:
I had some issues with the behavior of the iterator in my prime generator:

#include <vector>
#include <set>
#include <iostream>

using namespace std;

int main() {
    int a,b;
    int nbr;
    vector<int> t;
    set<int> s;

    // prime generated to b
    b = 10;
    // set 2 -> b.
    for (int i = 2; i != b; i++)
    {
        s.insert(i);
    }
    int i = 0;
    while (s.size() != 0)
    {
        i++;
        cout << "Iteration = " << i << endl;
        t.push_back(*s.begin());
        for (set<int>::iterator it = s.begin() ; it != s.end(); it++)
        {
            cout << "       s  = " << *it << endl;
            if (*it % t.back() == 0) {s.erase(it++);}
            if (it == s.end()) break;
        }
    }
    cout << "++++++++++++++++++++++++++++" << endl;
    cout << "affichage des nombres premiers stockés dans le vecteur t" << endl;
    cout << "taille t = " << t.size() << endl;
    for (vector<int>::iterator it = t.begin() ; it != t.end(); ++it)
    {
        cout << "t = " << *it << endl;
    }

I think erasing an element of s in the for loop can be a problem, but the compiler doesn't complain and it seems to work. Is it a problem? I am also happy for a general review.


texts:
Recently I needed to manipulate with cookies using JavaScript, so I wrote a class:

function Cookies() {
    var cookieLifeTime = null;

    this.setCookie = setCookie;
    this.getCookie = getCookie;
    this.deleteCookie = deleteCookie;
    this.setLifeTime = setLifeTime;

    function setLifeTime(lifeTime) {
        cookieLifeTime = lifeTime;
    }

    function setCookie(name, value) {
        if (this.lifeTime !== null) {
            var date = new Date();
            date.setTime((date.getTime() + cookieLifeTime));
            var expires = '; expires=' + date.toGMTString();
        } else {
            var expires = '';
        }

        document.cookie = name + '=' + value + expires + '; path=/';
    }

    function getCookie(name) {
        name += '=';
        var ca = document.cookie.split(';');

        for(var i=0; i < ca.length; i++) {
            var c = ca[i];

            while (c.charAt(0) === ' ')
                c = c.substring(1, c.length);

            if (c.indexOf(name) === 0)
                return c.substring(name.length, c.length); //Edited. Reduced not extra iterations
        }

        return null;
    }

    function deleteCookie(name) {
        setCookie(name, '', -1);
    }
}

I am not a JavaScript developer so maybe I've over-complicated things. Are there parts that can be optimized (I mean readability mostly)? I am also interested if there could be some edge-cases where this script will fail.


texts:
I have created several mixins for a button to attempt to reduce duplication and contribute to the overall improvement of performance. I am looking for guidance on how to tighten this up so it is as DRY (Don't Repeat Yourself) as possible. Or is it already as DRY as possible?

Here is the code:

// mixin - button shape
@mixin buttonShape {
    vertical-align:middle;
    line-height:1.333rem;height:2.166rem;
    color:#282a2e;
    border-radius:0;
    margin-top:1.083rem;
    margin-bottom:.333rem;
    margin-right:1.073rem;
    border:none;
    transition: background-color .2s;
}

// mixin - button gradients
@mixin gradientNormal {
    background-color:#efefee;
    background:linear-gradient(to bottom,#efefee 0,#d0d0ce 100%);
    box-shadow:inset 0 0 0 .083rem #fff;outline:1px solid silver;
}

@mixin gradientHoverActive {
    background:linear-gradient(to bottom,#ffffff 0,#ffffff 100%);
    box-shadow:inset 0 0 0 .083rem #fff;outline:2px solid #e87722;
}

// normal state
.ui-button {
    font-size: 12px;
    @include buttonShape;
    @include gradientNormal;
}

// hover
.ui-button:enabled:hover,
.ui-button:focus {
    @include buttonShape;
    @include gradientHoverActive;
}

// active
.ui-button:enabled:active {
    @include buttonShape;
    @include gradientHoverActive;
}


texts: Django functions to sanitize URL, return welcome message, redirect, compute HMAC, and manage profile picture

texts:
I wrote this code to to perform the following:

I will remove the "spaces" within the url.
Return welcome message.
Redirect the user to different url.
Compute HMAC for the request.
Return and revoke the user profile picture.

Would someone please help me in checking if my code contains any security issues that I should avoid?

import base64
import mimetypes
import os
import hashlib
import hmac
import requests

from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.views.decorators.csrf import csrf_exempt

def ordenary(s):
     return s.strip().replace(' ', '').lower()

def form_of_message(request):
     env = {'message': request.GET.get('message', 'hello')}
     response = render(request, 'forms/message_form.html', env)
     response.set_cookie(key='message_rendered_at', value=time.time())
     return response

 def proxy(request):
     url = request.GET.get('url')
     return redirect(url)

 def compute_hmac_signature(message, key):
     key = bytes(key, 'UTF-8')
     message = bytes(message, 'UTF-8')

     digest = hmac.new(key, message, hashlib.sha1).hexdigest()
     return "sha1={}".format(str(digest))

 def user_pic(request):
     """A view that returns the user's avatar image"""

     base_path = os.path.join(os.path.dirname(__file__), '../../images/avatars')
     filename = request.GET.get('u')

     try:
         data = open(os.path.join(base_path, filename), 'rb').read()
     except IOError:
         return render(request, 'templates/avatar.html')

     return HttpResponse(data, content_type=mimetypes.guess_type(filename)[0])


texts: Generically Cache Database Lookups By Id

texts:
For a project I am working on I had to query a database for a number of "child objects". Now in the mapping POJO for said child objects a reference to the parent is kept. That reference is available in the database as a foreign key constraint.

But if I retrieve a collection of all child elements they all map to vastly less (on the order of 1.5k:1) parent objects.
To prevent accessing the database for each and every parent object lookup I decided to cache the results of parent-object queries for the duration of child-object retrieval.

To accomplish this in a typesafe, but generic way I've written the following class:

public class LookupCache<T,P,R> {
    private final T delegate;

    private final Map<BiFunction<T, P, R>, Map<P, R>> cache = new HashMap<>();

    public static <T,P,R> LookupCache<T,P,R> forObject(T object) {
        return new LookupCache<>(object);
    }

    private LookupCache(T object) {
        this.delegate = object;
    }

    public R lookupOrCompute(BiFunction<T,P,R> compute, P param) {
        Map<P,R> cachedResults = cache.computeIfAbsent(compute, a -> new HashMap<>());
        return cachedResults.computeIfAbsent(param, p -> compute.apply(delegate, p));
    }
}

The usage is pretty simple:

try (ResultSet dbResult = connection.createStatement().executeQuery("SELECT id, parent_id, property FROM child;")) {
    final BiFunction<ParentDAO, Long, Parent> parentLookup = ParentDAO::getById;
    final LookupCache<ParentDAO, Long, Parent> lookupCache = LookupCache.forObject(new ParentDAOImpl());
    List<Child> result = new ArrayList<>();
    while (dbResult.next()) {
        Parent p = lookupCache.lookupOrCompute(parentLookup, dbResult.getLong("parent_id"));
        result.add(new Child(dbResult.getLong("id")
            , Property.fromDbState(result.getLong("property"))
            , p));
    }
    return result;
} // catch clause and default return for error

Note that usage is not up for review here, what I'm significantly more interested in is:

Is this Cache designed in a way that's intuitive to use?
Am I possibly overcomplicating things by passing the DAO to the Cache instead of capturing it in a lambda?
Anything else I might have missed?


texts:
Code review my quicksort! It isn't supposed to be superfast or anything and doesn't basecase out to insertion sort or anything. It's optimized for clarity and only sorts arrays of pointers.

#define MISC_XCHG(a, b) ({ __typeof__(a) MISC_XCHG__A = (a); (a) = (b); (b) = MISC_XCHG__A; })

static void misc_qsort_internal(void const** A, void const** Z, bool (*cmp)(void const*, void const*))
{
  while ((Z - A) > 1) {
    /*
      quicksort is a bit tricky. the basic idea of just partitioning
      into < and >= partitions and recursing on each isn't guaranteed
      to terminate, because everything can end up in the >= part.

      the key to termination is to make sure at least one element
      drops out.

      the element that drops out must be equal to the pivot, so that
      it can be >= everything in the < part and <= to everything in
      the >= part. most simply, this element can be the pivot, which
      should be inserted between the < and the >= parts.

      so as we build up the regions we keep the pivot at the start of
      the array and later exchange it with the last element in the <
      part.
    */
    void const* pivot = *A;

    /* S points to the first element in the >= part */
    void const** S = A+1;

    for (void const** I = S; I < Z; I++) {
      if (cmp(*I, pivot)) {
        /* when *I < pivot */
        /* we must exchange with the first element in the >= part */
        MISC_XCHG(*I, *S);
        /* and shift the >= part over by one */
        S++;
      } else {
        /* when *I >= pivot */
        /* nothing to do, the >= part grows "automatically" */
      }
    }

    /* now do the business of exchanging the pivot */
    void const** R = (S - 1);
    *A = *R;
    *R = pivot;

    /* recursively sort (>=A, <R) and (>=S, <Z) */
    /* recurse on the smaller partition */
    /* this keeps stack usage always at or below O(log n) */
    if ((R - A) < (Z - S)) {
      misc_qsort_internal(A, R, cmp);
      A = S; /* loop to sort (>=S, <Z) */
    } else {
      misc_qsort_internal(S, Z, cmp);
      Z = R; /* loop to sort (>=A, <R) */
    }
  }
}

/*
  cmp should return true iff [arg1] < [arg2] (strictly).
*/
static INLINE void misc_qsort(void const** A, uintptr_t L, bool (*cmp)(void const*, void const*))
{
  misc_qsort_internal(A, (A + L), cmp);
}

#define MISC_QSORT_VARIANT(s, t)                                        \
  static INLINE void misc_qsort_##s(t** A, uintptr_t L, bool (*cmp)(t const*, t const*)) \
  {                                                                     \
    misc_qsort(((void const**)(A)), L, ((bool (*)(void const*, void const*))(cmp))); \
  }


texts: CLRS implementation (opportunity to sort subarray) of merge sort in golang

texts:
I'm reading "Introduction to Algorithms" by CLRS and I can't find an implementation of the pseudo code from the book in golang. By the original implementation I mean that we deal with extra parameters in the function to define slice of an original array. All implementations on the web deal with whole array. And that's not what Thomas Cormen wanted.
So I write this one:

package sort_merge

import (
    "math"
)

/*
CLRS implementation - we deal with slice of original array arr[p, r], indexes p and r are inclusive
*/
// arr={6, 5, 4, 3}; p=0; q=3
// arr={6, 5};       p=0; q=1
// arr={6};          p=0; q=0
func MergeSort(arr []int, p int, r int) {
    if p < r {
        q := (p + r) / 2 // last index of left array (rounding down)
        MergeSort(arr, p, q)
        MergeSort(arr, q+1, r)
        Merge(arr, p, q, r)
    }
}

func Merge(arr []int, p int, q int, r int) {
    left := make([]int, len(arr[p:q+1]))    // q+1, because right part of slice is exclusive
    right := make([]int, len(arr[q+1:r+1])) // q+1, because this is last index of left array
    copy(left, arr[p:q+1])
    copy(right, arr[q+1:r+1])          // r+1, because right part of slice is exclusive
    left = append(left, math.MaxInt64) // math.MaxInt64 used here as Infinity from original implementation
    right = append(right, math.MaxInt64)

    i, j := 0, 0
    for k := p; k <= r; k++ {
        if left[i] <= right[j] {
            arr[k] = left[i]
            i++
        } else { // left[i] > right[j]
            arr[k] = right[j]
            j++
        }
    }
}

You can run it:

package main

import "fmt"
import "./sort-merge"

func main() {
    arr := []int{6, 5, 4, 3}
    sort_merge.MergeSort(arr, 0, len(arr)-1)
    fmt.Println(arr)
}


texts:
I want to optimise this code and improve it using advanced C++.

#include <iostream>

template <class T>
class LinkedList
{
  struct Node
  {
    T data;
    Node * next;
    Node(T value) : data(value), next(nullptr) {}
  };
  Node *head;

public:
  LinkedList() : head(nullptr) {}
  ~LinkedList();
  void insert(T);
  void printList();
  void recursiveReverse()
  {
    Node *temp = head;
    head = recursiveReverse(temp);
  }
private:
  Node* recursiveReverse(Node* head)
  {
    if(head == nullptr)
      return nullptr;

    if(head->next == nullptr)
      return head;

    Node *firstElement = head;
    Node *secondElement = firstElement->next;
    head = firstElement->next;
    firstElement->next = nullptr; //unlink first node
    Node *remainingList = recursiveReverse(head);
    secondElement->next = firstElement;
    return remainingList;
  }
};

template <class T>
void LinkedList<T>::insert(T data)
{
  Node *node = new Node(data);
  Node *tmp = head;
  if(tmp == nullptr)
  {
    head = node;
  }
  else
  {
    while(tmp->next != nullptr)
    {
      tmp = tmp->next;
    }
    tmp->next = node;
  }
}

template <class T>
void LinkedList<T>::printList()
{
  Node *node = head;
  while(node)
  {
    std::cout << node->data << " ";
    node = node->next;
  }
  std::cout<<"\n";
}
template <class T>
LinkedList<T>::~LinkedList()
{
  Node *tmp = nullptr;
  while(head)
  {
    tmp = head;
    head = head->next;
    delete tmp;
  }
  head = nullptr;
}

int main()
{
  LinkedList<int> ll1;
  ll1.insert(2);
  ll1.insert(3);
  ll1.insert(4);
  ll1.insert(5);
  ll1.insert(6);
  ll1.printList();
  ll1.recursiveReverse();
  ll1.printList();
}


texts:
I have two tables, one for jobs, and one for the names of industries (e.g. automotive, IT, etc).

In SQL I would just do:

SELECT industryName, count(*)
FROM jobs
JOIN industry
ON jobs.industryId = industry.id
GROUP BY industryName

In LINQ I have the following, but it's three separate statements and I'm pretty sure this would be doable in one.

var allIndustries =
    from j in dbConnection.jobs
    join i in dbConnection.industries on j.industryId equals i.id
    select i.industryName;
var industriesWithCount =
    from i in allIndustries
    group i by i into iGrouped
    select new { Industry = iGrouped.Key, Count = iGrouped.Count() };
var industries = new Dictionary<string, int>();
foreach (var ic in industriesWithCount)
{
    industries.Add(ic.Industry, ic.Count);
}

Is there a way to make this simpler or shorter?


texts: squaring a number using bitwise multiplication or using *

texts:
I had written a code which is given in the following code 1,code1 & Driver program section of the post.
I have to ask which of the following code is more efficient and takes less time to execute on the C(GCC 4.9.2) compiler.
I had a little confusion in the following code which is multiplication of input1 *input1 which  I might think will takes lot more time so
Is there any way to optimize like using bitwise multiplication.
Code 1
int FindingMoves(int input1)
    {
        if(input1>0)
        {
               ++input1;
               input1 <<=1;
               ++input1;
               return input1*input1;

        }
        if(input1 == 0){return 8;}

    }

This is the first code which I had written using bitwise multiplication but fails to write a code to multiply two numbers(input1*input1).
Code 2
int FindingMoves(int input1)
    {
        if(input1>0)
        {

               return (2*(input1+1)+1)*(2*(input1+1)+1);

        }
        if(input1 == 0){return 8;}

    }

This is straight forward code which is a simpler version of above.
DriverProgram
int main() {
    int output = 0;
    int ip1;
    scanf("%d", &ip1);
    output = FindingMoves(ip1);
    printf("%d\n", output);
    return 0;
}

This is the driver program to above code snippets.
Help me here to write optimized and efficient code. Any mysteries will be welcome regarding macro or something.


texts: Fetching photos and tweets related to selected publications

texts:
1) Postgresql
2) User has_many :reports
3) Report belongs_to :user
3) Report belongs_to :publication
4) Publication has_many :reports
4) Publication scope :photos, -> { where(publication_type: 'Social::Photo').where(show: true) }
4) Publication scope :tweets, -> { where(publication_type: 'Social::Tweet').where(show: true) }

def index

  looked_pub_ids = Publication.where(show: true).
    joins(:reports).
    where(reports: { user: current_user } ).
    pluck(:id)

  if looked_pub_ids.empty
    publicatons = Publication.all
  else
    publicatons = Publication.where( 'id NOT IN (?)', looked_pub_ids )
  end

  if request.xhr? && params[:id]
    @photos = publicatons.where('id > ?', params[:id]).
      photos.paginate(page: 1, per_page: 30)
    @tweets = publicatons.where('id > ?', params[:id]).
      tweets.paginate(page: 1, per_page: 30)
  else
    @photos = publicatons.photos.paginate(page: 1, per_page: 30)
    @tweets = publicatons.tweets.paginate(page: 1, per_page: 30)
  end
end

Is there more optimal way to get photos, and tweets from Publication which the user has not reported (main target are admin-panel for manager, who will report some content)?

User see Publication, and can report them (Report table: user_id, publication_id) and next I do not have to show publications to user, what he had reported, example:

publication_1
publication_2
user_1
report_1: {user_id: 1, publication_id: 1}

user_1 can see only publication_2

Now I find all publication_id from user.reports, and then find all publication, except that ids, — I think it is not a nice solution.

P.S. Is it possible to write pure sql for getting that?


texts:
I'm trying to create an URL-router, where the website language is defined by the first two chars in the domain.

Example:

  domain.com/en

(the site will then display content in English).

The script below is what I've come up with so far. Focus is on functionality instead of SEO. However, I would like it to be optimized for both, and honestly I'm no expert at search engine optimization.

Would Googlebot be able to index both the English and Danish content? (notice the way I get the visitors language, and make redirects accordingly)
Is there anything I could do to improve the script functionality, including SEO handling?

All suggestions for improvement are more than welcome.

class Router {
    private $allowedLang = array('da', 'en');
    private $langRouter = array(
        'en' => 'en_US',
        'da' => 'da_DK'
    );

    function __construct() {
        $locale = in_array($_GET['locale'], $this->allowedLang);

        if ($locale) {
            // If get-var locale is allowed, set it as session
            $_SESSION['language'] = $_GET['locale'];
        }
        if (empty($_SESSION['language'])) {
            // If session isn't set, use visitor's browser language
            $_SESSION['language'] = $this->getLanguage();
        }

        // Only redirect if get-var locale is empty or isn't allowed, and target file is not located in lib folder (ajax files etc.)
        if ((empty($_GET['locale']) || !$locale) && substr($_SERVER['SCRIPT_NAME'], 0, 4) != '/lib') {
            header('Location: /'.$_SESSION['language']);
        }

        $this->setLanguage($_SESSION['language']);
    }

    public function setLanguage($lang) {
        // If $lang is allowed use it, else default to DEFAULT_LANGUAGE
        $locale = (in_array($lang, $this->allowedLang) ? $this->langRouter[$lang] : DEFAULT_LANGUAGE);

        // Initiate gettext
        putenv("LC_ALL=$locale");
        setlocale(LC_ALL, $locale);
        bindtextdomain("messages", CLIENT_PATH."/lib/locale");
        textdomain("messages");
    }

    /**
     * Get the visitor's language based on browser settings.
     * If language isn't found or isn't allowed, default to DEFAULT_LANGUAGE
     */
    private function getLanguage() {
        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $langs = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
            foreach ($langs as $value) {
                $choice = substr($value, 0, 2);
                if (in_array($choice, $this->allowedLang)) {
                    return $choice;
                }
            }
        }
        return DEFAULT_LANGUAGE;
    }
}


texts:
I have taken over maintenance of some code, and have restructured it after reading some documents about PSR-2:

<?php

function calc_p()
{
    list($arg1, $arg2, $arg3) = func_get_args();
    switch($arg1) {
      case 'ebook':
            $bp = 5;
            $tax = .08;
              break;
      case 'audio_book':
           $bp = 5;
           $tax = .08;
              break;
      case 'text_book':
           $bp = 7.5;
           $tax = .1;
           break;
    }
    $bp = ($bp + ($bp*$tax));
    //Calclate shipping
    if($arg3 == 'California') {
    }
    else {
        $bp = $bp + 1;
    }
    if ($arg3 == 'Texas') {
        $norm = $bp;
        $bp = $norm + 5;
    }
    //final price format: $XX:XX
    $final_price = '$'.$bp;
    if (strpos($final_price, '.')) {
        $num = (2 - (strlen(substr($final_price, strpos($final_price, '.') + 1))));

            for ($num>0; $num--;) {
                $final_price .= '0';
            }
    }
    elseif (strpos($final_price, '.') == FALSE) {
        $final_price = $final_price .'.00';
    }
    else {
    }
    return $final_price;
}
$totalprice = calc_p('text_book','oldversion','Texas');
echo '<p style="font-weight: bold;">Total Price: </p>' . $totalprice;
?>

I wanted to ask if what I've done is already enough to follow the coding standards, or if I am missing something.


texts: Leaving an APScheduler in a while True loop

texts:
I want to run a background job on my web server to do some database maintenance. I am looking at using APScheduler to do this.

I am planning on running the below code in a separate process to my main web server. I don't really want to tie the code to my web server.

Question: Is using While True pass at the end of a cron-like scheduler considered bad practice? How should it be done? (time.sleep()?)

from apscheduler.scheduler import Scheduler

@sched.interval_schedule(days=1)
def tick():
    # do a clean up job

while True:
    pass


texts: Program for entering 1000 random numbers into two different databases, one for odd numbers and one for even

texts:
I have created a program in java for entering 1000 random numbers into two different database one for odd numbers and one for even. The code is executing fine but it takes nearly a minute to execute. How can I minimize the execution time?

The source code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;

public class Test1 extends Thread {

public static void main(String[] args) throws ClassNotFoundException, SQLException {
long start = System.currentTimeMillis();

int evencount = 0;
int oddcount = 0;
int breakcon = 0;
int breakcon1 = 0;

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1" + "?useSSL=false", "root",
        "1234");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db2" + "?useSSL=false", "root",
        "1234");

try {

    Class.forName("com.mysql.jdbc.Driver");

    for (int n = 1; n <= 1000; n++) {
        Random r = new Random();
        int val = r.nextInt(100000);

        if (val % 2 == 0) {
            PreparedStatement ps = con.prepareStatement(" insert into try values (?)");
            ps.setInt(1, val);
            ps.executeUpdate();
            ps.addBatch();
            breakcon = breakcon + 1;
            if (breakcon % 500 == 0 || breakcon == val)
                ps.executeBatch();
            evencount++;

        } else {
            try {

                Class.forName("com.mysql.jdbc.Driver");
                PreparedStatement ps3 = conn.prepareStatement(" insert into try1 values (?)");
                ps3.setInt(1, val);
                ps3.executeUpdate();
                ps3.addBatch();
                breakcon1 = breakcon1 + 1;
                if (breakcon1 % 500 == 0 || breakcon1 == val)
                    ps3.executeBatch();

                oddcount++;

            }

            catch (Exception e2) {
                System.out.println(e2);
            }
        }
    }

}

catch (Exception e) {
    System.out.println(e);
}

long end = System.currentTimeMillis();
NumberFormat formatter = new DecimalFormat("#0.00000");
System.out.println("Execution time is " + formatter.format((end - start) / 1000d) + " seconds");
System.out.println(oddcount + evencount);

}
}


texts:
I've got a class called Movie and within this class I use an AsyncTask to get a Bitmap from a url passed in the constructor.

To store the image I use new DownloadImage().execute(url).get();. However I'm concerned about this blocking the UI Thread as now its a synchronous call. Is there another way I can go about saving the image in the Bitmap variable?

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.AsyncTask;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class Movie
{
    //Variable for a movie
    private String name;
    private String rating;
    private String genre;
    private String plot;
    private String pathToMovie;

    private int movieId;
    private int runtime;
    private int year;

    private Bitmap image;

    public Movie(String name, String rating, String genre, String plot, String pathToMovie, int movieId, int runtime, int year, String imagePath) throws ExecutionException, InterruptedException
    {
        //Set the variables
        this.name = name;
        this.rating = rating;
        this.genre = genre;
        this.plot = plot;
        this.pathToMovie = pathToMovie;
        this.movieId = movieId;
        this.runtime = runtime;
        this.year = year;

        //Download the image from the imagePath
        this.image = getImageFromUrl(imagePath);
    }

    /*
     * A function to download the image from the imagePath provided
     */
    private Bitmap getImageFromUrl(String url) throws ExecutionException, InterruptedException
    {
        return new DownloadImage().execute(url).get();
    }

    //Define getters
    public String getName(){ return this.name; }
    public String getRating(){ return this.rating; }
    public String getGenre(){ return this.genre; }
    public String getPlot(){ return this.plot; }
    public String getPathToMovie(){ return this.pathToMovie; }
    public int getMovieId(){ return this.movieId; }
    public int getRuntime(){ return this.runtime; }
    public int getYear(){ return this.year; }
    public Bitmap getImage(){ return  this.image; }

    //Set up a AsyncTask to download the images from the url
    private class DownloadImage extends AsyncTask<String, Void, Bitmap>
    {
        @Override
        protected Bitmap doInBackground(String... params)
        {
            //Get the image from the url
            try
            {
                //Create a new URL based on the string provided
                URL url = new URL(params[0]);

                //Create a new HTTP connection from the URL
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();

                //Get the content of the page
                InputStream inputStream = connection.getInputStream();

                //Use a BitmapFactory to convert the InputStream into a bitmap
                return BitmapFactory.decodeStream(inputStream);

            }
            catch (IOException e)
            {
                e.printStackTrace();
                return null;
            }
        }
    }
}


texts:
I have done a lot of research on OOP and I keep seeming to read different opinions on several items, especially the scope resolution operator (::) and handling class containing private functions.

When calling a private function from within the class it seems that a majority of programmers recommend self::method(), is this accurate? I have also seen and tested Class::method().

Also, I am looking for more information, or recommendations on appropriate ways to instantiate class variables, whether it be protected, private, var, etc...

Take this Timer class I wrote for example:

class Timer {
    protected $_start, $_pause, $_stop, $_elapsed;
    protected $_laps = array();
    protected $_count = 1;
    protected $_lapTotalTime = 0;

    public function __construct($start = '') {
        $start = strtolower($start);
        ($start === 'start') ? self::start() : NULL;
    }

    public function start( ) {
        $this->_start = Timer::getMicroTime();
    }

    public function stop( ) {
        $this->_stop = Timer::getMicroTime();
    }

    public function pause( ) {
        $this->_pause = Timer::getMicroTime();
        $this->_elapsed += ($this->_pause - $this->_start);
    }

    public function resume( ) {
        $this->_start = Timer::getMicroTime();
    }

    // Used to build an array of times for multiple timers
    public function lap($key = '') {
        ($key === '') ? $key = 'Lap' : $key = $key;
        if (isset($this->_start)) {
            self::stop();
            $this->_lapTotalTime += ($this->_stop - $this->_start);
            $this->_laps[$key.' '.$this->_count] = self::getLapTime();
            self::start();
            $this->_count++;
        }
    }

    public function getTime() {
        if (!isset($this->_stop)) {
            $this->_stop = Timer::getMicroTime();
        }
        if (!empty($this->_laps)) {
            $this->_laps['Total'] = self::timeToString($this->_lapTotalTime);
            return $this->_laps;
        }
        return self::timeToString();
    }

    // PRIVATE CLASS FUNCTIONS
    private function getLapTime() {
        return self::timeToString();
    }

    private function getMicroTime( ) {
        list($usec, $sec) = explode(' ', microtime());
        return ((float) $usec + (float) $sec);
    }

    private function timeToString($seconds = '') {
        if ($seconds === '') {
            $seconds = ($this->_stop - $this->_start) + $this->_elapsed;
        }
        $seconds = Timer::roundMicroTime($seconds);
        $hours = floor($seconds / (60 * 60));
        $divisor_for_minutes = $seconds % (60 * 60);
        $minutes = floor($divisor_for_minutes / 60);
        return $hours . "h:" . $minutes . "m:" . $seconds . "s";
    }

    private function roundMicroTime($microTime) {
        return round($microTime, 4, PHP_ROUND_HALF_UP);
    }
}

All of my instantiated variables are declared as protected. My reasoning, if I am understanding correctly is because although this Class doesn't extend another class, the other class may extend Timer. Am I on the right track?

Example of Timer use with laps:

$t = new Timer('start');
usleep(3215789);

// Declare a key for the lap array
$t->lap('Sleep');
usleep(4445666);

// No key declaration
$t->lap();
usleep(1000000);

echo "
";
if (is_array($t->getTime())) {
    print_r($t->getTime());
} else {
    echo $t->getTime();
}
echo "
";

Output:

Array
(
    [Sleep 1] => 0h:0m:3.2154s
    [Lap 2] => 0h:0m:4.4462s
    [Total] => 0h:0m:7.6616s
)

Without laps:

$t = new Timer('start');
usleep(3215789);
usleep(1000000);

echo "
";
if (is_array($t->getTime())) {
    print_r($t->getTime());
} else {
    echo $t->getTime();
}
echo "
";

Output:

0h:0m:4.2158s


texts:
As a lone developer I don't really have anyone to peer review my work in-house so I was hoping someone could take a look at this class and tell me in what ways I could improve it.

Essentially what this class does is receive a string from a socket that could possibly have multiple messages in it and isolates these messages based on the message terminator. In the isolate message method, it acquires the number of terminators with split and then loops through and adds the substring to the list of messages. Afterwards it removes that substring from the data string.

Off the top of my head the first opts I spot are using an array based off the terminator count instead of a list and making the terminator string array global so it's not making a new array each time.

internal class MessageHandler
{
    const string m_MessageTerminator = "<|>";
    int m_TerminatorLength = m_MessageTerminator.ToArray().Length;

    internal void ProcessStream(SocketState state)
    {
        ///Extract individual messages from socket message queue.
        ProcessMessages(IsolateMessages(state.MessageQueue.ToString()));

        //Find the last index of the message terminator and remove the substring from the string builder.
        //We do not want to clear the string builder because it could have partial messages inside.
        int lastTerminatorIndex = state.MessageQueue.ToString().LastIndexOf(m_MessageTerminator);
        state.MessageQueue.Remove
            (0, lastTerminatorIndex + m_TerminatorLength);
    }

    internal string[] IsolateMessages(string data)
    {
        List<string> messages = new List<string>();
        string[] terminators = new string[] { m_MessageTerminator };
        int terminatorCount = data.Split(terminators, StringSplitOptions.None).Length -1;

        for(int i = 0; i < terminatorCount; i++)
        {
            //Find The First Instance Of Message Termination
            int terminatorIndex = data.IndexOf(m_MessageTerminator);

            //Extract The Message Based On Terminator's Index
            //Then Remove The Terminator From The Message.
            messages.Add(data.Substring
                (0, terminatorIndex + m_TerminatorLength)
                    .Remove(terminatorIndex, m_TerminatorLength));

            //Remove The Message We Just Extracted From Overall Data Set
            data = data.Remove(0, terminatorIndex + m_TerminatorLength);
        }

        if (messages.Count > 0)
            return messages.ToArray();
        else
            return null;
    }

    internal void ProcessMessages(string[] messages)
    {
        if (messages == null)
            return;

        for(int i = 0; i < messages.Length; i++)
        {
            Console.WriteLine(messages[i]);
        }
    }
}


texts: Peer to Peer GraphQL with Relay over WebSocket

texts:
Here is my Relay Network:
async function fetchQuery(
    operation,
    variables,
) {
    // hash graphql query for unique listener
    const hash = await digestMessage(operation.text);

    // send query to websocket
    doSend(JSON.stringify({
        message: 'request',
        query: operation.text,
        hash,
        variables,
    }));

    // listen on response from WebSocket, events to promise
    return await response({ eventEmitter, hash })
}

Here is my WebSocket listener:
function onMessage (evt: MessageEvent) {
  const payload = JSON.parse(evt.data)

  if (payload.message === 'request') {
    // run graphql query if WebSocket message is a 'request'
    graphql(schema, payload.query).then(result => {
      doSend(
        JSON.stringify({
          message: 'response',
          hash: payload.hash,
          data: result.data
        })
      )
    })
  } else if (payload.message === 'response') {
    // emit local event with results of graphql resolver if WebSocket message is a 'response'
    eventEmitter.emit(payload.hash, { data: payload.data })
  }
}

Design Goals:

GraphQL support with minimal backing services, here just a WebSocket server.
Use client devices, the browser, for persistence instead of a server.

Design Constraints / GraphQL and Relay Goals:

Provide data in a form that is useful to product developers building
a view.
Fetch data more efficiently.
Decouple product code and server logic.

Attempted Approaches:

WAMP: Needs a server for router.
Web-RTC: Needs a WebSocket server for signaling. For a broadcast, each peer needs to connect to all peers without a server or use WebTorrent / DHT
WebSocket in React useEffect: No React reconciliation. No Relay declarative data-fetching.

Work in Progress:

Load balancing: Limiting only one response, and deciding who responds next.
Versioning: If peers have an old schema or resolver logic changes.
Authentication: Verifying OAuth tokens in browser.
Local storage security and risk: Browser now stores credentials, like payment processing tokens, instead of server.
Abuse: Just anyone joins WebSocket and sends out bad data.

Feedback welcome. I looked for similar projects and found a lack of references.


texts:
The query below is quite slow (taking about half a second). Any obvious things I could improve?

The PRICES table has about 21 million rows and 30 columns while CONTRACTS has 130 k rows and 10 columns.

SELECT
 CONTRACTS.EXT_ID,
 PRICES.REFERENCE_DATE,
 PRICES.PRICE_DATE,
 CONTRACTS.PERIOD,
 PRICES.TIME_TO_MATURITY,
 PRICES.CLOSE_PRICE,
 PRICES.ORIGINAL_PRICE_ID
FROM
 PRICES INNER JOIN CONTRACTS ON PRICES.CONTRACT_ID = CONTRACTS.ID
WHERE
 (((CONTRACTS.EXT_ID)=@CONTRACTID)
 AND ((PRICES.REFERENCE_DATE)=@REFDATE)
 AND ((PRICES.STATUS_TYPE) LIKE 'CAL%'));


texts:
Quick disclaimer. I've programmed Java for years but this is the first Objective C I've ever written.
I've written some code which almost unfortunately works but frankly hurts my eyes with the number of lines of code and quality. Basically looking for the right way to convert the original string:
<TUHandle 0x280479f50 type=PhoneNumber, value=07700000000, normalizedValue=(null), isoCountryCode=(null)>

Into JSON (ignoring the TUHandle 0x280479f50) part which I don't need:
{"value": "07700000000",
"normalizedValue": "(null)",
"type": "PhoneNumber",
"isoCountryCode": "(null)"}

Line breaks and indents are NOT important, only that this is valid JSON
        //Format of string
        //<TUHandle 0x280479f50 type=PhoneNumber, value=07700000000, normalizedValue=(null), isoCountryCode=(null)>
        NSString *original = [NSString stringWithFormat:@"%@", hand];

        //Trim off unused stuff
        NSRange startKeyValues = [original rangeOfString:@"type="];
        NSRange endKeyValues = [original rangeOfString:@">"];
        NSRange rangeOfString = NSMakeRange(startKeyValues.location, endKeyValues.location - startKeyValues.location);
        NSString *keysValues = [original substringWithRange:rangeOfString];

        //Create a dictionary to hold the key values
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];

        //Split the keysValuesstring
        NSArray *items = [keysValues componentsSeparatedByString:@","];

        for (NSString* o in items)
        {
            //Create key value pairs
            NSArray *item = [o componentsSeparatedByString:@"="];
            NSString *key=[item objectAtIndex:0];
            NSString *value=[item objectAtIndex:1];
            [dict setObject:value forKey:key];
        }

        [dict setObject:currentUUID forKey:@"uid"];

        //Convert to Json Object
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];

Any tips which would make this look a hell of a lot less clunky?


texts: Splitting payments in a number of installments

texts:
I was reviewing today some code which gets as input a list of payments (paymentList) and a list of installments (installmentList) has to populate two other lists, respectively depositList and balanceList.

Basically it calculates the sum of all payments from paymentList and fills depositList with the amount enough to let each specific installment be payed.

If the sum of all payments is less then the total of installments it fills as many installments as it can and then sets the balanceList with the amount which is missing.

To make this clearer this is the output:

paymentList    : 1200, 1000, 400,
installmentList: 1200, 1200, 1200, 900,
depositList    : 1200, 1200, 200, 0,
balanceList    : 0, 0, -1000, -1900,

if I made a total of 3 payments for 2600$, and I had to pay 4 installments, I would be able to pay the first two completely (with balance 0) and the third only with 200$ still having to pay 1000$, and the last installment would be completely missed for a total debt of 1900$.

Seems easy enough however the code which does it stinks to me, here is a simplified version:

public class Payment
{

    public static void main(String[] args)
    {
        ArrayList<Integer> paymentList = new ArrayList<Integer>()
        {
            {
                add(1200);
                add(1000);
                add(400);
            }
        };

        ArrayList<Integer> installmentList = new ArrayList<Integer>()
        {
            {
                add(1200);
                add(1200);
                add(1200);
                add(900);
            }
        };

        printArray("paymentList    ", paymentList);
        printArray("installmentList", installmentList);

        ArrayList<Integer> depositList = new ArrayList();
        ArrayList<Integer> balanceList = new ArrayList();

        Integer settledTotalAmount = 0;
        for (Integer i : paymentList)
        {
            settledTotalAmount += i;
        }

        for (Integer currentInstallmentAmount : installmentList)
        {
            Integer settledAmount = 0;
            if (settledTotalAmount > 0)
            {
                int tmpAmount = settledTotalAmount - currentInstallmentAmount;
                if (tmpAmount > 0)
                {
                    settledAmount = currentInstallmentAmount;
                    settledTotalAmount = tmpAmount;
                    balanceList.add(0);
                }
                else
                {
                    settledAmount = currentInstallmentAmount+(tmpAmount);
                    settledTotalAmount = (currentInstallmentAmount-settledAmount)*-1;
                    balanceList.add((currentInstallmentAmount-settledAmount)*-1);
                }
            }
            else
            {
                settledAmount = 0;
                int k = (settledTotalAmount * -1)+currentInstallmentAmount;
                settledTotalAmount = k*-1;
                balanceList.add(settledTotalAmount);
            }
            depositList.add(settledAmount);
        }

        printArray("depositList    ", depositList);
        printArray("balanceList    ", balanceList);

    }

    public static void printArray(String name, ArrayList<Integer> array)
    {
        System.out.print(name + ": ");
        for (Integer i : array)
        {
            System.out.print(i + ", ");
        }
        System.out.println();
    }
}

in particular the series of if else switches seems redundant to me, is there something cleaner for the above (which seems to work for now)?
The version above actually is a simplified version, the original one I have uses BigDecimal and is even messier than that.


texts: Order of evaluation of function arguments

texts:
From SICP:

  Exercise 3.8

  When we defined the
  evaluation model in section 1.1.3, we
  said that the first step in evaluating
  an expression is to evaluate its
  subexpressions. But we never specified
  the order in which the subexpressions
  should be evaluated (e.g., left to
  right or right to left). When we
  introduce assignment, the order in
  which the arguments to a procedure are
  evaluated can make a difference to the
  result. Define a simple procedure f
  such that evaluating (+ (f 0) (f 1))
  will return 0 if the arguments to +
  are evaluated from left to right but
  will return 1 if the arguments are
  evaluated from right to left.

I wrote this solution:

(define it false)
(define (f x)
  (if it
      it
      (begin (set! it (/ x 2)) it)))

(+ (f 1) (f 0))

Is there a better way?


texts: Percentage of questions that are unanswered or answered - Part 2

texts:
I've refactored my previous query and added better checks when selecting the data. The query link can be found here. The formulas used to calculate the two percentages are the same, and can be seen below:

$$
\text{Answered Percentage} = 100 - \left(\frac{\text{Unanswered}}{\text{Answered}} \times 100\right) \\
\text{Unanswered Percentage} = \frac{\text{Unanswered}}{\text{Answered}} \times 100
$$

Finally, here's the source.

DECLARE @TotalQuestions FLOAT = (
  SELECT COUNT(*) FROM Posts WHERE
        PostTypeId = 1
    AND ClosedDate IS NULL
);

DECLARE @UnansweredQuestions FLOAT = (
  SELECT COUNT(*)
    FROM Posts AS TopPostsQuery WHERE (
            ClosedDate IS NULL
        AND PostTypeId = 1
        AND AnswerCount = 0
      )
      OR (
            ClosedDate IS NULL
        AND PostTypeId = 1
        AND AnswerCount <= 1
        AND AcceptedAnswerId IS NULL
        AND (
          SELECT Score FROM Posts AS SubPostsQuery WHERE
                PostTypeId <> 1
            AND ParentId = TopPostsQuery.Id
        ) <= 0
      )
);

DECLARE @AnsweredPercentage FLOAT =
  100.0 - ((@UnansweredQuestions / @TotalQuestions) * 100.0);

DECLARE @UnansweredPercentage FLOAT =
  (@UnansweredQuestions / @TotalQuestions) * 100.0;

SELECT
    [Percentage Of Answered Questions]   = @AnsweredPercentage
  , [Percentage Of Unanswered Questions] = @UnansweredPercentage;


texts:
I am working on the lossy 16 bit representation for 32 bit integers that catches all 32 bit range with precision depending on absolute value.

My idea is to store integer lv = sign(x)*ilog2(x) in first bite, and a tail that approximates the error x - 2^ilog2(x).  In order to do that I divide possible error values in 256 bins and store the index of the bin.

To reconstruction of the integer value, I calculate sign(lv) * (2^lv) + bin_size * tail.

I have initial implementation for that, but my code have several problems.

It is not as clear as I'd like to.
short_int32_t(x) should be equal to -short_int32_t(-x) but it is not.  I am pretty sure that it is possible to achieve it, but I am not sure how to do it not making code more ugly.
Any performance suggestions welcome.

Look at functions void set(int32_t) and int32_t get():

template <typename T>
int32_t signum(T x) {
    return (T(0) < x) - (x < T(0));
}

inline int8_t signum_log2(int32_t x) {
    int8_t log2 = static_cast<int8_t>(8 * sizeof(int32_t) - __builtin_clz(abs(x)) - 1);
    static_assert(8 * sizeof(int32_t) == __builtin_clz(1) + 1, "log is wrong");
    return log2 * signum(x);
}

inline int8_t abs_log2(int32_t x) {
    static_assert(8 * sizeof(int32_t) == __builtin_clz(1) + 1, "log is wrong");
    return static_cast<int8_t>(8 * sizeof(int32_t) - __builtin_clz(abs(x)) - 1);
}

class short_int32_t {
public:
    short_int32_t(int32_t x) {
        set(x);
    }

    void operator=(int32_t x) {
        set(x);
    }

    bool operator<(short_int32_t x) {
        return m_log == x.m_log ? (signum(m_log) * m_tail < signum(x.m_log) * x.m_tail) : (m_log < x.m_log);
    }

    short_int32_t operator*(short_int32_t x) {
        return short_int32_t(get() * x.get());
    }

    short_int32_t operator+(short_int32_t x) {
        return short_int32_t(get() + x.get());
    }

    short_int32_t operator-(short_int32_t x) {
        return short_int32_t(get() - x.get());
    }

    short_int32_t operator*(int32_t x) {
        return short_int32_t(get() * x);
    }

    short_int32_t operator+(int32_t x) {
        return short_int32_t(get() + x);
    }

    short_int32_t operator-(int32_t x) {
        return short_int32_t(get() - x);
    }

    void set(int32_t x) {
        if (x == 0) {
            m_log = 0;
            m_tail = 0;
            return;
        }

        int8_t abs_log = abs_log2(x);
        int32_t interval = abs_log ? 1 << abs_log : 0;
        if (interval == abs(x)) {
            m_log = x < 0 ? -abs_log : abs_log;
            m_tail = 0;
            return;
        }

        int32_t bin_size = interval < 512 ? 1 : (x < 0 ? (interval >> 9) : (interval >> 8));

        m_log = x > 0 ? abs_log : -abs_log - 1;
        int32_t tail = x > 0 ? x - interval : ((1 << -m_log) + x);

        m_tail = tail / bin_size;
    }

    int32_t get() const {
        int32_t interval = 1 << abs(m_log);
        int32_t bin_size = interval < 512 ? 1 : (m_log < 0 ? (interval >> 9) : (interval >> 8));

        return signum(m_log) * interval + static_cast<int32_t>(m_tail) * bin_size;
    }

public:
    int8_t m_log;
    uint8_t m_tail;
};

short_int32_t operator*(int32_t x, short_int32_t y) {
    return y * x;
}

short_int32_t operator+(int32_t x, short_int32_t y) {
    return y + x;
}

short_int32_t operator-(int32_t x, short_int32_t y) {
    return short_int32_t(x - y.get());
}


texts: Refactoring Logger interface to open and close logs

texts:
I asked a question about an implementation of a logger using syslog and error_log as fallback that made me re-evaluate my Logger interface.  Before it simply forced a log($timestamp, $message) to be implemented but after reading over the answer to the question I'm not sure that this is the best API possible to work with all the different logging options available.

Here's my new interface that allows logs to be opened and closed.

<?php

/**
 * @file
 * @brief Holds the interface to be implemented by objects responsible for logging
 * messages and data.
 */

namespace SprayFire\Logger;

interface Logger {

    /**
     * @brief We have left the parameters for this method blank on purpose; the
     * implementations should be responsible for passing the appropriate arguments.
     *
     * @details
     * It should be noted that if your implementation defines the method signature
     * with parameters you may assign a default value to that parameter and your
     * implementation will satisfy this method signature.
     *
     * @return true if log opened, false if didn't
     */
    public function openLog();

    /**
     * @param $timestamp the timestamp for the given message
     * @param $message The string message that should be appended to the end
     *        of the log
     * @return true if the message was logged, false if it didn't
     */
    public function log($timestamp, $message);

    /**
     * @return true if the log was closed, false if it didn't.
     */
    public function closeLog();

}

My problem is keeping the interface generic enough while allowing the various different options needed in opening a log to be satisfied.  For example, NullLogger wouldn't really need any parameters passed to openLog() where as SysLogLogger would probably need some parameters passed.  How would I accomplish this?

What I'm thinking now

That parameters will be passed as variable arguments to the function and the implementation uses func_get_args() to retrieve the necessary information to open the log, if necessary.

Alternatively, the implementation could simply define the parameters needed and ensure there are default values for all parameters.  This would ultimately supply the needs of the interface while still communicating to the user that parameters are needed.

What I could be doing

I could declare the parameter passed to openLog() as an array that holds the appropriate option information.  This means though that I would need to create an array for every Logger, whether it is needed or not.  I'm not one to micro-optimize but at the same time I don't want to be creating unused/needless resources.

I could declare the three parameters passed to openlog in Logger::openLog, and then declare default values for those in the method signature signaling that you could simply not provide these arguments.  But, this really doesn't "feel" right, you'd also be signaling to the user that you could pass arguments to say, NullLogger, that might actually influence the way the implementation works and it really wouldn't.

I'm not sure what would be the best solution here and would appreciate any feedback on the interface's API and the solutions proposed.


texts: Reduce duplication while accessing Visual Studio services

texts:
If you write a VS extension, you can get access to VS services with the IServiceProvider interface:

var vsUIShell = (IVsUIShell)serviceProvider.GetService(typeof(SVsVsUIShell));
vsUIShell.SetWaitCursor(); // for example

To reduce duplication every time I need this, I created a class like this:

static class VisualStudioServices
{
    public static IVsUIShell UIShell { get { return vsUIShell.Service; } }
    static readonly LazyService<SVsUIShell, IVsUIShell> vsUIShell = new LazyService<SVsUIShell, IVsUIShell>();

    class LazyService<TService, T>
    {
        static T GetService()
        {
            return (T)ServiceProvider.GlobalProvider.GetService(typeof(TService));
        }

        readonly Lazy<T> serviceLazy = new Lazy<T>(GetService);

        public T Service { get { return this.serviceLazy.Value; } }
    }
}

To add a new service to the list, I have to mention its name 8 time (assuming the Service type and the interface type are the same, which is not always true).

I'm looking for a way to reduce this duplication further. Any suggestions?


texts:
I'm pretty new to this so constructive criticism is acceptable. I'm trying to find any way I can improve this system, all it does is take a string, determine if that string is a web address or a file location, if its a web address, it will download the elements, if file then it loads the elements.

Pretty simple stuff, but is there any way I can improve here?

public class JsonConfigProvider : IConfigProvider
{
    private readonly ILogger _logger;
    private IDictionary<string, string> _elements;

    public JsonConfigProvider(
        ILogger logger,
        IDictionary<string, string> elements)
    {
        _logger = logger;
        _elements = elements;
    }

    public void Load(string fileLocation, WebClient webClient = null)
    {
        try
        {
            _elements = Uri.TryCreate(fileLocation, UriKind.Absolute, out var uri) ? DownloadElements(uri, webClient) : LoadElements(fileLocation);
        }
        catch (WebException)
        {
            _logger.Error($"Failed to download the config from web address: {fileLocation}");
        }
        catch (FileNotFoundException)
        {
            _logger.Error($"Failed to load config from file: {fileLocation}");
        }
        catch (Exception)
        {
            _logger.Error("Something went wrong, we couldn't load the config file.");
        }
    }

    private static IDictionary<string, string> DownloadElements(Uri uri, WebClient webClient)
    {
        if (webClient == null)
        {
            throw new WebException("webClient is null.");
        }

        var content = webClient.DownloadString(uri);
        return JObject.Parse(content).ToFlatDictionary(content);
    }

    private static IDictionary<string, string> LoadElements(string configFile)
    {
        var content = File.ReadAllText(configFile);
        return JObject.Parse(content).ToFlatDictionary(content);
    }

    public string this[string key] => _elements[key];

    public void Set(string key, string value, bool updateFile)
    {
        _elements[key] = value;
    }
}

Not really needed, but here is the ToFlatDictionary method.

public static Dictionary<string, string> ToFlatDictionary(this JToken token, string path = null)
{
    switch (token.Type)
    {
        case JTokenType.Object:
            return token.Children<JProperty>()
                .SelectMany(x => x.Value.ToFlatDictionary(x.Name))
                .ToDictionary(x => path == null ? x.Key : string.Join(".", path, x.Key), x => x.Value);

        case JTokenType.Array:
            return token
                .SelectMany((x, i) => x.ToFlatDictionary(i.ToString()))
                .ToDictionary(x => path == null ? x.Key : string.Join(".", path, x.Key), x => x.Value);

        default:
            return new Dictionary<string, string>
            {
                [path] = ((JValue)token).Value.ToString()
            };
    }
}


texts: Image loader/writer design (no API, pure C++ on Windows)

texts:
I have an image loader, now only for bitmaps. I'm a little confused because I want to split my code to different classes, one for writing a BMP data to a file (WRITER), one for loading BMP data from file, or from pre-generated dataset (1) and storing it in its private members.( (1) like a noise function saved to an array).

Currently I have the 2 class for this. The header:

namespace PND
{

    inline void out(const ::std::string); //standard output log
    inline void err(const ::std::string); //error log

    bool file_exists(::std::string m_filename) //this could be used in both classes
    {
        ::std::ifstream infile(m_filename+".bmp");
        return infile.good();
    }

    class BMP
    {
    public:
        BMP();
        BMP(const BMP&);//copy csrt
        ~BMP();
        BMP& operator= (BMP other); //ass. operator

        bool loadData(::std::string filename);//from file, filename is the file's filename
        bool loadData(::std::string filename,const int width, const int height, const unsigned char* data, const unsigned int length);//from array, filename is user defined
        //they are simple pixel data accessors with out of bounds handling
        unsigned char getData_B(const unsigned int x, const unsigned int y);
        unsigned char getData_G(const unsigned int x, const unsigned int y);
        unsigned char getData_R(const unsigned int x, const unsigned int y);

        unsigned int* getSize() { return m_size; }; //some getter
        ::std::string getName() { return m_filename; };

    private:

        void swap(BMP& other);
        void freeData();
            //the bitmap data:
        BITMAPINFOHEADER m_infoheader;
        BITMAPFILEHEADER m_fileheader;
        ::std::string m_filename;
        unsigned char* m_data;
        unsigned int m_size[2];
        long __m_size; //it is the length of the m_data array (num of pixels * 3)
    };

    class WRITER
    {
    public:
        bool writeData(::std::string filename, const int width, const int height, const unsigned char* data, const unsigned int length);
        bool writeData(::std::string filename, const BMP& bmp);//now this is the problem, more info below the code

    private:
        ::std::ofstream outstream;

        bool openFile(::std::string filename);
        bool writeHeader(const int width,const int height);
        bool writeFile(const unsigned char* data, const unsigned int length);
        bool closeStream();
    };
}

I'm in trouble because I would like to access (read only) the bitmap data (headers, pixel data) from the image - that was saved to a BMP object - in the WRITER class. But because they are private members I can not access them in the writeheader() and writefile() functions. It would be nice to access them without making them public members, and I also try to avoid using inheritance in this case since a WRITER is not really a BMP. Lots of gettersare also not the best way for accessing arrays I think.

So the BMP could only load and save the image data. And with a WRITER I can write this data to a .bmp file. I want to make a pretty clean interface with public functions, and do not mix classes if not neccessary.


texts: Move all zeros to the left with TDD approach

texts:
The task

  Given an integer array, move all elements that are equal to 0 to the
  left while maintaining the order of other elements in the array. Let's
  look at the following integer array.

  After moving all zero elements to the left, the array should look like
  this. We need to maintain the order of non-zero elements.

0 0 0 1 10 20 59 63 88

My approach, I used TDD and hoped my solution would become just as good as the sample solution.

test('contains no element', () => {
  expect(moveZeroToLeft([])).toStrictEqual(undefined);
});

test('contains only a 0 element', () => {
  expect(moveZeroToLeft([0])).toStrictEqual([0]);
});

test('contains only a non 0 element', () => {
  expect(moveZeroToLeft([1])).toStrictEqual([1]);
});

test('contains more than one element with a 0', () => {
  expect(moveZeroToLeft([1, 0])).toStrictEqual([0, 1]);
});

test('contains more than one element without 0', () => {
  expect(moveZeroToLeft([1, 3])).toStrictEqual([1, 3]);
});

test('contains more than one element with a 0 somewhere in the middle', () => {
  expect(moveZeroToLeft([1, 0, 3])).toStrictEqual([0, 1, 3]);
});

test('contains random number of zeros and non-zero elements', () => {
  expect(moveZeroToLeft([1, 0, 3, 0, 0, 44, 1, 0, 2])).toStrictEqual([0, 0, 0, 0, 1, 3, 44, 1, 2]);
});

My solution

function moveZeroToLeft(arr) {
  if (arr.length < 2) {
    return arr;
  }
  if (arr.some(x => x === 0)) {
    let zeroCounter = 0;
    const res = arr.filter(el => {
      if (el !== 0) {
        return true;
      }
      zeroCounter++;
    });
    const leadingZeros = Array(zeroCounter).fill(0);
    return leadingZeros.concat(res);
  }
  return arr;
}

But the sample solution is much more elegant than mine:

let move_zeros_to_left = function(A) {
  if (A.length < 1) {
    return;
  }

  let lengthA = A.length;
  let write_index = lengthA - 1;
  let read_index = lengthA - 1;

  while (read_index >= 0) {
    if (A[read_index] != 0) {
      A[write_index] = A[read_index];
      write_index--;
    }

    read_index--;
  }

  while (write_index >= 0) {
    A[write_index] = 0;
    write_index--;
  }
};

How could I have come to the sample solution with a TDD approach?


texts:
Design a Tips class that calculates the gratuity on a restaurant meal.

  Its only class member variable, taxRate, should be set by a
  one-parameter constructor to whatever rate is passed to it when a Tips
  object is created. If no argument is passed, a default tax rate of
  .065 should be used.

  The class should have just one public function, computeTip. This
  function needs to accept two arguments, the total bill amount and the
  tip rate. It should use this information to compute what the cost of
  the meal was before the tax was added. It should then apply the tip
  rate to just the meal cost portion of the bill to compute and return
  the tip amount.

  Demonstrate the class by creating a program that creates a single Tips
  object, and then allows the program user to retrieve the correct tip
  amount using various bill totals and desired tip rates.

What can I do better?

#include<iostream>
#include <string>

using namespace std;

class Tips
{
       private :
           double taxRate;

       public:
          Tips()
          {
                taxRate = .65;
                cout << "Tax rate is "<<taxRate<<endl;
          }

          Tips(double tax)
          {
                     taxRate = tax;
                     cout << "Tax rate is"<<taxRate<<endl;
          }

          double computeTip(double billAmount,double tipRate)
          {
                double mealCost = billAmount - billAmount*(taxRate);

                cout << "Meal cost is with no tax "<<mealCost<<endl;
                return mealCost+tipRate;
          }
};

int main()
{
    Tips tip ;
    cout << "Meal cost + tip rate is "<<tip.computeTip(100,20)<<endl;

    return 0;
}


texts:
I wrote a function to decode GSM 7-Bit encoded messages as defined in the 3GPP standard. Example available here. I found a tool to help me check my answers here. I used the charset from here.

public String decode(final byte[] data) {
    if (data == null) {
        return null;
    }

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    for (int i = 0, counter = 0; i < data.length; i++, counter++) {
        final byte current = data[i];
        final byte previous = i == 0 ? 0 : data[i - 1];

        if (counter == 7) {
            counter = 0;
        }

        final int shiftedCurrent = (current << counter) & 0x7F;
        final int shiftedPrevious = (previous & 0xFF) >> (8 - counter);
        bos.write(shiftedCurrent | shiftedPrevious);

        if (counter == 6) {
            bos.write((current & 0xFF) >> 1);
        }
    }

    try {
        final String result = bos.toString("X-Gsm7Bit");
        return result.endsWith("\r") ? result.substring(0, result.length() - 1) : result;
    } catch (final UnsupportedEncodingException e) {
        throw new AsnDecodeException("Cannot get charset: X-Gsm7Bit");
    }
}

Tests:

@Test
public void decodeTests() throws DecoderException {
    assertThat(decode(Hex.decodeHex("f4f29c9e769f1b".toCharArray()))).isEqualTo("testing");
    assertThat(decode(Hex.decodeHex("31D98C56B3DD70".toCharArray()))).isEqualTo("12345678");
    assertThat(decode(Hex.decodeHex("6176D94DAFCB1B".toCharArray()))).isEqualTo("alentur");
    assertThat(decode(Hex.decodeHex("61F79B8E2ECB5B657CB80D679701E77638CD768DDF6D".toCharArray()))).isEqualTo("another-example@gmail.com");
}

I feel like I could have done this with fewer shifts or & checks, but the thing I really don't like is my counter variable that I reset at 7. Any advice on how to improve this code?


texts: Convert international datestring to ISO-format

texts:
The function below takes a datestring in the form d-mmm-yyyy and converts it to ISO date format (yyyy-mm-dd). Delimiters may be hyphen, space or /,  and Dutch or English month abbreviations may be used.

Now, I know there is dateutil, but it returns unknown string format if you try to parse something with a non-English month in it. I haven't digested all its documentation, but I think dateutil is mainly intended for date calculation. I'm not doing that, I'm just cleaning up user input.

So I wrote my own.

import re
.
.

def ISOdate(date):
    '''
        converts the following date string format to ISO (yyyy-mm-dd):
        28-okt-1924 (dutch month abbreviations)
        28 oct 1924 (english..)
         9/nov/2012 (single digit)
    '''

    shortmonths = [
        'jan', 'feb', 'mrt', 'apr', 'mei', 'jun',
        'jul', 'aug', 'sep', 'okt', 'nov', 'dec',
        'jan', 'feb', 'mar', 'apr', 'may', 'jun',
        'jul', 'aug', 'sep', 'oct', 'nov', 'dec'
        ]

    # Month abbrevs are only different march, may and october.

    pat = r'(\d{1,2})\s?[-\/]?\s?(\w{3})\s?[-\/]?\s?(\d{4})'

    q = re.match(pat, date)
    if q:
        year = q.group(3)
        day = int(q.group(1))
        month = shortmonths.index(q.group(2).lower()) % 12 + 1
        return u'{}-{:02d}-{:02d}'.format(year, month, day)
    else:
        # just return input, date fields may be empty
        return date

The regex match parses date month and year may not be pretty, but it works and it's easy to expand for other patterns. Likewise for the month number lookup with index, which is more concise than a chain of if, elif to match month strings to numbers.

Instead of the code between if q: and else:, I also had this, which uses datetime:

year = int(q.group(3))
day = int(q.group(1))
month = shortmonths.index(q.group(2).lower()) % 12 + 1
d = datetime.datetime(year, month, day)
return u'{:%YY-%m-%d}'.format(d)

This works too, but I think the first version is more to-the-point.

I'm always striving for optimal Pythonicness, but I'm by no means a seasoned coder.

Please comment.


texts: LinQ wrapper to get distinct items from a IEnumerable based on a function of item

texts:
I often need to perform LinQ queries to get distinct items from a IEnumerable based on one of its properties. I would like to know if this is a good way to wrap this operation:

<Extension()> Function DistinctOn(Of T)(iet As IEnumerable(Of T),
                                        identity_property As Func(Of T, Object)
                                       ) As IEnumerable(Of T)
    Return iet.GroupBy(identity_property).Select(Function(g) g.First)
End Function

Using example (pastas is a IEnumerable of Newtonsoft.Json.Linq.JObject):

Dim dpastas = pastas.DistinctOn(Function(jo) jo.Value(Of Integer)("id")).ToArray

It works Ok, but I'd like to know if it is good code also. Thank you very much!


texts: Macro to run code once during the lifetime of the program

texts:
I'm using this little macro a lot:

#define RUN_ONCE(runcode) \
{ \
    static bool code_ran = 0; \
    if(!code_ran){ \
        code_ran = 1; \
        runcode; \
    } \
}

I find it useful when I want to initialize stuff just once when I don't really care about performance (for example, if it's inside a render loop, it takes just 60 if's per sec).  In a random generator, I can do RUN_ONCE(init_random()), so I don't need to separately initialize it, which prevents me from crashing when I call the function without initializing it first.

I'd like to know if any of you use a similar system, and if there's better way of doing this. Or if I should stop using this method immediately...


texts:
This is some code that I found in a project I work on. Please tell me that I am crazy and that this code is good. Please do.

public class ExceptionHandlingHelper
{
    static IExeptionHandlerProvider _exeptionHandlerProvider = null;
    static IExeptionHandlerProvider ExeptionHandlerProvider
    {
        get
        {
            if (_exeptionHandlerProvider == null)
            {
                Assembly clientLib = Assembly.Load("Bla.BlaDiBla");
                Type type = clientLib.GetType("Bla.BlaDiBla.Controls.ExeptionHandlerProvider");
                _exeptionHandlerProvider = (IExeptionHandlerProvider)Activator.CreateInstance(type);
            }
            return _exeptionHandlerProvider;
        }
    }

    public static void HandleException(FaultException<DefaultFaultContract> fault)
    {
        var message = new StringBuilder();
        var detail = new StringBuilder();

        ExeptionHandlerProvider.GetMessage(fault, message, detail);

        if (!string.IsNullOrWhiteSpace(fault.Detail.FullStack))
        {
            detail.AppendLine();
            detail.AppendLine(fault.Detail.FullStack);
        }

        if (!string.IsNullOrWhiteSpace(fault.Detail.InnerExceptionStack))
        {
            detail.AppendLine();
            detail.AppendLine("Inner Exception Stack");
            detail.AppendLine(fault.Detail.InnerExceptionMessage);
            detail.AppendLine(fault.Detail.InnerExceptionSource);
            detail.AppendLine(fault.Detail.InnerExceptionStack);
        }

        Handle(message.ToString(), detail.ToString());
    }

    ...
}

Used like this:

        string serverName = GetServerName();
        using (var factory = new ChannelFactory<T>(GetBinding(TransportType), GetEndPointAddressForClient(typeof(T), TransportType, serverName)))
        {
            var client = GetChannel(factory);
            try
            {
                using (var op = new OperationContextScope(client as IContextChannel))
                {
                    OperationContext.Current.OutgoingMessageHeaders.Add(GetCachedHeader());
                    action(client);
                    ((IClientChannel)client).Close();
                }
            }
            catch (FaultException<DefaultFaultContract> ex)
            {
                ((IClientChannel)client).Abort();
                factory.Abort();
                ExceptionHandlingHelper.HandleException(ex);
            }
            catch (FaultException ex)
            {
                ((IClientChannel)client).Abort();
                factory.Abort();
                ExceptionHandlingHelper.HandleException(ex);
            }
            catch (Exception ex)
            {
                ((IClientChannel)client).Abort();
                factory.Abort();
                ExceptionHandlingHelper.HandleException(ex);
            }
        }


texts: Higher Order Functions in VBA, the dirty way

texts:
I have been building a small library of VBA functions.  I have a small section with higher order functions that I'd like to share.  It uses strings as delegates/function pointers and Application.Run to actually call the functions.

This isn't by any means a true implementation; just a quick and dirty implementation without connecting external libraries or creating objects for every function.  I haven't found real drawbacks yet. Application.Run always passes arguments by value, which would be a draw back, but is desirable in all of these implementations.  Also not being able to declare lambdas is a buzz-kill.

Public Sub Map(ByVal delegate As String, ByRef sequence As Variant)

    Dim i As Long
    For i = LBound(sequence) To UBound(sequence)

        sequence(i) = Application.Run(delegate, sequence(i))

    Next i

End Sub
Public Function Mapped(ByVal delegate As String, ByVal sequence As Variant) As Variant

    Mapped = sequence
    Map delegate, Mapped

End Function
Public Function Fold(ByVal delegate As String, ByVal sequence As Variant, _
                     ByVal initial_value As Variant) As Variant

    Fold = initial_value

    Dim el As Variant
    For Each el In sequence

        Fold = Application.Run(delegate, Fold, el)

    Next el

End Function
Public Function Reduce(ByVal delegate As String, ByVal sequence As Variant) As Variant

    ' Head and Tail return the first element and the rest, respectively.
    Reduce = Fold(delegate, Tail(sequence), Head(sequence))

End Function
Public Function Compose(ByVal delegates As Variant, ByVal initial_value As Variant) As Variant

    Compose = initial_value

    Dim delegate As Variant
    For Each delegate In delegates

        Compose = Application.Run(delegate, Compose)

    Next delegate

End Function


texts: Efficient way to extract the first row in a Group By group

texts:
I have a large Sql Server view with this schema:

[archive_ID] (int, not null)
[archive_date] (datetime, not null)
[archdata_path_ID] (varchar(50), not null)
[archdata_value] (int not null)

I need to group the records by the Date, and I need to extract just the first record for each group.

This is the current query:

WITH cte
AS (
        SELECT *
               ,CAST(archive_date AS DATE) AS C
               ,ROW_NUMBER() OVER (
                       PARTITION BY CAST(archive_date AS DATE) ORDER BY CAST(archive_date AS DATE) ASC
                       ) AS ad
        FROM ArchiveData
        WHERE archdata_path_ID = @PathID
        )
SELECT DISTINCT C
        ,archdata_value AS val
FROM cte
WHERE ad = 1
ORDER BY C ASC

The main problem is to improve the readability.
Would be great to optimize also the performance, but it's not mandatory.


texts:
I'm developing an app which stores some different user settings in app.config such as connection strings, paths for saving reports, default printer e.t.c
For retrieving them I made a static class StoredSettingsTools which contains an Enum of settings types and a public method which calls (depending of setting type) some private method and get the settings from app.config:

public static class StoredSettingsTools
{

    public enum StoredSettingsType
    {
        DBConnection,
        Printer,
        ReportsFolder
    };

    private static ConnectionStringsSection GetConfigurationConnectionStringsSection()
    {
        ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
        Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
        ConnectionStringsSection conectionSettings = (ConnectionStringsSection)config.SectionGroups.Get("UserSettingsGroup")
            .SectionGroups.Get("StoredConnectionSettings")
            .Sections.Get("defaultConnectionString");
        return conectionSettings;
    }

    private static Hashtable GetConfigurationPrinterSection()
    {
        ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
        Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
        ConfigurationSectionGroup userSettingsGroup = config.SectionGroups["UserSettingsGroup"];
        Hashtable sectionSettings = ConfigurationManager.GetSection(userSettingsGroup.Sections.Get("printerSettings").SectionInformation.SectionName) as Hashtable;
        return sectionSettings;
    }

    private static Hashtable GetConfigurationReportsFolderSection()
    {
        ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
        Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
        ConfigurationSectionGroup userSettingsGroup = config.SectionGroups["UserSettingsGroup"];
        Hashtable sectionSettings = ConfigurationManager.GetSection(userSettingsGroup.Sections.Get("reportsFolderSettings").SectionInformation.SectionName) as Hashtable;
        return sectionSettings;
    }

    public static Hashtable GetStoredSettings(StoredSettingsType sectionType)
    {
        Hashtable table = new Hashtable();
        switch (sectionType)
        {
            case StoredSettingsType.DBConnection:
                {
                    ConfigurationSection section = GetConfigurationConnectionStringsSection();
                    ConnectionStringSettingsCollection col = ((ConnectionStringsSection)section).ConnectionStrings;

                    foreach (ConnectionStringSettings settings in col)
                    {
                        table.Add(settings.Name, settings.ConnectionString);
                    }

                    return table;
                }
            case StoredSettingsType.Printer:
                {
                    table = GetConfigurationPrinterSection();
                    return table;
                }

            case StoredSettingsType.ReportsFolder:
                {
                    table = GetConfigurationReportsFolderSection();
                    return table;
                }

        }
        return null;
    }
}

Is anything wrong with this code? Could it be more object-oriented?


texts: Insert a number in a sorted list and return the list with the number at the correct index

texts:
I feel like the title is a bit wordy. What I have defined here is a function that takes two parameters:

a list that contains valued sorted from smallest to biggest
a number to insert at the right index so that the returned list print its values from smallest to biggest

NOTE: Recursion is mandatory

def insert(lst, to_insert):
    """
    parameters : lst of type list, that contains values sorted from smallest to largest;
                 to_insert : represents a value
    returns : same list with the to_insert value positioned at the right index
              in order for the list to remain sorted from smallest to largest;
    """
    if len(lst) == 1:
        return []
    if lst[0] < to_insert and to_insert < lst[1]:
        lst[3] = to_insert
        return [lst[0]] + [lst[3]] + insert(lst[1:], to_insert)
    else:
        return [lst[0]] + insert(lst[1:], to_insert)

print(insert([1,2,3,4,5,7,8,9], 6))

The list outputs the following :

[1,2,3,4,5,6,7,8]   #not sure where 9 got left

How do I optimize this function, using only simple functions.


texts:
I'm trying to get some confidence with RXJS and FRP. This code handles file sharing via socket.io. I need some advice about general RXJS style and reactive programming.

io.sockets.on('connection', function (socket) {
  var msgStream = Rx.Observable.fromEvent(socket, 'message');
  msgStream.filter(function(x) {
    return x.type === 'get';
  }).do(function() {
    socket.send({type: 'start'});
  }).do(function() {
    msgStream.filter(function (x) { return x.type === 'next'; })
      .zip(
        RxNode.fromReadableStream(
          fs.createReadStream('file.mpg')
        ),
        function(a, b) {·
          return [a, b];
        }
      )
      .pluck('1')
      .do(function(data) {
        socket.send({type: 'chunk', data: data});
      }).subscribe(undefined, undefined, function() {
        socket.send({type: 'end'});
      });
  }).subscribe();
});


texts: Checking if a line in a file contains user.Handle and '-r'+any single digit number

texts:
The title pretty much explains everything. I'm try to check if a line in a file contains user.Handle and '-r'+any single digit number, AND that the aforementioned user.Handle does not contain '-r'. I'm sure there is an easier way to do this. And I'm sorry if this made your eyes bleed.

if (line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
line.Contains("-r1") || line.Contains(user.Handle) &&
!user.Handle.Contains("-r") && line.Contains("-r2") ||
line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
line.Contains("-r3") || line.Contains(user.Handle) &&
!user.Handle.Contains("-r") && line.Contains("-r4") ||
line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
line.Contains("-r5") || line.Contains(user.Handle) &&
!user.Handle.Contains("-r") && line.Contains("-r6") ||
line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
line.Contains("-r7") || line.Contains(user.Handle) &&
!user.Handle.Contains("-r") && line.Contains("-r8") ||
line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
line.Contains("-r9"))


texts: Iteratively determine the diameter of a binary tree

texts:
Can the performance of the iterative approach be improved? I find that this approach lags behind many recursive options. no recursive answers, please.

Baseline recursive approach: takes 52 steps for this sized tree O(N) for every nested input each object is only touched once.

function diameterOfBinaryTree(root) {
  return diameterInternal(root).diameter;
};

function diameterInternal(root) {
  if (root == null) {
    return {
      diameter: 0,
      depth: 0
    }
  }
  let left = diameterInternal(root.left);
  let right = diameterInternal(root.right);
  let diameter = left.depth + right.depth;
  return {
    diameter: Math.max(diameter, left.diameter, right.diameter),
    depth: Math.max(left.depth, right.depth) + 1
  };
}

let tree = {
  "val": 3,
  "right": {
    "val": 20,
    "right": {
      "val": 7,
      "right": null,
      "left": null
    },
    "left": {
      "val": 15,
      "right": null,
      "left": null
    }
  },
  "left": {
    "val": 9,
    "right": null,
    "left": null
  }
}

console.log(diameterOfBinaryTree(tree))

Iterative approach: takes 85 steps. However, the number of steps will double as the branches become more nested. That's because as you walk the nodes, they are walked in trios. Counting the roots while unpacking the right and left side. Culminating the counts on every retrograde unpacking, while passing every root object more than once. time complexity is O(N^2) for every nested object added it will be touched twice, once on entering and a second time on exiting.

function diameterOfBinaryTree(root) {
  let stack = [
    [1, root]
  ];
  let d = new WeakMap()
  let diameter = 0;
  while (stack.length) {
    let [indicator, node] = [...stack.pop()];
    if (indicator) {
      let place = 0,
        extend = [];
      extend[place++] = [0, node]
      if (node.right !== null) {
        extend[place++] = [1, node.right]
      }
      if (node.left !== null) {
        extend[place++] = [1, node.left]
      }
      stack.push.apply(stack, extend);
    } else {
      let left = d.get(node.left) + 1 || 0;
      let right = d.get(node.right) + 1 || 0;
      d.set(node, Math.max(left, right))
      diameter = Math.max(diameter, left + right);
    }
  }
  return diameter;
}

let tree = {
  "val": 3,
  "right": {
    "val": 20,
    "right": {
      "val": 7,
      "right": null,
      "left": null
    },
    "left": {
      "val": 15,
      "right": null,
      "left": null
    }
  },
  "left": {
    "val": 9,
    "right": null,
    "left": null
  }
}

console.log(diameterOfBinaryTree(tree))


texts: Simple atomic pseudo-random number generation

texts:
I like to use a single global PRNG in my c programs (similar to Javascript's Math.random) because it simplifies things and the unpredictable nature of a global is quite fitting for a PRNG. I recently started using multithreading more so I adapted my global PRNG by making it atomic.

Besides the obvious, it is meant to be atomic in such a way that two threads requesting a pseudo-random number simultaneously won't get the same number in the sequence of pseudo-random numbers. Using a CAS-loop seems to be the only way of accomplishing this, if there is a better way do let me know.

Primarily I'm looking for confirmation that it actually is atomic. Note that struct randomic isn't the same as randomic, the latter is a typedef of _Atomic struct randomic. Admittedly not the best naming ever.

The real magic happens in randomicNext but the whole thing is pretty small so I've included all of it. It can also be found on github.

//include only once
#ifndef RANDOMIC_H
#define RANDOMIC_H

//process configuration
#ifdef RANDOMIC_STATIC
    #define RANDOMIC_IMPLEMENTATION
    #define RADEF static
#else //RANDOMIC_EXTERN
    #define RADEF extern
#endif

//includes
#include <stdatomic.h>
#include <stdint.h>

//types
typedef _Atomic struct randomic {
    uint32_t a, b, c, d;
} randomic;

//function declarations
RADEF void randomicSeed(randomic*, uint32_t);
RADEF float randomicFloat(randomic*, float, float);
RADEF double randomicDouble(randomic*, double, double);
RADEF uint32_t randomicNext(randomic*);

//implementation section
#ifdef RANDOMIC_IMPLEMENTATION

//function declarations
static struct randomic randomicInternal(struct randomic);

//public functions
RADEF void randomicSeed (randomic* rdic, uint32_t seed) {
    struct randomic ctx;
    ctx.a = 0xf1ea5eed;
    ctx.b = ctx.c = ctx.d = seed;
    for (int i = 0; i < 20; i++)
        ctx = randomicInternal(ctx);
    atomic_store(rdic, ctx);
}
RADEF float randomicFloat (randomic* rdic, float a, float b) {
    return a + (b-a)*((float)randomicNext(rdic)/(float)UINT32_MAX);
}
RADEF double randomicDouble (randomic* rdic, double a, double b) {
    return a + (b-a)*((double)randomicNext(rdic)/(double)UINT32_MAX);
}
RADEF uint32_t randomicNext (randomic* rdic) {
    struct randomic ctx = atomic_load(rdic), ntx;
    while (!atomic_compare_exchange_weak(rdic, &ctx, (ntx = randomicInternal(ctx))));
    return ntx.d;
}

//internal functions
static struct randomic randomicInternal (struct randomic ctx) {
    uint32_t e = ctx.a - ((ctx.b << 27)|(ctx.b >> 5));
    ctx.a = ctx.b ^ ((ctx.c << 17)|(ctx.c >> 15));
    ctx.b = ctx.c + ctx.d;
    ctx.c = ctx.d + e;
    ctx.d = e + ctx.a;
    return ctx;
}

#endif //RANDOMIC_IMPLEMENTATION
#endif //RANDOMIC_H


texts:
This code shows an icons from the Segoe MDL2 Assets font, depending on the number in a variable. However, I'm sure there is a more elegant way of doing this.

switch (numberOfPeople)
{
    case 0:
        return "";
    case 1:
        return "\xE77B";
    case 2:
        return "\xE77B \xE77B";
    case 3:
        return "\xE77B \xE77B \xE77B";
    case 4:
        return "\xE77B \xE77B \xE77B \xE77B";
    default:
        break;

}