texts: Recursively Convert Roman Number to Integer

texts:
I'm practicing recursive functions and I would be glad to receive some feedback for the following Python code I wrote. I did several tests and the function yielded correct results but I wonder if it can be written more concise or if it can be criticised in some way. Your feedback would help me become better. The functionality of the function is described in the docstring.

def roman(n):
  """Takes a roman number n as an argument
     (roman(n) assumes that the string n is
     correctly written, i.e. it provides no
     error-checking) and returns an integer."""

  #The base-cases:

  if n == "":
    return 0
  elif n == "M":
    return 1000
  elif n == "D":
    return 500
  elif n == "C":
    return 100
  elif n == "L":
    return 50
  elif n == "X":
    return 10
  elif n == "V":
    return 5
  elif n == "I":
    return 1

  #If a smaller number precedes a bigger number,
  #then the smaller number is to be subtracted from
  #the bigger number. Else, it has to be added:

  else:
    if roman(n[0]) < roman(n[1]):
      return (roman(n[1]) - roman(n[0])) + roman(n[2:])
    else:
      return roman(n[0]) + roman(n[1:])

def main(n):
  print(roman(n))

main("MMMCMXCIX")


texts:
I am trying to work on writing readable code and reducing the amount of redundant code I write. I find this hard to do especially when it comes to algorithms. So, I wrote a quicksort program to practice.

Is there any way I can improve this? I know in terms of efficiency it could be better (instead of taking the leftmost as the pivot, I could choose a pivot in the middle of the array). However, is there a way I could have declared or initialized things better or could I have used a more efficient method of checking different cases?

 package quicksort;

/**
 * @date December 4, 2015
 */
public class Quicksort {

   // private static int[] intArray = new int[]{4, 8, 1, 6, 3, 7, 2, 5};
   private static int[] intArray = new int[]{11,10,9,8,7,6,5,4,3,2,1};
    //private final static int[] intArray = new int[]{1,2,3,4,5};

    /**
     * @purpose This method partitions the array and subarrays based on the current pivot point
     * @param pivot
     * @param leftPointer
     * @param rightPointer
     */
private static void partition(int pivot, int leftPointer, int rightPointer) {

    while (leftPointer <= rightPointer) {
        if (pivot < intArray[rightPointer]) {
            rightPointer--;
        } else if (pivot > intArray[rightPointer]) {
            intArray[leftPointer] = intArray[rightPointer];
            intArray[rightPointer] = pivot;
            leftPointer++;
        } else if (intArray[leftPointer] > pivot) {
            intArray[rightPointer] = intArray[leftPointer];
            intArray[leftPointer] = pivot;
            rightPointer--;
        } else {
            leftPointer++;
        }

    }
    for (int x = 0; x <= intArray.length - 1; x++) {
        System.out.print(intArray[x] + " ");
    }
    System.out.println();

}

/**
 * @purpose This method recursively runs the partition method for the array and subarrays
 * @param pivot
 * @param leftPointer
 * @param rightPointer
 */
private static void quicksort(int pivot, int leftPointer, int rightPointer) {

    while (rightPointer != 0) {
        partition(intArray[0], 0, rightPointer);
        rightPointer--;
    }

    while (leftPointer != intArray.length - 1) {
        leftPointer++;
        partition(intArray[leftPointer], leftPointer, intArray.length - 1);
    }

}

/**
 * @purpose Runs the Quicksort class
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int leftPointer = 0;
    int rightPointer = intArray.length - 1;
    int pivot = intArray[0];
    quicksort(pivot, leftPointer, rightPointer);

}

}


texts:
Using Laravel, I need to export some value from the DB in a CSV and then upload the CSV via sFTP or return it in a Response.

I'm trying to be use S.O.L.I.D. principles but with this scenario, I'm not sure how to proceed. As I understand I should have one class that handles the CSV, one that handles the sFTP, one for the Response, and one to handle the logic of the model (the mapping in my case). But I don't understand how I can separate them.

Later one, I will have more Model data to export.

<?php

namespace App\Services;

use App\Line;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Storage;

class LinesCsv
{
    const DOCUMENT_TYPE = 20;
    const DELIMITER = ';';

    public function exportCSVFileToSftp($filename = 'export.csv')
    {
        $handle = fopen('php://temp', 'w');
        $handle = $this->buildCsv($handle);
        return Storage::disk('sftp')->put($filename, $handle);
    }

    public function exportCSVFileToResponse($filename = 'export.csv')
    {
        return new StreamedResponse(function () use ($filename) {
            $handle = fopen('php://output', 'w');
            $handle = $this->buildCsv($handle);
            fclose($handle);
        }, 200, [
            'Content-Type'        => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ]);
    }

    public function buildCsv($handle, $header = false)
    {
        if ($header) {
            fputcsv(
                $handle,
                array_keys($this->lineMapping(Line::first())),
                self::DELIMITER
            );
        }

        Line::with(['invoice', 'invoice.customer', 'item'])
            ->whereHas('invoice', function ($query) {
                $query->where('is_exportable', 1);
            })
            ->chunk(200, function ($lines) use ($handle) {
                foreach ($lines as $line) {
                    fputcsv(
                        $handle,
                        $this->lineMapping($line),
                        self::DELIMITER
                    );
                }
            });

        return $handle;
    }

    protected function lineMapping(Line $line)
    {
        return [
            'Invoice number'            => $line->invoice->id,
            'Document type'             => self::DOCUMENT_TYPE,
            'Date'                      => $line->invoice->date,
        ];
    }
}


texts: Return character frequency in the order of occurrence

texts:
Problem:
Given a string aaabbcccaad print the no. of occurrence of the character in the same order in which the character occurred.
Expected output:
(a, 3), (b, 2), (c, 3), (a, 2), (d, 1)
The approach:

Loop through each character.
When the next character is not same as the current character, record the next character and its position.
count of occurence = Iterate the pos_list (position list ), take the difference
Return character and its count in in the same order

Solution:
def seq_count(word):
    wlen = len(word)
    pos = 0
    pos_list=[pos]
    alph = [word[0]]
    result = []

    for i in range(wlen):
        np = i+1
        if np < wlen:
            if word[i] != word[i+1]:
                pos = i+1
                pos_list.append(pos)
                alph.append(word[i+1])
    pos_list.append(wlen)

    for i in range(len(pos_list)-1):
        result.append((alph[i], pos_list[i+1] - pos_list[i]))
    return result

print seq_count("aaabbcccaad")

Note:
I know this may not be the conventional solution, i was finding difficult to count the character and maintain its count as we iterate through the string, since I'm a beginner in python. Pls let me know how can i do it better.


texts: Using two wordlists to search a list of texts

texts:
I have a function that takes two separate wordlists and searches a third list, which is a text formatted as a list of wordlists.

The function finds the proximity between words in word_list1 and word_list2 by taking the difference between their indexes; (it takes one over the difference, so that larger numbers will indicate closer proximity).

I ultimately will write the output to a .csv file and create a network of the word proximities in gephi.

This function works for me, but it is very slow when used on a large number of texts. Do you have any suggestions for making it more efficient? (If this is unclear at all, let me know, and I will try to clarify.)

text = [
    'This, Reader, is the entertainment of those who let loose their own thoughts, and follow them in writing, which thou oughtest not to envy them, since they afford thee an opportunity of the like diversion if thou wilt make use of thy own thoughts in reading.',
    'For the understanding, like the eye, judging of objects only by its own sight, cannot but be pleased with what it discovers, having less regret for what has escaped it, because it is unknown.'
]

word_list1 = ['entertainment', 'follow', 'joke', 'understanding']
word_list2 = ['envy', 'use', 'nada']
text_split = []
for line in text:
    text_split.append(line.split(' '))

def word_relations(list_a, list_b, text):
    relations = []
    for line in text:
        for i, item in enumerate(line):
            for w in list_a:
                if w in item:
                    first_int = i
                    first_word = w
                    for t, item in enumerate(line):
                        for x in list_b:
                            if x in item:
                                second_int = t
                                second_word = x
                                if first_int:
                                    if second_int != first_int:
                                        dist = 1.0 / abs(second_int-first_int)
                                        if dist in relations:
                                            continue
                                        else:
                                            relations.append((first_word,
                                            second_word, dist))
    return(relations)
print(word_relations(word_list1, word_list2, text_split))

Here is the output:

[('entertainment', 'envy', 0.05263157894736842), ('entertainment', 'use', 0.02857142857142857), ('follow', 'envy', 0.1111111111111111), ('follow', 'use', 0.04), ('understanding', 'use', 0.03571428571428571)]


texts: Designing stack and queue from scratch in C

texts:
As a beginner and curious guy I'm interested in implementing data structures and algorithms from scratch. Here's my implementation of Stack and Queue, the most fundamental data structures.

Are there are any mistakes/ memory leaks in the code that I have missed? How I can improve my implementation.

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

typedef struct NODE {
    int data;
    struct NODE *next_node;

    } NODE;

NODE *check_queue(NODE *head);
NODE *check_stack(NODE *head);
void push_node(NODE **head, int value);
void enqueue_node(NODE **head, int value, NODE **tail);
int  pop(NODE **s_head);
int  dequeue(NODE **q_head);
void print_stack(NODE *head);
void print_queue(NODE *head);
void free_memory(NODE **head);

int main(){

    NODE *Q_head = NULL;
    NODE *Q_tail = NULL;
    NODE *S_head = NULL;
    /*operations here*/

    return 0;
}

/*----- check functions for queue and stack if empty-----------*/

NODE *check_queue(NODE *head){
    return head;
}

NODE *check_stack(NODE *head){
    return head;
}

/*--------------------------------------------------------------*/

void push_node(NODE **head, int value){

    NODE *cache;
    cache = (NODE *) malloc(sizeof(NODE));
    cache->data = value;
    /*first commit / allocate a new head*/

    if ((*head) == NULL) {
        cache->next_node = NULL;
        (*head) = cache; /*assign the cache to head head*/
    }

    else {
        /*point to the previous head*/
        cache->next_node = (*head);
        (*head) = cache;
    }
}

void enqueue_node(NODE **head, int value, NODE **tail) {

    NODE *cache;
    cache = (NODE *) malloc(sizeof(NODE));
    cache->data = value;
    cache->next_node = NULL;

    if ((*head) == NULL && (*tail) == NULL) {
        (*head) = cache; /*assign the cache to head*/
        /*now assign tail the job as a cachet head and extends the queue*/
        (*tail) = (*head);
    }

    else {
        /*now tail is the representative of head and extened the queue*/
        (*tail)->next_node = cache;
        (*tail) = cache;
    }
}

int pop(NODE **s_head){

    if(check_stack((*s_head)) == NULL){
        printf("Stack is empty ! ! !\n");
        return -1;
    }

    else {
        /*put next head into a cache, free present head, take next head to present head*/
        NODE *cache ;
        cache = (*s_head)->next_node;
        int popped_value = (*s_head)->data;
        free((*s_head));
        (*s_head) = cache;
        return popped_value;
    }
}

int dequeue(NODE **q_head){

    if(check_queue((*q_head)) == NULL){
        printf("queue is empty ! ! !\n");
        return -1;
    }

    else {
        /*ditto of stack as we've got queue sequence*/

        NODE *cache ;
        cache = (*q_head)->next_node;
        int dequeued_value = (*q_head)->data;
        free((*q_head));
        (*q_head) = cache;
        return dequeued_value;
    }
}

void print_stack(NODE *head){

    while (head) {

        printf(" %d \n", head->data);
        printf(" |\n");
        head = head->next_node;
    }

    /*for further assurance*/
    if ( head == NULL){
        printf("NULL\n");
    }

    printf("\n");
}

void print_queue(NODE *q_head){

    while (q_head) {

        // printf(" %d  -> ", head->next_node);
        printf(" %d  -> ", q_head->data);
        q_head = q_head->next_node;
    }
    /*for further assurance*/
    if ( q_head == NULL){
            printf("NULL\n");
    }

    printf("\n");
}

void free_memory(NODE **head){
    NODE *cache_head;

    while ((*head)) {

        /*assign next head to the cache*/
        cache_head = (*head)->next_node;
        free((*head));
        (*head) = cache_head;
    }

    printf("memory release complete !!! \n");
}


texts:
Basically I'm displaying an array of images on a page with checkboxes. The idea is when a user is editing a post and the checkbox is checked, the image will get deleted. Each image also has an order_id and description.

I'm pretty new to Ruby and programming and I'm looking for a way to simplify the following code.

Codeclimate is saying:

  Cyclomatic complexity for update is too high

lessons_controller.rb:

def update

@lesson.attachments.each.with_index do |attachment, index|

  unless params[:delete_array].nil?
    if params[:delete_array][index].to_i == attachment.id && params[:delete_array][index].to_i != 0
      puts "DELETE: #{attachment.attachment_file_name}"
      attachment.destroy
    end
  end

  unless attachment.nil?
    unless params[:order_array].nil?
      if params[:order_array][index].to_i != attachment.order
        attachment.order = params[:order_array][index]
        puts "ORDER: #{attachment.order} = #{params[:order_array][index]}"
        @save = true
      end
    end

    unless params[:description_array].nil?
      if params[:description_array][index] != attachment.description
        attachment.description = params[:description_array][index]
        puts "DESCR: #{attachment.description} = #{params[:description_array][index]}"
        @save = true
      end
    end
  end
end

if @save == true
  @lesson.attachments.each(&:save)
end

  respond_to do |format|
  if @lesson.update(lesson_params)
    format.html { redirect_to @lesson, notice: 'Lesson was successfully updated.' }
    format.json { render :show, status: :ok, location: @lesson }
  else
    format.html { render :edit }
    format.json { render json: @lesson.errors, status: :unprocessable_entity }
  end
end
end

view/_form.html.erb

    <% if @lesson.attachments.any? %>
    <button type="button" id="check_all" class="center"><%="Check all/Uncheck all"%></button>

      <% @lesson.attachments.order(:order).each do |attachment| %>

          <%= image_tag attachment.attachment.url(:thumb), class: "thumbnail img-responsive center" %>

          <%= check_box_tag 'delete_array[]', attachment.id, checked = false %> Delete

          <%= number_field_tag 'order_array[]', attachment.order %>
          <%= text_field_tag 'description_array[]', attachment.description, placeholder: "Description" %>

      <% end %>
    <% else %>
      No attachments found.
    <% end %>


texts: RAII pattern for downgradable ReadWriteLock

texts:
The example for downgrading ReentrantReadWriteLock in the Java documentation seems really unsafe when handling exceptions. I tried to write a simple class to simplify it. Do you see any cases where it can fail?

I'm looking for a review from a concurrency point of view, such as if this code may fail if an exception is thrown inside a nested lock before the downgrade.

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;

public class RWLockWrapper implements AutoCloseable {
    private final ReadWriteLock rwl;
    private Lock current;

    //RAII
    public RWLockWrapper(ReadWriteLock rwl) {
        this.rwl = rwl;
        this.current = rwl.writeLock();
        this.current.lock();
    }

    public void downgrade() {
        final Lock read = rwl.readLock();
        read.lock();
        try {
            current.unlock();
        } finally {
            current = read;
        }
    }

    @Override
    public void close() {
        current.unlock();
    }
}

To be used like this:

try (RWLockWrapper lock = new RWLockWrapper(rwl)) {
    //write locked

    lock.downgrade();

    //read locked
}


texts:
How can the following code be made idiomatic in ELisp? Can the temporary f variable be removed?

(global-set-key [f3]
  (lambda () (interactive)
    (let ((f (ffap-file-at-point)))
      (start-process "test" "output" "mpv" f))))


texts:
This is my solution to LeetCode – Minimum Area Rectangle in Swift

939. Minimum Area Rectangle
Given a set of points in the xy-plane, determine the minimum area of a rectangle formed from these points, with sides parallel to the x and y axes.
If there isn't any rectangle, return 0.

Example 1:

Input: [[1,1],[1,3],[3,1],[3,3],[2,2]]
Output: 4

Example 2:

Input: [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
Output: 2

class Solution {
    struct Point_Dng: Hashable{
        var x: Int
        var y: Int

        init(_ x: Int, _ y: Int) {
            self.x = x
            self.y = y
        }

        var hashValue: Int{
            return x * 100000 + y
        }

        static func == (_ lhs: Point_Dng, _ rhs: Point_Dng) -> Bool{
            return lhs.x == rhs.x && lhs.y == rhs.y
        }
    }

    func minAreaRect(_ points: [[Int]]) -> Int {
        let points_new = points.map({ (point: [Int]) -> Point_Dng in
            return Point_Dng(point[0], point[1])
        })
        let set = Set(points_new)
        var ans = Int.max
        for point in points{

            for point_piece in points{

                if point[0] != point_piece[0] , point[1] != point_piece[1] , set.contains(Point_Dng(point[0], point_piece[1])) ,set.contains(Point_Dng(point_piece[0], point[1])) {

                    ans = min(ans, abs((point_piece[1] - point[1] ) * (point_piece[0] - point[0])))
                }

            }
        }

        if ans == Int.max {
            return 0
        }
        else{
            return ans
        }

    }
}

Note:

1 <= points.length <= 500

0 <= points[i][0] <= 40000

0 <= points[i][1] <= 40000

All points are distinct.

According to LeetCode's note, I improved the hash performance.
I turned
var hashValue: Int{
     return "\(x)\(y)".hashValue
}

into
var hashValue: Int{
     return x * 100000 + y
}

because Swift's tuple is not hashable.
The prior one will lead to “Time Limit Exceeded”
How can I improve it further?
In fact I want to know is there something I missed in Swift.
Something out of my knowledge.
Because I did it simple.


texts:
The "parser state" of a module in rubberduck can be one of several values:

//note: ordering of the members is important
public enum ParserState
{
    /// <summary>
    /// Parse was requested but hasn't started yet.
    /// </summary>
    Pending,
    /// <summary>
    /// Project references are being loaded into parser state.
    /// </summary>
    LoadingReference,
    /// <summary>
    /// Code from modified modules is being parsed.
    /// </summary>
    Parsing,
    /// <summary>
    /// Parse tree is waiting to be walked for identifier resolution.
    /// </summary>
    Parsed,
    /// <summary>
    /// Resolving identifier references.
    /// </summary>
    Resolving,
    /// <summary>
    /// Parser state is in sync with the actual code in the VBE.
    /// </summary>
    Ready,
    /// <summary>
    /// Parsing could not be completed for one or more modules.
    /// </summary>
    Error,
    /// <summary>
    /// Parsing completed, but identifier references could not be resolved for one or more modules.
    /// </summary>
    ResolverError,
}

Now, Rubberduck uses each modules' state, and determines what the "overall" state is - and then displays that value in a status bar.

The rules are:

If all modules have the same state, overall state is that value.
If any module is in an error state, overall state is that error value.
Overall state can only be "ready" when all modules are "ready".
Overall state can only be "parsed" when all modules are "parsed".
Otherwise return the state of the most advanced non-ready module.

The code started simple, got complicated, then too simple, and now looks like this - basically it went back to "too complicated":

private static readonly ParserState[] States = Enum.GetValues(typeof(ParserState)).Cast<ParserState>().ToArray();
private ParserState EvaluateParserState()
{
    var moduleStates = _moduleStates.Values.ToList();
    var state = States.SingleOrDefault(value => moduleStates.All(ps => ps == value));

    if (state != default(ParserState))
    {
        // if all modules are in the same state, we have our result.
        Debug.WriteLine("ParserState evaluates to '{0}' (thread {1})", state, Thread.CurrentThread.ManagedThreadId);
        return state;
    }

    // error state takes precedence over every other state
    if (moduleStates.Any(ms => ms == ParserState.Error))
    {
        Debug.WriteLine("ParserState evaluates to '{0}' (thread {1})", ParserState.Error,
        Thread.CurrentThread.ManagedThreadId);
        return ParserState.Error;
    }
    if (moduleStates.Any(ms => ms == ParserState.ResolverError))
    {
        Debug.WriteLine("ParserState evaluates to '{0}' (thread {1})", ParserState.ResolverError,
        Thread.CurrentThread.ManagedThreadId);
        return ParserState.ResolverError;
    }

    // intermediate states are toggled when *any* module has them.
    var result = moduleStates.Min();
    if (moduleStates.Any(ms => ms == ParserState.Parsing))
    {
        result = ParserState.Parsing;
    }
    if (moduleStates.Any(ms => ms == ParserState.Resolving))
    {
        result = ParserState.Resolving;
    }

    if (result == ParserState.Ready && moduleStates.Any(item => item != ParserState.Ready))
    {
        result = moduleStates.Except(new[] {ParserState.Ready}).Max();
    }

    Debug.Assert(result != ParserState.Ready || moduleStates.All(item => item == ParserState.Ready));

    Debug.WriteLine("ParserState evaluates to '{0}' (thread {1})", result,
    Thread.CurrentThread.ManagedThreadId);
    return result;
}

Does anything stick out? Could it be simplified? Any/all feedback welcome!


texts: "Functionalizing" this tree walking method and cleaning it up

texts:
I have a MessageTree class that represents a binary tree of negative/positive. I'm looking to improve my walkTree method and make it more functional and succinct. Right now the try/catch is kind of ugly.

The goal is to feed an array of "steps" (Array[Boolean]) that indicate whether to walk right or left through each node. If the number of steps exceeds the number of available children, it simply returns None.

Here's what I've got:

case class MessageTree(
  val value: String,
  val negative: Option[MessageTree] = None,
  val positive: Option[MessageTree] = None

) {

  /**
   * Walk the node using a boolean input.
   * @param step
   * @return
   */
  def walk(step: Boolean): Option[MessageTree] = {
    step match {
      case true => this.positive
      case false => this.negative
    }
  }
}

object MessageTree {

  /**
   * Walk the tree and retrieve a child using a sequence of boolean steps.
   * @param tree
   * @param steps
   * @return
   */
  def walkTree(tree: MessageTree, steps: Array[Boolean]): Option[MessageTree] = {
    var walks = 0
    var node: Option[MessageTree] = Some(tree)

    try {
      while (walks < steps.size) {
        node = node.get.walk(steps(walks))
        walks += 1
      }
    } catch {
      case e: Throwable =>
        node = None
    }

    node
  }
}


texts: Passing standard data through serviceprovider

texts:
I am using Laravel 5. To pass the users his favorites and permalink, I edited the AppServiceProvider. I was wondering if my solution is the most reasonable solution.

Of particular concern is future extensibility in terms of adding additional views.  I only have the two now but I think it's quite possible that I'll add more in the future.

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use App\Models\Favorites;
use Auth;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer('navigation.top-menu-only', function($view) {
            $this->getData($view);
        });

        view()->composer('navigation.menu', function($view) {
            $this->getData($view);
        });
    }

    /**
     * Register any application services.
     *
     * This service provider is a great spot to register your various container
     * bindings with the application. As you can see, we are registering our
     * "Registrar" implementation here. You can add your own bindings too!
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            'Illuminate\Contracts\Auth\Registrar',
            'App\Services\Registrar'
        );
    }

    /**
     * Get data for menu
     *
     * @param  object $view
     *
     * @return view
     */
    private function getData($view)
    {
        if (Auth::Check()) {
            $favoritesModel = new Favorites();
            $companiesModel = new Companies();
            $messagesModel = new MessagesSend();

            $favorites = $favoritesModel->getFavorites();
            $company = $companiesModel->findByUserId(Auth::User()->id);
            $unreadMessages = $messagesModel->countRecivedUnreadedMessages();
            $lastMessages = $messagesModel->getRecivedMessages(Auth::User()->id, 5);

            $view->with('permalink', Auth::User()->permalink)
                 ->with('favorites', $favorites)
                 ->with('company', $company)
                 ->with('unreadMessages', $unreadMessages)
                 ->with('lastMessages', $lastMessages);
        }
    }

}


texts: Form involving several models related to each other

texts:
I have a form that I feel I am overcomplicating because of the relationship between models that are involved.  Can you let me know if there's a more elegant solution to what I have?

(for reference) The form ultimately looks like this:

The relationship between the involved models:

user_relation has_many :user_relation_skills
user_relation_skills has_many :progresses
progress has_many :ratings, :as => :ratable

The form looks like this (I removed most of the classes/extraneous information but left the divs in to give a better idea of whats going on):

<%= simple_form_for(@user_relation) do |f| %>
    <%= f.fields_for :user_relation_skills do |ff| %>
        <%= ff.fields_for :progresses do |fff| %>
            <%= fff.fields_for :ratings do |ffff| %>

                        <%= link_to(user_relation_skill_path(ffff.object.scope)) do %>
                          <%= ffff.object.scope.skill.category.name %>&nbsp&nbsp<%= ffff.object.scope.skill.name %>
                        <% end %>

                <% if @current_type_for_views == 'coach' %>

                            <%= ffff.select("value", 1..8, {}, {class: "ratings-skill"}) %>

                                <%= button_tag(type: 'submit', class: "small button") do %>
                                    Update
                                <% end %>

                <% else %>

                            <%= ffff.select("value", 1..8, {}, {class: "static-rating"}) %>

                <% end %>

            <% end %>
        <% end %>
    <% end %>
<% end %>

Are this many 'nests' in a form typical or should I be doing something else?

I'm including part of a simple UML diagram with a focus on the "Rating" model that is attached to many things (there are lots of things in the app that can be rated):

Most of the lines going up out of the screen connect either to unimportant models or Active Record directly.  The only pertinent thing that is not pictured is the fact that Rating rates Users (a user model that someone would typically expect).


texts: Generate all possible numbers which can be representated as the sum of 2 cubes below N

texts:
I have written a program that generates all possible numbers which can be represented by adding 2 cubes which have value less than N

For example: when \$N = 10, 1^3 + 2^3 = 9\$

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class AllNumberLessThanNasCubes {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("enter an integer n");
        int n = new Scanner(System.in).nextInt();

        System.out.println("all possible numbers are as follows ");
        generateAllPossibleNumbers(n);

    }

    /**
     * This function will generate all possible numbers less the {@link n} which can
     * be represented as the sum of 2 cubes
     * For eg.when N=10 ,  1^3 + 2^3 = 9
     * @param n
     */
    public static  void generateAllPossibleNumbers(int n) {
            // TODO Auto-generated method stub

    List<Long> cubes = new ArrayList<>((int) Math.cbrt(n));
    List<Long> allSum = new ArrayList<>();
    for (int i=1; Math.pow(i, 3)< n ;++i){
        cubes.add((long) Math.pow(i, 3));
    }
    long sum=0 , tempSum=0;
    int cubesSize= cubes.size();
    System.out.println(cubes);
    for (int i=0; i < cubesSize ;++i){
        sum = cubes.get(i);

        for (int j=i+1; j< cubesSize ; ++j){
            tempSum = sum + cubes.get(j) ;
            //System.out.println(tempSum);
            if (tempSum >= n){
                break;
            }else{
                allSum.add(tempSum);
            }
        }
    }
    System.out.println(allSum);
}
}

Is this the correct way to solve the problem? Is there an efficient way to solve it?

Except for error checking while taking input, what else can be improved?


texts: What is the best way to deal with multiple return types in Python's is_number?

texts:
I have not tried decorators yet or functions within functions, but this current un-pythonic method seems a little convoluted. I don't like how I need to repeat myself when I check the return_type 3 times.

Any suggestions are welcome, especially if the repetion can be dealt with in an elegant way. Please note that I am not that interested in the numerous reference to test if an object is a number as I believe this part is incorporated within my solution. I am interested in addressing the 3x duplication to deal with the return type. Moreover, while I appreciate the locale method is the more rigorous way of dealing with internationalisation, I prefer the simplicity of allowing the caller more flexibility in choosing the characters.

Also, some people on Stack Overflow just posted trivial solutions to the smaller boolean is_number function that has been asked many times.

def is_number(obj, thousand_sep=',', decimal_sep=None, return_type='b'):
    """ determines if obj is numeric.

    if return_type = b, returns a boolean True/False
    otherwise, it returns the numeric value

    Examples
    --------
    >>> is_number(3)
    True
    >>> is_number('-4.1728')
    True
    >>> is_number('-4.1728', return_type='n')
    -4.1728
    >>> is_number(-5.43)
    True
    >>> is_number("20,000.43")
    True
    >>> is_number("20.000,43", decimal_sep=",", thousand_sep=",")
    True
    >>> is_number("20.000,43", decimal_sep=",", thousand_sep=".", return_type="n")
    20000.43
    >>> is_number('Four')
    False
    >>> is_number('Four', return_type='n')
    """
    try:
        if is_string(obj):
            if decimal_sep is None:
                value = float(obj.replace(thousand_sep, ""))
            else:
                value = float(obj.replace(thousand_sep, "").replace(decimal_sep, "."))
            if return_type.lower() == 'b':
                return True
            else:
                return value
        else:
            value = float(obj)
            if return_type.lower() == 'b':
                return True
            else:
                return value
    except ValueError:
        return False
        if return_type.lower() == 'b':
            return False
        else:
            return None


texts: Program to accept numbers, then calculate the mean, median, and range

texts:
I created a basic program that allows a user to continuously input values until he or she is satisfied; furthering, the program outputs the mean, median, and range. Then, the code gives you the option to run it again or exit.

#Mean, median, and range
from clear import *
def main():
    clear()
    list_one = []
    while True:
        q = input('Type a number or type stop at any time: ').lower()
        if q.isnumeric():
            list_one.append(int(q))
            print('''
Great choice! Choose again or type stop the sequence.''')
        elif q == 'stop':
            list_one.sort(key=int)
            print('''
And the values are...''')

            def mean():
                return 'Mean: ' + str(sum(list_one)/len(list_one))

            def median():
                length = len(list_one)
                if length % 2 == 0:
                    return  'Median: ' + str(sum(list_one[length//2-1:length//2+1])/2)
                else:
                    return 'Median: ' + str(list_one[length//2])

            def range_():
                return 'Range: ' + str(list_one[-1] - list_one[0])

            print(mean())
            print(median())
            print(range_())
            break

        else:
            print('''
That\'s not a number or stop! Try again brudda man.
''')

def end():
    while True:
        q = input('Type anything and and press enter to repeat or press only \'Enter\' to exit. ')
        if len(q) >= 1:
            main()
            break
        else:
            exit()
main()

while True:
    q = input('''
Type anything and and press enter to repeat or press only \'Enter\' to exit. ''')
    if len(q) >= 1:
        main()
    else:
        clear()
        exit()

Additionally, the "clear" library that I imported is a custom library of my making which only prints out a ton of blank lines so the script "clears" and outputs are then at the bottom. If there is a better way of doing this please let me know.

I want to get familiar with what is "right" or "wrong" in terms of programming with Python. I would like my work to look professional and practice more respected coding ethics, so please be as harsh as you wish.


texts:
In my project we have a few singletons, which tends to be problematic in unit tests. So I wanted to find solution for the problem. Here is what I came with so far:

smart_singleton.h

class smart_singleton
{
public:
    static std::shared_ptr<smart_singleton> get_instance();

private:
    smart_singleton();

    smart_singleton(const smart_singleton&) = delete;
    smart_singleton operator=(const smart_singleton&) = delete;
    smart_singleton(smart_singleton&&) = default;
    smart_singleton& operator=(smart_singleton&&) = default;

    static std::weak_ptr<smart_singleton> weak_instance;
};

smart_singleton.cpp

std::weak_ptr<smart_singleton> smart_singleton::weak_instance;

std::shared_ptr<smart_singleton> smart_singleton::get_instance()
{
    if (auto existing_instance = weak_instance.lock()) {
        return existing_instance;
    } else {
        std::shared_ptr<smart_singleton> tmp_shared(new smart_singleton());
        weak_instance = tmp_shared;
        return tmp_shared;
    }
}

smart_singleton::smart_singleton()
{

}

The difference is that you need to hold one shared_ptr from "get_instance()" anywhere in your code for the object to not be destroyed. In your prodution code that would be somewhere in the main function (or some object that is alive for the whole scope of main). In UT that would be for the duration of one test.

IMPORTANT:
Please don't focus on the singleton pattern itself being discouraged. My project has singletons and changing that would mean a lot of effort. My attempt is only to make unit testing easier. What I'm interested in, therefore, are the differences between having a classic implementation of singleton in C++ and my implementation and what possible problems could the latter one cause.


texts:
I have been trying to write a sample code block to remove multiple backward or forward slashes from a path (e.g. //a//b should be /a/b; on Windows, c:\\a\\b\\\c should be c:\a\b\c).

I am assuming that:

Code must be platform independent
Should work in all cases (or report a proper error)
It should be readable and maintainable
It shouldn't be over-complex and shouldn't have errors

Please provide point-wise comments for the following code sample (you may ignore main and assume that path is not NULL - it is just for demonstration purposes). Or else you may provide a better mechanism for the same.

    void
    die( int error_code, char* message )
    {
        fprintf( stderr, message );
        exit( error_code );
    }

    /*Following function removes duplicate slashes from a given path*/
    char*
    validate_path ( char* path )
    {
        char* path_copy = path;
        int dup_flag = 0;
        char* path_without_dup_slash = (char*)malloc(strlen(path)+1);
        if ( path_without_dup_slash == NULL ) {
             die( EXIT_FAILURE, "Failed to allocate memory for processing path.");
        }
        char* copy_pwds = path_without_dup_slash;
        /* Travel through given path */
        while( *path_copy != '\0' ) {
              /* If there is '\' or '/' then copy a single '/'
               * , ignore others until a real char comes */
               if ( (( *path_copy == '\\') || ( *path_copy == '/' )) &&
                    (dup_flag == 0) ) {
                    *copy_pwds = *path_copy;
                    dup_flag = 1;
                    copy_pwds++;
                }else if (( *path_copy != '\\') && ( *path_copy != '/' ))  {
                    *copy_pwds = *path_copy;
                    dup_flag = 0;
                    copy_pwds++;
                }
                path_copy++;
         }
         *copy_pwds = '\0';
         path_without_dup_slash = (char *)realloc( path_without_dup_slash,
                                  strlen( path_without_dup_slash ) + 1 );
         if ( path_without_dup_slash == NULL ) {
               die( EXIT_FAILURE, "Failed to allocate memory for processing path.");
         }
         return path_without_dup_slash;
    }
    /*You please ignore the parts written in main - it is just for demonstration purpose. */
    int
    main( void ) {
         char* bad_path_1 = malloc(100);
         char* bad_path_2 = malloc(100);
         char* p1 = bad_path_1;
         char* p2 = bad_path_2;
         char* path_1;
         char* path_2;
         bad_path_1 = "//a//b//c";
         bad_path_2 = "c:\\\\a\\\\b\\\\c";
         path_1 = validate_path(bad_path_1);
         printf( "Good path:%s Bad Path:%s\n",path_1,bad_path_1);
         path_2 = validate_path(bad_path_2);
         printf( "Good path:%s Bad Path:%s\n",path_2,bad_path_2);
         free(path_1);
         free(path_2);
         free(p1);
         free(p2);
         return EXIT_SUCCESS;

     }


texts:
A dollar word is a word for which the sum of the values of the letters adds up to 100 ($1.00).

"a" has a value of 1 and "z" has a value of 26.  Special characters such as apostrophes are ignored.

First try looked like:

import string

valMap = {}
for index,item in enumerate(string.lowercase):
    valMap[item] = index +1

def isDollarWord(word):
    lowercase = word.lower().strip()
    total = 0
    for letter in lowercase:
        if letter in valMap:
            total += valMap[letter]
    return total == 100

words = open("C:\Users\astroboy\Downloads\UKACD17.TXT")

for line in words:
    if isDollarWord(line):
        print(line)

I started feeling kind of bad that words like "Hälleflinta" and "divorcée" might be denied their rightful place in the dollar word list.  No known rules for how to handle characters  with accents, so I made up my own as below (à would be counted as a).  That means replacing all diactritics with the plain letter.

import string
import unicodedata

valMap = {}
for index,item in enumerate(string.lowercase):
    valMap[item] = index +1

def remove_marks(word):
    unicode_word = word.decode('cp1252')
    return unicodedata.normalize('NFKD',unicode_word).encode('ascii','ignore')

def isDollarWord(word):
    lowercase = word.lower().strip()
    normalized = remove_marks(lowercase)

    total = 0
    for n in normalized:
        if n in valMap:
            total += valMap[n]

    return total == 100

words = open("C:\Users\astroboy\Downloads\UKACD17.TXT")

for line in words:
    if isDollarWord(line):
        print(remove_marks(line))

I'm posting for any feedback about this code.  See any room for improvement?


texts:
I was hoping I could get some feedback on performance of my animations overall. It could just be me but I keep getting a bit of lag despite being at 60FPS constantly.

Objects on screen seem to tear a little bit.

Here's my code in full.

Here is my game loop:

//clocks and times used to get custom game loop working
    sf::Clock clock;
    sf::Time timeSinceLastUpdate = sf::Time::Zero;

    //setting g_GameState to be intro on run
    g_GameState = 0;

            //main loop to run the entire length of games
            //life
            while (g_Window.isOpen())
            {
                sf::Time dt = clock.restart();
                timeSinceLastUpdate += dt;

                while(timeSinceLastUpdate > TIME_PER_FRAME)
                {

                    timeSinceLastUpdate -= TIME_PER_FRAME;
                    processEvents();
                    update(TIME_PER_FRAME);

                }
                updateFPSCounter(dt);
                render();
            }

It's this performance issue I'd like any feedback or advice on.

Also, if anyone thinks I could do collision detection better as well, could you give me any pointers?

For the player paddles I use this to update their movement:

 //Not using deceleration
    //so setting mVelocity as 0 each time
    mVelocity.x = 0;
    mVelocity.y = 0;

    //Handle if player keys are pressed to move up
    //or down
    if(mIsMovingUp){
        mVelocity.y = -mSpeed;
    }
    else if(mIsMovingDown){
        mVelocity.y = mSpeed;
    }

    //move the play based on current mVelocity size
    this->move(mVelocity * elapsedTime.asSeconds());


texts:
I'm attempting to get an image to spin a certain amount when a separate div is clicked - in this case, a 72 degree rotation.

I've added clickable divs in the top right and left of the viewport, that should make the planet image spin 72 degrees on each click.

However, it only spins once. Unless I click it before the end of the animation, which is a weird effect. Can you please review this code and let me know why I can only spin once?

https://codepen.io/Punchyoual/pen/oGRLpX

HTML:

CSS:

body {
  background-image:url('https://space-facts.com/wp-content/uploads/magellanic-clouds.png');
  overflow:hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

#left-button {
  position:fixed;
  top:0px;
  left:0px;
  height:50px;
  width:50px;
  background-color:red;
}

#right-button {
  position:fixed;
  top:0px;
  right:0px;
  height:50px;
  width:50px;
  background-color:red;
}

#inner-orbit {
  margin:0 auto;
  width:150vw;
  height:145vw;
  text-align:center;
  background-image:url('https://my-rewards.co.uk/s3/W1siZiIsIjIwMTcvMTAvMjMvMTUvNDMvNTAvODE3L3BsYW5ldHMyXzAxLnBuZyJdXQ?sha=069b6bb83dffffde');
    background-size: 100% 100%;
    background-repeat: no-repeat;
  /*-webkit-animation: spin-right 25s linear infinite;
  animation: spin-right 25s infinite;
  transform:rotate(72deg);*/
}

#inner-orbit{transition: all 2s ease-in-out;}

@-webkit-keyframes spin-right {
  100% {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

JS:

var degrees = 0;

$("#right-button").click(function() {

  degrees += 72;

  //$('.img').addClass('rotated'); // for one time rotation

  $("#inner-orbit").css({
    transform: "rotate(" + degrees + "deg)",
    "-ms-transform": "rotate(" + degrees + "deg)",
    "-moz-transform": "rotate(" + degrees + "deg)",
    "-webkit-transform": "rotate(" + degrees + "deg)",
    "-o-transform": "rotate(" + degrees + "deg)"
  });

  console.log(degrees);
});

$("#left-button").click(function() {

  degrees -= 72;

  //$('.img').addClass('rotated'); // for one time rotation

  $("#inner-orbit").css({
    transform: "rotate(" + degrees + "deg)",
    "-ms-transform": "rotate(" + degrees + "deg)",
    "-moz-transform": "rotate(" + degrees + "deg)",
    "-webkit-transform": "rotate(" + degrees + "deg)",
    "-o-transform": "rotate(" + degrees + "deg)"
  });

  console.log(degrees);
});


texts: A small custom encryption / decryption script

texts:
I have made a small script for encrypting data. Now I'm wondering how efficient it is for normal users who aren't programmers and for people who are programmers.

I mean if you don't have this script there is no way to find out what the text is right?

function cipher(message, action) {
  var text = message;
  var encrypted = "";

  for(var i = 0; i < text.length; i++) {
    var ASCII = text[i].charCodeAt(0);
    var n = null;

    if(i % 2 == 0) {
      n = action == 'encrypt' ? ASCII + 4 : ASCII - 4;
    }

    else if(i % 2 == 1) {
      n = action == 'encrypt' ? ASCII + 7 : ASCII - 7;
    }

    var s = String.fromCharCode(n);

        encrypted += s;;
  }
   return encrypted;
}

console.log(cipher("Hello World", 'encrypt'))

If you were to make it more secure, what would you add? I was thinking of a complete custom random mapping for each letter but retrieving it after decryption is something I can't figure out yet.


texts:
I just want to see if any part of one "rectangle" overlaps the other.
Is this the correct code?

 bool checkCollide(int x, int y, int oWidth, int oHeight, int x2, int y2, int o2Width, int o2Height){
    bool collide;
    collide = false;

    if(x >= x2 && x <= x2+o2Width && y >= y2 && y <= y2+o2Height){
        collide = true;
    }

    if(x+oWidth >= x2 && x+oWidth <= x2+o2Width && y >= y2 && y <= y2+o2Height){
        collide = true;
    }

    if(x >= x2 && x<= x2+o2Width && y+oHeight >= y2 && y+oHeight <= y2+o2Height){
        collide = true;
    }

    if(x+oWidth >= x2 && x+oWidth <= x2+o2Width && y+oHeight >= y2 && y+oHeight <= y2+o2Height){
        collide = true;
    }
    return collide;
}


texts: Recover a secret string from random triplets

texts:
Got this problem from Codewars.

There is a secret string which is unknown to you. Given a collection of random triplets from the string, recover the original string.
A triplet here is defined as a sequence of three letters such that each letter occurs somewhere before the next in the given string. "whi" is a triplet for the string "whatisup".
As a simplification, you may assume that no letter occurs more than once in the secret string.
You can assume nothing about the triplets given to you other than that they are valid triplets and that they contain sufficient information to deduce the original string. In particular, this means that the secret string will never contain letters that do not occur in one of the triplets given to you.

For example, given triplets [['t','u','p'], ['w','h','i'], ['t','s','u'], ['a','t','s'], ['h','a','p'], ['t','i','s'], ['w','h','s']], the code should return the string whatisup. All the context that I had to solve the problem came from the description. This is a programming challenge, not meant to solve a real life problem. My code passed the tests. There where no random tests though. My main interest is about performance.
function recoverSecret(triplets) {
    const after = {};

    const precedence = (a, b) => after[a].has(b)
        || [...after[a]].some(c => precedence(c, b) == -1) ? -1 : 1;

    for (let triplet of triplets) {
        after[triplet[0]] = new Set([...(after[triplet[0]] || []), ...triplet.slice(1)]);
        after[triplet[1]] = new Set([...(after[triplet[1]] || []), triplet[2]]);
        after[triplet[2]] = new Set([...(after[triplet[2]] || [])]);
    }

    return Object.keys(after).sort(precedence).join``;
}

Tried destructuring triplet into [a, b, c] to make it more readable, but got execution timeout. Codewars platform has a max time limit of 12000ms. Wanted to do this:
for (let [a, b, c] of triplets) {
    after[a] = new Set([...(after[a] || []), b, c]);
    after[b] = new Set([...(after[b] || []), c]);
    after[c] = new Set([...(after[c] || [])]);
}


texts:
In our hg workflow we use default as testing branch and stable as the one that contains stable code. All changes are made in feature-branches that are started from latest stable. This hook checks if there is a "direct" commit to default or stable (they are denied, only merges may change contents of default and stable) or that new feature branch has been started from default (which is denied by conventions too).

Any proposal to make it more "pythonic" (or just better)?

from mercurial import context

def check(ui, repo, hooktype, node=None, source=None, **kwargs):
    for rev in xrange(repo[node].rev(), len(repo)):
        ctx = context.changectx(repo, rev)
        parents = ctx.parents()

        if len(parents) == 1:
            if ctx.branch() in ['default', 'stable']:
                ui.warn('!!! You cannot commit directly to %s at %s !!!' % (ctx.branch(), ctx.hex()))
                return True

            if parents[0].branch() == 'default':
                ui.warn('!!! You cannot start your private branch from default at %s !!!' % (ctx.hex()))
                return True

    return False


texts: Queue with O(1) enqueue and dequeue with JS arrays

texts:
If you simply implement it with .push() to .enqueue() and .shift() to .dequeue() that's easy but the the time complexity of .enqueue() is O(1) and .dequeue() is O(n).
While still using arrays, I have come come up with a nice solution to make both .enqueue() and .dequeue() in O(1). I am using sparse arrays. It turns out to be super efficient but only when the Queue size is larger than 25000. My benchmarks are like this;
Queue size 100
Queue: 0.12999999523162842
Array: 0.03999999910593033

Queue size 1000
Queue: 1.1049999967217445
Array: 0.5250000059604645

Queue size 10000
Queue: 3.0750000029802322
Array: 1.7799999937415123

Queue size 100000
Queue: 13.944999992847443
Array: 887.390000000596

OK Queue becomes much faster than Array as the size grows but i can not tell what to improve so that Queue doesn't fall behind Array at smaller scales. Is there anything that you can suggest in the below code?

class Queue extends Array {
  constructor(){
    super();
    Object.defineProperty(this,"head",{ value   : 0
                                      , writable: true
                                      });
  }
  enqueue(x) {
    this.push(x);
    return this;
  }
  dequeue() {
    var first;
    return this.head < this.length ? ( first = this[this.head]
                                     , delete this[this.head++]
                                     , first
                                     )
                                   : void 0;
  }
  peek() {
    return this[this.head];
  }
}

var p = Array(100000).fill().map(_ => ~~(Math.random()*1000)),
    q = p.reduce((r,e) => r.enqueue(e), new Queue());

var s,e;

s = performance.now();
for (i=0; i < 100000; i++){
  q.dequeue();
}
e = performance.now();
console.log("Queue:", e-s);

s = performance.now();
for (i=0; i < 100000; i++){
  p.shift();
}
e = performance.now();
console.log("Array:", e-s);

Edit:
After some research, now i understand that what many of us have been told is in fact not correct. .shift() is not O(n). It's been optimized to O(1) many years ago and i think last ones to optimize were the Firefox guys in 2017. Here the guys are discussing how to implement the optimization and it turns they do a very similar thing to what i implemented here. Unlike me, they just skip the "delete out the dequeued item" part since they write it in C++ and can move the pointer (head in above code) by leaving out freed spaces to GC. But in JS we have to delete them either in each .dequeue() operation or wait for (this.length - this.head) > 50000 and make a .splice(0,this.head)  in order to prevent memory leak. This is inline with what i see with Chrome and new Edge (Chromium). Up until 50000 items .shift() works O(1) but then they switch to non optimized code. In Firefox this seems to be not the case as mentioned in a developer's comment.
Verdict:
You may safely and simply implement efficient Queues with .push() and .shift().


texts: Reading a string-to-string map from an archive

texts:
I have a CArchive Which contains a serialized CMapStringToString.

From my research it is my understanding that it is quite difficult to directly read a CArchive from within a C# DLL. So I decided to read it in the MFC application and feed it into the DLL interface.

At the moment I am doing the following:

m_pInterface->UpgradeDatabase();

CFile           fileNotes;
CFileException  ex;
TCHAR           szError[_MAX_PATH];
CMapStringToString mapSSBrotherNotes;

if (fileNotes.Open(_T("d:\\BrotherNotes.BIN"), CFile::modeRead, &ex))
{
    TRY
    {
        CArchive ar(&fileNotes, CArchive::load);
        mapSSBrotherNotes.Serialize(ar);
        ar.Close();

        POSITION sPos = mapSSBrotherNotes.GetStartPosition();
        while (sPos != NULL)
        {
            CString strName, strNotes;
            CComBSTR bstrName, bstrNotes;

            mapSSBrotherNotes.GetNextAssoc(sPos, strName, strNotes);

            bstrName = strName.AllocSysString();
            bstrNotes = strNotes.AllocSysString();

            m_pInterface->SetPublisherNotes(bstrName, bstrNotes);
        }
    }
    CATCH(CException, pEx)
    {
        pEx->GetErrorMessage(szError, _MAX_PATH);
        AfxMessageBox(szError, MB_OK | MB_ICONERROR);
    }
    END_CATCH

    fileNotes.Close();
}
else
{
    // If the file was not found, this is probably not an error
    if (ex.m_cause != CFileException::fileNotFound)
    {
        ex.GetErrorMessage(szError, _MAX_PATH);
        AfxMessageBox(szError, MB_OK | MB_ICONERROR);
    }
}
m_pInterface->SavePublisherData(&iResult);

It works fine but is there a better way to read this data file from within the C# DLL?

Side question - can my use of CString / CComBSTR be simplified in my current code?


texts:
I was bored, so I wrote something that could turn .wav files in to .bmps:

#include <stdio.h>
char bmp[12000029]; // Need 12000028 bits, 1 pixel is 3
                    // bits and table is 28 (1500^2 * 3 + 28)

int main() {

  bmp[0]  = 0x42;   // Bitmap signature
  bmp[1]  = 0x4D;   // 'BM'

  bmp[2]  = 0x1C;   //
  bmp[3]  = 0x1B;   // Size of bitmap
  bmp[4]  = 0xB7;   // in bytes
  bmp[5]  = 0x00;   //

  bmp[10] = 0x1A;   // Image data location

  bmp[14] = 0x0C;   // Size of header

  bmp[18] = 0xDC;   //
  bmp[19] = 0x05;   // Dimensions of image
  bmp[20] = 0xDC;   // 1500 * 1500
  bmp[21] = 0x05;   //

  bmp[22] = 0x01;   // Something
  bmp[24] = 0x18;   // standard (?)

  FILE *fp;
  fp = fopen("file.wav", "rb");
  if (fp == NULL) {
    printf("Error opening 'file.wav'\n");
    return 1;
  }
  for (int i = 41; i < 12000043; i++) {     // Actual music data starts at 41
    bmp[i - 15] = fgetc(fp);                // Store first data to bmp[26] (41 - 15)
  }
  fclose(fp);

  fp = fopen("file.bmp", "w+");
  for (int i = i; i < 12000028; i++) {
    fputc(bmp[i], fp);
  }
  fclose(fp);

return 0;
}

I know this is probably the most random thing ever, but it is quite intriguing in my opinion.

(You just got Rickroll'd).


texts:
I've seen the code for this function in John Resig's book 'Secrets of JavaScript Ninja' yesterday.

I considered it useful at once because I've disliked repeatedly typing console.log for some time.

Here's my implementation of a helper function to reduce typing:

// -- Function definition -------------
// Helper function for to simplify the
//  usage of console.log().
// -- Parameter -----------------------
//  Pass as many parameter as you like.
//  Separate them with commas.
function l() {
  console.log.apply(console, arguments);
}

Usage examples:

var car = new Car(180, 'Fiat');
var someArbitraryNumber = 248;

l('My car', car, ' - ', someArbitraryNumber);

l(123, 'abc', false, 248, 'A', ' > --- < ')

Output:

My car Car { color="red",  maxFuel=40,  speed="180 km"}  - 248

123 abc false 248 A  > --- <

What's great about it: instead of typing console.log(...), you can type l(...); much quicker! This simple helper behaves exactly like console.log. For example, the parameters can be any mixture of types, and objects printed on your browser console can be expanded to see their content, they aren't converted to string representations.

If there are any ideas to improve / enhance the function I would be pleased to get that feedback.


texts:
I have to define a lot of values for a Python library, each of which will represent a statistical distribution (like the Normal distribution or Uniform distribution). They will contain describing features of the distribution (like the mean, variance, etc). After a distribution is created it doesn't really make sense to change it.

I also expect other users to make their own distributions, simplicity is an extra virtue here.

Scala has really nice syntax for classes in cases like this. Python seems less elegant, and I'd like to do better.

Scala:

class Uniform(min : Double, max : Double) {
    def logp(x : Double) : Double =
        1/(max - min) * between(x, min, max)

    def mean = (max + min)/2
}

Python:

class Uniform(object):
    def __init__(self, min, max):
        self.min = min
        self.max = max
        self.expectation = (max + min)/2

    def logp(self, x):
        return 1/(self.max - self.min) * between(x, self.min, self.max)

It's not terrible, but it's not great. There are a lot of extra selfs in there and the constructor part seems pretty boilerplate.

One possibility is the following nonstandard idiom, a function which returns a dictionary of locals:

def Uniform(min, max):
    def logp(x):
        return 1/(max - min) * between(x, min, max)

    mean = (max + min)/2
    return locals()

I like this quite a bit, but does it have serious drawbacks that aren't obvious?

It returns a dict instead of an object, but that's good enough for my purposes and would be easy to fix with a that made it return an object.

Is there anything better than this? Are there serious problems with this?


texts:
I was hoping to get some feedback on my basic recreation of the google homepage. Im doing the Odin Project learning course and this was the first project trying to use the basics of HTML/CSS

HTML file:

    <!DOCTYPE html>

    <title>Google</title>
    <link rel="stylesheet" href="style.css">

        About
        Store

        Gmail
        Images
        Apps
        <button type="button" name="button" id="signin">Sign In</button>

      <input type="text" name="userinput" id="userinput">

      <button type="button" id="searchbutton">Google Search</button>
      <button type="button" id="searchbutton">Im Feeling Lucky</button>

        Advertising
        Business

        Privacy
        Terms
        Settings

CSS file:

    #userinput{
  height: 30px;
  width: 500px;
  border-radius: 24px;
  box-shadow:5px 10ox;
}

#signin{
  background-color: blue;
  color: white;
  border-radius: 3px;
  border: 1px solid blue;
}

#searchbutton{
  margin-top: 20px;
  opacity: .60;
  padding: 0 12px;
}

.right{
  float: right;
}

.left{
  float: left;
}

.middle{
  margin-left: 130px;
  padding-top: 200px;
}

button{
  line-height: 28px;
}

body{
  position: relative;
  text-align: center;
  font-size: 14px;
}

footer{
  padding-top: 200px;
}

a{
  color: black;
  text-decoration: none;
}

div{
  word-spacing: 40px;
  display: inline-block;
}


texts: Go program to generate S3 presigned PUT URL

texts:
I'm have a made a simple Go program to generate a s3 presigned put url:

package main

import (
    "fmt"
    "log"
    "time"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/kelseyhightower/envconfig"
)

type Configuration struct {
  Bucket string
}

func main() {
    var configuration Configuration
    // Add Bucket to configuration from environment variable
    // e.g:
    //    CONFIGURATION_BUCKET -> configuration.Bucket
    err := envconfig.Process("configuration", &configuration)
    if err != nil {
        log.Fatal(err.Error())
    }

    sess := session.Must(session.NewSessionWithOptions(session.Options{
      SharedConfigState: session.SharedConfigEnable,
    }))
    svc := s3.New(sess)

    req, _ := svc.PutObjectRequest(&s3.PutObjectInput{
      Bucket: aws.String(configuration.Bucket),
      Key: aws.String("default"),
    })

    url, err := req.Presign(15 * time.Minute)
    if err != nil {
        log.Fatal(err.Error())
    }

    fmt.Println("Url is", url)
}

I would like to ask for help to turn into a more modular code / idiomatic. This is my first code written in Go, and I have mainly a JavaScript background, so I'm used to use asynchronous programming with callbacks (now Promises, async/await), and in Go things are very different (there are no classes, for example).


texts: iOS UITableView; saving cell checkmarks to disk

texts:
As per suggestion on SO, I am posting my code here to be reviewed. It was said I should not be saving and reading from disk so many times when a user selects and deselects a cell in my tableView.

@property (nonatomic, strong) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray *list;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.list = [[NSArray alloc] initWithObjects:@"Alabama", @"Alaska", @"Arizona",
    @"Arkansas", @"California", @"Colorado", @"Connecticut", @"Delaware", @"District of Columbia",
    @"Florida", @"Georgia", @"Hawaii", @"Idaho", @"Illinois", @"Indiana", @"Iowa", @"Kansas",
    @"Kentucky", @"Louisiana", @"Maine", @"Maryland", @"Massachusetts", @"Michigan", @"Minnesota",
    @"Mississippi", @"Missouri", @"Montana", @"Nebraska", @"Nevada", @"New Hampshire",
    @"New Jersey", @"New Mexico", @"New York", @"North Carolina", @"North Dakota", @"Ohio",     @"Oklahoma",
    @"Oregon", @"Pennsylvania", @"Rhode Island", @"South Carolina", @"South Dakota",
    @"Tennessee", @"Texas", @"Utah", @"Vermont", @"Virginia", @"Washington", @"West Virginia",
    @"Wisconsin", @"Wyoming", nil];
}

- (NSString *)SettingsPlist
{
    NSString *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *PlistPath = [paths stringByAppendingPathComponent:@"Settings.plist"];
    return PlistPath;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    return [[self list] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *contentForThisRow = [[self list] objectAtIndex:[indexPath row]];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }

    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:[self SettingsPlist]];

    NSString *row = [NSString stringWithFormat:@"%d",indexPath.row];

    if([[dict objectForKey:row]isEqualToString:@"0"])
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }

    [[cell textLabel] setText:contentForThisRow];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *plist = [NSMutableDictionary dictionaryWithContentsOfFile:[self SettingsPlist]];

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    NSString *row = [NSString stringWithFormat:@"%d",indexPath.row];

    if(cell.accessoryType == UITableViewCellAccessoryNone)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        NSString *on = @"1";
        [plist setObject:on forKey:row];
        [plist writeToFile:[self SettingsPlist] atomically:YES];
    }
    else if(cell.accessoryType == UITableViewCellAccessoryCheckmark)
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        NSString *off = @"0";
        [plist setObject:off forKey:row];
        [plist writeToFile:[self SettingsPlist] atomically:YES];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


texts:
I'm trying to write a platform independent Python (>=3.6.5) package that has a handful of java .class files that need to compiled using javac and run using java. This is simple enough task but I need to know if user has these installed already and the location of the executable assuming that neither of them is on the system path. That way I can just call the executable by it's path using subprocess.run. Which bring me to the subject of this review a platform independent whereis command.

import os, subprocess
from subprocess import CalledProcessError

def whereis(app):
    """Return a list of locations a given application.

    Relies on the `where` system command in Windows and the `whereis` command in Unix.

    Parameters
    ----------
    app : str
        Can be any application on the system path e.g. java.

    Returns
    -------
    result : list
        A list of locations where applications is installed.

    Useage
    ------
    >>>whereis('javac')
    'C:\\Program Files\\Java\\jdk1.8.0_162\\bin\\javac.exe'
    """

    result = None

    if os.name == "nt":# Windows
        try:
            result = subprocess.check_output("where {}".format(app))

        except CalledProcessError as err:
            print("Application ,",app,", not forund.",err)

    else:# Unix
        try:
            result = subprocess.check_output("whereis {}".format(app))

        except CalledProcessError as err:
            print("Application ,",app,", not found.",err)

    if result is None:
        print("")
        result = []
        return result

    else:
        result = result.decode().replace("\r", "").split("\n")
        result = list(filter(lambda x: len(x)>0, result))
        return result

Questions

Is there a standard library function that already covers this? I couldn't find one but that doesn't mean anything.
Are there any caveats or edge cases that I'm missing?
Can any general improvements be made to the code or docstring?


texts:
In my Rails app, I have a form.  The form has radio buttons for entity type and has a text field for SSN and another for EIN. Based on the radio button selected, one of the text fields will be disabled and the other enabled (disabled = false).

If the user selects the radio button for entity_type_i, it should disable the EIN field, and enable SSN.  For the other four radio buttons, it should do the opposite - disable SSN and enable EIN.  Since I don't know JavaScript, I ended up copying and pasting the same code and just changing the name of the id (i.e.
#user_entity_type_c).  Basically #user_entity_type_c, #user_entity_type_p, #user_entity_type_l and #user_entity_type_o should behave the same.

Without knowing any better, the code seems like it's redundant.  Is there a more efficient way to write the JavaScript?

Radio buttons for the form:

    <input class="radio_buttons required" required="required" aria-required="true" type="radio" value="I" name="user[entity_type]" id="user_entity_type_i" />
    Individual / Sole Proprietor

    <input class="radio_buttons required" required="required" aria-required="true" type="radio" value="C" name="user[entity_type]" id="user_entity_type_c" />
    Corporation

    <input class="radio_buttons required" required="required" aria-required="true" type="radio" value="P" name="user[entity_type]" id="user_entity_type_p" />
      Partnership

    <input class="radio_buttons required" required="required" aria-required="true" type="radio" value="L" name="user[entity_type]" id="user_entity_type_l" />
    Limited Liability Company

     <input class="radio_buttons required" required="required" aria-required="true" type="radio" value="O" name="user[entity_type]" id="user_entity_type_o" />
       Other

The JavaScript:


texts: Converting partial XML (Node List) to a String

texts:
I have a need to extract a part of XML tree (everything under root) and convert it to a string.  (The result string will be later pasted inside XSL-FO XSLT file.)

The above functionality is a part of Java 6 application.  I use org.w3c.dom and javax.xml.transform. Still in the debugging process.

// ...

// Extract all child notes of root from foDoc
// and convert the result to String
Node root = foDoc.getElementsByTagNameNS("*","root").item(0);
NodeList body = root.getChildNodes();
String foResult;

try {
    foResult = nodeListToString(body);
} catch (TransformerException e) {
    logger.error(e);

    foResult = "";
}
// ...

private static String nodeListToString(NodeList nodes) throws TransformerException {
    StringBuilder result = new StringBuilder();
    int len = nodes.getLength();
    for(int i = 0; i < len; ++ i) {
        result.append(nodeToString(nodes.item(i)));
    }
    return result.toString();
}

private static String nodeToString(Node node) throws TransformerException {
    StringWriter buf = new StringWriter();
    Transformer xform = TransformerFactory.newInstance().newTransformer();
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    xform.transform(new DOMSource(node), new StreamResult(buf));
    return(buf.toString());
}

My questions:

Assuming that there will always be exactly one root node, how reliable is my code in extracting everything under it?
Am I missing any edge cases?
Anything just plain wrong?

Please disregard any exception handling inadequacies.

Edited on 10/06/2015

Since my originally posted code had a "just plain wrong" part, I've fixed it. There were no answers based on the old code.


texts:
I wrote this code to overcome the deadlock condition described in this Oracle tutorial.

Summary of Problem:

  Alphonse and Gary are friends, and great believers in courtesy. A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time.

I used a volatile boolean CanBow() to check if either of the friends are bowing so that the condition when both of them bow and wait for the other to bow back will not happen.

Is this a valid way to handle deadlocks as opposed to using locks?

public class NewThread extends Thread {
    Friend bower;
    Friend bowBack;
    NewThread(Friend bower,Friend bowBack){
       this.bower = bower;
       this.bowBack = bowBack;
    }
    @Override
    public void run(){
       if(bowBack.canBow())
             bower.bow(bowBack);
    }
}

public class ApplicationThread {
    public static void main(String[] args) {
        final Friend alphonse = new Friend("Alphonse");
        final Friend gary = new Friend("Gary");
        NewThread t1 = new NewThread(alphonse,gary);
        NewThread t2 = new NewThread(gary,alphonse);
        t1.start();
        t2.start();
    }
    static class Friend {
        private final String name;
        private volatile boolean canBow;
        public Friend(String name) {
            this.name = name;
            canBow = true;
        }
        public String getName() {
            return this.name;
        }
        public boolean canBow(){
            return canBow;
        }
        public synchronized void bow(Friend bower) {
                canBow = false;
                System.out.format("%s: %s"
                    + "  has bowed to me!%n",
                    this.name, bower.getName());
                bower.bowBack(this);
                canBow = true;
        }
        public synchronized void bowBack(Friend bower) {
            System.out.format("%s: %s"
                + " has bowed back to me!%n",
                this.name, bower.getName());
        }
    }
}


texts:
I am new to Java and not quite familiar with its design patterns.

I have tried to implement a CSV-File reader from scratch. The CSVFile constructor accepts the path to the file and a class which represents each datapoint (line in file). This class must implement the "fromLine" method (which accepts an array of Strings (each element being in a different column)) and the "toLine" method (which turns an object into a CSV-File line (String)). Both are described in the CSVDataPoint interface.

import java.util.List;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.io.FileReader;
import java.io.PrintWriter;

public class CSVFile
{
    Class dp;
    String path;

    public CSVFile(String path, Class<? extends CSVDataPoint> dp)
    {
        this.path = path;
        this.dp = dp;
    }

    public List load(int skip) throws Exception
    {
        List fields = new ArrayList<CSVDataPoint>();
        int lineCount = 0;

        try(BufferedReader br = new BufferedReader(new FileReader(path))){
            String line;
            while((line = br.readLine()) != null){
                lineCount++;

                if(lineCount > skip)
                {
                    CSVDataPoint a = (CSVDataPoint) dp.newInstance();
                    fields.add(a.fromLine(line.split("\\,")));
                }
            }
        }

        return fields;
    }

    public void dump(List<CSVDataPoint> lines) throws Exception
    {
        String result = "";
        PrintWriter writer = new PrintWriter(path, "UTF-8");

        for(int n = 0; n < lines.size(); n++)
        {
            writer.println(lines.get(n).toLine());
        }

        writer.close();
    }
}

CSVDataPoint interface:

public interface CSVDataPoint
{
    Object fromLine(String[] line);
    String toLine();
}

Although the code does work, I am not sure whether it is stylistically correct. Any criticism would be appreciated greatly.


texts:
I wrote three versions of the same code using Reduce, a functional approach and also a regex pattern approach.

I'd like to get feedback, especially from the functional one since I'm learning  functional programming and I'm sure my solution can be greatly improved.

const CHAR = 'X'
const BANNED = ['nice', 'is', 'stupid', 'potato']
const sentence = 'lorem ipsum is a nice and stupid sentence'

// VERSION 1 - REDUCE
const censor = (sentence) =>
  sentence.split(' ').reduce((acc, word) =>
    acc + ' ' + (BANNED.includes(word) ? CHAR.repeat(word.length) : word), '')

const censored = censor(sentence).trim()

console.log(censored)

// VERSION 2 - PIPE (functional?)
const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)))

const extractWords = (sentence) => sentence.split(' ')

const removeBanned = (arr) =>
  arr.reduce((acc, word) => acc + ' ' + replaceIfBanned(word), '')

const cleanUp = (arr) => arr.trim()

const replaceIfBanned = word =>
  BANNED.includes(word) ? replaceWithChar(word) : word

const replaceWithChar = (word) => CHAR.repeat(word.length)

const work = pipe(extractWords, removeBanned, cleanUp)(sentence)

console.log(work)

// VERSION 3 - REGEX
const styleHyphenFormat = (sentence) => {
  const replaceWithX = (match) => CHAR.repeat(match.length)
  const filter = new RegExp(BANNED.join('|'), 'gi')

  return sentence.replace(filter, replaceWithX)
}

console.log(styleHyphenFormat(sentence))

You can also check it out in JSFiddle.


texts:
Please note the following:

All edges are directed
Removal of edges/nodges is not implemented yet
A user of the class Graph can never (hopefully) access a Node directly
If one tries to add an edge to a node that does not exist, insert_edge() will do nothing.
A Vertex cannot point to another vertex with several edges.
While the base class Graph works perfectly, I would like to create more advance graphs that could be used for maximum flow algorithm, weighted graphed etc. by creating new classes and inherit functions from Graph. But this seems impossible by the current implementation. It seems that the only way for a smooth solution for this right now is to add more data members to Node (int weight for example). Any idea on what I can do for making this possible with inheriting from Graph instead?

class Node
{
public:

std::string get_name()const;

//protected:
Node() = default;

Node( const std::string & n )
: name(n)
{}

std::vector<Node*> neighbours;
private:
std::string name;
};

class Graph : public Node
{
public:
void insert_node( std::string);
void insert_edge( std::string, std::string);
void print_node( const std::string) const;
void print_graph() const;

protected:
void insert_edge( Node*, Node*);
Node* get_node( std::string ) const;
bool is_node( Node * );

private:
std::vector<Node*> list;
};

std::string
Node::get_name() const
{
return name;
}

void
Graph::insert_node( std::string name)
{
for( auto& node  : list  )
{
  if( name == node -> get_name() )
  {
     return;
  }
}

Node *temp = new Node(name);
list.push_back ( temp );
}

void
Graph::insert_edge( Node *n, Node *new_edge )
{
if( n == nullptr || new_edge == nullptr )
{
  return;
}

if( !is_node( n ) )
{
  return;
}

for( auto& node : list )
{
  if( n -> get_name() == node -> get_name() )
  {
     for( auto& current_edges : node -> neighbours )
     {
        if( current_edges -> get_name() == new_edge -> get_name() )
        {
           return;
        }
     }
     node -> neighbours.push_back( new_edge );
  }
}
}

void
Graph::insert_edge( std::string n, std::string new_edge)
{
Node* temp1 = get_node( n );
Node* temp2 = get_node( new_edge );
insert_edge( temp1, temp2 );
}

Node*
Graph::get_node( std::string name ) const
{
   for( auto& node : list )
{
  if( name == node -> get_name() )
  {
     return node;
  }
}
return nullptr;
}

void
Graph::print_node( std::string name ) const
{
std::cout << name << " : ";
for( auto&  node : list )
{
if(name == node -> get_name() )
  {
     for( auto& edge : node -> neighbours )
     {
        std::cout << " -> " << edge -> get_name();
     }
     std::cout << std::endl;
     break;
  }
}
}

void
Graph::print_graph() const
{
for( auto&  node : list )
{
  std::cout << node -> get_name() << " : ";
  for( auto& edge : node -> neighbours )
  {
   std::cout << " -> " << edge -> get_name();
  }
  std::cout << std::endl;
}
}

bool
Graph::is_node( Node *n )
{
for( auto& node : list )
{
  if( node -> get_name() == n -> get_name() )
  {
     return true;
  }
}
return false;
}


texts: Selecting folders based on last modified date

texts:
I am attempting to find folders based on their last modified dates.

import os, shutil, stat, errno, time, datetime
srcFolders = "C:\Users\Test\Desktop\Test"
archiveDate = datetime.datetime.strptime("2016/11/20", '%Y/%m/%d')
os.chdir(srcFolders)

for name in os.listdir('.'):
    if os.path.isdir(name):
        modifiedDate = time.strftime('%Y/%m/%d', time.gmtime(os.path.getmtime(name)))
        strLastModified = datetime.datetime.strptime(modifiedDate, '%Y/%m/%d')
        if  strLastModified > archiveDate:
            print name

This is what I've got and it seems to be right in that they're comparing the same attributes. If there is a better, more Pythonic way for this, please advise.


texts: Pulling host list from ldapserach command from netgroup

texts:
As i am learning bash, i have written a small code which is nothing but a simple ldapsearch query which lists all thememberNisNetgroup under Infra_Global netgroup.
I am pulling the list out of the netgroup and iterating over the list with a for loop which works fine. I am just curious if the below code which works fine can have an improvement from the bash standard.
Would appreciate any help on this.
#!/bin/bash
#
NTGRP=$(ldapsearch -h ldapServer -xLL -b "cn=Infra_Global,ou=Netgroup,ou=tdi,o=tdp" | awk '/^memberNisNetgroup/{print $2}'| cut -d"_" -f2-)

for netg in $NTGRP ;

do
echo "-- $netg --";

ldapsearch -h ldapServer -xLL -b "ou=Netgroup,ou=$netg,ou=location,ou=tdi,o=tdp" | awk '/,,/{print $2}' | tr -d '(),'

done

Result:
---- SAT-GEN11 ----
inv0602.tdi.tdp.com
inv0557.tdi.tdp.com


texts: SQL self-join to label nodes on binary search tree

texts:
Would like feedback on my SQL (1) efficiency and (2) readability, and if the conditions I featured in my CASE statement could be transferred to a join, etc.

Here's the problem I'm solving:

  Say you have a table bst with a column of nodes and column or
  corresponding parent nodes:

node   Parent
1       2
2       5
3       5
4       3
5       NULL

  We want to write SQL such that we label each node as a “leaf”, “inner”
  or “Root” node, such that for the nodes above we get:

Node    Label
1       Leaf
2       Inner
3       Inner
4       Leaf
5       Root

Here's my solution:

WITH join_table AS
(
SELECT
    a.node a_node,
    a.parent a_parent,
    b.node b_node,
    b.parent b_parent
 FROM
    bst a
 LEFT JOIN
    bst b ON a.parent = b.node
 )

 SELECT
    a_node as Node,
    CASE
        WHEN b_node IS NOT NULL and b_parent IS NOT NULL THEN 'Leaf'
        WHEN b_node IS NOT NULL and b_parent IS NULL THEN 'Inner'
        WHEN b_node IS NULL and b_parent IS NULL THEN 'Root'
        ELSE 'Error'
    END AS Label
 FROM
    join_table


texts:
In an interview about multithreading I was asked to write code to satisfy the requirements below:

  In the exercise you need to provide implementation of single-threaded TaskScheduler class with the following signatures:

TaskScheduler {

   TaskScheduler(List<Task> tasks)

  int getPriority()

  void execute()

  where Task object is considered interruptible if it implements Interruptible interface.

Now I have to consider the below 4 requirements also in developing the class:

  Define TaskScheduler and Task classes

  Define classes, write a test or vice versa.
  executeAllByPriority()

  Add void executeAllByPriority() method to TaskScheduler, test and implement it.
  executeAllByPriorityWithUninterruptableFirst()

  Add void executeAllByPriorityWithUninterruptableFirst() method to TaskScheduler, implement and test it.
  Bonus

  Provide multi-threaded version of TaskScheduler such that it guarantees that a higher priority task always starts execution
  before a lower priority task.

Keeping these above 4 points in consideration I have coded the below program. Please advise whether it is the correct approach.

public class MultiThreadedTaskScheduler  {

      AtomicInteger priorityCounter = new AtomicInteger(-1);
private ExecutorService executorService = Executors.newFixedThreadPool(10);

private PriorityQueue<Task> taskQueue;
private static final PriorityComparator PRIORITY_COMPARATOR = new PriorityComparator();

        public MultiThreadedTaskScheduler(List<Task> tasks){
            this.taskQueue = new PriorityQueue<Task>(tasks.size(), PRIORITY_COMPARATOR);
            this.taskQueue.addAll(tasks);
        }

        public void executeAllByPriority(){
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    for (Task task : taskQueue) {
                        executeMethod(task);
                    }
                }
            });

        }

    private void executeMethod(Task task) {
        if (task.getPriority()  > priorityCounter.get() ){
            task.execute();
            priorityCounter.getAndSet(task.getPriority());
        }

    }

        public void executeAllByPriorityWithUnInterruptableFirst(){
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    PriorityQueue<Task> interruptedQueue = new PriorityQueue<Task>(taskQueue.size(),PRIORITY_COMPARATOR);
                    for (Task task : taskQueue) {
                        if (task instanceof Interruptible && ((Interruptible) task).isInterrupted() ){
                            interruptedQueue.add(task);
                        } else {
                            executeMethod(task);
                        }
                    }

                    for (Task task : interruptedQueue ){
                        executeMethod(task);
                    }
                }
            });

        }

        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            executorService.shutdown();
        }

}


texts: Job shop scheduling with Clojure's core.logic

texts:
Here's a job shop scheduler using core.logic. I had a lot of fun coding it. I'd appreciate ideas on how to make the code faster or more readable.

Setup

(ns schejule.no-db
  (:require [clojure.core.logic :refer [== all everyg lvar run run* fresh succeed] :as l]
            [clojure.core.logic.fd :as fd])
  (:refer-clojure :exclude [==]))

(def test-data
  [{:id 1 :job :cooljob :duration 180 :machine 1}
   {:id 2 :job :cooljob :duration 120 :machine 2}
   {:id 3 :job :cooljob :duration 100 :machine 3}
   {:id 4 :job :cooljob :duration 150 :machine 4}
   {:id 5 :job :ajob :duration 180 :machine 1}
   {:id 6 :job :ajob :duration 120 :machine 2}
   {:id 7 :job :ajob :duration 100 :machine 3}
   {:id 8 :job :ajob :duration 150 :machine 4 :startby 300}
   {:id 9 :job :another :duration 180 :machine 1}
   {:id 10 :job :another :duration 120 :machine 2}
   {:id 11 :job :another :duration 100 :machine 3}
   {:id 12 :job :another :duration 150 :machine 3 :startby 400}])

Ratiocinate!

(defn init-jobs
  "Binds tasks in a job to occur in the correct order.
  `lengths` must be a seq of integers defining no. of tasks in nth job."
  [tasks lengths]
  (if (seq lengths)
    (let [l (first lengths)]
      (all
      (everyg (fn [[x y]] (fd/< x y)) (partition 2 1 (take l tasks)))
      (init-jobs (drop l tasks) (next lengths))))
    succeed))

(defn sort-tasks
  "Sorts tasks by `:job`, then by `:id` to prepare for `solvo`"
  [tasks]
  (->> tasks (sort-by :job) (sort-by :id)))

(defn solvo*
  "Find a feasible ordering for tasks.
  tasks **MUST** be sorted by `:job`, then by `:id`."
  [tasks]
  (let [n (count tasks)
        lengths (->> tasks (partition-by :job) (map count))
        vars (repeatedly n lvar)]
    (run* [q]
          (== q vars)
          (init-jobs vars lengths)
          (everyg #(fd/in % (fd/interval (- n 1))) vars)
          (fd/distinct vars))))

(defn constructo*
  "Calls solvo on some tasks, then associates ords with tasks.
  Returns a lazy (possibly huge) sequence."
  [tasks]
  (let [ts (sort-tasks tasks)
        feasible* (solvo* ts)]
    (map (fn [tasks ords]
          (map (fn [t ord]
                  (assoc t :ord ord))
                tasks
                ords))
        (repeat ts)
        feasible*)))

Filter

I'm a bit worried about the (lack of) speed of this gargantuan filter expression!

(some (fn [tasks]
        (reduce (fn [solution task]
                  (let [{:keys [machine duration job id startby]}
                        task

                        prev-machine (get-in solution [:prev-task job])

                        prev-end (max
                                  (or (:end-time (last (get-in solution [:tasks machine]))) 0)
                                  (or (:end-time (get-in solution [:tasks prev-machine])) 0))

                        task-w-end (assoc task :end-time (+ prev-end duration))]

                    (when (and startby (< startby prev-end))
                      (reduced nil))
                    (-> solution
                        (update-in [:tasks machine] #(conj % task-w-end))
                        (assoc-in [:prev-task job] machine))))
                {}
                tasks))
      (map (partial sort-by :ord) (constructo* test-data-2)))


texts:
I am working on converting a PHP application to MVC, and have a couple questions!

1) I have a main Model object, that I require a database connection for, as well as a User object that uses a database object also. Is it a bad practice to create a new database object for each of these classes, like the following?

or should I create a $databaseObject variable on the index.php page and pass that same variable in as a construct parameter for both User and Model? What is the difference?

Is there anything else that sticks out as something that I am doing wrong?

class Model {

    function __construct() {
        $this->user = new User();
        $this->db = new Database( DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS );
    }
}

class User {

    public function getUserId(){
        return $this->_userid;
    }

    public function __construct( ){
        $this->db = new Database( DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS );
        $this->_userid = 1;
    }
}

Thanks in advance for the help!


texts: Handling errors when using PDO to connect to a database instead of MySQLi

texts:
What would be the preferred method for handling errors when using the PDO to connect to a MySQL database? I was using mysqli_error($this->pdo), but I heard this was bad practice. Any feedback would be much appreciated.

class Database
{
    /*
     * Database properties
     */
    private $server   = 'localhost';
    private $username = 'root';
    private $password = 'root';
    private $database = 'posts';
    public $pdo;
    public static $instance;

    /**
     * Static method used to instantiate singleton
     * @return [object] Database object
     */
    public static function getInstance()
    {
        if (!isset($instance)) {
            Database::$instance = new Database();
        }
        return Database::$instance;
    }

    /**
     * Connect to DB when class is instantiated
     */
    private function __construct()
    {
        $this->connect();
    }

    /**
     * Connects to the database
     */
    private function connect()
    {
        // Assign dsn string
        $dsn = 'mysql:host=' . $this->server . ';dbname=' . $this->database;

        // Assign connection to $pdo
        $pdo = new PDO($dsn, $this->username, $this->password);

        // $pdo inside the function is added to the objects parameter pdo
        else {
            $this->pdo = $pdo;
        }
    }

    /**
     * Queries database for the argument $sql
     * @param  string $sql
     * @return Sql Query $statement
     */
    public function query($sql)
    {
        // Prepare SQL query
        $statement = $this->pdo->prepare($sql);

        // return mysql query array
        else {
            return $statement;
        }
    }

    /**
     * Queries for post of id $id
     * @param  [$id] Post ID
     * @return [array]
     */
    public function getPost($id)
    {
        // Query
        $stmt = $this->query("SELECT * FROM posts WHERE id=(:id)");

        // Binds $id parameter to the PDO
        $stmt->bindParam(':id', $id);

        // Execute query
        $stmt->execute();

        // Create an empty array for the posts
        $posts = array();

        while($row = $stmt->fetch()) {
            // Data is fetched from the database as an array
            $posts[] = $row;
        }

        // Return post in an array
        return $posts;
    }

}


texts: Improvement for std::map  double dispatch

texts:
I am trying to do my c++ homework and as a part of it I have to implement a std::map with an int as its key and a value should be a specific void function, which prints some text.
I can`t find an answer to what are the correct ways of doing that.

This is what I have so far:

#include <map>
#include <string>
#include <iostream>

class testClass
{
public:
    void testFunc1() { std::cout << "func1\n"; }
    void testFunc2() { std::cout << "func2\n"; }
};

typedef void(testClass::*runFunc)(void);
typedef std::map<int, runFunc> myMapType;

int main() {
    testClass t1;

    std::map<int, runFunc> myMap;
    myMap.emplace(1, &testClass::testFunc1);
    myMap.emplace(2, &testClass::testFunc2);

    myMapType::const_iterator itr;
    itr = myMap.find(2);

    if (itr != myMap.end()) {
        (t1.*(itr->second))();
    }
}

The code is working now, however I am not sure if that is the way people with more experience do.

Also, if you are aware of any sources where one can read more about knowledge required to achieve the needed result - any ideas are appreciated.


texts:
I have an assignment for writing a Sudoku solver and have achieved the functionality required but a lot of the code is "ugly" and I'm wanting to simplify it but unsure how to.

def hiddenSingleCol(snapshot, cell):
    j = cell.getCol()                           # Get column number for cell
    colCells = snapshot.cellsByCol(j)           # Get all cells in that column
    for num in cell.getAvailNum():              # For each available number for the cell we are looking at
        hidden = True                           # Is it a hidden single? (set hidden as True to start)
        for tempCell in colCells:               # For each cell in the list of cells
            if tempCell == cell:                # If it is our cell, ignore
                pass
            elif num in tempCell.getAvailNum(): # If one of the available num is the same
                hidden = False                  # Set hidden to false
                break
        if hidden:
            cell.setAvailNum(num)               # If hidden is still true, set available num to num
            break

More code snippets:

    for cell in cUnsolved:                          # we're only interested in cells without assigned values
    updateAvailNums(snapshot, cell)             # update the list of potential answers for each cell

for cell in cUnsolved:
    hiddenSingleCol(snapshot, cell)
    hiddenSingleRow(snapshot, cell)
    hiddenSingleBlock(snapshot, cell)

for cell in cUnsolved:
    if (len(cell.getAvailNum()) == 0):          # and if any have no possible numbers, this is a failed solution
        return None
    if (len(cell.getAvailNum()) == 1):          # and if there are any with only one possibility, we do this first
        x = cell.getRow()
        y = cell.getCol()
        break
    elif (len(cell.getAvailNum()) < minNum):    # otherwise we are interested in the cell with the least possible numbers so far
        x = cell.getRow()
        y = cell.getCol()
        minNum = len(cell.getAvailNum())

Not only are the multiple for-loops in here ugly, but I have 2 other versions, slightly altered, for the row and 3x3 blocks. I've tried looking at other code snippets on this but I seem incapable of applying it to my own work.


texts:
In JUnit 3, I cannot tell JUnit what type of exception is expected. In JUnit 4, the declaration @Test(expected=NullPointerException.class) does it.

But, unfortunately in Android development, I can use only JUnit 3. So I wrote this simple method:

public class TestingUtils {

    public static void assertExpectedException(
                           Class<? extends Exception> exceptionClass, Runnable runnable) {
        try {
            runnable.run();
            throw new AssertionFailedError(
                         "Expected exception: <" + exceptionClass.getName() + ">");
        } catch (Exception e) {
            if (!exceptionClass.equals(e.getClass())) {
                throw new AssertionFailedError(
                        "Expected exception: <" + exceptionClass.getName() + "> " +
                        "but was: <" + e.getClass().getName() + ">"
                );
            }
        }
    }
}

Using:

public void testConstructorThrowsExceptionIfArgumentIsNull() {
    TestingUtils.assertExpectedException(IllegalArgumentException.class, new Runnable() {
        @Override
        public void run() {
            new SomeTestedClass(null);
        }
    });
}


texts:
The goal is to find \$f(n,r)\mod(m)\$ for the given values of \$n\$, \$r\$, \$m\$, where \$m\$ is a prime number.

$$f(n,r) = \dfrac{F(n)}{F(n-r) \cdot F(r)}$$

where

$$F(n) = 1^1 \cdot 2^2 \cdot 3^3 \cdot \ldots  \cdot n^n$$

Here is the Python code snippet I've written:

    n_r = n - r
    num = 1
    den = 1

    if n_r > r:
        for j in xrange(n_r + 1, n + 1):
            num = num*(j**j)
        for k in xrange(2, r + 1):
            den = den*(k**k)

        answer = num/den
        ans = answer%m
        print ans

    else:
        for j in xrange(r + 1, n + 1):
            num = num*(j**j)
        for k in xrange(2, n_r + 1):
            den = den*(k**k)

        answer = num/den
        ans = answer%m
        print ans

This code runs for small values of \$n\$ (when \$n <= 100\$). But for large values of \$n\$ ~ \$10^5\$, the code seems to be inefficient, exceeding the time limit of 2 sec. How can I generalize and optimize this computation?